number to cardinal python euler - python

I am doing euler problems to practice python, I can't seem to get the right answer for problem 17. The problem is to find the number of letters in all numbers 1-1000 without spaces or hyphens.
Any comment would be useful.
Python code:
def numberToString(number):
""" Writes a cardinal number to a string. """
numberString=""
c = str(number)
l = len(c)
while l>0:
if l == 1: #unit digit
if int(c[-1]) == 1:
numberString += 'one'
elif int(c[-1]) == 2:
numberString += 'two'
elif int(c[-1]) == 3:
numberString += 'three'
elif int(c[-1]) == 4:
numberString += 'four'
elif int(c[-1]) == 5:
numberString += 'five'
elif int(c[-1]) == 6:
numberString += 'six'
elif int(c[-1]) == 7:
numberString += 'seven'
elif int(c[-1]) == 8:
numberString += 'eight'
elif int(c[-1]) == 9:
numberString += 'nine'
l = l-1
elif l == 2 and int(c[-2])==1 and int(c[-1]) != 0: #teens
if int(c[-1]) == 1:
numberString += 'eleven'
elif int(c[-1]) == 2:
numberString += 'twelve'
elif int(c[-1]) == 3:
numberString += 'thirteen'
elif int(c[-1]) == 4:
numberString += 'fourteen'
elif int(c[-1]) == 5:
numberString += 'fifteen'
elif int(c[-1]) == 6:
numberString += 'sixteen'
elif int(c[-1]) == 7:
numberString += 'seventeen'
elif int(c[-1]) == 8:
numberString += 'eighteen'
elif int(c[-1]) == 9:
numberString += 'nineteen'
l = l-2
elif l == 2: #tens
if int(c[-2]) == 1:
numberString += 'ten'
elif int(c[-2]) == 2:
numberString += 'twenty'
elif int(c[-2]) == 3:
numberString += 'thirty'
elif int(c[-2]) == 4:
numberString += 'fourty'
elif int(c[-2]) == 5:
numberString += 'fifty'
elif int(c[-2]) == 6:
numberString += 'sixty'
elif int(c[-2]) == 7:
numberString += 'seventy'
elif int(c[-2]) == 8:
numberString += 'eighty'
elif int(c[-2]) == 9:
numberString += 'ninety'
if int(c[-1]) != 0 and int(c[-2]) > 1:
numberString += '-'
l = l-1
elif l == 3: #hundreds
if int(c[-3]) == 1:
numberString += 'one'
elif int(c[-3]) == 2:
numberString += 'two'
elif int(c[-3]) == 3:
numberString += 'three'
elif int(c[-3]) == 4:
numberString += 'four'
elif int(c[-3]) == 5:
numberString += 'five'
elif int(c[-3]) == 6:
numberString += 'six'
elif int(c[-3]) == 7:
numberString += 'seven'
elif int(c[-3]) == 8:
numberString += 'eight'
elif int(c[-3]) == 9:
numberString += 'nine'
if int(c[-3]) != 0:
numberString += ' hundred'
if int(c[-1])+int(c[-2]) != 0:
numberString += ' and '
l = l-1
elif l == 4: #thousands
if int(c[-4]) == 1:
numberString += 'one'
elif int(c[-4]) == 2:
numberString += 'two'
elif int(c[-4]) == 3:
numberString += 'three'
elif int(c[-4]) == 4:
numberString += 'four'
elif int(c[-4]) == 5:
numberString += 'five'
elif int(c[-4]) == 6:
numberString += 'six'
elif int(c[-4]) == 7:
numberString += 'seven'
elif int(c[-4]) == 8:
numberString += 'eight'
elif int(c[-4]) == 9:
numberString += 'nine'
if int(c[-4]) != 0:
numberString += ' thousand'
if int(c[-3]) != 0:
numberString += ' '
l = l-1
return numberString
def NumbersInString(min, max):
""" Writes all cardinal numbers on a seperate line on a string, from min to max. """
allNumberString=""
for i in range (min,max+1):
allNumberString += numberToString(i)
allNumberString += '\n'
return allNumberString
def stringNumberCount(numberString):
""" Returns the ammount of letters without spaces, hyphens or newlines. """
numberString=numberString.replace(' ', '')
numberString=numberString.replace('-', '')
numberString=numberString.replace('\n', '')
return len(numberString)
def run(filename, min=1, max=1000):
s=NumbersInString(min, max)
string='Number of letters without spaces or hyphens: '+str(stringNumberCount(s))+'\n'+'List of cardinal numbers:\n'
string += s
f=open(filename, 'w')
f.write(string)
f.close
run('output.txt')

