r/pythonhelp • • Dec 07 '21

HOMEWORK I have an assignment due and no idea what to do.

0 Upvotes
  1. Greek mathematicians took a special interest in numbers that are equal to the sum of their proper divisors (a proper divisor of n is any divisor less than n itself). They called such numbers perfect numbers. For example, 6 is a perfect number because it is the sum of 1, 2, and 3, which are the integers less than 6 that divide evenly into 6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14. Write a function sum divisors that takes an integer n and returns the sum of all the proper divisors of that number (here you will want to use the remainder operator, %). Use this function in writing a program to check for perfect numbers in the range 1 to 9999 by testing each number in turn. When a perfect number is found, your program should display it on the screen. The first two lines of output should be 6 and 28. Your program should find two other perfect numbers in the range as well.

  2. Write a program that asks the user to enter either a binary or octal string of numbers. Then convert this string to the corresponding decimal value. You should include two functions binary to decimal and octal to decimal which perform these conversions. Additionally, this program should include a menu interface similar to that of Area options.py from Homework 5. You should ask the user what type they are converting from (i.e. binary or octal) accounting for input errors on their part, and continue running the program until the user indicates they want to quit. A few things to remember for this: • The computer will be reading in numbers from the user as if they were decimal values by default, so if the user enters (101)2 this will be stored as (101)10 when in actuality this is the decimal number 5. So we have to take this into account when converting. • One trick for isolating place values from right to left is by taking remainder after division by 10 (since the computer is treating these as decimal values). For example, in the binary to decimal function 101%10 would give 1 as a remainder which is the first place value. • We can move to future place values by subtracting the first place value away, then dividing by 10. For example, 101 − 1 = 100 then dividing by 10 we get 100/10 = 10. So we can then repeat the above process again: the remainder from division by 10 will now be 0, 10 − 0 = 10 then 10/10 = 1 and now we have isolated each place value one at a time. • All that is left is to figure out what to do with each place value, and then try implementing a similar process for the octal to decimal function. • You may also want to remember the difference between the / and // operators in python


r/pythonhelp • • Jan 06 '22

Flask : Iterate through the templates folder and assign route to each one of them automatically

0 Upvotes

-1

I am making a link shortener and I write a html file to the templates folder and I have to route to the file automaticly, Here's what I have tried.

The Code

from flask import Flask from flask import render_template import random import string import glob, os  app = Flask(__name__)   def create_link(page):     linkparam = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8))     print(f"Creating link on https://l-nqs.herokuapp.com/{linkparam}")     f = open(f'C:/Users/xpyth/OneDrive/Documents/GitHub/l-nqs/templates/{linkparam}.html', 'x')     with open(f'C:/Users/xpyth/OneDrive/Documents/GitHub/l-nqs/templates/{linkparam}.html', 'w+') as linkhtml :         markup = f''' <!DOCTYPE html> <html>     <head>         <title>Redirecting...</title>     </head>     <body>         <script>             window.location.replace("https://{page}");         </script>         </body> </html> '''         linkhtml.write(markup)      @app.route(f'/{linkparam}') def linkshortened():         return render_template(f'{linkparam}.html')   os.chdir("C:/Users/xpyth/OneDrive/Documents/GitHub/l-nqs/templates") file = glob.glob("*.html") fileWithoutExtention = [item.replace(".html", "") for item in file] print(file) print(fileWithoutExtention) for i in range(len(file) - 1) :     print(f'/{fileWithoutExtention[i]}')     @app.route(f'/{fileWithoutExtention[i]}') def linkshortenedp():         return render_template(f'{file[i]}')  @app.route('/') def default_route():     return render_template('index.html')  @app.errorhandler(404) def not_found(e):     return render_template('404.html'), 404 @app.route('/create') def create():     create_link("www.google.com")     return render_template('about.html')  @app.route('/join') def join():     return render_template('join.html')  if __name__ == '__main__':     app.run() 

The error I am getting in python upon running my script:

