r/pythonhelp • • Feb 07 '24

Generating white noise?

2 Upvotes

Hello! I'm looking to generate simple white noise in python, but can't find any proper way to do it. I want to be able to take a sample from the noise by passing a coordinate, and for the noise to be infinite* (not a fixed size is what I mean by that).I can find resources for perlin noise (smooth noise), but none for white noise. Thanks for any help!

Something like this:

class Noise:
    def __init__(self, frequency: int = 50):
        """Create noise. Frequency is the frequency of white pixels. 1 means roughly every other pixel is white, 100 means roughly every hundredth pixel is white."""
        self.frequency = frequency

    def get_sample(self, x, y) -> int:
        """Gets a sample of the noise at specified coordinates. Returns 1 if white, 0 if black"""
        # return noise sample

r/pythonhelp • • Jan 17 '24

Could someone say what is going on in my code

2 Upvotes

Hello,

I come here to be help by people because I can't complete my assignment by my own.

Im French so its normal if they are french word in the program.

The code (on Thonny):

import math  
def volume_tore():  
r = int(input("Entrez le rayon du 'petit cercle' : "))  
R = int(input("Entrez le rayon du 'grand cercle' : "))  
alpha = math.acos(-1)\*(R/r)  
Oi = math.asin(-1)\*(R/r)  
if R >= r > 0:  
S = 4 \* math.pi\*\*2 \* r \* R  
V = 2 \* math.pi\*\*2 \* r\*\*2 \* R  
elif r > R > 0:  
S = 4 \* math.pi \* r \* (R \* (math.pi-alpha) + r \* math.sin(alpha))  
V = math.pi \* r \* \[(math.pi + 20) \* r \* R + (4/3 \* r\*\*2 + 2/3 \* R\*\*2) \* math.cos(Oi)\]  
elif r > R == 0:  
S = 4 \* math.pi \* r\*\*2  
V = 4/3 \* math.pi \* r \*\*3  
return V  

The issue that appear :

Traceback (most recent call last):  
File "<stdin>", line 1, in <module>  
File "C:\\Users\\Eleve\\LibVol.py", line 18, in volume_tore  
V = math.pi \* r \* \[(math.pi + 20) \* r \* R + (4/3 \* r\*\*2 + 2/3 \* R\*\*2) \* math.cos(Oi)\]  
TypeError: can't multiply sequence by non-int of type 'float'  

Im just starting to do some Python so im sorry if theres some errors :)


r/pythonhelp • • Dec 13 '23

SOLVED When trying to subscript a geopy.location.Location object I have no issues, but inside a loop Python tells me "NoneType object is not subscriptable". Why?

2 Upvotes

So I have a variable named coords

It's a list of these geopy.location.Location type objects returned by a geopy handled api request. So if I index the list like coords[1], I get a result like Location(Place Name, (23.6377, 15.062036, 0.0))

If I run coords[1][1] to try to grab just the tuple, this works without issue and get the output (23.6377, 15.062036). But if I do this inside a loop I get the error "NoneType object is not subscriptable".

I don't understand because it seems perfectly subscriptable outside the loop.

# Method 1
coords_new=[]
for i in range(len(coords)):
    temp_c=coords[i]
    coords_new.append(temp_c.raw["geometry"]["coordinates"])

# Method 2    
coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]

# Method 3
fp='coords_file17.txt'
file1 = open(fp,'w')
for i in range(len(coords)):
    x_lat=coords[i].latitude
    file1.writelines(x_lat)

file1.close()


# But outside loops
i=82
coords[i].raw["geometry"]["coordinates"] #this works
coords[i][1] #this works
coords[i].latitude #this works
coords[i].longitude #this works


# Method 1 Error
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[113], line 4
      2 for i in range(len(coords)):
      3     temp_c=coords[i]
----> 4     coords_new.append(temp_c.raw["geometry"]["coordinates"])
      7 # coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]
      8 
      9 
   (...)
     22 # coords[i].latitude #this works
     23 # coords[i].longitude #this works

# AttributeError: 'NoneType' object has no attribute 'raw'


# Method 2 Error
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[116], line 7
      1 # coords_new=[]
      2 # for i in range(len(coords)):
      3 #     temp_c=coords[i]
      4 #     coords_new.append(temp_c.raw["geometry"]["coordinates"])
----> 7 coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]
     10 # file1 = open(fp,'w')
     11 # for i in range(len(coords)):
     12 #     x_lat=coords[i].latitude
   (...)
     38 
     39 # AttributeError: 'NoneType' object has no attribute 'raw'

