How to join list elements into strings? - python

I have a list here where I only need to input 10 letters or strings. I am having a problem separating the list.
print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = ' '.join([str(item) for item in num_string])
print (string)
In my code, for example, I inputted a b c d e f g h i j since it is only 10 inputs. Instead of having an output like a b c d e f g h i j because I used the join method, I want to have a NewLine for every list. So I want it to be like
a
b
c
d
e
f
g
h
i
j

You are almost there just instead of joining a whitespace, join a newline, also you don't need to convert each element to string because each element is a string already because input always returns a string (in Python3) (so this is redundant: str(input()), it is the exact same as: input()):
string = '\n'.join(num_string)
Complete example (removed the redundant str):
print("Please input letter: \n")
num_string = []
num = 10
# the 0 isn't necessary either but
# I guess for clarification it can stay
for i in range(0, num):
element = input(str(i + 1) + ". ")
num_string.append(element)
string = '\n'.join(num_string)
print(string)
Alternatively you can use this (instead of the last two lines in the above code example):
print(*num_string, sep='\n')
And if you really want to shorten the code (it can be as short as 3 lines):
print("Please input letter: \n")
num = 10
print('\n'.join(input(f'{i + 1}. ') for i in range(num)))

print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = '\n' .join([str(item) for item in num_string])
print (string)
Use '\n' , it is like a breakline in your output

Related

Return values from dictionary?