first you change fourty to forty (as written in problem statement)
and second
in elif l==3: block
why r you writing if int(c[-3]!=0):
since we have already covered those cases just before (i mean c[-3]==1,2,3... are not equal to zero )
correct me if i'm wrong and try to put some comment in your code.
http://ideone.com/egeX0k
def countLetter(n):
p=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
q=['','Ten','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']
r=['','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']
c=str(n)
l=len(c)
a=""
if l==1:
a+=p[int(c[0])]
elif l==2:
if c[1]=='0':
a+=q[int(c[0])]
elif c[0]=='1':
a+=r[int(c[1])]
else:
a+=q[int(c[0])]+p[int(c[1])]
elif n==100:
a+="OneHundred"
elif l==3:
a+=p[int(c[0])]+"Hundred"
if c[1]=='0' and c[2]=='0':
a+=""
elif c[2]=='0' and c[1]!='0':
a+="And"+q[int(c[1])]
elif c[1]=='1':
a+="And"+r[int(c[2])]
else:
a+="And"+q[int(c[1])]+p[int(c[2])]
else:
a+="OneThousand"
#print a,len(a)
return len(a)
def main():
sum=0
for i in range(1,1001):
sum+=countLetter(i)
print sum
main()

Related

how do i break this python loop in a efficent manner after ive entered a valid number

while True:
month_num = int(input("enter the month number: "))
if month_num == 1:
print("january")
elif month_num == 2:
print("February")
elif month_num == 3:
print("March")
elif month_num == 4:
print("April")
elif month_num == 5:
print("May")
elif month_num == 6:
print("June")
elif month_num == 7:
print ("July")
elif month_num == 8:
print ("August")
elif month_num == 9:
print ("September")
elif month_num == 10:
print ("October")
elif month_num == 11:
print ("November")
elif month_num == 12:
print ("December")
else:
print("Enter a valid number")
i want to end the code cleanly but dont know to go about doind it i just stared it but i want to do it so that if i do put in the vlaues from 1 to 12 it would break after but i dont know how to do it efficently
import calendar
while True:
try:
month_num = int(input("enter the month number: "))
if 0 < month_num < 13:
print(calendar.month_name[month_num])
break
except ValueError:
pass

How do i make my code better python (tic tac toe) [duplicate]