C:\Users\xpyth\OneDrive\Documents\GitHub\l-nqs\venv\Scripts\python.exe C:/Users/xpyth/OneDrive/Documents/GitHub/l-nqs/app.py Traceback (most recent call last):   File "C:\Users\xpyth\OneDrive\Documents\GitHub\l-nqs\app.py", line 43, in <module>     def linkshortenedp():   File "C:\Users\xpyth\OneDrive\Documents\GitHub\l-nqs\venv\lib\site-packages\flask\scaffold.py", line 439, in decorator     self.add_url_rule(rule, endpoint, f, **options)   File "C:\Users\xpyth\OneDrive\Documents\GitHub\l-nqs\venv\lib\site-packages\flask\scaffold.py", line 57, in wrapper_func     return f(self, *args, **kwargs)   File "C:\Users\xpyth\OneDrive\Documents\GitHub\l-nqs\venv\lib\site-packages\flask\app.py", line 1090, in add_url_rule     raise AssertionError( AssertionError: View function mapping is overwriting an existing endpoint function: linkshortenedp ['404.html', 'about.html', 'index.html', 'join.html', 'layout.html', 'Z5NKFQJ3.html'] ['404', 'about', 'index', 'join', 'layout', 'Z5NKFQJ3'] /404 /about  Process finished with exit code 1

r/pythonhelp • • Dec 20 '21

HOMEWORK Can somebody run this code on python mu?

0 Upvotes

from turtle import *

setup(800, 500)

speed(0)

# Sky

bgcolor("lightskyblue")

# Water

penup()

goto(-400, -150)

pendown()

color("mediumblue")

begin_fill()

for i in range(2):

forward(800)

right(90)

forward(100)

right(90)

end_fill()

# Boat

penup()

goto(-200, -80)

pendown()

color("saddlebrown")

begin_fill()

right(45)

forward(100)

left(45)

forward(250)

left(45)

forward(100)

end_fill()

# Mast

penup()

goto(0, -80)

pendown()

color("black")

begin_fill()

left(45)

for i in range(2):

forward(200)

left(90)

forward(10)

left(90)

end_fill()


r/pythonhelp • • Nov 22 '21

root=Tk() not workig for tkinter.....!

0 Upvotes

please help me:

code:

from tkinter import *
root =Tk()
l=Label(root,text="hehehehe")
l.pack()
root.mainloop()


r/pythonhelp • • Nov 25 '21

INACTIVE A Problem in Python (3.7.4) with the phrase 'Bool'

0 Upvotes

I was trying to follow along to a ping pong python video (on version 3.7.4) using its built in software: Turtle but when ive followed along to a certain step, the code starts to bug out? The highlighted in bold part is where it started to give me errors, here is the code:

import turtle

wn = turtle.Screen()

wn.title("PythonPingPong")

wn.bgcolor("white")

wn.setup(width=800, height=600)

wn.bgcolor("black")

#Paddle 1

Paddle = turtle.Turtle()

Paddle.speed(0)

Paddle.shape("square")

Paddle.color("white")

Paddle.shapesize(stretch_wid=5, stretch_len=1)

Paddle.penup()

Paddle.goto(-350, 0)

#Paddle 2

Paddle1 = turtle.Turtle()

Paddle1.speed(0)

Paddle1.shape("square")

Paddle1.color("white")

Paddle1.shapesize(stretch_wid=5, stretch_len=1)

Paddle1.penup()

Paddle1.goto(350, 0)

#Ball

Ball = turtle.Turtle()

Ball.speed(0)

Ball.shape("circle")

Ball.color("white")

Ball.shapesize(stretch_wid=1, stretch_len=1)

Ball.penup()

Ball.goto(0, 0)

Ball.dx = 2

Ball.dy = 2

#functions

def Paddle__up():

y = Paddle.ycor()

y += 20

Paddle.sety(y)

def Paddle__down():

y = Paddle.ycor()

y -= 20

Paddle.sety(y)

#functions B

def Paddle1__up():

y = Paddle1.ycor()

y += 20

Paddle1.sety(y)

def Paddle1__down():

y = Paddle1.ycor()

y -= 20

Paddle1.sety(y)

#Keyboard Binding / keybinds

wn.listen()

wn.onkeypress(Paddle__up, "w")

wn.listen()

wn.onkeypress(Paddle__down, "s")

#Keyboard Binding / keybinds B

wn.listen()

wn.onkeypress(Paddle1__up, "Up")

wn.listen()

wn.onkeypress(Paddle1__down, "Down")

#Main game loop

while True():

wn.update()

#move ball uwu

Ball.setx(Ball.xcor() + Ball.dx)

Ball.sety(Ball.ycor() + Ball.dy)

When using the code it gives me the error:

line 78, in <module>

while True():

TypeError: 'bool' object is not callable

Anyhelp with this and maybe a updated piece of code for it to work would be greatly appreciated and much help! Thanks.I was trying to follow along to a ping pong python video (on version 3.7.4) using its built in software: Turtle but when ive followed along to a certain step, the code starts to bug out? The highlighted in bold part is where it started to give me errors, here is the code:

import turtle

wn = turtle.Screen()

wn.title("PythonPingPong")

wn.bgcolor("white")

wn.setup(width=800, height=600)

wn.bgcolor("black")

#Paddle 1

Paddle = turtle.Turtle()

Paddle.speed(0)

Paddle.shape("square")

Paddle.color("white")

Paddle.shapesize(stretch_wid=5, stretch_len=1)

Paddle.penup()

Paddle.goto(-350, 0)

#Paddle 2

Paddle1 = turtle.Turtle()

Paddle1.speed(0)

Paddle1.shape("square")

Paddle1.color("white")

Paddle1.shapesize(stretch_wid=5, stretch_len=1)

Paddle1.penup()

Paddle1.goto(350, 0)

#Ball

Ball = turtle.Turtle()

Ball.speed(0)

Ball.shape("circle")

Ball.color("white")

Ball.shapesize(stretch_wid=1, stretch_len=1)

Ball.penup()

Ball.goto(0, 0)

Ball.dx = 2

Ball.dy = 2

#functions

def Paddle__up():

y = Paddle.ycor()

y += 20

Paddle.sety(y)

def Paddle__down():

y = Paddle.ycor()

y -= 20

Paddle.sety(y)

#functions B

def Paddle1__up():

y = Paddle1.ycor()

y += 20

Paddle1.sety(y)

def Paddle1__down():

y = Paddle1.ycor()

y -= 20

Paddle1.sety(y)

#Keyboard Binding / keybinds

wn.listen()

wn.onkeypress(Paddle__up, "w")

wn.listen()

wn.onkeypress(Paddle__down, "s")

#Keyboard Binding / keybinds B

wn.listen()

wn.onkeypress(Paddle1__up, "Up")

wn.listen()

wn.onkeypress(Paddle1__down, "Down")

#Main game loop

while True():

wn.update()

#move ball uwu

Ball.setx(Ball.xcor() + Ball.dx)

Ball.sety(Ball.ycor() + Ball.dy)

When using the code it gives me the error:

line 78, in <module>

while True():

TypeError: 'bool' object is not callable

Anyhelp with this and maybe a updated piece of code for it to work would be greatly appreciated and much help! Thanks.


r/pythonhelp • • Dec 10 '21

Could someone explain what this code does

0 Upvotes

(I know that it is a multiplication table I just want an explanation for each code line for an assignment)

startingFactor1Str = input("What is the starting factor1 number? ")
endingFactor1Str = input("What is the ending factor1 number? ")
factor2MaxNumberStr = input(" How far do you want each product to go up for factor2 ? ")
startingFactor1Int = int(startingFactor1Str)
endingFactor1Int = int(endingFactor1Str)
factor2MaxNumberInt = int(factor2MaxNumberStr)
for inputValueXInt in range(startingFactor1Int, endingFactor1Int+1, 1):
for outputValueYInt in range(1, factor2MaxNumberInt+1, 1):
product = inputValueXInt* outputValueYInt
print( str(inputValueXInt) + "*" + str(outputValueYInt) + "=" + str(product))


r/pythonhelp • • Nov 19 '21

HOMEWORK How to get the next line a character says in a film script after putting his first line in a list.

0 Upvotes

I have a homework assignment where I I need to get a certain characters lines from a script. I have gotten my code to recognize when its a certain character which is good and get the line he says after the ':' that I also used in a split function. for example.

Michael: hello world I am Michael
how is everyone today?

police: stop right there
you are under arrest.

I got my code to know when its michael talking and I got it to get the line 'hello world I am michael'
but I dont know how to get the other part where it says how is everyone today?

so far my code looks like this.

def words(person,filelist)

list =[]

for line in filelist:
if line[0] == person+':':
list.append(line[1:])
elif line[0] == '(':
continue

the elif part is to skip sound that is in the script like (wind blows), and it would just skip that extra stuff so it only looks at he person : and what they say.


r/pythonhelp • • Aug 01 '22

HOMEWORK How to find the duplicate letter Distance of an String

0 Upvotes

I need to find the Duplicate Letter distance of a string . I need All the letter distances of the word. please Help me.😊

Question In detail

https://i.ibb.co/bdr0yv4/New-Project-1.png


r/pythonhelp • • Jul 20 '22

i want to code a picture into python, so it will return the picture to me

0 Upvotes

my sister sent me pictures on whatsapp. i want to to code them into python, so it will return all the pictures to me in a random order, so i can send it back to my sister on whatsapp.

i guess you can download the picture and get access to them from your computer. however, i want the program to be able to interact with the pictures also in a device that dont have those pictures downloaded. how can i do that?

thanks for the helpers


r/pythonhelp • • Jul 20 '22

HOMEWORK Incoporating len(df) value into group by()

0 Upvotes

Task 5b: Calculate percentage of people with work experience that are offered a job, the percentage of people with work experience not offered a job, the people with no work experience offered a job and the percentage of people with no work experience not offered a job.

len(df.index)
print(df.index)

output

 RangeIndex(start=0, stop=120, step=1) 

Tried to put the value of 120 into groupby but failed

df_workexp = (df.groupby('index')['status']
            .value_counts(normalize=True)
            .reset_index(name='perc'))
print (df_workexp)

r/pythonhelp • • Jul 24 '22

How to make your own programming language in python?

0 Upvotes

How make your own programming language in python?

Thank you


r/pythonhelp • • Aug 22 '19

Help with inventory for a text based RPG. I don’t know how to have multiple of the same item in the same space. If I wanted to have 2 gold coins it would display as..Gold Coin, Gold Coin. I want it to display it as Gold Coin x 2

Post image
0 Upvotes

r/pythonhelp • • Jan 04 '19

Python Regex GitLab Repo URL Matching

0 Upvotes

Hey all. I'm having an issue with my regular expression in Python and was hoping somebody could help. This is what I have so far:

git_url = re.compile(r'([\w+@\:/\-~]+\.git)')

This returns both:

https://gitlab.aa.bb.cc.dd/username/repo-name.git    # repo names could included - or _
[email protected]/username/repo-name.git

I basically want the possibility of either, so I can select using a script. To give some context, this Python script uses the GitLab API and clones all repositories based on the username specified. The second part of the script reads:

[..]
for url in re.findall(git_url, group_attr):    # group_attr is a list of group attributes
    subprocess.call(['git', 'clone', url])

Any help is much appreciated :-)