I am having a lot of trouble understanding this problem. I need to enter a string in the format of 2X+4Y (e.g number + letter, can be two letters such as HE, +number + letter
if the input value is 2X+4Y Then return the value should be x2y4. The values need to be distinct and need to match the dictionary symbol and be positive integers.
#enter a string in form xA + yB +zC
#x, y, z are postive integers
#A,B,C are distinct symbols of elements (2H + 1O + 1C)
symbol = {"H":1,"He":4, "Li":7, "Be":9, "B":11, "C":12, "N":14, "O":16, "F":19, "Ne":20}
def stoi_coefficent(final_input): # this will only work when letter inputs are 'H', 'O' rather than 'HE'
output=[]
for i in final_input:
output+= i[1::2]
output+=i[0: :2]
print(output)
return output
def Convert(output):
output_dct = {output[i]: output[i + 1] for i in range(0, len(output), 2)}
print(output_dct)
return output_dct
def check_if_in_symbol(output):
active = True
while active:
for i in output:
if i not in symbol or i not in numbers:
print('enter another symbol or number')
else:
active=False
continue
a = (stoi_coefficent(final_input))
print(output)
print(Convert(output))
b = (check_if_in_symbol(a))
while True:
user_input = input('\nEnter a string in the format of xA + yB + zC: ') # "4Ne + 1Be + 2Li"
split_str = user_input.replace(" ", "").split("+")
try:
pairs = [str_parser(userstr) for userstr in split_str]
check_elements(pairs)
except ValueError:
continue
final_result = swap(pairs)
print(f"Final Result: {final_result}")
break
I have tried various other ideas but I think I need to make the input into a dictionary. But how do I make a dictionary when the split function makes a list in the format of [2x,4y]
and how would I use a comparative operator when the numbers and letters are one list item?
Based on your recent comments, you should edit your question to be something like this:
Question
I want to take input from the user in the form of xA + yB + zC.
And I want an output like this AxByCz.
They should be able to enter any number of combinations.
If x, y, or z are 1, I want to exclude them.
For example:
4Ne + 1Be + 2Li
Ne4BeLi2
If the first number of every element isn't a positive integer or the element isn't a key in the SYMBOLS dict below, I want to print an error message and have the user try again.
SYMBOLS = {"H":1,"He":4, "Li":7, "Be":9, "B":11, "C":12, "N":14, "O":16, "F":19, "Ne":20}
Here's what I tried:
My code here
Problem I'm having here.
Answer
If you can't use other modules, you'll need to make your own string parser.
There are many different ways to do it, but here's one way, including a loop that starts over whenever the user enters invalid input:
SYMBOLS = {"H":1,"He":4, "Li":7, "Be":9, "B":11, "C":12, "N":14, "O":16, "F":19, "Ne":20}
def str_parser(userstr):
if not userstr:
print("Empty string detected. Please try again.")
raise ValueError()
first_char = userstr[0]
if not first_char.isdigit():
print(f"First digit of element must be a positive integer: {userstr}. Please try again.")
raise ValueError()
index = 1
lastindex = 1
digits = []
char = first_char
while char.isdigit():
digits.append(char)
try:
next_char = userstr[index]
except IndexError:
break
else:
char = next_char
lastindex = index
index += 1
coefficent = "".join(digits)
return coefficent, userstr[lastindex:]
def check_elements(pairs):
for _, element in pairs:
if element.capitalize() not in SYMBOLS:
print(f"Element not recognized: {element}. Please try again.")
raise ValueError()
def swap(pairs):
final_str = ""
for coeff, element in pairs:
if int(coeff) < 2:
final_str += element
else:
final_str += element+coeff
return final_str
while True:
user_input = input('\nEnter a string in the format of xA + yB + zC: ') # "4Ne + 1Be + 2Li"
split_str = user_input.replace(" ", "").split("+")
try:
pairs = [str_parser(userstr) for userstr in split_str]
check_elements(pairs)
except ValueError:
continue
final_result = swap(pairs)
print(f"Final Result: {final_result}")
break
# Ne4BeLi2
You can split the input as you do (user_input.split('+')), then apply this to each element in the list to split numbers from letters.
Product code looks like abcd2343, how to split by letters and numbers?
You then have the symbols and numbers which you can check for validity separately.

how to extract a sentence from string in python using simple for loop?

str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")

Sum of Digits in a specific way in Python

I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()

How to display A B C D E if a input 5 numbers 1 2 3 4 5

import random
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(ltr.strip())
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
var1 = random.randrange(1,26)
var2 = random.randrange(1,26)
var3 = random.randrange(1,26)
var4 = random.randrange(1,26)
var5 = random.randrange(1,26)
print(var1,var2,var3,var4,var5)
What I want to do is when I input numbers from 1 to 26 it should display a corresponding result. As you can see, the user must input 5 numbers. For example, if we input 1 2 3 4 5 the result must be A B C D E. Also, we have random numbers. For example, if our random numbers are 4 5 3 1 2 the result must be D E C A B.
I don't know what to do to display the result.
random.randrange(1,26)
This is wrong. Random's second parameter is non-inclusive, meaning you'll get numbers from 1 to 25.
You should use:
random.randrange(1, len(ltr))
Then your result letter is just accessing the correct index in your ltr string - simply doing ltr(var1)
As for user input, you need to invert it to integer values like this:
a = int(input(''))
strip() your ltr and find element at (entered_position-1) , repeat for five times ,and join the list separated by a space
ltr = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(' '.join([ltr.strip()[int(input('number 1-26: '))-1] for _ in range(5)]))
print(' '.join([ltr.strip()[random.randrange(1,27)-1] for _ in range(5)]))
What you want to do is to print the letter in the alphabet which is at the position the user entered. In other words, the user enters the index of that letter inside the alphabet. Since you can access a character inside a string using its index in python using letter = string[index] you can do this:
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
print(ltr[a], ltr[b], ltr[c], ltr[d], ltr[e])
Note that due to the space at the start of ltr, A will be output when entering 1.
Edit: Update according to question in comments.
You can sort the inputs if you put them in a list and sort() them. Then you can get the characters at the positions from the input list:
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
inputs = []
for _ in range(5):
inputs.append(int(input("Enter a number:")))
inputs.sort()
print(', '.join(map(str, inputs)))
print(', '.join(ltr[i] for i in inputs))

How to change the following output into a proper string?

I'm trying to code a chatbot that will print a string containing n times the first letter of my name, followed by "n" and then followed by n-1 times the second letter in my name.
Example:
name: chris
n = 5 (since there are 5 letters in the name)
n-1 = 4
first letter of the name: c
second letter of the name: h
The string I want to generate: ccccc5hhhh
My problem: The string generated is in brackets which I don't want. I want the string to be exactly as "ccccc5hhhh", no spaces; all in one line, but I keep getting ['c','c','c','c','c']5['h','h','h','h'] as the output.
st1 = input("First name? ==> ")
print("Please enter the first letter of your name")
letter = input ("First letter? ==>? ")
if (letter == st1[0]):
# initializing list of lists
test_list = st1[0]
test_list1 = st1[1]
# repeat letters n times
res = [ele for ele in test_list for i in range(len(st1))]
res2 = [ele for ele in test_list1 for i in range(len(st1)-1)]
# printing result
print(str(res), len(st1), str(res2))
You are looking for the join function. Using , with your arguments will insert a space though.
To get the result you are looking for you will want:
print(''.join(res) + str(len(st1)) + ''.join(res2))
Instead of converting your lists into string you can use the .join() function, like so ''.join(res)
So you final line should be:
print(''.join(res) + str(len(st1)) + ''.join(res2))
You're overcomplicating this. Just use string multiplication.
s = 'chris'
n = len(s)
res1 = s[0] * n
res2 = s[1] * (n - 1)
print(res1 + str(n) + res2) # -> ccccc5hhhh

Categories