This question already has an answer here:
Pygame Tic Tak Toe Logic? How Would I Do It
(1 answer)
Closed 1 year ago.
I've tried to make a tic tac toe game in Python. From what I make I feel that my code is working however it is really bad. Is there anyway to improve from this code?
class Board():
def __init__(self):
self.board = ["[]","[]","[]","[]","[]","[]","[]","[]","[]"]
def createboard(self):
board = ["[]","[]","[]","[]","[]","[]","[]","[]","[]"]
print(self.board[0],self.board[1],self.board[2])
print(self.board[3],self.board[4],self.board[5])
print(self.board[6],self.board[7],self.board[8])
def checkwin(self):
if self.board[0]=="[O]" and self.board[1]=="[O]" and self.board[2]=="[O]":
print("O Wins!")
#break
elif self.board[3]=="[O]"and self.board[4]=="[O]"and self.board[5]=="[O]":
print("O Wins!")
# break
elif self.board[6]=="[O]"and self.board[7]=="[O]"and self.board[8]=="[O]":
print("O Wins!")
# break
elif self.board[0]=="[O]"and self.board[3]=="[O]"and self.board[6]=="[O]":
print("O Wins!")
# break
elif self.board[1]=="[O]"and self.board[4]=="[O]"and self.board[7]=="[O]":
print("O Wins!")
# break
elif self.board[2]=="[O]"and self.board[5]=="[O]"and self.board[8]=="[O]":
print("O Wins!")
# break
elif self.board[0]=="[O]"and self.board[4]=="[O]"and self.board[8]=="[O]":
print("O Wins!")
# break
elif self.board[2]=="[O]"and self.board[4]=="[O]"and self.board[6]=="[O]":
print("O Wins!")
# break
elif self.board[0]=="[X]"and self.board[1]=="[X]"and self.board[2]=="[X]":
print("X Wins!")
# break
elif self.board[3]=="[X]"and self.board[4]=="[X]"and self.board[5]=="[X]":
print("X Wins!")
# break
elif self.board[6]=="[X]"and self.board[7]=="[X]"and self.board[8]=="[X]":
print("X Wins!")
# break
elif self.board[0]=="[X]"and self.board[3]=="[X]"and self.board[6]=="[X]":
print("X Wins!")
# break
elif self.board[1]=="[X]"and self.board[4]=="[X]"and self.board[7]=="[X]":
print("X Wins!")
# break
elif self.board[2]=="[X]"and self.board[5]=="[X]"and self.board[8]=="[X]":
print("X Wins!")
# break
elif self.board[0]=="[X]"and self.board[4]=="[X]"and self.board[8]=="[X]":
print("X Wins!")
# break
elif self.board[2]=="[X]"and self.board[4]=="[X]"and self.board[6]=="[X]":
print("O Wins!")
# break
def omove(self):
o = int(input("Its 'O's'move please insert 1-9"))
if o == 1:
self.board[0] = "[O]"
self.createboard()
elif o == 2:
self.board[1] = "[O]"
self.createboard()
elif o == 3:
self.board[2] = "[O]"
self.createboard()
elif o == 4:
self.board[3] = "[O]"
self.createboard()
elif o == 5:
self.board[4] = "[O]"
self.createboard()
elif o == 6:
self.board[5] = "[O]"
self.createboard()
elif o == 7:
self.board[6] = "[O]"
self.createboard()
elif o == 8:
self.board[7] = "[O]"
self.createboard()
elif o == 9:
self.board[8] = "[O]"
self.createboard()
else:
print('that column is out of range')
o = int(input("please insert 1-9"))
def xmove(self):
x = int(input("Its 'x's'move please insert 1-9"))
if x == 1:
self.board[0] = "[X]"
self.createboard()
elif x == 2:
self.board[1] = "[X]"
self.createboard()
elif x == 3:
self.board[2] = "[X]"
self.createboard()
elif x == 4:
self.board[3] = "[X]"
self.createboard()
elif x == 5:
self.board[4] = "[X]"
self.createboard()
elif x == 6:
self.board[5] = "[X]"
self.createboard()
elif x == 7:
self.board[6] = "[X]"
self.createboard()
elif x == 8:
self.board[7] = "[X]"
self.createboard()
elif x == 9:
self.board[8] = "[X]"
self.createboard()
else:
print('that column is out of range')
o = int(input("please insert 1-9"))
a = Board()
a.createboard()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
I would love any kind of feedback to improve my skills in programming. What I thought about this is I think I used too much if condition maybe it can be swapped by another simple method and how can I even break when the game is finished ex: if X wins the game, the game is then closed
A big change would be to refactor the move functions to pass in the token you need and avoid the elifs with maths.
def move(self, token):
o = int(input(f"Its '{token}'s'move please insert 1-9"))
while not (0 < o <= 9):
print('that column is out of range')
o = int(input("please insert 1-9"))
self.board[o-1] = f"[{token}]"
self.createboard()
used via...
move("O")
move("X")
self.board = 9*['[]']
def createboard(self):
for i,j in enumerate(board, 1):
print(j)
if i%3 == 0: print('\n')
Have a look at python tutorial: https://docs.python.org/3/tutorial/

Python print day name of week from number

I'm creating a program which I have to put a number and when I run the program, the solution should be the day for that number. But I don't know how to do. The program I did was this:
num = 4
if(num = 1)
print('Monday')
elif(num = 2)
print('Tuesday')
elif(num = 3)
print('Wednesday')
elif(num = 4)
print('Thursday')
elif(num = 5)
print('Friday')
elif(num = 6)
print('Sunday')
elif(num = 7)
print('Saturday')
elif(num < 1)
print('Put a number between 1 and 7')
else(num > 7)
print('Put a number between 1 and 7')
In python, for statements like if, for, etc. You have to add : at the end of it.
And for comparing (for equal) you have to use == and not =
num = 4
if(num == 1):
print('Monday')
elif num == 2:
print('Tuesday')
.....
You can compare without parenthesis and it will work too.
num = 0
while num <= 7:
num += 1
if num == 1:
print('Monday')
elif num == 2:
print('Tuesday')
elif num == 3:
print('Wednesday')
elif num == 4:
print('Thursday')
elif num == 5:
print('Friday')
elif num == 6:
print('Saturday')
elif num == 7:
print('Sunday')

