Find every possibility to insert random number into a string? (python) - 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

Related

How to print the reverse but as a string

I'm working on this question...and have encountered 2 problems that I am not smart enough to solve. Will you help?
Write a program that reads a list of integers, one per line, until an * is read, then outputs those integers in reverse. For simplicity in coding output, follow each integer, including the last one, by a comma.
Note: Use a while loop to output the integers. DO NOT use reverse() or reversed().
my code
user_input = int(input())
my_list = []
while True:
if user_input >= 0:
my_list.append(user_input)
user_input = int(input())
elif user_input <= 0:
print(my_list[::-1])
break
I need to stop when it hits the * but I don't know how to identify that in the code so for testing I set it to print when a negative number is entered.
I need to print the result in reverse without using reverse() but it has to be printed as a string and not a list. Can't figure out how to do that.
Check whether the input is * before converting it to an integer.
my_list = []
while True:
user_input = input('Enter a number, or * to stop')
if user_input = '*':
break
my_list.append(int(user_input))
while len(my_list) > 0:
print(my_list.pop(), end=",") # remove the last element and print it
print()
So, let's break down the the assignment:
Write a program that reads a list of integers, one per line
This means that you should have a loop that reads in values, converts them into an integer and adds them to a list.
But:
until an * is read
This means that you first have to check that the user's input was equal to "*". But, you'll have to be careful to not try to convert the user's input into an integer before you check if it's an asterisk, otherwise an error will be thrown. So, your loop would look like the following:
Get the user's input
Check if it's an asterisk. If so, break the loop.
If the user's input is not an asterisk, convert it to an int, and then add it to your list of inputted integers.
That's all you need for your first loop.
For the second loop, let's refer to the assignment:
then outputs those integers in reverse
This means that you will need a second loop; a for loop would work - you can have the loop go over a range(), except counting backwards. Here is a post about this exact thing.
Your range would start at the length of your list, minus one, because the last index of the list is one less than the number of items, since list indices start at zero.
Then, you end the range at -1, meaning the range will go down to zero, and stop, because it stops before it gets to the specified end.
Your range will count down by -1, instead of the implicit +1 by default. Refer to that post I linked if you're not sure how to do this.
Lastly, we need to actually print the items at those indices.
follow each integer, including the last one, by a comma.
To me this means that either we could output one integer per line, with a comma at the end of each line, or we could print them all in one line, separated by commas.
If you want everything to print on one line, you can just do a regular print() of the item at the current index, followed by a comma, like print(my_list[a] + ',').
But, if you want to output them on separate lines, you can set the end argument of print() to be a comma. This post explains this.
And that's it!
There are other ways to go about this, but that should be a pretty straightforward and clear way to do it.
You can check if the user input equals a string with str(user_input) == '*'.
To print it off in reverse, you could print off the last value of the string repeatedly with print(my_list[:-1]) or use my_list.pop() to take and remove the last value.
I would change around your current code to:
my_list = []
while True:
user_input = int(input())
if str(user_input) == '*':
for num in my_list:
print(my_list.pop())
break
else
my_list.append(int(user_input))

Iterate over string within list

lst = ["abc", "sassafrass", "bingo", "bass"]
My problem that I need help with is that I want to iterate through each character and count characters within each string. So I used the nested for loop......ex:
def multi_letter(s)
for c in s:
for l in c:
so basically I want to count each letter (l) in each word (c) in the list but organized as the word.....lets say that the letters have numerical value and I want to add them up...
I DON'T WANT THE ANSWER!!! Please help me find an answer......I'm lost and a beginner looking for understanding......Thanks in advance!!
You are off to a good start. The nested loop will give you each letter from each word. One way to get the numeric value is using:
ord(l)
From the documentation:
Given a string representing one Unicode character, return an integer
representing the Unicode code point of that character. For example,
ord('a') returns the integer 97.
97 is the ASCII value of the a.
You can add these values up and you will get the numerical value of the word.
But that won't be very helpful. Consider a string zz - your sum will be 244; and QQR will also give you 244. This is just one of infinite possibilities.
May be this code help you:
lst = ["abc", "sassafrass", "bingo", "bass"]
#make a empty list to store count
count=[]
for i in range(len(lst)):
count.append(len(lst[i]))
print(count)

Python: How to take multiple lines of inputed data and put it into a list

I know this is probably something incredibly simple, but I seem to be stumped.
Anyways for an assignment I have to have the user enter the number of data points(N) followed by the data points themselves. They must then be printed in the same manner in which they were entered (one data point/line) and then put into a single list for later use. Here's what I have so far
N = int(input("Enter number of data points: "))
lines = ''
for i in range(N):
lines += input()+"\n"
print(lines)
output for n = 4 (user enters 1 (enter) 2 (enter)...4 and the following is printed:
1
2
3
4
So this works and looks perfect however I now need to convert these values into a list to do some statistics work later in the program. I have tried making a empty list and bringing lines into it however the /n formating seems to mess things up. Or I get list index out of range error.
Any and all help is greatly appreciated!
How about adding every new input directly to a list and then just printing it.
Like this:
N = int(input("Enter number of data points: "))
lines = []
for i in range(N):
new_data = input("Next?")
lines.append(new_data)
for i in lines:
print(i)
Now every item was printed in a new line and you have a list to manipulate.
You could just add all the inputs to the list and use the join function like this:
'\n'.join(inputs)
when you want to print it. This gives you a string with each members of the list separated with the delimiter of your choice, newline in this case.
This way you don't need to add anything to the values you get from the user.
You could try to append all the data into a list first, and then print every item in it line by line, using a for loop to print every line, so there is no need to concatenate it with "\n"
N = int(input("Enter number of data points: "))
data = []
for i in range(N):
item = data.append(input())
for i in data:
print(i)

short way to store input variables in list

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.

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