Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Some Python Feedback plz


Demons Halo's Avatar
Member
0 0

Hi again guys :P

I'd like to see some feedback/tips about how I can improve my python programing, so I thought maybe the best way to do this is by posting a couple of projects I've been working on.

Project 1: PQ formula Calculator, ax^2+bx+c=0 using the PQ formula to solve x. any ideas about how I can improve this program? maybe add something or alter something to have a shorter code?

#Simple PQ Calculator
from math import sqrt

print 'This program use the PQ formula to solve the following equation: ax^2+bx+c=0'
print 'All you have to do is tell the program the values of a,b,and c.'
print

def pq(a,b,c):
    b=b/a
    c=c/a
    print               
    if ((b/2)**2-c)>0:
        print 'x1= ',(-b/2)+sqrt((b/2)**2-c),'  x2= ',(-b/2)-sqrt((b/2)**2-c)
        #This happens if everything is OK!
        return 'Problem Solved!'
    else:
        return 'Cant give you an answer :/'
        #This happens when ((b/2)**2-c) <= 0.
        
#Enter a,b and c
a=float(input('Insert The Value of a: '))
b=float(input('Insert The Value of b: '))
c=float(input('Insert The Value of c: '))

#Call the function pq
print pq(a,b,c)

Project 2: This one is not finished yet, I have a small problem which I need help with :(

"You just wrote a loop allowing the input of 10 names into a list. Alas, you made an error as you entered name number 8. Redesign your input loop, so you can correct the error easily without having to retype the previous 7 names."

#loop corrector
#This is a program that saves and edit info inside of a list.
listan={} #The List
for i in range(1,10):
    name=raw_input('Insert a name:  ')
    listan[i]=name
    print i,name
    print listan
    print

while 1: #Correction loop
    print
    print 'If you want to exit, type exit.'
    corrector=input('Enter the number of the string you want to correct: ')
    if corrector=='exit':
        break
    elif listan.has_key(corrector):
        listan[corrector]=raw_input('Insert the new name: ')
        print
        print corrector,name
        print listan
    else:
        print 'Unknown command. Please try again'

This problem with this function is that I use "corrector=input('..')". When using input() you get an error when entering the word exit, and using the raw_input() function results wrong key:value in the dictionary so that the loop jumps to 'Unknown command. Please try again'.

how can i fix this??

some help/feedback would be highly appreciated :)

//D.H.


ynori7's Avatar
Future Emperor of Earth
0 0

For project one, instead of returning 'Cant give you an answer :/' if the value inside the square root is negative, you could have it give the answer in terms of complex numbers (i.e. "i").

And for project 2, you're welcome:

#This is a program that saves and edit info inside of a list.
listan={} #The List
for i in range(1,10):
    name=raw_input('Insert a name:  ')
    listan[i]=name
    print i,name
    print listan
    print

