Why is this program not giving the expected output - python-3.x

MY CODE :
n = int(input())
arr = []
for i in range(0,n):
s = input().split()
for i in range(1,len(s)) :
s[i] = int(s[i])
if s[0] == "append" :
arr.append(s[1])
elif s[0] == "insert" :
arr.insert(s[1],s[2])
elif s[0] == "print" :
print(arr)
elif s[0] == "reverse" :
arr.reverse()
elif s[0] == "sort" :
arr.sort()
elif s[0] == "pop" :
arr.pop()
elif s[0] == "remove" :
arr.remove(s[1])
INPUT :
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
EXPECTED OUTPUT :
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
MY OUTPUT :
(No Output)

All of your lines from if s[0] == "append" to the end of the code are indented one level too many, making them part of the loop that converts the parameters to ints. This loop executes zero times for commands with no parameters, so in particular the "print" command does nothing.

Related

Python 3 | How do I check if first 2 digits of a number are 00?

When I input 00999 for example, I still get 'first 2 digits are not zeros' as an output when I should rather get 'first 2 digits are zeros' instead. I can't see the problem with the code.
while True:
x = input(">")
if 3 <= len(x) <= 5 and x[0] == 0 and x[1] == 0:
print("first 2 digits are zeros.")
else:
print("first 2 digits are not zeros.")
while True:
x = str(input(">"))
if 3 <= len(x) <= 5 and x[0] == "0" and x[1] == "0":
print("first 2 digits are zeros.")
else:
print("first 2 digits are not zeros.")
you must check x[0] == "0" because your input is a String.
Ex: You input 1100
-> x = "0011".
-> x[0] == "0",
x[1] == "0",
x[2] == "1",
x[3] == "1"
and a String ("0") is not equal to a number(in this case: 0)

Is there a way i can avoid getting "None" when i print out my function?