r/pythonhelp • • Jun 08 '18

Got some Problems with the whole global/local Variable thing

0 Upvotes

Well thats my code fullvar is not defined thing what did i wrong?

NameError: name 'fullvar' is not defined the short version with the problem:

fullvar = 1
def togglefull():
   global fullvar
      if (fullvar==1):
         fullvar = 0
   else:
      fullvar = 1

the long version with the problem:

class Page_Options(tk.Frame):
   def __init__(self, parent, controller):
      fullvar = 1
      tk.Frame.__init__(self, parent)
      self.controller = controller
      button = tk.Button(self, text='back', command=lambda : \
                       controller.show_frame('Page_MainMenu'))
      button.pack()
      def togglefull():
         global fullvar
         if (fullvar==1):
            controller.overrideredirect(True)
            controller.geometry('{0}x{1}+0+0'.format(controller.winfo_screenwidth(),
                        controller.winfo_screenheight()))
            controller.focus_set()
            fullvar = 0
        else:
            controller.overrideredirect(False)
            controller.geometry('{0}x{1}+0+0'.format(500,
                        500))
            controller.focus_set()
            fullvar = 1

    button2 = tk.Button(self, text='Toggle Fullscreen', command=togglefull)
    button2.pack()


    label = tk.Label(self, text='Das hier sind die Optionen')
    label.pack()

