This is my code:
lowMess=input('A\n')
if 'dice(' in lowMess:
diceLen = len(lowMess)
dice = []
for x in range (5,diceLen):
if x.isnumeric():
dice.append(x)
print(dice)
Your x is an integer (taken from range(5, diceLen)) and has nothing to do with the input, other than that it could be used as an index in the input string. So you would want to make that access in the input string:
digit = lowMess[x]
Then continue with the check. As noted in comments, for checking whether a character is a digit, isnumeric is not the right tool. Use isdecimal:
if digit.isdecimal():
...and convert to integer:
dice.append(int(digit))
All this can be done with list comprehension:
dice = [int(digit) for digit in lowMess if digit.isdecimal()]
Related
I wanted to write a rarther simple cipher program that can convert numbers to letters. So the user provides numbers as input and it gets decoded by the program and that's how you would read the secret message. The problem is that to be able to iterate through numbers i need variable type string and to (add 95 because of ascii codes) i need type int.
i have tried to take input as a string, i have tried converting it to int. I have even tried to convert it in the for loop to an int but i still get an error either that it has to be string or that this variable needs to an int.
a = int(input("Enter a number: "))
for numbers in a:
number = chr(numbers) + 95
print (number)
Your problem seems to be that you need to convert back and forth between different data types: strings, list of strings, and list of integers.
Your question might not be super helpful to others, but I hope this answer will help you at least :) I broke my answer from the comment into shorter steps. Each step has an example of what type of data you are dealing with at the end.
# Read a string like "8 5 12 12 15"
encoded = input("Enter some numbers, separated by spaces: ")
# Turn the string into a list of shorter strings.
# For example: ["8", "5", "12", "12", "15"]
# you should handle input errors here, too
encoded_list = encoded.split(' ')
# Conver the list of strings to a list of integers
# For example: [8, 5, 12, 12, 15]
encoded_numbers = [int(character) for character in encoded_list]
# Decode the numbers and turn them back into strings using chr()
# For example: ["h", "e", "l", "l", "o"]
character_list = [chr(number + 96) for number in encoded_numbers]
# Finally, turn the list of characters into a single string using
# join, then print it
print("Decoded message:")
print("".join(character_list))
I highly recommend playing with the interactive shell (just run python - or even better ipython if you have it installed). It's easier to check what type of data a function returns and experiment with it that way.
Now you're trying to get string and convert it to integer in first string, then you trying to put this integer into for loop.
I do not quite understand what you want from this code, but if you want to type a number of char in ascii ang get this char, use this:
a = input('Enter a number: ')
char = chr(int(a) + 96)
print('Decoded char: ' + char)
You need to iterate over a range of numbers, maybe 26?.
Then you must add 97 which is the ASCII value of a
for number in range(26):
char = f'{chr(number + 97)}'
print (char, end=' ')
output:
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
From then on, you can easily navigate between the ASCII code and the letter representation; adding an offset modulo 26 will give you a Caesar cypher.
The reverse operation (from letter to ASCII code, to the original (0-26) number is as follows:
ord(char) - 97
So my programming assignment wants me to take a user inputted list of numbers, ints and floating, and then order them in descending order and replace any of the floating with "0". I have got the reorder part done but the replace is getting me lost.
Reading Numbers
Write a program that shall ask the user to enter several integer numbers on
the same line, separated by vertical bars surrounded by zero or more spaces
(e.g., “|” or “ |” or “| ” or “ | ”). The program then shall display the entered
numbers in the descending sorted order (from the largest to the smallest),
all on the same line, separated by vertical bars and spaces (“ | ”). If
any entry on the command line is not an integer number, the program shall
replace it with a 0. Use only “for” loop(s) or list comprehensions. Use exception
handling.
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|' :
").split("|")
# replace the floating numbers with "0"
for number in numbers:
print(type(number))
if number.isdigit() == False:
numbers.replace(number,'0')
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(key = float , reverse = True)
[print(number,end = ' | ') for number in numbers]
One change I made was switching all of the for number in numbers to for i in range(len(numbers)). This allows you to access the actual variable by index, while for number in numbers just gets the value.
Here is my solution. I tried to add comments to explain why I did what I did, but if you have any questions, leave a comment:
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|'\n").split(
"|")
# strip any extra spaces off the numbers
for i in range(len(numbers)):
numbers[i] = numbers[i].strip(" ")
# replace the floating numbers and strings with "0"
for i in range(len(numbers)):
try:
# check if the number is an int and changes it if it is
numbers[i] = int(numbers[i])
except:
# set the item to 0 if it can't be converted to a number
numbers[i] = 0
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(reverse = True)
# changes the numbers back into strings
numbers = [str(numbers[i]) for i in range(len(numbers))]
# makes sure that there are more than one numbers before trying
# to join the list back together
if len(numbers) > 1:
print(" | ".join(numbers))
else:
print(numbers[0])
the instructions permit you to use exceptions. the following should get you most of the way there.
>>> numbers = ['1', '1.5', 'dog', '2', '2.0']
>>> for number in numbers:
>>> try:
>>> x = int(number)
>>> except:
>>> x = 0
>>> print(x)
1
0
0
2
0
Hi im trying to write a program which uses a repetition statement to allow users to enter 5 numbers and stores them in a list.Then allow the user to search the list for a number entered by the user and indicate whether the number has been found or not. Im quite stuck on this one, I've made as much of an effort as i can
data =raw_input('Please input 5 numbers: ')
print data
search =raw_input('Search for the numer: ')
for sublist in data:
if sublist[1] == search:
print "Found it!", sublist
break
data is a string, the for loop will loop over every character in this string. That's probably not what you want.
If you want to find an integer in a list of integers, split the input on whitespace and convert each to an integer using int.
ints = [int(x) for x in data.split()]
if int(search) in ints:
print "Found it"
You might try something like this
numbers = []
while len(numbers) < 5:
number = raw_input('Please input 5 numbers: ')
if number.isdigit():
numbers.append(int(number)) #may want to use float here instead of int
else:
print "You entered something that isn't a number"
search = raw_input('Search for the numer: ')
if int(search) in numbers:
print "Found it!"
your code indicates that you may be using sublists but it is unclear how you are creating them.
Issue 1: This line stores the input as a string in the variable data.
data =raw_input('Please input 5 numbers: ')
At this point it is necessary to split the string into a list, and converting the elements to integers.
If the user inputs numbers separated by a space, you can do:
data_list = data.split() # if the numbers are comma-separated do .split(',') instead
int_list = [int(element) for element in data_list]
Issue 2: The users search input should be converted to an integer
search =raw_input('Search for the numer: ')
search_int = int(search)
Issue 3: There is no need for indexing the sublist as you've attempted sublist[1].
The for-loop should then be:
for sublist in int_list:
if sublist == search_int:
print "Found it!", sublist
break
The question I'm answering requires you to validate a Car Reg Plate. It must look for a sequence of two letters, then three numbers, then three letters, otherwise return a message like "not a valid postcode"
I need to know how to check if a string contains a certain letter, or number, by comparing it with a list.
So far, I've got this:
# Task 2
import random
import re
def regNumber():
# Generate a Car Reg Number
letters = ["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"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
letter1 = random.choice(letters)
letter2 = random.choice(letters)
number1 = random.choice(numbers)
number2 = random.choice(numbers)
letter3 = random.choice(letters)
letter4 = random.choice(letters)
letter5 = random.choice(letters)
licensePlate = (letter1 + letter2 + number1 + number2 + letter3 + letter4 + letter5)
return licensePlate, letters, numbers
carReg, letters, numbers = regNumber()
print(carReg)
if letters not in carReg: print("Success")
However, I get this error:
TypeError: 'in <string>' requires string as left operand, not list
Any help appreciated.
You need to be checking for characters in your string with this method, it will not simply iterate over your list for you.
Try using something like this instead, to check every character in your list of strings:
if any(letter in carReg for letter in letters):
This will cut out on the first True, which is I think what you're looking for.
Note: If using any like this is unfamiliar territory for you, you can also always just iterate over every string within your list of strings to check for those given characters.
Update: If you're attempting to match a given format of letters and numbers, it would make much more sense (IMHO) for you to familiarize yourself with Python's regex methods to pattern match to a valid license plate than attempt to use loops to validate one. I won't write the regex for your particular case, but to give you an idea, the following would allow you to match 3 letters followed by 1-4 digits (valid license plate where I live)
match_plate = re.compile(r"^[A-Z]{3}\d{1,4}$",re.I)
If you really must use a list to check, you will have to use a series of conditional statements to split the license plate into parts over which you can validate with iterations.
The error is telling you the exact issue in this case,
letters is a list being returend from regNumber but in requires a string on the leftside
like 'ASD111' in carReg
change
if letters not in carReg: print("Success")
to
for l in letters:
if l not in carReg:
print("Success")
in your code you are having a list of strings and, that is why I have changed your if condition to a for loop so that each element of the list is checked for occurance in carReg string.
alternatively, i think you should be using a flag to solve your probem. Like so:
flag = 0
for l in letters:
if l in carReg:
flag = 1
break
if flag == 0:
print("Success")
Another way in which you could generate a certain number of letters rather than having to use so many variables would be to use just two variables that would allow the generation of, for the first one, 2 letters and for the second 3 letters.
An example of how I would implement this would be:
def randomLetters1(y):
return ''.join(random.choice(string.ascii_uppercase) for x in range(y))
firstLetters = (randomLetters1(2))
secondLetters = (randomLetters1(3))
I know this because I have had to do this exact same task.
You could do it without regular expressions:
Define the pattern you want using str methods in a list
pattern = [str.isalpha, str.isalpha,
str.isdigit, str.isdigit, str.isdigit,
str.isalpha, str.isalpha, str.isalpha]
Use that pattern to check a string.
def is_foo(pattern, s):
'''Return True if s matches pattern
s is a string
pattern is a list of functions that return a boolean
len(s) == len(pattern)
each function in pattern is applied to the corresponding character in s
'''
# assert len(s) == len(pattern)
return all(f(c) for f, c in zip(pattern, s))
Usage
if is_foo(pattern, 'aa111aaa'):
print 'yes!!!'
if not is_foo(pattern, '11aa111'):
print ':('
I have a function here and I want it to count the length of list like 1,2,3,4,5 =5
but the function only counts numbers 1234=4
how can i fix this
def mylen(alist):
if alist:
return 1 + mylen(alist[1:])
return 0
def main():
alist=input("Enter a list of number :")
print(mylen(alist))
main()
fyi i cannot use len
I'm assuming you want mylen('1234') to be = 1. Take your input and split up the numbers by the comma separator.
def mylen(alist):
if alist:
return 1 + mylen(alist[1:])
return 0
def main():
alist=input("Enter a number :")
print(mylen(alist.split(','))
main()
There is no need for the computer to do so much processing for something that is built into the language. This will work just fine:
alist=input("Enter a number :")
print(len(alist.split(','))
In Python 3:
alist=input("Enter a list of number :")
alist will now be a string. If you enter "1,2,3,4,5", a list will be the string "1,2,3,4,5", not a list of numbers [1,2,3,4,5].
A string is a sequence type, just like a list, so your code works with the string as well, and counts the number of elements (characters) in it.
You can use split to convert the input in a list:
userinput = input("Enter a list of number :")
alist = userinput.split(",")
(Note that this is still a list of strings, not numbers, but this doesn't matter for this exercise.)