Cell In[116], line 7, in <listcomp>(.0)
      1 # coords_new=[]
      2 # for i in range(len(coords)):
      3 #     temp_c=coords[i]
      4 #     coords_new.append(temp_c.raw["geometry"]["coordinates"])
----> 7 coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]
     10 # file1 = open(fp,'w')
     11 # for i in range(len(coords)):
     12 #     x_lat=coords[i].latitude
   (...)
     38 
     39 # AttributeError: 'NoneType' object has no attribute 'raw'

AttributeError: 'NoneType' object has no attribute 'raw'

# Method 3 Error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[117], line 13
     11 for i in range(len(coords)):
     12     x_lat=coords[i].latitude
---> 13     file1.writelines(x_lat)
     15 file1.close()
     17 # #But outside loops
     18 # i=82
     19 # coords[i].raw["geometry"]["coordinates"] #this works
   (...)
     67 
     68 # AttributeError: 'NoneType' object has no attribute 'raw'

TypeError: 'float' object is not iterable

r/pythonhelp • • Oct 08 '23

Open tkinter GUI and write text to file not using the run window

2 Upvotes

I'm trying to make a pig latin translator gui that writes the results to a txt file.

code is here : https://pastebin.com/g4Ec0DMt

I want to write to the txt file the results of what occurs in the gui, not what i have to write in the run window. Ideally i don't want to type anything in the run window at all but without that nothing writes to a txt file at all.

Which makes me assume my issue comes between lines 51-60 with what is being asked to be written but i am unsure what i need to put there to get it to.

Any help would be greatly appreciated.


r/pythonhelp • • Sep 26 '23

Exec and lists, it is not working.

2 Upvotes