r/pythonhelp • • Jan 27 '21

SOLVED Very strange issues using the subprocess module

0 Upvotes

Edit for anyone looking for a solution:

I was running a 32-bit version of Python, so the file system redirector intercepted the path and changed it to C:/Windows/SysWOW64/ which does not have ssh.exe.


I'll try to keep this concise. I'm working on using the subprocess module to send shell commands from Python, specifically, "ssh". Below is a barebones sample:

import subprocess

sp = subprocess.run(["ssh"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"stdout: {sp.stdout.decode()} \n\nstderr: {sp.stderr.decode()}")

This should return the ssh command help from stdout, and nothing from stderr. However, I get

stdout:  

stderr: 'ssh' is not recognized as an internal or external command,
operable program or batch file.

I've tried other commands, like echo and cd, and those work fine. I am also able to use ssh when manually typing the command into the shell, but it fails when I try to do it through subprocess. The directory C:\Windows\System32\OpenSSH does exist on my computer (and it contains ssh.exe), but for some strange reason I'm unable to cd to it using subprocess.

If it matters, subprocess is using the command prompt, cmd.exe, as it seems to be the default.

Any help is appreciated. Thanks!


r/pythonhelp • • Feb 14 '18

Python assignment help

0 Upvotes

"Write a function that takes a tree and a function and maps each element of the tree to the passed in function"

Given the functions: label which returns tree[0]

branches which returns tree[1:]

is_tree checks if is tree

is _leaf checks if is leaf

and tree constructor

tree(label,branches=[]):

    for branch in branches:

	      assert(is_tree(branch))

    return [label] + list(branches)

r/pythonhelp • • Apr 25 '17

Pandas: Need help with appending or concatenating a dataframe or column to an existing dataframe

0 Upvotes

Good day,

I put dataframe or column, due to the fact that I want the best strategy. I'm not going to write the details again, as I posted this on stackoverflow already. Here is the link. http://stackoverflow.com/questions/43617288/pandas-appending-dataframe-via-for-loop-to-existing-dataframe

Hope someone can help. Thanks


r/pythonhelp • • Sep 15 '20

Please help I'm a beginner.

Post image
0 Upvotes

r/pythonhelp • • Sep 20 '20

I need help to find an answer about this, I've made a program to record myslef then play it, but I've realised the record part without problem, then when I call the function ecouteRec then I've got an error

0 Upvotes

The program :

import pygame #écoute de fichier audio

import tkinter as tk # visuel
from PIL import Image, ImageTk 

import sounddevice as sd # enregistrement de sons
from scipy.io.wavfile import write # enregistrement du fichier son

# fonction d'enregistrement
def recAudio():

    fs = 44100 # sample rate
    time1 = zoneSaisieTime.get()
    bad, court = True, True
    while bad and court:
        if time1 == "":
            warning("put a time sup to 10s")
        else:
            bad = False
        time2 = int(time1)
        
        if time2 < 10:
            warning("time to short put more than 10s")
        else:
            court = False

    seconds = 3 + time2 # duree d'enregistrement + 3 sec de préparation
    print (seconds, "time1:", time1, "time2:", time2)
    myRec = sd.rec( (seconds*fs) , samplerate=fs, channels=2)
    sd.wait()   # attente du fin d'enregistrement
    write("rec.mp3", 12, myRec) # sauvegarde du fichier
    

def ecouteRec():
    filename = "rec.mp3"
    print(filename)
    pygame.mixer_music.load(filename)
    pygame.mixer_music.play()

The error :


r/pythonhelp • • Jun 02 '20

Help to Compile Python to JAR

0 Upvotes

I have a python 3 code which my manager wants to convert to a JAR file.

I saw Jython but I am unable to find something to compile to jar.

the main point is the code is to shipped to the client and we do not want the client to see the code.


r/pythonhelp • • Feb 19 '22

Python project of grade

0 Upvotes

It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. The input will always be at least 2 characters.

def remove_char(s):

What do I have to do in this problem? Please I really need it.


r/pythonhelp • • Feb 09 '22

I'm having trouble scraping from a website using Python and Flask:

0 Upvotes

r/pythonhelp • • Feb 11 '22

Searching a code to acces blocked sites at school pls

0 Upvotes

Pls help, i have created a website in python for access blocked site but i don't know how to do it.

Can someone help sending a github link or a code?


r/pythonhelp • • Feb 02 '22

HOMEWORK Hey! Does anyone know how to solve this python problem?

0 Upvotes

Hi, can anyone help me with solving this problem:

Snail - a wall climber 

A snail climbs on a wall, it starts at the bottom and climbs up n meters a day. Regretfully, every night it slides m meters down. Given the height of the wall, H write a program to calculate how many days required for the snail to reach the top of the wall. 

Input: 3 non-negative integers n,m H separated by a space e.g 3 2 11 

Output: a single integer number, which is the number of days required for the snail to reach the top of the wall. E.g 9 

If the snail will never be able to reach the top of the wall print FAIL