Multiple inputs from one input - python

I'm writing a function to append an input to a list. I want it so that when you input 280 2 the list becomes ['280', '280'] instead of ['280 2'].

>>> number, factor = input().split()
280 2
>>> [number]*int(factor)
['280', '280']
Remember that concatenating a list with itself with the * operator can have unexpected results if your list contains mutable elements - but in your case it's fine.
edit:
Solution that can handle inputs without a factor:
>>> def multiply_input():
... *head, tail = input().split()
... return head*int(tail) if head else [tail]
...
>>> multiply_input()
280 3
['280', '280', '280']
>>> multiply_input()
280
['280']
Add error checking as needed (for example for empty inputs) depending on your use case.

You can handle the case with unspecified number of repetitions by extending the parsed input with a list containing 1. You can then slice the list to leave the first 2 items (in case the number of repetitions was provided, that [1] will be discarded)
number, rep = (input().split() + [1])[:2]
[number] * int(rep)

from itertools import repeat
mes=input("please write your number and repetitions:").split()
listt= []
listt.extend(repeat(int(mes[0]), int(mes[1]))
#repeat(object [,times]) -> create an iterator which returns the object
#for the specified number of times. If not specified, returns the object
#endlessly.

This code provides exception handling against no second number being provided with in put.
def addtolist():
number = input("Enter number: ")
try:
factor = input("Enter factor: ")
except SyntaxError:
factor = 1
for i in range(factor):
listname.append(number)

Related

Can we get multiple input as tuples?

I want to get multiple inputs as tuples in a list. Example: [(1,2),(1,3),(1,4),(2,5)] I wrote this code, it works not bad. But I'm just wondering if there is another way to do this or can we make this code clear?
def make_tuple(k):
tup_list = []
for i in range(0, len(k)-1, 2):
tup_list.append((k[i],k[i+1]))
return tup_list
list1 = list(map(int, input("Enter multiple values: ").split()))
make_tuple(list1)
In this way, user should enter the input like; 1 2 1 3 1 4 2 5 for getting [(1,2),(1,3),(1,4),(2,5)]. The actual thing I want is enter the input like; 1,2 1,3 1,4 2,5
import ast
a = ast.literal_eval(input('some text: '))
input-(1,2)
output-(1,2)
input-[(1,2)]
output=[(1,2)]
This function will accept any input that look like Python literals, such as integers, lists, dictionaries and strings
ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
you can use Zip function to achieve this.You can read more on Splitting a long tuple into smaller tuples
a = [int(char) for char in input("Enter multiple values: ")]
def zipper(iterable,n):
args = [iter(iterable)] * n
return zip(*args)
print(*zipper(a,2))
This way if user inputs only 5 digits it can output only 2 tuples of 2 elements each

Longest sequence of equal numbers in python

I tried to generate the longest sequence of equal numbers in python, but it doesn't work
def lista_egale(lst1 = input("numbers go here ")):
l = 0
lst1 = []
maxi = -9999
prev_one = None
lmax = -9999
for current in lst1:
if prev_one == current:
l += 1
else:
l = 1
if l > lmax:
lmax = l
maxi = current
prev_one = current
print("longest sequence is ", lmax, " and ", maxi)
lista_egale()
Input:
1 2 2 2 2 3 4 5 6 2 2 2
Expected Output:
longest sequence is 4 and 2
I was going to write up the same concern about your default argument, but that would at least work correctly the first time it is called. This function does not. Everyone jumped on that common problem, and failed to notice the next line. Let's look another look at this abridged version of your code:
irrelevant = input("numbers go here ")
def lista_egale(lst1 = irrelevant):
# while it is true that your default argument is bad,
# that doesn't matter because of this next line:
lst1 = []
for current in lst1:
# unreachable code
pass
To clarify, since your reply indicates this is not clear enough, it doesn't matter what value was passed in to lst1 if you immediately overwrite it with an empty list.
(for others reading this:) Separating out what I labeled "irrelevant" is not quite identical, but I'm trying to point out that the input was overwritten.
I don't think this function should take user input or have a default argument at all. Let it be a function with one job, and just pass it the data to work on. User input can be collected elsewhere.
Based on Barmar's note, and the principle of using only unmutable default values, your code should look something more like this:
def lista_egale(inp1 = None):
if not inp1:
inp1 = input("numbers go here ")
# optionally do some error checking for nonnumerical characters here
lst1 = [int(i) for i in inp1.split(" ")]
# rest of your code here
lista_egale()
Basically, input returns a string value, and you need to convert it into a list of integers first before you start working on it.
You can swap out the list comprehension for map(int, inp1.split(" ")) as it will do the same (but you can't iterate through a map more than once unless you wrap it in a list() function first).
Secondly, avoid setting mutable default arguments as (in short) can lead to weird results when rerunning the same function multiple times.

Function to find the max of 3 numbers in Python

I'm trying to write a function that takes the inputs and puts them into a list, then sorts the list, and finds the greatest number. I keep getting errors and I'm not really sure what's wrong. I'll post the current code that I have typed up already. Any help or advice would be greatly appreciated, thank you.
Code:
def findMax3():
y = list(lst)
y.sort(lst)
y[0] == y[-1]
lst = int(input())
print(findMax3())
You need to pass in a variable - lst maybe?
You need to return value if you want your main to print something.
You need a constant input format for integer arrays, I will suggest 1 2 3 4 5 (space separated), that can be reversed to list using map(int, input().split())
Use the built-in max.
Do you want to limit yourself to 3 number arrays? if yes, use assertion.
That should be enough:
def findMax3(lst):
assert len(lst) == 3
lst.sort()
return max(lst)
lst = map(int, input().split())
print(findMax3(lst))
This is the corrected code:
def findMax3(lst):
y = lst[:]
y.sort()
return y[-1]
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I'd say findMax() would be a better name as this could find the maximum of lists of any length.
Bear in mind the following does the same thing:
lst = [int(x) for x in input().split()]
print(max(lst))
Put the numbers in a list, then use max() function to get the maximum value in a list, like this:
#create an empty numbers list
lst=[]
#loop for getting input numbers
for i in range(1,4):
try:
#here we get the input number
my_new_number=int(raw_input("Please input the number "+str(i)+"/3 :\n"))
except:
#in case of it is not a number raise an alert
print "not regular integer number"
#here we check that number not exist
if my_new_number not in lst:
#add the current input number to the list
lst.append(my_new_number)
else:
print "the number",my_new_number,"already exist in this list"
#show the maximum number of the list
print "The maximum number is",max(lst)
You might be interested in typing your list items one by one instead of using split() function to split your input. Also, to retrieve your list max, you have already a built-in max() function that you can use:
>>> num_list = []
>>>
>>> for i in range(3):
... num = input("Enter number {}: ".format(i + 1))
... num_list.append(int(num))
...
Enter number 1: 3
Enter number 2: 6
Enter number 3: 2
>>>
>>> max_num = max(num_list)
>>> print(max_num)
6
First off, Ebe Isaac gave a good explanation and you should look at his solution and understand why it works.
There's a few issues with your code.
lst = int(input())
print(findMax3())
You're inputting a list of numbers that need to be separated by some non-numeric character, so you cannot use int() on your input value.
lst = [int(x) for x in input().split()]
should give you what you want (with default separator being blank space). To learn more about this format, see list comprehensions.
Next, you call findMax3() but this function does not return a value so it will not have anything to print (see below). Additionally, it would be better to send it your list as an argument, this will save you from another line copying it later (see below).
lst = input().split()
print(findMax3(lst))
Now for your function:
def findMax3():
y = list(lst)
You should probably send an argument (the inputted list) to the function. This argument can be renamed whatever you put in the parentheses after the name of the function. You are using y here so we can rewrite it as:
def findMax3(y):
and delete the y = list(lst) line.
y.sort(lst)
When using a method or function, it's a good idea to look up the documentation to identify what arguments it takes. You'll see that sort can take two arguments (key and reverse) neither are needed here so we can fix this line by changing it to:
y.sort()
The next line:
y[0] == y[-1]
is a Boolean expression and returns either True or False if the first element of the sorted list (y[0]) is equal to the last element of the sorted list (y[-1]). To be honest, I'm not really sure what you were trying to do here. Since the function is designed to find the max value of the list, it needs to return that value so we need to use return(). The max value will be the last of the list so you can do:
return(y[-1])
So if you want to keep the flow of your original code, it can work by changing it to:
def findMax3(y):
y.sort()
return(y[-1])
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I hope this helps. Best of luck.
As many have mentioned, you need to let your function know what list to find the max of. To do that, you need to put the name of the list in the parameter list of the function i.e. findMax3(lst).
Your function will still not work because you are not returning anything from it. You need to use the return keyword followed by what to return in order to have the function give you a response. For example, return 1 will return the value of 1 to anyone who called this function. Using that example, you need to decide what to return to the caller.
My version of findMax3 without any other function calls:
def findMax3(*args):
max3 = args[0]
for n in args[1:3]:
if n > max3:
max3 = n
return max3
This is pretty close to what the built in max function will do given those same 3 inputs
If you already have a list then you can simply use the max function to get the highest number among 3 numbers in the list.
lst = [5, 2, 9]
print(max(lst))
# output
9
Or I assume you have three different numbers as input and then you can pass them to your desired method to get the highest number.
# function to get max among 3 integers
find_max(x, y, z):
return max([x, y, z])
# take input
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
num3 = int(input("enter num3: "))
# call your function
print(find_max(num1, num2, num3))
If we do not want to use the built in function for solving the problem we could always follow the below simple approach.
Using max() to find maximum of numbers is already shown in above few solutions.
Posting a sample solution without use of max()
num1=51
num2=6
num3=72
def find_max(num1,num2,num3):
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
return largest
print(find_max(num1,num2,num3))

Manipulating string to repeat based on the length of another string

I am working on a python project, where I am required to include an input, and another value (which will be manipulated).
For example,
If I enter the string 'StackOverflow', and a value to be manipulated of 'test', the program will make the manipulatable variable equal to the number of characters, by repeating and trimming the string. This means that 'StackOverflow' and 'test' would output 'testtesttestt'.
This is the code I have so far:
originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
while len(manipulateinput) < len(originalinput):
And I was thinking of including a for loop to continue the rest, but am not sure how I would use this to effectively manipulate the string. Any help would be appreciated, Thanks.
An itertools.cycle approach:
from itertools import cycle
s1 = 'Test'
s2 = 'StackOverflow'
result = ''.join(a for a, b in zip(cycle(s1), s2))
Given you mention plaintext - a is your key and b will be the character in the plaintext - so you can use this to also handily manipuate the pairing...
I'm taking a guess you're going to end up with something like:
result = ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(cycle(s1), s2))
# '\x07\x11\x12\x17?*\x05\x11&\x03\x1f\x1b#'
original = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(cycle(s1), result))
# StackOverflow
There are some good, Pythonic solutions here... but if your goal is to understand while loops rather than the itertools module, they won't help. In that case, perhaps you just need to consider how to grow a string with the + operator and trim it with a slice:
originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
output = ''
while len(output) < len(originalinput):
output += manipulateinput
output = output[:len(originalinput)]
(Note that this sort of string manipulation is generally frowned upon in real Python code, and you should probably use one of the others (for example, Reut Sharabani's answer).
Try something like this:
def trim_to_fit(to_trim, to_fit):
# calculate how many times the string needs
# to be self - concatenated
times_to_concatenate = len(to_fit) // len(to_trim) + 1
# slice the string to fit the target
return (to_trim * times_to_concatenate)[:len(to_fit)]
It uses slicing, and the fact that a multiplication of a X and a string in python concatenates the string X times.
Output:
>>> trim_to_fit('test', 'stackoverflow')
'testtesttestt'
You can also create an endless circular generator over the string:
# improved by Rick Teachey
def circular_gen(txt):
while True:
for c in txt:
yield c
And to use it:
>>> gen = circular_gen('test')
>>> gen_it = [next(gen) for _ in range(len('stackoverflow'))]
>>> ''.join(gen_it)
'testtesttestt'
What you need is a way to get each character out of your manipulateinput string over and over again, and so that you don't run out of characters.
You can do this by multiplying the string so it is repeated as many times as you need:
mystring = 'string'
assert 2 * mystring == 'stringstring'
But how many times to repeat it? Well, you get the length of a string using len:
assert len(mystring) == 6
So to make sure your string is at least as long as the other string, you can do this:
import math.ceil # the ceiling function
timestorepeat = ceil(len(originalinput)/len(manipulateinput))
newmanipulateinput = timestorepeat * manipulateinput
Another way to do it would be using int division, or //:
timestorepeat = len(originalinput)//len(manipulateinput) + 1
newmanipulateinput = timestorepeat * manipulateinput
Now you can use a for loop without running out of characters:
result = '' # start your result with an empty string
for character in newmanipulateinput:
# test to see if you've reached the target length yet
if len(result) == len(originalinput):
break
# update your result with the next character
result += character
# note you can concatenate strings in python with a + operator
print(result)

Writing a custom sum function that sums a list of numbers

I am new to Python and need some help writing a function that takes a list as an argument.
I want a user to be able to enter a list of numbers (e.g., [1,2,3,4,5]), and then have my program sum the elements of the list. However, I want to sum the elements using a for loop, not just by using the built in sum function.
My problem is that I don't know how to tell the interpreter that the user is entering a list. When I use this code:
def sum(list):
It doesn't work because the interpreter wants just ONE element that is taken from sum, but I want to enter a list, not just one element. I tried using list.append(..), but couldn't get that to work the way I want.
Thanks in anticipation!
EDIT: I am looking for something like this (thanks, "irrenhaus"):
def listsum(list):
ret=0
for i in list:
ret += i
return ret
# The test case:
print listsum([2,3,4]) # Should output 9.
I'm not sure how you're building your "user entered list." Are you using a loop? Is it a pure input? Are you reading from JSON or pickle? That's the big unknown.
Let's say you're trying to get them to enter comma-separated values, just for the sake of having an answer.
# ASSUMING PYTHON3
user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number
def sum(lst):
accumulator = 0
for element in lst:
accumulator += element
return accumulator
The top three lines are kind of ugly. You can combine them:
user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))
But that's kind of ugly too. How about:
raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
processed_in = map(float, raw_in)
# if you specifically need this as a list, you'll have to do `list(map(...))`
# but map objects are iterable so...
except ValueError:
# not all values were numbers, so handle it
The for loop in Python is exceptionally easy to use. For your application, something like this works:
def listsum(list):
ret=0
for i in list:
ret+=i
return ret
# the test case:
print listsum([2,3,4])
# will then output 9
Edit: Aye, I am slow. The other answer is probably way more helpful. ;)
This will work for python 3.x, It is similar to the Adam Smith solution
list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
try:
value = int(value) #Check if it is number
except:
continue
total += value
print(total)
You can even write a function that can sum elements in nested list within a list. For example it can sum [1, 2, [1, 2, [1, 2]]]
def my_sum(args):
sum = 0
for arg in args:
if isinstance(arg, (list, tuple)):
sum += my_sum(arg)
elif isinstance(arg, int):
sum += arg
else:
raise TypeError("unsupported object of type: {}".format(type(arg)))
return sum
for my_sum([1, 2, [1, 2, [1, 2]]])
the output will be 9.
If you used standard buildin function sum for this task it would raise an TypeError.
This is a somewhat slow version but it works wonders
# option 1
def sumP(x):
total = 0
for i in range(0,len(x)):
total = total + x[i]
return(total)
# option 2
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
sumP([2,3,4]),listsum([2,3,4])
This should work nicely
user_input = input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")
print ("The list of numbers entered by user:" user_list)
ds = 0
for i in user_list:
ds += int(i)
print("sum = ", ds)
}
Using accumulator function which initializes accumulator variable(runTotal) with a value of 0:
def sumTo(n):
runTotal=0
for i in range(n+1):
runTotal=runTotal+i
return runTotal
print sumTo(15)
#outputs 120
If you are using Python 3.0.1 or above version then use below code for Summing list of numbers / integer using reduce
from functools import reduce
from operator import add
def sumList(list):
return reduce(add, list)
def oper_all(arr, oper):
sumlist=0
for x in arr:
sumlist+=x
return sumlist
Here the function addelements accept list and return sum of all elements in that list only if the parameter passed to function addelements is list and all the elements in that list are integers. Otherwise function will return message "Not a list or list does not have all the integer elements"
def addelements(l):
if all(isinstance(item,int) for item in l) and isinstance(l,list):
add=0
for j in l:
add+=j
return add
return 'Not a list or list does not have all the integer elements'
if __name__=="__main__":
l=[i for i in range(1,10)]
# l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
print addelements(l)
Output:
45
import math
#get your imput and evalute for non numbers
test = (1,2,3,4)
print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why?
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)]
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33

Categories