I am trying to calculate the avarage grade of a subject. but when i print the function i get printed None.
And i do not know how to fix it.
Ive tried returning the value instead then printing the function, but it wont work.
def karakterKonversjon(bokstav):
if bokstav == 'A':
return 6
if bokstav == 'B':
return 5
if bokstav == 'C':
return 4
if bokstav == 'D':
return 3
if bokstav == 'E':
return 2
if bokstav == 'F':
return 1
def konversjonTilBokstav(tall):
if tall == 6:
return 'A'
if tall == 5:
return 'B'
if tall == 4:
return 'C'
if tall == 3:
return 'D'
if tall == 2:
return 'E'
if tall == 1:
return 'F'
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in emner:
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
THe result i am expecting is
4
C
But i am getting
4
None
I made a few modifications to your code:
(I assume you are importing math in the eksamen file)
def karakterKonversjon(bokstav): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(len(atof)):
if bokstav.upper() == atof[i]:
return len(atof) - i
def konversjonTilBokstav(tall): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(1,7):
if tall == i:
return atof[len(atof)-i]
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in range(len(emner)): # if enmer == "enmer"(for example) you cannot reference enmer['e'] without raising an error
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
apart from the differences i made, your code should work well however i cannot test without knowing what enmer is (i assume it's a string) or what studiepoeng is.
the function konversjonTilBokstav did work fine for me. But what I have included in the code snippet should be less spaghetti code

Tic Tac Toe in python keeps returning int error

I am trying to create a simple tic tac toe game in python. This is my code so far but when i run it it, it asks for a spot to select I enter a number and it displays the board but then it returns this error:
line 32, in
input = int(input("Select a spot: "))
TypeError: 'int' object is not callable
please help how I can resolve this as the user has to select a number. i'm using python 3.
import random
board = [0,1,2,3,4,5,6,7,8]
def show():
print (board[0]," | ", board[1]," | ", board[2])
print ("----------------")
print (board[3]," | ", board[4]," | ", board[5])
print ("----------------")
print (board[6]," | ", board[7]," | ", board[8])
def checkLine(char, spot1, spot2, spot3):
if board[spot1] == char and board[spot2] == char and board[spot3] == char:
return True
def checkAll(char):
if checkLine(char, 0, 1, 2):
True
if checkLine(char, 1, 4, 7):
True
if checkLine(char, 2, 5, 8):
True
if checkLine(char, 6, 7, 8):
True
if checkLine(char, 3, 4, 5):
True
if checkLine(char, 2, 4, 6):
True
if checkLine(char, 0, 4, 6):
True
while True:
input = int(input("Select a spot: "))
if board[input] != 'x' and board[input] != 'o':
board[input] = 'x'
if checkAll('x') == True:
print("-- X WINS --")
break;
random.seed()
opponent = random.randint(0,8)
while True:
if board[opponent] != 'o' and board[opponent] != 'x':
board[opponent] = 'o'
if checkAll('o') == True:
print("-- O WINS --")
break;
break;
else:
print ('This spot is taken')
show()
You assign an integer to input:
input = int(input("Select a spot: "))
Don't do that. Once you use the name input for a different object, the built-in function input will not be available anymore. So in the second loop input is not a function as before but an integer.
Use a different name:
user_input = int(input("Select a spot: "))
The problem is that the first time this line runs you assign an integer value to input and second time you call input("") it gets error because you call an integer! The problem would be solved by changing variable name.
To solve it you can simply change the variable name:
inp = int(input("Select a spot: "))

how to make all the numbers add together till left with 1 digit number (in a list)

the program is suppose to ask for you full name and convert it to numbers then it will keep adding the numbers in the list till it gets a 1 digit number. I have finished the product and works just fine however it cannot add the third or more digits. please help. it says where i need help in the link
name1 = [] #its a list called name
name1 = str(raw_input("Enter your first name and second name ")) #this code asks the user and saves the name as a list
lettervalue =[]
index=0
#
THE CODE THAT CONVERTS THE NAME TO NUMBERS AND PUT IT IN A LIST
for index in range (len(name1)):
if name1 [index] == "a" or name1 [index] == "j" or name1 [index] == "s":
lettervalue.append(1)
elif name1 [index] == "b" or name1 [index] == "k" or name1 [index] == "t":
lettervalue.append(2)
elif name1 [index] == "c" or name1 [index] == "l" or name1 [index] == "u":
lettervalue.append(3)
elif name1 [index] == "d" or name1 [index] == "m" or name1 [index] == "v":
lettervalue.append(4)
elif name1 [index] == "e" or name1 [index] == "n" or name1 [index] == "w":
lettervalue.append(5)
elif name1 [index] == "f" or name1 [index] == "o" or name1 [index] == "x":
lettervalue.append(6)
elif name1 [index] == "g" or name1 [index] == "p" or name1 [index] == "y":
lettervalue.append(7)
elif name1 [index] == "h" or name1 [index] == "q" or name1 [index] == "z":
lettervalue.append(8)
elif name1 [index] == "i" or name1 [index] == "r":
lettervalue.append(9)
elif name1 [index] == " ":
lettervalue.append(0)
index = index + 1
#
print lettervalue #prints the list to reduce confusion
total1 = sum(lettervalue) #sums up the numbers in the list and turns it into a variable
print total1 # also prints the total to reduce confusion
#
A while loop that keeps adding each number until its left with 1 digit number (where i neeed help)
while total1 > 9:
split1 = 0
split2 = 0
total1 = str (total1)
split1 = total1[0]
split2 = total1[1]
total1 = int (split1) + int(split2)
print "your lucky number is " + str(total1)
#
this code makes the final number to its charecteristics and prints it letteing them know their lucky number
if total1 == 1:
print "WOW you are a Natural leader!"
if total1 == 2:
print "WOW you are a Natural peacemaker!"
if total1 == 3:
print "WOW you are Creative and optimistic !"
if total1 == 4:
print "WOW you are a Hard worker!"
if total1 == 5:
print "WOW you Value freedom!"
if total1 == 6:
print "WOW you one of them who cares and provides!"
if total1 == 7:
print "WOW you are a Think!"
if total1 == 8:
print "WOW you have diplomatic skills!"
if total1 == 9:
print "WOW you are selfless and generous!"
The following code addresses the problem with your while loop:
totals = []
total = sum(lettervalue)
while total > 9:
breakdown = list(str(total))
for i in breakdown:
i = int(i)
totals.append(i)
total1 = sum(totals)
This works with the rest of your program. If there any further errors please don't hesitate to let me know with a comment.
EDIT: The for i in breakdown part of the code means for iteration in breakdown.
Breakdown is an array, and so it has values stored in it. The for loop just iterates through all of these values, and does the same process on each of them. So if breakdown contained the values "1, 2, 3, 4", the code would turn that number into an integer, and then append it to the totals array.
Note: This part of the code is necessary because it enables the sum function to work properly. List returns a string, not an integer, thus we need to change all the values into integers
I suggest this. Using a dictionary to map your letters to values you can iterate through the name and get the result quite easily. If a value in a name does not match a value in the dictionary then it will return 0.
I used total % 10 to get total (mod 10) which will always be a single digit. This will also get 0 though if total = 10.
# dictionary of letter values
letter_dict = {'a': 1, 'j': 1, 's': 1,
'b': 2, 'k': 2, 't': 2,
'c': 3, 'l': 3, 'u': 3,
'd': 4, 'm': 4, 'v': 4,
'e': 5, 'n': 5, 'w': 5,
'f': 6, 'o': 6, 'x': 6,
'g': 7, 'p': 7, 'y': 7,
'h': 8, 'q': 8, 'z': 8,
'i': 9, 'r': 9}
# get name
name1 = str(raw_input("Enter your first name and second name "))
# For-loop | get list of values
# Using .get will return the value corresponding to the letter
# If not value matches eg. (' ', !, ' ) then 0 is returned
# .lower is used to include uppercase letters in result
letter_value = []
for s in name1:
letter_value.append(letter_dict.get(s.lower(), 0))
# While loop
total = sum(letter_value)
while total > 9:
total = sum(int(n) for n in str(total))
print "your lucky number is " + str(total)
Using list comprehension is generally a cleaner alternate method of using a for loop to append a value to a list. The for loop above can be replaced with this.
letter_value = [letter_dict.get(s.lower(), 0) for s in name1]

ValueError: invalid literal for int() with base 10: 'x'

when the the last index on string has "x" or "X" (It is represent as 10) so if I have something like "1x", which mean 11 (1 + 10)
def main():
s1 = "013162959x"
partial_sums(s1)
def partial_sums(s1):
lst =[]
sum = 0
for i in range(len(s1)):
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
else:
sum = sum + int(s1[i])
lst.append(sum)
print(lst)
main()
I got an ValueError: invalid literal for int() with base 10: 'x'
the output should be [0, 1, 4, 5, 11, 13, 22, 27, 36, 46]
When the string contain No "X" value it work fine.
def main():
s1 = "0131629592"
partial_sums(s1)
def partial_sums(s1):
lst1 =[]
sum = 0
for i in range(len(s1)):
sum = sum + int(s1[i])
lst1.append(sum)
print(lst1)
main()
How can I fix it?
This statement:
if (i == len(s1) -1) and (s1[i] == "x" or "X"):
sum = sum + int(s1[i]) + 10
still calls int on s1[i] even though s1[i] is "x". You simply want sum += 10.
However, note that or doesn't work the way you're using it. To quote the docs, "The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned." IOW, "a" == "b" or "c" returns "c", not False, and "c" evaluates as True.
Also, since sum is a really useful builtin, it's probably a bad idea to shadow it with a variable of your own with the same name. total is often used instead.

Resources