How do you get a string of characters in one line?

I'm trying to make a random generator of numbers and letters go into one line after being in a string, for example from:
a
b
c
Like so...:
To "abc"
I was wondering if there was any way of doing that. The code I use is:
import random
import time
amount = int(input("How many digits do you want the password to be?\n"))
time.sleep(0.5)
print("============================================================\n")
for count in range(amount):
time.sleep(0.1)
num = random.randint(1,62)
if num == 1:
a = print("1")
if num == 2:
print("2")
if num == 3:
print("3")
if num == 4:
print("4")
if num == 5:
print("5")
if num == 6:
print("6")
if num == 7:
print("7")
if num == 8:
print("8")
if num == 9:
print("9")
if num == 10:
print("a")
if num == 11:
print("b")
if num == 12:
print("c")
if num == 13:
print("d")
if num == 14:
print("e")
if num == 15:
print("f")
if num == 16:
print("g")
if num == 17:
print("h")
if num == 18:
print("i")
if num == 19:
print("j")
if num == 20:
print("k")
if num == 21:
print("l")
if num == 22:
print("m")
if num == 23:
print("n")
if num == 24:
print("o")
if num == 25:
print("p")
if num == 26:
print("q")
if num == 27:
print("r")
if num == 28:
print("s")
if num == 29:
print("t")
if num == 30:
print("u")
if num == 31:
print("v")
if num == 32:
print("w")
if num == 33:
print("x")
if num == 34:
print("y")
if num == 35:
print("z")
if num == 36:
print("A")
if num == 37:
print("B")
if num == 38:
print("C")
if num == 39:
print("D")
if num == 40:
print("E")
if num == 41:
print("F")
if num == 42:
print("G")
if num == 43:
print("H")
if num == 44:
print("I")
if num == 45:
print("J")
if num == 46:
print("K")
if num == 47:
print("L")
if num == 48:
print("M")
if num == 49:
print("N")
if num == 50:
print("O")
if num == 51:
print("P")
if num == 52:
print("Q")
if num == 53:
print("R")
if num == 54:
print("S")
if num == 55:
print("T")
if num == 56:
print("U")
if num == 57:
print("V")
if num == 58:
print("W")
if num == 59:
print("X")
if num == 60:
print("Y")
if num == 61:
print("Z")
This basically creates the string of how many characters you want but I can't get them all on one line.
You can use the string module.
Example Code:
import string
print(string.ascii_letters+string.digits)
You can then get a certain number of random letters and numbers using this code:
import random
import string
number_of_letters_and_digits = 5
print(''.join([random.choice(string.ascii_letters+string.digits) for i in range(number_of_letters_and_digits)]))
Completed Code:
import random
import string
import time
amount = int(input("How many digits do you want the password to be?\n"))
time.sleep(0.5)
print("============================================================\n")
print(''.join([random.choice(string.ascii_letters+string.digits) for i in range(amount)]))
If you need to use the code that you showed, you could append the letters to the string (replace print("letter") with listName.append("letter")). Then, after the for loop, you could run print(''.join(listName)).

Getting wrong result when adding random values in string format