loop=1
while loop==1: #Correction loop
    print 'If you want to exit, type exit.'
    corrector=raw_input('Enter the number of the string you want to correct: ')
    if corrector=='exit':
        loop=0
    elif listan.has_key(int(corrector)):
        listan[int(corrector)]=raw_input('Insert the new name: ')
        print
        print corrector,name
        print listan
    else:
        print 'Unknown command. Please try again'```

EDIT: typo

Demons Halo's Avatar
Member
0 0

thnx for the fast answer :)

@ project 1 I've not studied "higher" math :P the PQ formula is like the high-end of my mathematical knowledge xD

@ project 2 Wow! so it was that simple! Let me see if I understand that one correctly: you had the corrector function inside of an int so that the only way that one gets executed is if the corrector value is an integral. cool!

thanks a lot :D


ynori7's Avatar
Future Emperor of Earth
0 0

**Demons Halo wrote:**thnx for the fast answer :) No problem.

@ project 1 I've not studied "higher" math :P the PQ formula is like the high-end of my mathematical knowledge xD I must be getting old. Back when I learned it, it was called the quadratic formula. I've never heard the term PQ before.

@ project 2 Wow! so it was that simple! Let me see if I understand that one correctly: you had the corrector function inside of an int so that the only way that one gets executed is if the corrector value is an integral. cool! No, what the int() method does is pretty much the same as your use of the float() method in your other problem. It typecasts corrector to an integer because raw_input() takes the input as a string. The keys for your array (you're using an array, not a list) are integers. '3' is not equal to 3.

A few more corrections on your terminology just for your own knowledge: corrector is a 'variable', not a 'function'. int converts to an 'integer', not an 'integral'. Integral is something very different.


Demons Halo's Avatar
Member
0 0

No, what the int() method does is pretty much the same as your use of the float() method in your other problem. It typecasts corrector to an integer because raw_input() takes the input as a string. The keys for your array (you're using an array, not a list) are integers. '3' is not equal to 3.

A few more corrections on your terminology just for your own knowledge: corrector is a 'variable', not a 'function'. int converts to an 'integer', not an 'integral'. Integral is something very different.

my way of expressing myself sucks sometimes, I know… :P haha thanks for the corrections, rereading my last post made me feel so stupid considering the terms I use :$ I've heard the word integral, so i though that's what int is haha :P

well now that you have explained it, it seems like I have the same problem with another project, at least now I know the solution :)

thanks a lot dude! I really appreciate it

//D.H.


Demons Halo's Avatar
Member
0 0

instead of creating a new topic I'll just post here :P

import random

numlist=['1','2','3','4','5','6','7','8','9','0']
charlist=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
numcharlist=['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

def shuffler():
    random.shuffle(numlist)
    random.shuffle(charlist)
    random.shuffle(numcharlist)
        
while 1:
    passtype=int(input("""1)Only numbers
2)Only letters
3)Characters + letters
4)Exit
What do you want the password to consist of? Enter a number: """))
    if passtype==1:
        length=input('How long should the password be? ')
        shuffler()
        print numlist[:length]
        break
    elif passtype==2:
        length=input('How long should the password be? ')
        shuffler()
        print charlist[:length]
        break
    elif passtype==3:
        length=input('How long should the password be? ')
        shuffler()
        print numcharlist[:length]
        break
    elif passtype==4:
        print 'Bye Bye!'
        break
    else:
        print 'Please enter a number 1-4:'
        print

This is a random password generator, created so that the user can choose the length and the type of the password (num, char or num-char).

when you run the program and choose the type and the length the program shows the following:

1)Only numbers
2)Only letters
3)Characters + letters
4)Exit
What do you want the password to consist of? Enter a number: 3
How long should the password be? 5
['l', 'n', 'F', 'I', 'v']

How can I get rid of the [],'' characters? I want the password to be shown as a word, not as individual characters. and also, any feedback on the main code? it sure seems a bit too long for a password generator, can I change something to make it shorter?

Thnx in advance

//D.H.


ynori7's Avatar
Future Emperor of Earth
0 0

numlist=['1','2','3','4','5','6','7','8','9','0']
charlist=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
numcharlist=numlist+charlist
def shuffler():
    random.shuffle(numlist)
    random.shuffle(charlist)
    random.shuffle(numcharlist)
        
while 1:
    passtype=int(input("""1)Only numbers
2)Only letters
3)Characters + letters
4)Exit
What do you want the password to consist of? Enter a number: """))
    out=""
    if passtype==1:
        length=input('How long should the password be? ')
        shuffler()
        print out.join(numlist[:length])
        break
    elif passtype==2:
        length=input('How long should the password be? ')
        shuffler()
        print out.join(charlist[:length])
        break
    elif passtype==3:
        length=input('How long should the password be? ')
        shuffler()
        print out.join(numcharlist[:length])
        break
    elif passtype==4:
        print 'Bye Bye!'
        break
    else:
        print 'Please enter a number 1-4:'
        print```

That fixes your problem. There's not really much you can do to make it shorter. It's not a very long program.

EDIT:formatting

ghost's Avatar
0 0

Slap me if im wrong, but you could have used a switch: case here could you? Much nicer than nested elseif statements.


