Problem with sorted phone numbers from hackerrank - python

I know my attempt is very basic, so is my knowledge of python.
the problem asks for getting multiple numbers from user and remove possible 0, +91, or 91 from their left side to make them 10 digit and then sort and print them.
I tried num_list[1] = num_list[1][len(num_list[1])-10:]. It works, so I tried to put it in list comprehension format I'm just studying, but it is not working then. I need help with how to do it hopefully to get a better understanding of when the comprehension format is supposed to be employed.
n = int(input()) # get number of phone numbers from user
num_list = [] # an empty list to store phone numbers in
num_list = [input() for _ in range(n)] # store phone numbers in num_list
##################################
num_list = [num_list[num] = num_list[num][len(num_list[num])-10:] for num in num_list] #remove possible 0, +91, 91 from beginning of numbers
########################################
num_list = sorted(num_list)
num_list = ["+91 "+num[:5]+" "+num[5:] for num in num_list]
print(*num_list , sep="\n")

You shouldn't assign directly within a list comprehension.
The syntax that you're looking for is:
num_list = [num[-10:] for num in num_list]
which is logically equivalent to:
cleaned_list = []
for num in num_list:
cleaned_list.append(num[-10:])
num_list = cleaned_list

Related

Unable to extract numbers and sum them using regex and re.findall()

I try to extract numbers from a text file with regex. Afterward, I create the sum.
Here is the code:
import re
def main():
sum = 0
numbers = []
name = input("Enter file:")
if len(name) < 1 : name = "sample.txt"
handle = open(name)
for line in handle:
storage = line.split(" ")
for number in storage:
check = re.findall('([0-9]+)',number)
if check:
numbers.append(check)
print(numbers)
print(len(numbers))
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
if __name__ == "__main__":
main()
The problem is, if this string "http://www.py4e.com/code3/"
I gets add as [4,3] into the list and later summed up as 43.
Any idea how I can fix that?
I think you just change numbers.append(check) into numbers.extend(check)because you want to add elements to an array. You have to use extend() function.
More, you do not need to use ( ) in your regex.
I also tried to check code on python.
import re
sum = 0;
strings = [
'http://www.py4e.com/code3/',
'http://www.py1e.com/code2/'
];
numbers = [];
for string in strings:
check = re.findall('[0-9]+', string);
if check:
numbers.extend(check)
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
I am assuming instead of 43 you want to get 7
The number variable is an array of characters. So when you use join it becomes a string.
So instead of doing this you can either use a loop in to iterate through this array and covert elements of this array into int and then add to the sum.
Or
you can do this
import np
number np.array(number).astype('int').tolist()
This makes array of character into array on integers if conversion if possible for all the elements is possible.
When I add the string http://www.py4e.com/code3/" instead of calling a file which is not handled correctly in your code above fyi. The logic regex is running through two FOR loops and placing each value and it's own list[[4],[3]]. The output works when it is stepped through I think you issue is with methods of importing a file in the first statement. I replaced the file with the a string you asked about"http://www.py4e.com/code3/" you can find a running code here.
pyregx linkhttps://repl.it/join/cxercdju-shaunpritchard
I ran this method below calling a string with the number list and it worked fine?
#### Final conditional loop
``` for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(str(sum)) ```
You could also try using range or map:
for i in range(0, len(numbers)):
sum = sum + numbers
print(str(sum))

How to ask the user to enter numbers and then sum the numbers which are divisible by 3?

I want to make a Python script which has the user enter 7 numbers and then check which numbers can be divided by 3, then sum those numbers, and show it to the user as "sum=xx".
I tried:
input_string = input("Enter a list element separated by space ")
list = input_string.split()
Here is using list comprehension,
input_string = input("Enter a list element separated by space ")
numbers = [int(num) for num in input_string.split(',') if int(num) % 3 == 0]
print('Sum = {}'.format(sum(numbers)))
This is based on your question above.
But, you also said that you would want user to input 7 numbers and find sum for numbers which are divisible by 3.
Here is other simple example, where we ask user to input 7 numbers, one number at a time and print sum at the end.
all_numbers = []
for i in range(7):
num = int(input(f'Enter number {i + 1}:\n1'))
all_numbers.append(num)
sum_of_numbers = sum([num for num in all_numbers if num % 3 == 0])
print(f'Sum = {sum_of_numbers}')
You can get a list of integers from the input using the int function which gives you an integer object from a string, since the split function only gives you a list of separated strings.
input_string = input("Enter a list element separated by space ")
my_list = input_string.split()
numbers = []
for n in my_list:
numbers.append(int(n))
However, this will throw a ValueError if n is not a valid number (e.g. "a"), which you can catch with a try-exceptstatement.
Notice how I changed the name of your variable to my_list because the name list already has a meaning in Python and it's a good practice to not assign it to a variable.
If you want to do it in a single step, you can use the useful map function to apply the int function to all of the elements in list. You can check the documentation for this function, as well as any other on the python documentation, or using the help built-in function. (e.g. help(map))
numbers = map(int, my_list)
You can then check if there are 7 numbers in the list by using the len function, and if there aren't 7 you can prompt the user to input the numbers again if that is what you want to do.
>>> my_list = [1, 2, 3]
>>> len(my_list) == 3
True
If you want to keep prompting the user until there are seven numbers on your list, you can put the prompt inside a while block, like shown:
numbers = [] # We create an empty list
while len(numbers) != 7:
input_string = input("Enter a list element separated by space ")
my_list = input_string.split()
numbers = list(map(int, my_list)) # Get the numbers
After getting the numbers, you can see which ones are divisible by 3 by using the modulo operator, which gives you the rest of dividing a number by another (3 in your case). Some examples:
>>> 7%3 # 7 = 3*2 + 1
1
>>> 19%5 # 14 = 5*3 + 4
4
>>> 8%4 # 8 = 4*2 + 0
0
Since you want to check which numbers of your list are divisible by 3 you can check whether this module is 0 or not inside of a loop through the list.
If the numbers are divisible by 3, you can add them to a counting variable, you could initialize to 0 before the loop. That way, after the loop you'd get the sum you want in this variable.
Another, more elegant way of doing so is using a list comprehension instead of a loop, which would only retain the numbers divisible by 3, and then sum its elements using the sum function.
new_list = [x for x in numbers if x%3 == 0]
sum = sum(new_list)

