short way to store input variables in list - python

First of all: Yes I know, this is not what you call elegant programming, but my only target is to do it short, not readable.
Now the real problem:
I want to store an amount of x Strings in a list.
The user inputs how many Strings he wants to input and then one by one afterwards. Here's what I got so far:
print(
[
exec(
('input("text: "),' * int(input('number: ')))[:-1]
)
]
)
And this is a sample output:
number: 4
text: one
text: two
text: three
text: four
[None]
Why arent the inputs taken into account during list creation?
And how can i do this (short[er])?

Shorter and more readable.
print([input("text: ") for i in range(int(input("number: ")))])

The shortest and dumbest I could produce...
print map(input,['text: ']*input("number: "))
input("number: ") produce an str given the user input
['text: ']*input produce an array of length equal to the input, containing 'text: ' for every values
map iterate over the array and give the value to input
results are return as a list and printed
Edit Python3:
print(list(map(input,['text: ']*int(input("number: ")))))
Edit2: Saved one char for python2 thx to #Delgan

Readable > short almost every time.
In this instance, assuming you want a list of strings from the user, something like:
count = int(input("number of strings: "))
strings = []
for i in range(count):
strings.append(input("text: "))
print(strings)
should work.
In general, try to avoid exec.

Related

Find every possibility to insert random number into a string? (python)

I'm new to programming and for an exercise I need to create a list of every possibility to insert a random number (from 0 to 9) in to a string. The number can be inserted et every position in this string.
For example I have the string "Aht50rj2" and I need to find every possibility to insert one number at any position in this string (including the beginning and the end).
So far I wasn't able to find a way to solve this. What is the best way to do this?
Edit:
The Input is a String (like for example "Aht50rj2")
And the expected output is a list with all possible ways.
For example ["0Aht50rj2", "Ah1t50rj2", "Aht50rj29", "Aht501rj2", etc.]
def possibility(word):
possibilities = []
for i in range(0,10):
for j in range(len(word)+1):
H = [k for k in word]
H.insert(j,str(i))
possibilities.append(''.join(H))
return possibilities
I'm not sure what you mean but try my code and see if it worked:
import random # import module "random"
example_string = input('Input a string: ') # Asks user to input a string
length_of_string= len(example_string) # Counts how many characters there are in the string, it'll make sense trust me
example_list=[] # Create a temporary list
example_list[:0]=example_string # Get string, turns it into list
example_list.insert(random.randrange(0, length_of_string), str(random.randrange(0, 9))) # Insert a random number into a random position of the list
list_into_string= ''.join(example_list) # Get string, turns it into string
print(list_into_string) # Print result
Result number 1:
Input a string: stackoverflow
sta1ckoverflow
Result number 2:
Input a string: stackoverflow
stacko8verflow
Result number 3:
Input a string: stackoverflow
stackoverfl5ow

Repeat string in Python without multiplication

Hello, so my task is shown above in the image. I'm not asking for answers, I would just like to know how to get started on this.
My initial ideas are to:
1. Have user input str("example word")
2. Have user input int("Example number")
3. Use a for loop to read the number and then print the word out.
So far, my code is as shown below:
def repeat():
word=str(input("Please input a single word: "))
number=int(input("Please input a number: "))
for i in range(number):
number+=1
print(word,end=" ",sep='')
repeat()
However I'm running into two issues:
1. When printing the word out, the output is i.e "hello hello hello" instead of "hellohellohello"
2. I feel like I'm not exactly hitting the right points for the question.
Would appreciate any help!
This portion of your code:
print(word, end=' ', sep='')
is adding those spaces. You don't need those. Also, I'm not sure why you're incrementing the 'number' datatype. No need to do that since you're only using that for the amount of times the for loop will go based on the user input. Also, this should all be passed to a function that has two paramters: One to accept and integer and the other to accept a string. For example:
repeat(intA, strB)
Also, my suggestion would be to concatenate. Add your strings together instead of just displaying it multiple times. This will also allow you to create a new variable that will later be returned to the function that called it.
You can create function as below to repeat the string:
def repeat(text, occurrence):
new_text = ''
for i in range(occurrence):
new_text += text
return new_text
print(repeat('Hi', 4)) # sample usage
Finally you can implement your code like:
In [6]: repeat(input("Please input a single word: "), int(input("Please input a number: ")))
Please input a single word: hello
Please input a number: 5
Out[6]: 'hellohellohellohellohello'
More pythonic is to use a generator expression:
def f(s,n):
return ''.join(s for _ in range(n))
or Python's standard library:
import itertools as it
def f(s, n):
return ''.join(it.repeat(s, n))
print(f('Hi', 3))
Both produce
'HiHiHi'