ynori7's Avatar
Future Emperor of Earth
0 0

jjbutler88 wrote: Slap me if im wrong, but you could have used a switch: case here could you? Much nicer than nested elseif statements. Python doesn't have a built in switch-case. The alternative would be longer than what's already there.


Demons Halo's Avatar
Member
0 0

thnx a lot :D

I might need help with a couple more minor syntax stuff later on, I hope you don't mind if I post them here or pm you :)

//D.H.


ghost's Avatar
0 0

I dont want to start a new thread but i was wondering if someone could help me with me python script for timed 5. I know it works it prints out the right numbers and isdoing it in time but for some reason it says it's wrong. I was wondering if someone who knows python could help me out on this.


Demons Halo's Avatar
Member
0 0

post your code here if it's ok with you, I might be able to check it out and learn something from it, and maybe help you out in case I can :D


ghost's Avatar
0 0

Demons Halo wrote: post your code here if it's ok with you, I might be able to check it out and learn something from it, and maybe help you out in case I can :D Code for timed 5, no posting publicly, no spoilers.


ynori7's Avatar
Future Emperor of Earth
0 0

@fallingmidget - Go on AIM and I can take a look at it.


Demons Halo's Avatar
Member
0 0

my understanding of python have surely become a lot better, but my understanding of how to work the math still suck :P

I'm pretty close to the answer but I don't want to keep trying until I find the answer, instead I want to create a program that does that for me. here is the problem:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

I can immidietly say that the answer has the following characteristics:

  • ends with a zero (dividable by 10)
  • must be a multiplayer of 19 (19*a=the answer)
  • must be a multiplayer of 18 (18*x=the answer) –> divided by 18 is the same as 9,6,3
  • must be a multiplayer of 14 (14*y=the answer) –> divided by 14 is the same as 7
  • must be a multiplayer of 11 (11*b=the answer) etc.etc.

What's the best way to tackle this problem?

x=5040 #a good place to start
while 1:
    print x
    for i in range(1,21):
        if x%i==0:
            print i,'nice'
        else:
            print i,'lol try'
    print
    print
    x=x+720 #720 is a number dividable with: 18->(9,6,3), 16->(12,8,4,2), 10->(15,5). The number is however not dividable with: 11,13,14(7),17,19

Should I create a loop that keeps adding +720 / loop until if founds the number that is dividable with all values 1-20, or is there a better mathematical way of doing this?

I thought about putting all the values (1-20) in a list and use x%list, but that seems impossible since the % statement does not take in lists :/

any ideas? :P

cheers

//D.H.


ynori7's Avatar
Future Emperor of Earth
0 0

You could do it that way, but the answer is a very large number, so it wouldn't be very efficient. You should look up LCM (least common multiple) and prime factorization: http://en.wikipedia.org/wiki/Least_common_multiple#Finding_least_common_multiples_by_prime_factorization

And just because I'm bored, here you go: (2^25), 19, (3^22) , 17, 2^4, (72), 13, (2^23), 11, (25), 3^2, 2^3, 7, (23), 5, 2^2, 3, 2, 1

Which results in: 19 * 3^2 * 17 * 2^4 * 7 * 13 * 11 * 5 = 232,792,560

So if you really want to make a good program to find that answer, make a function that can find the prime factorization of a number.


Demons Halo's Avatar
Member
0 0

I see. I do hate math sometimes, and the more programming you learn the more math there is involved -_-

I created a prime calc, works nice :D

thnx a lot once again :)

//D.H.


Demons Halo's Avatar
Member
0 0

Edit: I've made a decent prime calc, but the problem now is that this calc is damn SLOW!

from math import sqrt
from time import time

def primes(n):
    s=time()
    x=input('Which prime number do you want? Ex. the forth prime is number 7. ')
    dictio={1:2}
    
    min_loop=2                      
    max_loop=x+1

    while min_loop<max_loop:
        n+=2
        i=3
        while 1:           
            if n%i==0 and n==i:     
                dictio[min_loop]=i        
                min_loop+=1
                break
            elif n%i==0:
                break
            else:
                i+=1
                
    print time()-s
    print 'The',x,'prime has the value:'
    return i


