Join items of a list with '+' sign in a string - python

I would like my output to be :
Enter a number : n
List from zero to your number is : [0,1,2,3, ... , n]
0 + 1 + 2 + 3 + 4 + 5 ... + n = sum(list)
Yet my actual output is :
Enter a number : 5
List from zero to your number is : [0, 1, 2, 3, 4, 5]
[+0+,+ +1+,+ +2+,+ +3+,+ +4+,+ +5+] = 15
I'm using join as it's the only type I know.
Why are the plus signs printed around the items and why are they surrounding blank spaces?
How should I print the list's values into a string for the user to read ?
Thank you. Here's my code :
##Begin n_nx1 application
n_put = int(input("Choose a number : "))
n_nx1lst = list()
def n_nx1fct():
for i in range(0,n_put+1):
n_nx1lst.append(i)
return n_nx1lst
print ("List is : ", n_nx1fct())
print ('+'.join(str(n_nx1lst)) + " = ", sum(n_nx1lst))

Change each individual int element in the list to a str inside the .join call instead by using a generator expression:
print("+".join(str(i) for i in n_nx1lst) + " = ", sum(n_nx1lst))
In the first case, you're calling str on the whole list and not on individual elements in that list. As a result, it joins each character in the representation of the list, which looks like this:
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'
with the + sign yielding the result you're seeing.

You don't need to call str on your list. That returns the str representation of your list and the output of that is joined with '+'.
You can instead use map to convert each item in your list to str, then join:
print('+'.join(map(str, n_nx1lst)) + " = ", sum(n_nx1lst))
You can also use the new style formatting to have a more readable output:
result = '+'.join(map(str, n_nx1lst))
print("{} = {}".format(result, sum(n_nx1lst)))

What you need to do is concatenate a string element with ' + ' for each element in your list. All you need from there is to have some string formatting.
def sum_of_input():
n = int(raw_input("Enter a number : ")) # Get our raw_input -> int
l = range(n + 1) # Create our list of range [ x≥0 | x≤10 ]
print("List from zero to your number: {}".format(l))
print(' + '.join(str(i) for i in l) + ' = {}'.format(sum(l)))
Sample output:
>>> sum_of_input()
Enter a number : 10
List from zero to your number: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
How does it work?
We use what's called a list comprehension (5.1.3) (generator in this specific usage) to iterate over our list of int elements creating a list of string elements. Now we can use the string method join() to create our desired format.
>>> [str(i) for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
>>> ' + '.join(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
'1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10'

Using f-string :
n_put = range(int(input("Choose a number : ")))
res = sum(n_put)
print ("List is : ", [*n_put])
print(*n_put, sep="+", end = f" = {res}")
gives
Choose a number : 5
List is : [0, 1, 2, 3, 4]
0+1+2+3+4 = 10

Related

Creating code to make sum of array elements with variable

I want to create a code that has the variable how many elements you take from an list and sum those. For example, if I type in 3, it takes the first 3 elements of an array and addes them together.
Preferably in some for loop but who knows what kind of creative solutions I get :)
x = [1, 3, 4, 2, 6, 9, 4]
Amount = 3
Sum = 0
Sum += x[Amount-3] + x[Amount-2] + x[Amount-1]
Desired result: 8
Amount_2 = 4
Sum = 0
Sum += x[Amount-4] + x[Amount-3] + x[Amount-2] + x[Amount-1]
Desired result: 11
Hope this explains it well.
x = [2, 6, 7, 7, 12] # your list here
amount = int(input("Enter amount: "))
print(f'desired result: {sum(x[:amount])}')

.join() gives back list as a result in python

Could someone, please, explain why .join() behaves in the following way:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)
And the result is:
[ 1 , 0 , 5 , 3 , 4 , 1 2 , 1 9 ]
Not only is there still a list, but also an additional space.
How come?
When I use map() it works:
a = " ".join(list(map(str, input)))
But I would like to know what is wrong with the .join method I'm using.
str(input) returns one string '[1, 0, 5, 3, 4, 12, 19]', so then join uses each character of the string as input (a string is an iterable, like a list), effectively adding a space between each.
The effect is more visible if we join with a -: '[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'
In contrast, list(map(str, input)) converts each number to string, giving a list of strings (['1', '0', '5', '3', '4', '12', '19']), which join then converts to '1 0 5 3 4 12 19'
See #mozway's answer to understand .join()'s behavior.
To get what you want (using join), you should try this:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join([str(i) for i in input])
print(a)
Output:
1 0 5 3 4 12 19

Convert string with hard coded line breaks into matrix in python

