Given a list, containing N user-provided strings, the task is to print whether each string is a palindrome or not. (PYTHON)
i have this code already. and keeps telling me errors that "Traceback (most recent call last):
File "C:\Users\jpsam\Desktop\fuckmylife.py", line 20, in <module>
palindrome_checker(q)
File "C:\Users\jpsam\Desktop\fuckmylife.py", line 4, in palindrome_checker
while y <len(inputlist()):
TypeError: 'list' object is not callable"
def palindrome_checker(q):
y = 0
while y <len(inputlist()):
if inputlist == inputlist[::-1]:
print(q, " is a panlindrome")
len(inputlist()-1)
else:
print (q, "not a palindrome")
len(inputlist()-1)
return (q)
x = 1
inputlist = []
while x == 1:
q = input("Input string: ")
inputlist.append(q)
x = int(input("Do you want to add more? [1]YES [0]NO ====>"))
palindrome_checker(q)
First, your indentation is incorrect.
Secondly, the statement len(inputlist()-1) is giving the exception because you have followed a list, inputlist, with (), which asks the interpreter to call inputlist as a function. Unfortunately I have no idea what this statement is supposed to achieve (not the other one in the if branch - your code could be refactored too).
A simpler palindrome function might read as follows:
def palindrome(s):
return s == s[::-1]
You might use it as follows:
if palindrome("able I was ere I saw elba"):
print("The phrase is palindromic")
Related
I am coding a simple program to add all positive integers not greater than a given integer n. My code:
print("Enter an integer:")
n=input()
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
#print("1+2+3+...+"+str(n)+"="+str(add(n)))
print(add(100))
The function works.
Why does the line in the one line comment not work, if I remove the hash tag? It should - there is a concatenation of four strings. Thank you.
EDIT: the whole output:
Enter an integer:
12
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "<string>", line 6, in add
TypeError: can only concatenate str (not "int") to str
>
input() returns a string. You are passing n=input() which is a string so it is not working as expected.
change it to n=int(input())
Also sum is a reserved keyword and it will be best to change that to a different name
input returns a string, so add(n) will look something like add("1234"). Then, range(k+1) inside the function will be range("1234" + 1), but "1234" + 1 is an error since it's not possible to add a string and a number.
The problem exists in your input, it's current data type is str, and must be converted into int.
Also, it's best if you use .format() when printing strings.
print("Enter an integer:")
n = int(input())
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
print("1 + 2 + 3 + ... + {} = {}".format(n, add(n)))
I have to create a function that creates a list with items given by the user and it stops creating a list when a space is given. It must then remove duplicates from this list. I cannot use the built in function set(). This is what I have but when a space is given a TypeError occurs.
def assignment():
x = input('Type anything')
random_list = []
while x != '':
x = input("Type anything")
random_list.append(x)
print(random_list)
x=x+1
for i in random_list:
if i not in random_list:
random_list.append(i)
assignment()
The error is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in assignment
TypeError: can only concatenate str (not "int") to str
The input function returns a string, so your variable x becomes a string when it's assigned with the returning value of input, and trying to add an integer to a string with x+1 produces the TypeError exception.
For your purpose you don't actually need to increment x at all. Remove x=x+1, and avoid appending x to random_list with a break when x is empty. Use another condition with the in operator to avoid adding duplicates:
while True:
x = input("Type anything")
if x == '':
break
if x not in random_list:
random_list.append(x)
I think the statememt x=x+1 is useless and buggy. :/
I rearranged your code to this one:
def assignment():
random_list = []
final_list = []
while True:
x = input("Type anything")
if x!='':
random_list.append(x)
else:
break
for i in random_list:
if i not in final_list:
final_list.append(i)
return final_list
assignment()
How about (tested under python 2.7 and 3.6.6)
import sys
if sys.version_info >= (3, 0):
input_func = input
else:
input_func = raw_input
user_data = []
while True:
item = input_func('Type input please:')
if item == ' ':
break
if item not in user_data:
user_data.add(item)
print(user_data)
I've been trying to write a program which finds the roots of an inputted mathematical function. I've only just started, so what I show here is only the start, and there are unused variables.
Here I wrote a function which is supposed to replace the term 'x' in a function with a value you input, say, 100. Here is the code:
code = list(input("Enter mathematical function: "))
lowBound = int(input("Enter lower bound: "))
upBound = int(input("Enter upper bound: "))
def plugin(myList, value):
for i in range(len(myList)):
if myList[i] == 'x':
myList[i] = value #replaces x with the inputted value
return ''.join(myList) #supposed to turn the list of characters back into a string
print(plugin(code,upBound))
But when I run the program, I get the error:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 9, in plugin
TypeError: sequence item 0: expected str instance, int found
(I'm using an online programming platform, so the file is just called 'python')
This doesn't make any sense to me. myList should not be an int, and even if it was the right data type (str), it should be a list. Can someone explain what's going on here?
You are replacing a str type (or character) with an int type.
Try this instead:
myList[i] = str(value)
You can only join an iterable of strings
return ''.join(str(x) for x in myList)
Or, more succinctly. Remove the function
print(''.join(str(upBound if x =='x' else x) for x in code)
import json
sentence = input("Please input a sentence: ")
splitsentence = sentence.split()
score = [0]
print(sentence)
for count, i in enumerate(splitsentence):
if splitsentence.count(i) < 2:
score.append(max(score)+1)
else:
score.append(splitsentence.index(i) +1)
score.remove(0)
print(splitsentence)
print(score)
numberandwordarrays = [score,splitsentence]
numberandword = open("numberandword.txt" , "w")
json.dump(numberandwordarrays, numberandword)
numberandword.close()
menu = input("Decompress? Y/N: ")
if menu.lower() == "y":
joinwords = open("numberandword.txt", "r")
recreate = json.load(joinwords)
jointwords = recreate[1]
positions = recreate[0]
print(" ".join(map(jointwords.__getitem__, map(int, positions))))
else:
print ("Thanks for using my program, have a good day!")
Hi, i am currently doing GCSE computing and this is my code for a453 Task 3. i am trying to split a sentence then save it as well as showing the position of each word. At the end I need an option to reconstruct the sentence from the file. When i run my code everything works fine until i get to the reconstructing part where either it recreates the sentence in a very jumbled order or it displays this syntax error:
Traceback (most recent call last):
File "D:\Computing\a453\Task 3.py", line 28, in <module>
print(" ".join(map(jointwords.__getitem__, map(int, positions))))
IndexError: list index out of range
does anyone know what ive done wrong and how i can fix it?
At least on of the indexes extracted from the positions list (or iterable) is out of range in the jointwords list.
Add a breakpoint on this line and debug.
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers's answer in stackoverflow but couldn't make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
In your function, you can directly convert num into a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:
In [1]: num = '1'
In [2]: num.split(',')
Out[2]: ['1']
In [3]: num = '1,2,3,4'
In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']
You can then use your function as you have it:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
number = map(int,num)
return number
x = inputnumber()
print x
However you can take it a step further if you want - map here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number and return the result of the comprehension (same would work for map as well, if you want to keep that):
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num]
x = inputnumber()
print x
If you want to handle other types of input without error, you can use a try/except block (and handle the ValueError exception), or use one of the fun methods on strings to check if the number is a digit:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num if n.isdigit()]
x = inputnumber()
print x
This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit() part).
And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):
print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:
def inputnumber():
num = raw_input()
for i, j in enumerate(num):
if j not in ', ':
try:
int(num[i])
except ValueError:
#error handling goes here
return num
def main():
x = inputnumber()
print x
I guess all it is is a long-winded version of RocketDonkey's answer.