print primes(1)                     

it takes ~75sec to get the 10001 prime. I'm trying to replace the while 1: with while i<=sqrt(n)+1 but the program keeps on not giving any response. It seems like I get stuck in a loop as soon as I insert the sqrt function into this code. what should I do? :P

cheers

//D.H.


Demons Halo's Avatar
Member
0 0

Thnx a lot :) that code helped me out :D

Now when I started this whole programming thing it was pretty easy since all you needed to do was to think logically, describe your way of thinking with python and making the PC calculate the results. But now it feels like I've reached the level where I need to go in deeper to gain some more programming experience.

The mathematical problems I'm working on right now (like the sum of all the primes below two million) requires a bit more "outside the box thinking". earlier i would have done some easy programming but this unfortunately does not work anymore now that the takes are a lot more advance!

So I was thinking of asking you guys for some tips about how to create faster programs. the codes I write takes ages cause they use simple mathematical way of thinking. How do you guys do/think before start coding a program?

What methods are the best when working with large numbers? for instance I've tried few methods for finding prime numbers:

  • Storng ex. 2 000 000 numbers in a list, and then % all the values in the list with i in range (2,200 000)
  • Starting with number 3 and increasing the number with +2 for each loop, dividing it by all the numbers from 2 to 2000 000
  • etc.

