Combining specific elements within a list [duplicate] - python

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.

Related

Checking if a number is present in string [duplicate]

This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 2 years ago.
I have a working function that takes an input as string and returns a string. However, I want my function to return an empty string ("") if the input contains any number in whatever position in the string.
For example :
>>> function("hello")
works fine
>>> function("hello1")
should return ""
The main thing you need for that is the method "isdigit()" that returns True if the character is a digit.
For example:
yourstring="hel4lo3"
for char in yourstring:
if char.isdigit():
print(char)
Will output 4 and 3.
I think it is a good exercise for you trying to do your code from that!

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()

Python comparing a list with set to find pangram [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 years ago.
I'm trying to find if a string is a Pangram. My approach is to get the string to have unique letters by using the set method. Then using the string.ascii as the base alphabet. I find out after some testing that if I try to compare the 2 with the 'in' operator. Some of the letters get passed over and won't be removed from the alphabet list.
def is_pangram(sentence):
uniqueLetters = set(sentence.lower().replace(" ", ""))
alphabet = list(string.ascii_lowercase)
for letter in alphabet:
if letter in uniqueLetters:
alphabet.remove(letter)
if len(alphabet) <= 0:
return True
return False
print(is_pangram("qwertyuiopasdfghjklzxcvbnm"))
this example will compare 13 letters and the rest will not. Anyone can point me in the right direction? Am I misunderstanding something about set?
Perhaps the following does what you want:
import string
target = set('qwertyuiopasdfghjklzxcvbnm')
all((k in target for k in set(string.ascii_lowercase)))

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

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

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).

Categories