I am trying to create a class that takes a string of digits with hard coded line breaks and outputs a matrix and details about that matrix. In the first instance i just want to be able to create the matrix but I am struggling. I'm aware that I could probably do this very easily with numpy or something similar but trying to practice.
class Matrix:
def __init__(self, matrix_string):
self.convert_to_list = [int(s) for s in str.split(matrix_string) if s.isdigit()]
self.split = matrix_string.splitlines()
I think i want to combine the two things I have already done but I cant figure out how to apply my convert_to_list method to every element in my split method.
Getting very confused.
SAMPLE INPUT/OUTPUT
Input = " 1 8 7 /n 6 18 2 /n 1 9 7 "
Desired Output = [[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It looks like you want a list of lists. For that you can use nested list comprehension.
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
lst = [[int(x) for x in r.split()] for r in s.split('/n')]
print(lst)
Output
[[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It's not that hard actually:
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
print([i.split() for i in s.split('/n')])
easier way but longer:
s = s.split('/n')
new = []
for i in s:
new.append(i.split())
print(new)
output:
[['1', '8', '7'], ['6', '18', '2'], ['1', '9', '7']]

Assigning numbers to given string's letters

I am currently trying to finish a project which wants encode given paragraph using given matrix. I wanted to start make a letter list:
letterlist = np.array([" ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"])
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY"
My goal is convert the letters to integer in order like A=1,B=2...Z=26 and " "=0. Then assign them to 1x3 arrays. like
But I couldn't even make a progress. First I tried make for loops to match same letter in the letter list and samplestr. Then if they are same, give the order in the letterlist as integer. But I didn't get any output.
for letter in samplestr:
for letter2 in letterlist:
if letter2==letter:
print("x") ## To see if I get any match
I don't know where did I wrong and how should I continue this. Would making dictionary make it easier to assign letters to integers? Need some advices. Thanks for your time.
The conversion to a number is done by converting the char to a ordinary number and then subtracting 64 because that is the starting ASCII-Index for 'A'
Code looks like this:
from math import ceil
samplestr = "MEET ME MONDAY"
# Pad string to be dividable by 3
samplestr = samplestr.ljust(ceil(len(samplestr)/3) * 3)
# "MEET ME MONDAY "
# Convert to number reprensentation
samplestr = [0 if c == ' ' else (ord(c)-64) for c in samplestr]
# [13, 5, 5, 20, 0, 13, 5, 0, 13, 15, 14, 4, 1, 25, 0]
# Split in chunks of 3
matrix = [samplestr[i:i+3] for i in range(0, len(samplestr), 3)]
print(matrix)
This produces the following output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Yes, dictionary will make it easier to assign letters to integers but if your final goal is to convert the letters to integer in order like A=1, B=2...Z=26 and " "=0, then assigning indices to the letters will also do the job.
I don't have much knowledge of numpy, so I will do it simply like this:
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY "
l = []
s = []
for i in samplestr:
s.append(letterlist2.index(i))
if len(s) == 3:
l.append(s)
s = []
if s != []:
l.append(s)
print(l)
Output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Use a dictionary (with a single list comprehension) to convert the letters to numbers (would probably be the fastest) and then reshape to have 3 columns (-1 will take care of number of rows):
convert = dict(zip(letterlist, np.arange(27)))
converted = np.array([convert[char] for char in samplestr])
#[13 5 5 20 0 13 5 0 13 15 14 4 1 25]
from math import ceil
#resize to closes upper multiple of 3
converted.resize(ceil(converted.size/3)*3)
#reshape to have 3 columns
converted = converted.reshape(-1,3)
output:
[[13 5 5]
[20 0 13]
[ 5 0 13]
[15 14 4]
[ 1 25 0]]
Here is another solution with a simple dictionary mapping and list comprehensions. Note that you don't need to hardcode letters, it's in the standard library.
from string import ascii_uppercase
chars = " " + ascii_uppercase
encode = {char:"{}".format(i) for i, char in enumerate(chars)}
def str2num(s):
return [[encode[char] for char in s[i:i+3]] for i in range(0, len(s), 3)]
s = "MEET ME MONDAY"
print(str2num(s))
which returns:
[['13', '5', '5'],
['20', '0', '13'],
['5', '0', '13'],
['15', '14', '4'],
['1', '25']]

Getting rid of commas in a list [duplicate]

This question already has answers here:
Python - Print items in list with neither commas nor apostrophes
(2 answers)
Closed 5 years ago.
Here is my program:
def Prob2( rows, columns ):
for i in range(1, rows+1):
print(list(range(i, (columns*i)+1, i)))
Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))
Essentially, it takes a user input of rows and columns and, based on those inputs, makes lists of multiples starting with 1.
For example, if the user typed in 4 rows and 5 columns, the program would output something like this:
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
The problem I have is that I need to get rid of the commas and only have spaces between the numbers. Is this possible?
As your title specifies :
Getting rid of commas in a list
I'll give the general version of it.
>>> l = [1,2,3,4]
>>> l
[1, 2, 3, 4]
>>> s = ' '.join(str(x) for x in l)
>>> s
'1 2 3 4'
Here since the list contains int, we use list comprehension to convert each individual into str before joining.
Suppose the list contained str, we can directly do :
>>> l = ['1','2','3','4']
>>> l
['1', '2', '3', '4']
>>> s = ' '.join(l)
>>> s
'1 2 3 4'
def Prob2( rows, columns ):
for i in range(1, rows+1):
print('['+' '.join(str(val) for val in range(i, (columns*i)+1, i))+']')
Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))
output:
[1 2 3 4 5]
[2 4 6 8 10]
[3 6 9 12 15]
[4 8 12 16 20]
Could just convert your lists to strings and remove your commas with the re.sub() method.
import re
def Prob2(rows, columns):
for i in range(1, rows + 1):
numbers = re.sub(",", "", str(range(i, (columns * i) + 1, i)))
print(numbers)
Prob2(rows=int(input("Enter number of rows here: ")),
columns=int(input("Enter number of columns here: ")))
Output:
[1 2 3 4 5]
[2 4 6 8 10]
[3 6 9 12 15]
[4 8 12 16 20]
You can do it like so:
def Prob2( rows, columns ):
for i in range(1, rows+1):
print('['+', '.join(map(str, list(range(i, (columns*i)+1, i))))+']')
Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))
Using ' '.join() is a trick that allows you to convert a list to a string where map(str, <list>) iterates over each value in that list and apply the str() function on it.

Categories

Resources