How can I make my program recognize if item is a string or an intiger? - python-3.x

I'm doing some python challenges for fun and I've found a challenge which tells me to make a program that takes an input and prints the numbers in the message.
but when I run the program it prints nothing but [] in the same number as the letters in the message, and also it do not recognize if a letter is actually a number or not, it just see every letter as a string and prints empty squares.
Here's the code:
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence:
if item == str():
WORDS.append(item)
if item == int():
NUMBERS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
Have any ideas?

Here is probably what you meant. You have to split the sentence first.
All of the resulting items will be of type string, therefore isinstance will not help.
str.isdigit() checks if a string contains only digits. If it is a number, you can convert it to an integer using int.
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence.split():
if item.isdigit():
NUMBERS.append(int(item))
else:
WORDS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
If you do not do the split first, it will work too, but give you just single characters in the WORDS list and single numbers in the NUMBERS list.

Typechecking is usually done using isinstance(obj, cls) :
x = 42
print(isinstance(x, int))
print(isinstance(x, str))
but in your case this will not work since input() always returns a string (a string composed of numeric characters is still a string), so the proper solution is to check if the string is composed only of numeric characters (and eventually build an int from it if you need proper ints).
Also, input() returns a single string, and from your namings (WORDS) I assume you want to iterate on the distinct words, not on each characters like you actually do:
words = []
numbers = []
sentence = input()
for item in sentence.strip().split():
if item.isnumeric():
numbers.append(int(item))
else:
words.append(item)
print(('[%s]' % ', '.join(map(str, numbers))))

Use the built-in isinstance function:
if isinstance(item, str):
WORDS.append(item)
if isinstance(item, int):
NUMBERS.append(item)

Related

What can I do to add a list and sort out all the prime numbers in the list? Python 3

I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.

Python inputs using list comprehensions

n = int(input("Enter the size of the list "))
print("\n")
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:n]
print("User list: ", num_list)
can anyone explain this ...... i.e how it will work.THANKYOU
The workflow is once you enter the size of the list value will be stored in variable 'n' and n printed in the interpreter.
n = int(input("Enter the size of the list "))
print("\n")
In the list comprehension input().strip().split() is executed first i.e once you entered data is striped(removed leading and trailing spaces) and split data by space(default behavior) . then you entered data is iterated by iter variable (num) and num was converted into an integer as well as stored in num_list. Then finally you got num_list contains elements as int type.
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())
finally, list slicing as before n elements are returned into num_list.
num_list[:n]
Without list comprehension of how the above code works like......
num_list=[]
n = int(input("Enter the size of the list "))
print("\n")
for num in input("Enter the list items separated by space ").strip().split()):
num_list.append(int(num))
num_list=num_list[:n]
in one short in list comprehension every element in input is iterated by loop and typecasting it into int and before nth index elements are stored into num_list.

Convert numbers string in list to number int

In Python, I want to convert all strings in a list to integers.
So if I have:
list1 = ['10,20,30']
How do I make it:
list1 = [10,20,30]
try this:
list1 = [int(i) for i in list1[0].split(',')]
First of all you have to define what the array contains, for how you have wrote the questions the array is:
0: 10,20,30
if your array is made of strings like that then you should make a regex to identify the numbers in every string and then convert the number into an integer.
But I think that your array is actually:
0: 10
1: 20
2: 30
In this case you would want to do:
for every number in the array
make the number an integer
which would be
for num in list:
# if the value is a string
if type(num) == str: # just to be sure
num = int(num)
In python every data type is easily changeable through int, float or str, but remember to assign the number after you have converted it.
int(num) would make a number an integer but would not actually convert it because have not stored it, you should do num = int(num) because those are functions that return what to want, to really understand how they works mean you should search about dynamically typed languages and functions

how to add characters from array into one string python

I'm trying to change characters from x into upper or lower character depending whether they are in r or c. And the problem is that i can't get all the changed characters into one string.
import unittest
def fun_exercise_6(x):
y = []
r = 'abcdefghijkl'
c = 'mnopqrstuvwxz'
for i in range(len(x)):
if(x[i] in r):
y += x[i].lower()
elif(x[i] in c):
y += x[i].upper()
return y
class TestAssignment1(unittest.TestCase):
def test1_exercise_6(self):
self.assertTrue(fun_exercise_6("osso") == "OSSO")
def test2_exercise_6(self):
self.assertTrue(fun_exercise_6("goat") == "gOaT")
def test3_exercise_6(self):
self.assertTrue(fun_exercise_6("bag") == "bag")
def test4_exercise_6(self):
self.assertTrue(fun_exercise_6("boat") == "bOaT" )
if __name__ == '__main__':
unittest.main()
Using a list as you are using is probably the best approach while you are figuring out whether or not each character should be uppered or lowered. You can join your list using str's join method. In your case, you could have your return statement look like this:
return ''.join(y)
What this would do is join a collection of strings (your individual characters into one new string using the string you join on ('').
For example, ''.join(['a', 'b', 'c']) will turn into 'abc'
This is a much better solution than making y a string as strings are immutable data types. If you make y a string when you are constructing it, you would have to redefine and reallocate the ENTIRE string each time you appended a character. Using a list, as you are doing, and joining it at the end would allow you to accumulate the characters and then join them all at once, which is comparatively very efficient.
If you define y as an empty string y = "" instead of an empty list you will get y as one string. Since when you declare y = [] and add an item to the list, you add a string to a list of string not a character to a string.
You can't compare a list and a string.
"abc" == ["a", "b", "c'] # False
The initial value of y in the fun_exercise_6 function must be ""

Return a dictionary with keys that are the first letter of a word and lists of those words?

I want to write a function that takes a list of words and keys and outputs those keys as dictionary keys with any words starting with that letter attached.
How could this be achieved using simple python 3 code?
eg. takes (['apples', 'apple', 'bananna', 'fan'], 'fad')
returns {'a' : ['apple', 'apples'], 'f' : ['fan']}
so far i have tried:
def dictionary(words, char_keys)
char_keys = remove_duplicates(char_keys)
ret = {}
keys_in_dict = []
words = sorted(words)
for word in words:
if word[0] in char_keys and word[0] not in keys_in_dict:
ret[word[0]] = word
keys_in_dict.append(word[0])
elif word[0] in keys_in_dict:
ret[word[0]] += (word)
return ret
This gives kinda the right output but it the output is in a single string rather than a list of strings.(the def is not indented properly i know)
If the input is a list of strings, you can check if the char is in the dict, if yes, append the word, otherwise add a list with the word:
def dictionary(inpt):
result = {}
for word in inpt:
char = word[0]
if char in result:
result[char].append(word)
else:
result[char] = [word]
return result
The modern way to do this is to use a collections.defaultdict with list as argument.
def dictionary(inpt):
result = defaultdict(list)
for word in inpt:
result[word[0]].append(word)
return result
Not sure if your list of inputs are consisted with only strings or it can also include sub-lists of strings (and I'm not so sure why "fad" disappeared in your example). Obviously, in the latter scenario it will need some more effort. For simplicity I assume if contains only strings and here's a piece of code which hopefully points the direction:
d = {}
for elem in input_list[0]:
if elem[0] in input_list[1]
lst = d.get(elem[0], [])
lst.append(elem)
d[elem] = lst

Resources