Reverse Lists in Python

So I'm trying to create a program in Python that:
A) Prompts a user to enter a number a certain amount of times
B) Then stores those numbers in a list and prints them in reverse order.
This is my code:
for numbers in range (1,4):
print("Please enter a number.")
numbers = input()
numbersList = list(reversed(str(numbers)))
print(numbersList)
When I run it, it just prints <list_reverseiterator object at 0x105447da0>. And even when I tried it without adding 'reversed' in the code, instead of printing a list of ALL the numbers entered in reverse order like I want it to, it spits out the most recent number entered in list format. So if I enter '4' for a number, it just prints: ['4']. No idea why it's doing that. Any help would be appreciated. Thanks.
If I understood correctly, this is what you're looking for:
numbers = []
for i in range (1,4):
print("Please enter a number.")
numbers.append(input())
numbersList = str(numbers)
numbersList.reverse()
print (numbersList)
As commented, i is an iterator generated by range command. One way to collect 3 numbers from the user is to append them into a list, numbers in this case.
After that you can process your list outside the loop. It also seems more viable to reverse the list once it is fully created which again points to outside the loop. I use Python 2.7 so the solution is a bit different than your initial one, but the result is as intended - first it converts all the numbers to strings using map and then it reverses the list in place using reverse.
Try something like this:
numbersList = []
for numbers in range (1,4):
print("Please enter a number.")
numbersList.append(input())
numbersList.reverse()
print(numbersList)
First, you have to define numbersList. Then, you append values to in while in the loop and finally print it out.
Your issue was that you were defining the list each time you ran the for loop (3 times in the above example) and so it only had the last value. (Also, you were tying to print it out each iteration as well).
Also, a 'point of interest' - you can use input("User prompt here: ") to avoid using print() the line before.
l=[]
for _ in range(1,5):
l.append(int(input("enter the number: ")))
print(l[::-1])

Functions to receive input from user and return sum and square in python