I am trying to make a game with Turtle, (yes, I know about Pygame, but I'm too lazy). The game is supposed to be like the Steam game Virtual Circuit Board, but I want to make it myself. In the early stages of making it (AKA right now), I came across an issue of that exec isn't updating the turtle (t).

(YES, I KNOW THAT THIS IS NOTHING LIKE VCB, I AM IN EARLY STAGES)

Any help, both with my problem, and the whole things would be appreciated.

This is my code:

from turtle import Turtle as T, Screen as S, onkey, listen, mainloop
global t

t = T(visible=False)
screen = S()
screen.tracer(False)
t.speed(0)
t.lt(90)
t.color(0,0,1)
global commands
commands = []


def up():
    commands.append(compile('t.fd(10)','','exec'))

def down():
    commands.append(compile('t.lt(180)','','exec')); 
    commands.append(compile('t.fd(10)','','exec')); 
    commands.append(compile('t.rt(180)','','exec'))

def left():
   commands.append(compile('t.lt(90)','','exec')); 
   commands.append(compile('t.fd(10)','','exec')); 
   commands.append(compile('t.rt(90)','','exec'))

def right():
   commands.append(compile('t.rt(90)','','exec')); 
   commands.append(compile('t.fd(10)','','exec')); 
   commands.append(compile('t.lt(90)','','exec'))

def runCommands():
    global commands
    global t
    [exec(command,{'t':t}) for command in commands]
    commands = []


listen(); onkey(up,'Up'); onkey(down,'Down'); onkey(left,'Left'); 
onkey(right,'Right'); onkey(runCommands,'a'); mainloop(); screen.exitonclick()

r/pythonhelp • • Jul 23 '23

Learning python

2 Upvotes

What are some ways you guys have learned python? What would you recommend? Anything from books, online courses, or even YouTube channels


r/pythonhelp • • Jul 20 '23

Group data in CSV file

2 Upvotes

I have a CSV file with the following

+ABCDEFG
1Store NumberDevice NameSerial NumberMedia NameLife Counter_1Life Counter_2Life Counter Difference
213DRS80 Dxxxxx8x103089731460563
313SSDS6801xxxxx4x6(a5)2369952402003205
413SDS6801xxxxx5x77883379310477
513SDS4801xxxxx4x87132571683358
614SDS6223xxxxx5x76763684784
714SDS6223xxxxx6x868448705132065
814SDS805xxxxx8x103701337242229
914SDS6223xxxxx6x854892561551263
1014SDS6223xxxxx6x861674636551981
1114SDS6223xxxxx6x866583681551572
1214SDS6223xxxxx5x766176741124
1323SDS6801xxxxx5x7241573241681108
1423SDS6801xxxxx5x7418004189191
1523SDS6801xxxxx4x6(a5)2327552341021347
1623SDS4801xxxxx4x8293602945595
1723DRS80 Dxxxxx8x107501375168155
1823SDS6801xxxxx4x6(a5)172003172745742
1930SDS6223xxxxx6x830519318001281
2030SDS805xxxxx8x102484024982142
2130SDS6223xxxxx6x825440269201480
2230SDS6223xxxxx6x835097367151618
2330SDS6223xxxxx5x72190822208300

What I would like to do is group the data by store number AND media name and then add up all the values for each combined media type using the initial values in the Life Counter Difference column

The desired output would be similar to below

+ABC
1Store NumberMedia NameTotals
2138x10563
3134x6(a5)3205
4135x7477
5134x8358
6145x7208
7146x86881
8148x10229
9234x6(a5)2089
10235x7199
11238x10155
12234x895
13306x84379
14305x7300
15308x10142

Any idea how I could go about this?


r/pythonhelp • • Jul 13 '23

Pygbag isnt working can someone hlp please

2 Upvotes

I've tried to use pygbag to convert my pygame game into a html which I have done before on the same file but when I've tried to do it again this time, it downloads the file but the screen just goes black. The only thing that I've added to the newest version on the game is controller support so I'm quite confused.


r/pythonhelp • • Jul 13 '23

Beginner - How to increment a 2 player rock, scissors, paper game until one person wins 3 games

2 Upvotes

I am not sure what I am doing wrong here but it stays on 'Round 1' no matter how many rounds you play.

print("Let's play ROCK PAPER SCISSORS! ")

p1score = 0 p2score = 0 p1 = input("Player 1 name: ") p2 = input("Player 2 name: ") counter = 1 while True: r=("R","ROCK", "rock", "Rock", "r") s=("S", "s", "Scissor", "scissor", "SCISSOR") p=("P", "p", "Paper", "paper", "PAPER") print() print() print ("Select your moves!") p1move = input("Player1 move>") p2move = input("Player2 move>") print("Round...", counter,+1)

if p1move in r and p2move in r: print(p1, p2,"Rocks and Rocks... it's a tie!")

elif p1move in r and p2move in p: print(p2, "Wins by wrapping the rock in the paper!" ) p2score += 1

elif p1move in r and p2move in s: print(p1,"Wins by breaking the scissors!! 🥳") p1score += 1

elif p1move in p and p2move in r : print(p1,"Wins by wrapping Rocks with paper 🥳") p1score += 1

elif p1move in p and p2move in p : print("Its a Draw 🥺")

elif p1move in p and p2move in s : print(p2,"Win 🥳") p2score += 1

elif p1move in s and p2move in r : print(p2,"Wins 🥳") p2score += 1

elif p1move in s and p2move in p : print(p1,"Wins 🥳") p1score += 1 else: if p1move in s and p2move in s : print("Its a draw again 🥺 ")

if p1score == 3 or p2score == 3 : print (p1,"has",p1score,"and",p2,"has",p2score)

break

else:

continue

r/pythonhelp • • Jun 23 '23

Connecting python to jira

2 Upvotes

So in summary I'm tryig to connect via python to jira. But Idk what is happening always appear an error "Module Request error". I decidid to search on google and I find a video making the connection but again I failed! does anyone can show me how can I connect via python to JIRA??!!
ty for help!


r/pythonhelp • • Jun 21 '23

Spyder not Launchin on Mac

2 Upvotes

Can someone help me?

I am extremely new to Python and Spyder and for some reason when trying to launch Spyder on my Mac it pops us the following error

"Launch error

See the py2app website fr debugging issues."

Which seems to be extremelly generic and when entering the site I dont really understand what to do


r/pythonhelp • • May 30 '23

Absolute beginner, trying to fix a python script to support past 2 bytes size

2 Upvotes

There's this game utility written in Python which among other things, compiles files in assembly (ASM) into the game's own maps format (BVM):

https://github.com/mp-s/edftools

Wherein its only scripts used for this operation, are:

bvm_compiler.py https://drive.google.com/file/d/1BMnwQlbLi9TW31PPh7qVI87BFBzLtXvk/view?usp=sharing

bvm_model.py https://drive.google.com/file/d/1BMnwQlbLi9TW31PPh7qVI87BFBzLtXvk/view?usp=sharing

Now, the issue is that it cannot compile ASMs over a certain filesize: after a few tries, I calculated that it can accept up to 6553 commands. Which I assume means there's a list that supports only up to 65535 bits or 2 bytes. In fact when you try to compile a map that's too large, you get this stack overflow error: https://postimg.cc/mzrBsbBg

Which references this part of the code, mentioning 2 bytes: https://postimg.cc/t1kpw10c

So I'm looking for help to extend this max bytes limit. I tried changing that 2 into a 4, and it ended up allowing for the script to compile larger files... but also corrupts the maps and makes them useless. For reference, here are two ASM files of different size:

ASM, Small, Can be compiled https://drive.google.com/file/d/1hvnUTbu0KzYPHjlUO8Ndc63c_pBjVeqb/view?usp=sharing

ASM, Large, Cannot be compiled https://drive.google.com/file/d/1cDa18pKzSr6o0WpJyFwoFp1PaurSZ0g3/view?usp=sharing

Thanks for any help!


r/pythonhelp • • May 08 '23

How to make markers different shapes according to x value in Seaborn Catplot?

2 Upvotes

I have a catplot with 4 categorical groups along the x axis, and right each grouping is a different colour on the catplot, but they're all circle markers (and I want each grouping to be a different shape of marker for accessibility reasons, e.g. colour vision deficiency). How can I do that?

dataframe = pd.read_csv(r"C:\Users\zoesh\Downloads\CatPlotCompare.csv")

print(dataframe.head())

print(dataframe.isnull().values.any())

isolation = dataframe["isolation"]

mainhouse = dataframe['mainhouse']

classroom = dataframe['classroom']

community = dataframe['community']

g = sns.catplot(data=dataframe,jitter=0, marker="o")

plt.ylabel("Airborne Concentration of SARS-CoV-2 (RNA copies/m³)")

#make the y axis log scale

plt.yscale('log')

#plt.xlabel ("xlabel", fontsize=8)

#g.fig.get_axes()[0].set_yscale('log')

plt.savefig("catplot4", dpi=2000)

#fig.get_axes()[0].set_yscale('log')


r/pythonhelp • • Apr 25 '23

INACTIVE Comma vs Plus Sign (Beginner Querstion)

2 Upvotes

Is there any difference, since the output is the same?

name = input("What's your name? ")

print("Your name is"+ name)

age = input("What's your age? ")

print("You are " + name +" and your age is " + age +"." )

address = input("Where do you live? ")

print("Hello," + name + "! Your age is " + age +" and you live in " + address + "." )

name = input("What's your name? ")

print("Your name is", name)

age = input("What's your age? ")

print("You are ", name ," and your age is " , age ,"." )

address = input("Where do you live? ")

print("Hello," , name , "! Your age is ", age," and you live in ", address ,"." )

PS: the same code with f strings... I know the code above could be shorter, but I'm curious about the difference between a comma and plus sign in that context.

name = input("What's your name? ")

print(f"Your name is {name}")

age = input("What's your age? ")

print(f"You are {name} and your age is {age}.")

address = input("Where do you live? ")

print(f"Hello, {name}! Your age is {age} and you live in {address}." )


r/pythonhelp • • Mar 17 '23

SOLVED How to do multiprocessing in python where I have a return value from the process?

2 Upvotes

Hi All, I have a function that runs some algorithm and return me a np array of values. For that I need it provide it the starting and ending values so the function looks like.

def f(x,y):
    ## Do something else that return a np list
    return [x,y,0,0,0,0]

How do I do multiprocessing in this case? as I have list of X and Y values? I have tried the below. but it does not work.

from multiprocessing import Pool

list = [5,2,3]
values = []

with Pool(5) as p:
    for i in range(len(list)-1):
        vals = p.map(f,(list[i],list[i+1]))
        values.append(vals) # Note I want to still get this values in order
    print(values)

I want it to return [[5,2,0,0,0,0][2,3,0,0,0,0]] but it gives me a error. Any help is appreciated


r/pythonhelp • • Mar 16 '23

How do I get it to find and recognise text files

2 Upvotes

For context I am using repl.it with files build into the repl
I have a system to create a txt file with the user's name and I want to have it so that if a user re-enters the name of an existing 'account' it'll ask for a password. at the moment it will always skip that and go straight to creating an account. any ideas why?

import os
a = 0
name = input("enter your username ")
search = name + ".txt"
for files in os.walk("users"):
  if (search in "users"):
    a = 1
    enteredpass = input("password for " + name + " ")
if a != 1:
  print("I don't recognise you, lets make an account")

lets say for example i have a file on my repl in the directory 'users' called 'mlem.txt', so 'users/mlem.txt' and the user puts in the name 'mlem', 'a' should become 1 and the password part should kick in but instead its printing "I don't recognise you, lets make an account"


r/pythonhelp • • Jan 09 '23

Running Python reliably on a Windows computer without installing Python

2 Upvotes

This is probably going to sound a little convoluted, but this might be a solution to a problem I'm encountering with Python software I'm creating and distributing at work...

I'm wondering...instead of creating an executable or installing Python using its normal installer file, I thought maybe I could manually copy over the Python interpreter and associated files, including the Lib and the Scripts folder. The interpreter and associated files will already be configured properly (e.g., any needed libraries will already be installed).

On this computer, I want to create a batch file for the user to run my code. (It'd just point to the Python interpreter and to the Python code I've written.)

I tested this and it seems to work...I know this probably sounds like a needlessly complicated process, but it may be simpler than my alternatives.

Is this likely to work reliably, or are there problems I'm going to encounter here that I haven't thought of?

Thanks!


r/pythonhelp • • Jan 09 '23

tf2 key buying bot

2 Upvotes

Ok so I have been working on a bot that uses the steams api to buy keys but honestly am so lost right now, what is wrong with my code? https://pastebin.com/5bEE95FV


r/pythonhelp • • Dec 26 '22

Setting one array equal to another causes them to mirror each other, why?

2 Upvotes

I simply don't understand what's going on here. I have the following code that produces the following result:

list = [1, 2, 3]
print("list:", list)
newList = list
print("newList:", newList)
newList.append(1000)
print("Appended newList:", newList)
print("list:", list)

Result:

list: [1, 2, 3]
newList: [1, 2, 3]
Appended newList: [1, 2, 3, 1000]
list: [1, 2, 3, 1000]

Why in the world does list get appended when I append newList? The same doesn't happen for variables so I can't seem to understand why it would happen for arrays.


r/pythonhelp • • Dec 23 '22

if else in one line syntax

2 Upvotes

My question is how exacly is the syntax on something like:

color = ("white" if val == "1" elif val == "2" "black")

Basically this, but in one line:

if val == "1":

color = "white"

elif val == "2":

color = "black"

Thanks in advance


r/pythonhelp • • Dec 15 '22

Installing Numpy

2 Upvotes

Just wondering, what's the easiest and simplest way to install Numpy?


r/pythonhelp • • Dec 07 '22

trying to get value from a dict with integer key

2 Upvotes

I am working with a dict which is structured like this inside a function:

listOfInformation = [{123456789: {'PokemonId': '123456789', 'PokemonName': 'Pikachu', 'PokemonAttack': 'thunderbolt'}}]

In that function, I'm passing an integer as an argument (pokemon_id) and then trying to test if the key-value pair exists like this:

listOfInformation[pokemon_id]

But I am getting an error of IndexError, list index out of range. I can't figure out why would I get this error. how can I fix this?


r/pythonhelp • • Nov 23 '22

Calculating R squared of a poly function

2 Upvotes
def polynom(x, p):
    r = np.array(x)
    s = np.array(x)
    for i in range(1, p):
        r = r*s
        jepps = np.column_stack((x, r))
    return jepps

def lollispoly(x,y, plot=False, vif = False):
    x = polynom(x, p)
    b_hatt = np.array(inv(x.T@x)@x.T@y)
    
    hattematrise = x@inv(x.T@x)@x.T
    y_hatt = hattematrise@y
    
    TSS = np.sum((y - np.mean(y))**2)
    ESS = np.sum((y_hatt - np.mean(y))**2)
    RSS = (TSS - ESS)
    
    R2 = ESS/TSS
    
    R2_tilpasset = 1-((RSS/x-p-1))/(TSS/(x-1))
    print(R2_tilpasset)

So I am trying to calculate the r squared of the poly function which is the first function (polynom). My error is that p is not defined, but I am not sure where to put it in, and everywhere I try gives me new errors. And I feel like my code is kinda unneccesary, is it also possible to short it down?All help is appreciated

Regards


r/pythonhelp • • Sep 22 '22

Lists and Indexes

2 Upvotes

So i have been trying to make a program in which the user inputs the amount of elements that they will include in a list. After that they start to input numbers to fill the list. I want to print the list elements separated in each line with their index, like for example.

user input:

>>> 5
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5

output:

list[0] = 1
list[1] = 2
list[2] = 3
list[3] = 4
list[4] = 5

I have not been able to achieve this since apparently I cant print two different things in the same print, i have used sep= '\n' to separate list elements but i cant add their index. Help would be appreciated. Thanks!