I'm trying to make a script that receives a number of desired random numbers as input, and then generates and prints them.
However, my script adds the numbers instead of joining the strings. I would like for the strings to join so it would generate the pins like:
Enter the amount of lunch pins to generate:
10
26141
128111
937502
2436
56516
83623
246317
My code:
import random
PTG = int(input("Enter the amount of pins to generate: \n"))
PG = 0
PS = ""
while PTG > PG:
RN1 = random.randint(0, 9)
RN2 = random.randint(0, 9)
RN3 = random.randint(0, 9)
RN4 = random.randint(0, 9)
RN5 = random.randint(0, 10)
RN6 = random.randint(0, 10)
if RN1 == 0:
PS += "0"
elif RN1 == 1:
PS += "1"
elif RN1 == 2:
PS += "2"
elif RN1 == 3:
PS += "3"
elif RN1 == 4:
PS += "4"
elif RN1 == 5:
PS += "5"
elif RN1 == 6:
PS += "6"
elif RN1 == 7:
PS += "7"
elif RN1 == 8:
PS += "8"
elif RN1 == 9:
PS += "9"
elif RN2 == 0:
PS += "0"
elif RN2 == 1:
PS += "1"
elif RN2 == 2:
PS += "2"
elif RN2 == 3:
PS += "3"
elif RN2 == 4:
PS += "4"
elif RN2 == 5:
PS += "5"
elif RN2 == 6:
PS += "6"
elif RN2 == 7:
PS += "7"
elif RN2 == 8:
PS += "8"
elif RN2 == 9:
PS += "9"
if RN3 == 0:
PS += "0"
elif RN3 == 1:
PS += "1"
elif RN3 == 2:
PS += "2"
elif RN3 == 3:
PS += "3"
elif RN3 == 4:
PS += "4"
elif RN3 == 5:
PS += "5"
elif RN3 == 6:
PS += "6"
elif RN3 == 7:
PS += "7"
elif RN3 == 8:
PS += "8"
elif RN3 == 9:
PS += "9"
elif RN4 == 0:
PS += "0"
elif RN4 == 1:
PS += "1"
elif RN4 == 2:
PS += "2"
elif RN4 == 3:
PS += "3"
elif RN4 == 4:
PS += "4"
elif RN4 == 5:
PS += "5"
elif RN4 == 6:
PS += "6"
elif RN4 == 7:
PS += "7"
elif RN4 == 8:
PS += "8"
elif RN4 == 9:
PS += "9"
elif RN5 == 0:
PS += "0"
elif RN5 == 1:
PS += "1"
elif RN5 == 2:
PS += "2"
elif RN5 == 3:
PS += "3"
elif RN5 == 4:
PS += "4"
elif RN5 == 5:
PS += "5"
elif RN5 == 6:
PS += "6"
elif RN5 == 7:
PS += "7"
elif RN5 == 8:
PS += "8"
elif RN5 == 9:
PS += "9"
elif RN5 == 10:
PS += ""
elif RN6 == 0:
PS += "0"
elif RN6 == 1:
PS += "1"
elif RN6 == 2:
PS += "2"
elif RN6 == 3:
PS += "3"
elif RN6 == 4:
PS += "4"
elif RN6 == 5:
PS += "5"
elif RN6 == 6:
PS += "6"
elif RN6 == 7:
PS += "7"
elif RN6 == 8:
PS += "8"
elif RN6 == 9:
PS += "9"
print(PS)
PG += 1
PS = ""
Python version: 3.7.4
import random
# PTG = int(input("Enter the amount of pins to generate: \n"))
PTG = 10
PG = 0
PS = ""
while PTG > PG:
RN1 = random.randint(0, 9)
RN2 = random.randint(0, 9)
RN3 = random.randint(0, 9)
RN4 = random.randint(0, 9)
RN5 = random.randint(0, 10)
RN6 = random.randint(0, 10)
PS = str(RN1) + str(RN2) + str(RN3) + str(RN4) + str(RN5) + str(RN6)
print(int(PS))
PG += 1
When I understand your code right, you want to generate n pins with 6 digits. You can do that a lot easier than you want to:
number_of_pins = int(input("Enter the amount of pins to generate: \n"))
pins = []
for i in range(number_of_pins):
pins.append(str(random.randint(100_000, 999_999)))
print(" ".join(pins))
Explaination:
pins = [] makes a new empty list to store the pins
for i in range(n): executes the following indented block n times.
pins.append(random.randint(100_000, 999_999)) generates a random number and adds it to the list. 100000 is the first number with 6 digits and 999999 is the last. (The _ is just for readability). str() converts it to a string.
print(" ".join(pins)) joins all the pins and puts a space between.
Let's go through your code step by step:
First, notice that random.randint returns an int. Therefore you need to convert it to a String.
You can use the str() function in order to convert it to a string, for example:
str(random.randint(0, 9))+"9"
will return a string like 59 (for example).
Therefore, when initializing each random number, you need to do it the following way, for example:
RN1 = str(random.randint(0, 9))
Then, instead of checking the value of each random variable, you can just add them up:
PS = RN1 + RN2 + RN3 + RN4 + RN5 + RN6
Furthermore, instead of using six different variables to handle the random values, you can use a for loop for the first four which are from 0 to 9:
for x in range(4):
RN = str(random.randint(0, 9))
PS += RN
And then add the remaining two that are between 0 and 10:
PS += str(random.randint(0, 10))
PS += str(random.randint(0, 10))

Categories