I am a first time programmer learning Python and need to receive input from the user and return the input along with the sum and square of the entered data. I have prompted for the input and can print that but not sure how to pass the input to the sum function and square function.
Here is what I have:
def sum(list):
data = input("Enter a list of numbers or enter to quit: ")
for data in list():
return sum(list) # Not sure how to make it x*y for my list of values?
print("The sum of your list is: ", list)
and this is the same for my square function. not sure how to make:
return(list**2) #return each number in list by **2?
Your code has a lot of problems, but they're mostly pretty simple ones that trip a lot of people up their first time. Don't let them get you down.
First, you shouldn't reuse names that already have meaning like list and sum. Basically, any of the names in the table at the top of this page.
Second, you are taking in two "lists" (Not really, but we'll get there). One is being passed into your function as an argument (list in def sum(list):). The other is data in the line
data = input("Enter a list of numbers or enter to quit: ")
Third, data in the above line isn't really a list, it's a string. If you want to split data from that input up and use it as numbers later, you'll have to do that manually.
Fourth, when you use the name data again in the line for data in list() you're overwriting the information contained in the existing data variable with the elements in list(). At least you would be except that.
Fifth, list() is a function call. There is a list function in Python, and this would work, but I think you probably expect this to iterate through the list you passed into the function.
Sixth, return sum(list) will call this function again, potentially forever.
Now, how do we go about fixing this?
Thankfully, the built-in function sum can add up lists for us if we want, but first we have to get the list from the user.
def input_list():
s = input("Enter integers separated by spaces:\n")
return [int(x) for x in s.split()]
The [int(x) for x in ...] bit is something called a list comprehension
. You'll see another in a second.
This function takes input like
23 45 12 2 3
and turns it into a list of ints.
Then we can just
print(sum(input_list()))
The squares are a bit more difficult, but list comprehensions make them easy. Just
print([x**2 for x in input_list()])
Feel free to ask any followup questions if any of this is unclear.
repl for code below:
def square(numbers):
squared = []
for number in numbers:
squared.append(number**2)
return(squared)
str_of_numbers = input("Enter a list of numbers or enter to quit: ")
print("input (string):", str_of_numbers)
numbers_as_strings = str_of_numbers.split(' ') # now have a list of strings
print("list of numbers (as strings):", numbers_as_strings)
# turn list of strings into list of numbers
numbers_list = []
for number_as_string in numbers_as_strings:
numbers_list.append(int(number_as_string))
print("list of numbers: ",numbers_list, "\n")
print("The sum of your numbers is: ", sum(numbers_list)) # uses built in `sum` function
print("The squares of your numbers are:", square(numbers_list))
Output of code above:
Enter a list of numbers or enter to quit: 1 2 3
input string: 1 2 3
numbers as a list of strings: ['1', '2', '3']
list of numbers: [1, 2, 3]
The sum of your numbers is: 6
The squares of your numbers are: [1, 4, 9]
This can also be done more succinctly using map, reduce and list comprehensions.
However, this seems more appropriate, based on content of OP's question.
Firstly, you shouldn't use list as a variable name as it is actually a data type (https://docs.python.org/3/library/stdtypes.html#list).
As for doing mathematical operations on a list of numbers, I would recommend looking into numpy. It allows you to do operations on arrays as well as a lot more varied and useful mathematical functions.
For your squaring each item in the list, you could simply do the following:
import numpy as np
myList = [1,2,3,4]
print(np.square(myList))
The above code would print [ 1 4 9 16].
More information on numpy (http://www.numpy.org/) and the square function (https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.square.html).

Taking multiple integers on the same line as input from the user in python

I know how to take a single input from user in python 2.5:
raw_input("enter 1st number")
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box.
How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number:................
enter second number:.............
This might prove useful:
a,b=map(int,raw_input().split())
You can then use 'a' and 'b' separately.
How about something like this?
user_input = raw_input("Enter three numbers separated by commas: ")
input_list = user_input.split(',')
numbers = [float(x.strip()) for x in input_list]
(You would probably want some error handling too)
Or if you are collecting many numbers, use a loop
num = []
for i in xrange(1, 10):
num.append(raw_input('Enter the %s number: '))
print num
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop's level.
For instance,
data=""
while 1:
data=raw_input("Command: ")
if data in ("test", "experiment", "try"):
data2=""
while data2=="":
data2=raw_input("Which test? ")
if data2=="chemical":
print("You chose a chemical test.")
else:
print("We don't have any " + data2 + " tests.")
elif data=="quit":
break
else:
pass
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:
print(i)
a, b, c = input().split() # for space-separated inputs
a, b, c = input().split(",") # for comma-separated inputs
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
The best way to practice by using a single liner,
Syntax:
list(map(inputType, input("Enter").split(",")))
Taking multiple integer inputs:
list(map(int, input('Enter: ').split(',')))
Taking multiple Float inputs:
list(map(float, input('Enter: ').split(',')))
Taking multiple String inputs:
list(map(str, input('Enter: ').split(',')))
List_of_input=list(map(int,input (). split ()))
print(List_of_input)
It's for Python3.
Python and all other imperative programming languages execute one command after another. Therefore, you can just write:
first = raw_input('Enter 1st number: ')
second = raw_input('Enter second number: ')
Then, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:
product = int(first) * int(second)
print('The product of the two is ' + str(product))
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way.
I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]
print items
You can try this.
import sys
for line in sys.stdin:
j= int(line[0])
e= float(line[1])
t= str(line[2])
For details, please review,
https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects
Split function will split the input data according to whitespace.
data = input().split()
name=data[0]
id=data[1]
marks = list(map(datatype, data[2:]))
name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.
A common arrangement is to read one string at a time until the user inputs an empty string.
strings = []
# endless loop, exit condition within
while True:
inputstr = input('Enter another string, or nothing to quit: ')
if inputstr:
strings.append(inputstr)
else:
break
This is Python 3 code; for Python 2, you would use raw_input instead of input.
Another common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can't for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)
with open(filename) as lines:
strings = [line.rstrip('\n') for line in lines]
n = int(input())
for i in range(n):
i = int(input())
If you dont want to use lists, check out this code
There are 2 methods which can be used:
This method is using list comprehension as shown below:
x, y = [int(x) for x in input("Enter two numbers: ").split()] # This program takes inputs, converts them into integer and splits them and you need to provide 2 inputs using space as space is default separator for split.
x, y = [int(x) for x in input("Enter two numbers: ").split(",")] # This one is used when you want to input number using comma.
Another method is used if you want to get inputs as a list as shown below:
x, y = list(map(int, input("Enter the numbers: ").split())) # The inputs are converted/mapped into integers using map function and type-casted into a list
Try this:
print ("Enter the Five Numbers with Comma")
k=[x for x in input("Enter Number:").split(',')]
for l in k:
print (l)
How about making the input a list. Then you may use standard list operations.
a=list(input("Enter the numbers"))
# the more input you want to add variable accordingly
x,y,z=input("enter the numbers: ").split( )
#for printing
print("value of x: ",x)
print("value of y: ",y)
print("value of z: ",z)
#for multiple inputs
#using list, map
#split seperates values by ( )single space in this case
x=list(map(int,input("enter the numbers: ").split( )))
#we will get list of our desired elements
print("print list: ",x)
hope you got your answer :)

Categories