How to input a list in Python?

Usually, we input() a list in Python 3.X like this:
x = list(map(int, input()))
print (x)
But here let's say we give an input of 1234 then it prints:`
[1, 2, 3, 4]
Is there a way that I can print it like:
[12, 34]
Thanks in Advance!
Let's say you want the numbers to be entered separated by spaces. First get the entire line as input:
line = input()
Now parse the input. In this case, split on spaces:
words = line.split(' ')
Finally, convert each "word" to an int:
numbers = [int(i) for i in words]
Of course you can use map() instead of a list comprehension.
Note that this requires input such as
12 34
You can do this all in one line, but it is better to use variables to store each intermediate step. When you get it wrong, you can debug much more easily this way.
In my opinion, I would not complicate things :
I would declare an empty list :
l = []
Then I would simply append the input :
for i in range(0, n):
print("l[", i, "] : ")
p = int(input())
l.append(p)
You can notice here the "n",it's the size for the list,in your case it would be:
for i in range(0, 1):
print("l[", i, "] : ")
p = int(input())
l.append(p)
We always start from 0,so range(0,1) would count 0, then 1 and so on with other cases.
Hope this would help.

how can i compare string within a list to an integer number?

my task today is to create a function which takes a list of string and an integer number. If the string within the list is larger then the integer value it is then discarded and deleted from the list. This is what i have so far:
def main(L,n):
i=0
while i<(len(L)):
if L[i]>n:
L.pop(i)
else:
i=i+1
return L
#MAIN PROGRAM
L = ["bob", "dave", "buddy", "tujour"]
n = int (input("enter an integer value)
main(L,n)
So really what im trying to do here is to let the user enter a number to then be compared to the list of string values. For example, if the user enters in the number 3 then dave, buddy, and tujour will then be deleted from the list leaving only bob to be printed at the end.
Thanks a million!
Looks like you are doing to much here. Just return a list comprehension that makes use of the appropriate conditional.
def main(L,n):
return([x for x in L if len(x) <= n])
Just use the built-in filter method, where n is the cut off length:
newList = filter(lambda i:len(i) <= n, oldList)
You should not remove elements from a list you are iterating over, you need to copy or use reversed:
L = ["bob", "dave", "buddy", "tujour"]
n = int(input("enter an integer value"))
for name in reversed(L):
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
Making a copy using [:] syntax:
for name in l[:]:
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
This is a simple solution where you can print L after calling the main function. Hope this helps.
def main(L,n):
l=len(L)
x=0
while x<l:
#if length is greater than n, remove the element and decrease the list size by 1
if len(L[x])>n:
L.remove(L[x])
l=l-1
#else move to the next element in the list
else:
x=x+1

Square list of numbers user input Python

i'm trying to write a function where user can input a list of numbers, and then each number gets squared, example [1,2,3] to [1,4,9]. so far my code is this:
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
list = []
for n in num:
list += int(n)*int(n)
print list;
x = squarenumber()
but i get this error saying 'int' object is not iterable. I tried different ways, but still no clue so if anyone can help me i'd be greatly appreciated.
First of all do not use list as a variable, use lst. Also you are incrementing a value not appending to a list in your original code. To create the list, then use lst.append(). You also need to return the list
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
lst = []
for n in num:
if n.isdigit():
nn = int(n)
lst.append(nn*nn)
print lst
return lst
x = squarenumber()
With lists, you should use append() instead of +=. Here is the corrected code:
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
lst = []
for n in num:
lst.append(int(n)*int(n))
print lst
x = squarenumber()
[Running the code]
Enter numbers, eg 1,2,3: 1,2,3
[1, 2, 3]
[1, 4, 9]
def squarenumber(inp):
result = [i**2 for i in inp]
return result
>>>inp = [1,2,3,4,5]
>>>squarenumber(inp)
[1, 4, 9, 16, 25]
You can get the desired output using list comprehension instead another loop to append the square of a number to list. Dont use list as a variable name
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print num # display user input
lst= [int(n)* int(n) for n in num if n.isdigit()]
print lst # display output
x = squarenumber()
Since you're using the list comprehension to print the input, I thought you might like a solution that uses another one:
def squarenumber():
num = raw_input('Enter numbers, e.g., 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()]
print [int(n)**2 for n in num if n.isdigit()]
x = squarenumber()

Categories

Resources