Python noob-- Probably a simple typo? [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
I really just can't understand why this code is not working...
It's probably just a typo. But even my more experienced friend is stumped here.
The prompt is simply "write a program that tells you how many 4s there are in a given list." Its all working except that count says zero no matter how many 4s I submit.
def num_four(number_list):
count = 0
print number_list
for i in number_list:
print i
if i == 4:
count = count + 1
return count
number_list = raw_input("Enter list of integers here: ")
print num_four(number_list)
the output looks like this:
Enter list of integers here: 123444
123444
1
2
3
4
4
4
0

raw_input returns a string like "8675409". When you iterate over this string (it's not a list), you get the string "8", then "6", then "7" -- it will eventually be "4", but never be the int 4.

The problem is that you don't pass a list of numbers to your function because raw_input returns a string.
number_list = raw_input("Enter list of integers here: ")
number_list = map(int, number_list.split())
print num_four(number_list)
This assumes that the numbers you input are separated by whitespace.
If you just put in strings like '1234', iterate over the string and check against '4' instead of the integer 4 in your function. If that's the case, consider renaming number_list to something more fitting like continuous_number_string.
And if you want to simplify your function, use the count method of either str or list:
>>> [1,2,3,4,4,5].count(4)
2
>>> '1234544'.count('4')
3

Please check the answer of #Mike Graham.
And just in case you are looking for a more Pythonic solution:
from collections import Counter
Counter(raw_input()).get("4")

raw_input will produce a string, not a list of integers, regardless of what you type in. So i will never equal 4 (integer) at most "4" (string).

Related

Basic math in python [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
The code below is giving me a return of 25 with inputs of 3 & 4. Obviously it should be 7. This is a problem for school and I can't edit the first 3 lines or the last one. What am I missing here?
total_owls = 0
num_owls_A = input()
num_owls_B = input()
num_owls_A = int(input())
num_owls_B = int(input())
total_owls = (num_owls_A + num_owls_B)
print('Number of owls:', total_owls)
input() returns input value as a string. So, you are basically concatenating strings not integers.
If you want to add them as numbers you need to convert them to numbers first like below
num_owls_A = int(input())
num_owls_B = int(input())
Again, this will create an error, if you input a non-numerical value, so you need to handle the exceptions in such case.

Combining specific elements within a list [duplicate]

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 3 years ago.
I'm trying to convert a user inputted string into a list of 2 digit numbers.
When the user enters a string, say "1234" and I convert that into a list, it becomes [1,2,3,4]. What I need it to become is [12,34] and so on. How would one go about doing this?
print("Please insert string.") # User enters "12345678"
string1 = input()
list1 = list(string1) # "12345678" becomes [1,2,3,4,5,6,7,8]
if not any(char.isdigit() for char in string1):
print("Submission must be numbers only.")
else:
magically turn list1 into 2digitlist
print(2digitlist)
# Desired output: [12,34,56,78]
Hopefully there's a solution to this but I certainly have no clue what it is. That's what I get for trying to do something complex even though I have little experience I suppose. Thanks in advance.
My attempt with strided array access, combined with zip:
string1 = "123456"
list1 = list(string1) #"12345678" becomes [1,2,3,4,5,6,7,8]
if not all(char.isdigit() for char in string1):
print("Submission must be numbers only.")
else:
digitlist=[10*int(e1) + int(e2) for (e1,e2) in zip(list1[::2], list1[1::2])]
print(digitlist)
[12, 34, 56]
Of course, this only works correctly if the input contains an even amount of digits, otherwise it will ignore the last digit. But that wasn't specified in the question.

How to sort list into ascending order? sort() function not working? [duplicate]

This question already has answers here:
Python: sorting string numbers not lexicographically
(5 answers)
Closed 3 years ago.
I have started a simple code that gets an input of numbers, and then sorts those numbers into ascending order. I tried using the sort() function, but it sorts those numbers into 'alphabetical' order instead. For example:
[3,13,20] would sort into 13,20,3 as the first number digit is 1-3 and the second 2-0 and the third 3.
I have tried simply using the sort function on a list with [3,13,20] and it gives the right answer: 3,13,20
I therefore conclude that the problem is with the first part of my code.
inputstring = input("Enter Numbers:")
numbers = inputstring.split()
numbers.sort()
print(numbers)
This would result in the numbers being sorted into 3,13,20 (alphabetically) instead. Whereas:
list = [13,3,20]
list.sort()
print(list)
Would give the answer 3,13,20 (in ascending order)
Would anybody be able to help debug why the first part of my code:
inputstring = input("Enter Numbers:")
numbers = inputstring.split()
gives the wrong ascending order?
Thanks!
The result of split is always a list of strings, which are sorted differently from ints. You need to convert them; one way is a list comprehension:
numbers = [int(number) for number in inputstring.split()]
As far as I know you are giving the input to the program as follows.
13 3 20
By default it will consider the input as string.
So, when you split the input, it creates a list containing string elements and not integer elements like this ['13', '3', '20'] and not [13, 3, 20] and that is the reason you might be seeing unexpected output.
Try this to fix it.
lis = input().split()
lis = [int(i) for i in lis]
lis.sort()

I'm not sure why I keep getting 12 < 3 [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
I know the names are kind of long but I wanted to make sure there was no way it was pulling from used variables
firstvalue = input("first")
secondvalue = input("second")
if firstvalue < secondvalue:
print ("first value is < second value")
print ( firstvalue, "less than", secondvalue)
else:
if firstvalue == secondvalue:
print ("first is = second")
else:
print ("first is greater than 2nd")
print (firstvalue , "greater than", secondvalue)
when i input 12 for the first value and 3 as the second value, i get 12 < 3
You're reading the variables as strings not integers, try this instead:
firstvalue = int(input("first"))
secondvalue = int(input("second"))
You are currently comparing strings and "12" is less than "3" because 1 comes before 3 in the ASCII table.
If you wish to compare the int value of the inputted string use int(input()) but then you may want to catch ValueError
When you input from commandline your values are text values. And remain such if you do not convert them to int or float.
When comparing text values python of course compares alphabetically and so the first character is compared to the first character. Which in your example are 1 and 3 and "1" is less than "3"

Enter list in Python3 [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
How can I ask from the user to enter a list in Python3,so as every time the program runs,the input list is the mutable data of the program?
For example, number lists,that user maybe enters are:
L1 = [7,9,16,25],L2 = [5,10,15,20],L3 = [10,17,19,24],`L4 = [16,20,20,23]
Please write the commensurable commands/statements.
python3's input() now always returns a string instead of evaluating the text as it did in python2.7. this means that you have to convert an input string into the type of data you need. a simple way of achieving this is to prompt the user to enter a list of numbers separated by commas. the resulting string can then be split into a list of strings by calling the string's .split() method. after converting to a list of strings, you can call int() or float() to convert each string into an individual number.
Example:
s = input("enter a list of numbers separated by commas:") #string
l = s.split(",") #list
n = [int(x) for x in l] #numbers

Categories