such methods are really basic and takes ages for the program to work out :(

I know you guys have uploaded some great codes, but I don't want to steal your codes :P I want to learn how to create my own codes that runs faster than the methods mentioned above!

I'd really appreciate it in case you guys could give me some tips!!

thnx once again for your time

//D.H.


ghost's Avatar
0 0

If you have several large numbers, try generating them on the spot, rather than storing them. This takes huge amounts of memory.

for your second question, you can use the extra bit of the range function, so:

range(min,max,step)

If you want every number from 3 to 20000 adding 2 each time, use:

for i in range(3,20000,2)

Hope this helps


Demons Halo's Avatar
Member
0 0

awesome!

Thnx a lot for the tips. That step thing is pretty cool making everything run twice as fast :D


Demons Halo's Avatar
Member
0 0

hmm Now that I've got most of my mathematical programs to work a lot faster (thnx to the tips from gothicbob, jjbutler88 and ynori7), I decided to learn a bit about file I/O. Problem 8 @ Project Euler seems to be a good place to start!

http://projecteuler.net/index.php?section=problems&id=8

fil=open(&#39;P8.txt&#39;, &#39;r&#39;)
lines=str(fil.read())

for x in lines:
    if x.find(&#39;731&#39;)==True:
        print &#39;lal :D&#39;
        break
    else:
        print &#39;lol :/&#39;
        break    

This is just a test code for the .find method which I can't seem to get right :/ My syntax is somehow wrong…

if line.find('731')==True

This one should be modified somehow. The ==True part should be replaced with some other syntax if I'm not mistaken.

any ideas?

thnx :)

//D.H.


ynori7's Avatar
Future Emperor of Earth
0 0

Demons Halo wrote: if line.find('731')==True

The find method returns an index value, not a boolean. If the search string is not found, it returns "-1". markupif line.find(&#39;731&#39;)&gt;=0:


Demons Halo's Avatar
Member
0 0

ynori7 wrote: The find method returns an index value, not a boolean. If the search string is not found, it returns "-1". markupif line.find(&#39;731&#39;)&gt;=0:

works perfect, thnx :D


Demons Halo's Avatar
Member
0 0

aiight. This will be my first program ever. This is not a challenge or an equation. My friend who's working as a mod on a game site, they do usually check for ip matches to find cheaters, he asked me in case I could make a short program that can check the file of PLAYER1 and file of PLAYER2 for ip and time matches.

this is how a file looks like: 1. ip.xx.xx.xx 2009-04-06 23:47:00

Player1 file:

  1.  xx.xx.xx.xx 	2009-04-06 23:47:00 
    
  2.  xx.xx.xx.xx 	2009-04-06 20:01:00 
    
  3.  xx.xx.xx.xx 	2009-04-05 21:15:00 
    
  4.  xx.xx.xx.xx 	2009-04-04 15:37:00 
    

player 2:

  1.  xx.xx.xx.xx 	2009-04-18 23:31:00 
    
  2.  xx.xx.xx.xx 	2009-04-18 23:15:00 
    
  3.  xx.xx.xx.xx 	2009-04-18 20:55:00 
    
  4.  xx.xx.xx.xx 	2009-04-18 17:54:00 
    
  5.  xx.xx.xx.xx 	2009-04-18 16:49:00 
    

Now the program menu will have 2 options: 1- Check for date and time matches irrespective of IP for 15 mins range of time between Player1 and Player2. 2- Check for IP matches irrespective of time and date for Player1 and Player2

If the program find any matches it should print them out. That's all

This is easy to do if not for the date matching thing. What syntax should I use to compare the date and time in 2 different files?

You don't have to write any codes, just mention the syntax you see fit this project the best and I'll do the googling :P

thnx

//D.H.


ynori7's Avatar
Future Emperor of Earth
0 0

Demons Halo wrote: This is easy to do if not for the date matching thing. What syntax should I use to compare the date and time in 2 different files?

Well, if all it is is just a date written in the file, you just parse it and check that the years match, then month, then day, then hour, and then just subtract the minutes of one from the other to check whether it's within 15 minutes (i.e. if absolute value of min1-min2<=15).


Demons Halo's Avatar
Member
0 0

ynori7 wrote: Well, if all it is is just a date written in the file, you just parse it and check that the years match, then month, then day, then hour, and then just subtract the minutes of one from the other to check whether it's within 15 minutes (i.e. if absolute value of min1-min2<=15).

That was my plan B :P I just though that maybe there is a simpler way of doing it. I'm almost done with the second menu choice. If only there was a built in command for comparing dates :P well.. I guess I'll have to make one myself xD


Demons Halo's Avatar
Member
0 0

hmm my idea was to have the ip as a key and the date + time as the value of the key, and then compare values in the dictionary. If the date is the same, the program should check the time for matches within a cap of +- 15 mins.

what I've realized is that using a dictionary makes it just 10 times harder than it should be. I'm almost certain there there is a better method for prasing an input string than using a dictionary. I'm going to test assigning a piece of a string to a variable and then comparing variables from 2 different files, but this might not even work :/

any ideas??


ynori7's Avatar
Future Emperor of Earth
0 0
&gt;&gt;&gt; t1=datetime.datetime(2007, 3, 3, 22, 20, 11, 443849)
&gt;&gt;&gt; t2=datetime.datetime(2007, 3, 3, 22, 20, 30, 443849)
&gt;&gt;&gt; abs(t2-t1)
datetime.timedelta(0, 19)
&gt;&gt;&gt; abs(t1-t2)
datetime.timedelta(0, 19)
&gt;&gt;&gt; limit=datetime.timedelta(0, 15)
&gt;&gt;&gt; abs(t2-t1)&gt;limit
True```
You should be able to figure it out from there.

Demons Halo's Avatar
Member
0 0

awesome module I must say :D

thnx and cheers!


Demons Halo's Avatar
Member
0 0

I'm stuck again :P

let's say that I have a list full of numbers. [0,1,5,6,12,65,66,67,68,123,445,…]

What syntax can I use to get the first 4 consecutive integers? (65,66,67,68)


clone4's Avatar
Perl-6 Wisdom Seeker
0 0

ynori7 wrote: Try something like this:

i=0
while i&lt;len(array):
    for j in range(i, i+4):
        if (array[j]+1)==array[j+1]:
            continue
        else:
            break
    if j==i+3:
        print str(i)+&quot;:&quot;+str(j)
        break
    else:
        i+=j```
But seriously, by now you should be able to do this yourself. This isn&#39;t that complicated. You can&#39;t keep asking for help otherwise you&#39;ll never learn. This is the last time I help you unless you have a good question.
    


nice, but remember to put functions before the loop into a variable, so it gets evaluated only once, and not multiple times. Also dont solve whole problem for the guy, this isn&#39;t that hard to code

ynori7's Avatar
Future Emperor of Earth
0 0

Demons Halo wrote: haha that Is not what I had in mind. I'm tired of using the same syntax over and over again in every program I create, so I thopugh maybe I should get into some advance syntax this time. Creating loops that checks arrays is basic syntax, I'm trying to get into some more "serious" programing, Like the date/time module. What makes you think that using built-in modules like date/time is more "serious"? Anyone can use a predefined function; it doesn't take any special skills, just a simple google search. And I hate to break it to you, but if you don't like making loops then programming is not for you.

clone4 wrote: remember to put functions before the loop into a variable, so it gets evaluated only once Yeah, I know. I wrote it fast and didn't bother with finer details.


Demons Halo's Avatar
Member
0 0

ynori7 wrote: [quote]Demons Halo wrote: haha that Is not what I had in mind. I'm tired of using the same syntax over and over again in every program I create, so I thopugh maybe I should get into some advance syntax this time. Creating loops that checks arrays is basic syntax, I'm trying to get into some more "serious" programing, Like the date/time module.

What makes you think that using built-in modules like date/time is more "serious"? Anyone can use a predefined function; it doesn't take any special skills, just a simple google search. And I hate to break it to you, but if you don't like making loops then programming is not for you. [/quote]

I'm just trying to practice the syntax so that I can have a wider understanding of the language! Don't get me wrong, I like creating loops etc. I just want to get more serious and I don't really know where to begin. I'm trying with project Euler, but the problems there are mathematical, so you end up using the same syntax almost all the time with different mathematical equations :/ (a bit of variation can't hurt you :P)


ynori7's Avatar
Future Emperor of Earth
0 0

Try the timed challenges, or come up with an idea for a program that will make your life easier. Look up modules as you need them. They're merely useful tools that somebody created, they are not part of the language.


clone4's Avatar
Perl-6 Wisdom Seeker
0 0

Demons Halo wrote: I'm just trying to practice the syntax so that I can have a wider understanding of the language! Don't get me wrong, I like creating loops etc. I just want to get more serious and I don't really know where to begin. I'm trying with project Euler, but the problems there are mathematical, so you end up using the same syntax almost all the time with different mathematical equations :/ (a bit of variation can't hurt you :P)

You are repeating 'syntax' all the time, but python's got probably the easiest (understandable to be more exact) syntax amongst high level languages, so there isn't that much to practice(dont want to sound like it's really easy to learn python though). If you want wider understanding of the language, good idea is first to set the aim, is it gonna be sockets, string manipulation or something else. Then take that aboard and start doing some projects, research modules and built in functions, read a quality code, and then write a backdoor, your own encryption algo, or web bruteforcer, the possibilities are endless…


Demons Halo's Avatar
Member
0 0

clone4 wrote: You are repeating 'syntax' all the time, but python's got probably the easiest (understandable to be more exact) syntax amongst high level languages, so there isn't that much to practice(dont want to sound like it's really easy to learn python though). If you want wider understanding of the language, good idea is first to set the aim, is it gonna be sockets, string manipulation or something else. Then take that aboard and start doing some projects, research modules and built in functions, read a quality code, and then write a backdoor, your own encryption algo, or web bruteforcer, the possibilities are endless…

That's why I love python, the short and easy syntax. Ideas like backdorrs/web bruteforcer are the type of things I'm looking for :D Awesome advice thnx.

@ynori7 well I find it easy to work with python, all I need is a couple of creative ideas to work on that's all. I've been doing timed challenges and Project Euler for a long time now, so I got kind a bored. That's why I went looking for ways to shrink my codes in order to make them shorter & faster using module syntax :P