How to delete spaces in printing the list? - python

def lexemize_Ari_Exp():
arithmeticExpression = input("Write an Arithmetic Expression: ")
list_Of_Arit_Exp = []
for x in arithmeticExpression:
list_Of_Arit_Exp.append(x)
print(list_Of_Arit_Exp)
lexemize_Ari_Exp()
#Input: x + 1
#Output: ['x', ' ', '+', ' ', '1']

If each element of the expression is divided by a space you can simply use the split() function:
def lexemize_Ari_Exp():
arithmeticExpression = input("Write an Arithmetic Expression: ")
list_Of_Arit_Exp = arithmeticExpression.split()
print(list_Of_Arit_Exp)
lexemize_Ari_Exp()
Example of output:
Write an Arithmetic Expression: x + 1
['x', '+', '1']

You can simply add an if statement like this:
for x in arithmeticExpression:
if not x == ' ':
list_Of_Arit_Exp.append(x)
This is because your for loop iterates on every single character of the input string, and x just represents the character in each iteration.

def remove (list, toRemove):
for i in range (0, list.count (toRemove)):
list.pop (list.index (toRemove))
return list
Use this function to remove the elements you want from a list
list = [0, 1, 0]
print (remove (list, 0))#Remove all the 0 from the list
Works with every type (int, float, string...)

Related

How to transform a string into a list of char and int using a list comprehension in Python

Given the following string:
"[10,20]"
I want to create the following list using a list comprehension in Python:
['[', 10, ',', 20, ']']
Being 10 and 20 integers and the rest of the elements in the list chars.
I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:
Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.
However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?
Group by whether this character is numeric or not. This can be done using the str.isnumeric function as the key argument to groupby().
s = "[10,20]"
g = itertools.groupby(s, key=str.isnumeric)
Then, for the True groups, convert it to an integer. Leave False groups as-is.
Since the values of the groupby are iterators where each element is a separate character, you need to join it with "" to convert it into a single string, and optionally convert that string to an integer.
lst = [int("".join(chars)) if is_numeric else "".join(chars) for is_numeric, chars in g]
Which gives:
['[', 10, ',', 20, ']']
In one line:
lst = [ int("".join(chars))
if is_numeric else "".join(chars)
for is_numeric, chars in itertools.groupby(s, key=str.isnumeric)
]
This can also be done with regex with ease.
import re
NUMCHR = re.compile(r'\d+|[^\d]') #consecutive digits OR one "not-a-digit"
data = '[10,20]'
out = [int(m[0]) if m[0].isdigit() else m[0] for m in NUMCHR.finditer(data)]
print(out) #['[', 10, ',', 20, ']']
.finditer (in this case) will return either consecutive numbers or only 1 character on each iteration. We just check the return and proceed accordingly.
Use str.isdigit as your grouping key and convert groups that have a key of True to integers:
from itertools import groupby
s = "[10,20]"
r = [[str,int][k]("".join(g)) for k,g in groupby(s,key=str.isdigit)]
print(r)
['[', 10, ',', 20, ']']
You could also use reduce from functools:
from functools import reduce
def fun(x, y):
if isinstance(x[-1], str) and x[-1].isdigit():
x[-1] = x[-1] + y if y.isdigit() else int(x[-1])
else:
x += [y]
return x
reduce(fun, '[10,[20,30]]', [''])[1:]
Out[]: ['[', 10, '[', 20, 30, ']']
Another approach may be to use recursion:
def fun_recurse(y, x=None):
if x is None:
x = ['']
if len(y) == 1:
return x[1:] + [y]
if isinstance(x[-1], str) and x[-1].isdigit():
x[-1] = x[-1] + y[0] if y[0].isdigit() else int(x[-1])
return fun_recurse(y[1:], x)
else:
return fun_recurse(y[1:], x + [y[0]])
fun_recurse('[10,[20,30]]')
Out[]: ['[', 10, '[', 20, 30, ']']

How would I reference something akin to an input more than once with list comp in Python?

For example, this simple code for outputting the middle character of a word - if it has a middle character.
string = str(input("String: "))
print(list(letter for letter in string if letter == string[((len(string) - 1) // 2)]))
Could I have the input inside of the list comp whilst still being able to reference the length of it in another part? Usually I do something like this with my inputs in list comp:
print(''.join(str(y) for y in [x for x in str(input("Please enter a string: "))
if x.isnumeric() == False]))
Just wanting to learn more about list comp's possibilities.
One approach is to store it inside its own list and unpack it using for
string = input("String: ")
would become
for string in [input("String: ")]
>>> print([letter for string in [input("String: ")] for letter in string if letter == string[(len(string) - 1) // 2]])
String: abcde
['c']
formatted over multiple lines:
>>> print(
... [letter for string in [input("String: ")]
... for letter in string
... if letter == string[(len(string) - 1) // 2]]
... )
Also, your logic may have undesired behaviour.
String: abcdecccccc
['c', 'c', 'c', 'c', 'c', 'c', 'c']
If I wanted to cram something like this onto one line I'd use a lambda:
>>> print((lambda x: x[(len(x) - 1) // 2])(input()))
middle
d
In this case I think readability is vastly improved by doing the variable assignment on its own line, though.

How to input negative numbers into a list

I require some help since whenever I input a negative number the list it interprets it as a separate element so once it gets to sorting it puts all the negative symbols at the beginning. The end goal of the code is to sort 2 merged lists without using the default sort functions. Also if there is a better way to get rid of spaces in a list I would appreciate it, since at the moment I have to convert the list to a string and replace/strip the extra elements that the spaces cause.
list1 = list(input())
list2 = list(input())
mergelist = list1 + list2
print(mergelist)
def bubble_sort(X):
nums = list(X)
for i in range(len(X)):
for j in range(i+1, len(X)):
if X[j] < X[i]:
X[j], X[i] = X[i], X[j]
return X
mergelist = bubble_sort(mergelist)
strmergelist = str(mergelist)
strmergelist = strmergelist.replace("'", '')
strmergelist = strmergelist.replace(",", '')
strmergelist = strmergelist.strip('[]')
strmergelist = strmergelist.strip()
print(strmergelist)
The output for lists with no negatives is:
1 2 3 4 4 5 5
However with negatives it becomes:
- - - - 1 2 3 3 4 4 5
and my first print function to just check the merging of the lists looks like this when I input any negatives (ignore the spaces since I attempt to remove them later):
['1', ' ', '-', '2', ' ', '3', '3', ' ', '-', '4', ' ', '-', '4', ' ', '-', '5']
list() doesn't parse a string to a list of integers, it turns an iterable of items into a list of items.
To read a list from the console, try something like:
def read_list():
"""
read a list of integers from stdin
"""
return list(map(int, input().split()))
list1 = read_list()
list2 = read_list()
input.split() reads one line of user input and will separate it by whitespace - basically to words.
int() can convert a string to an integer.
map(int, ...) returns an iterable which applies int() to each "word" of the user input.
The final call to list() will turn the iterable to a list.
This should handle negative numbers as well.
Additionally, I see that you want to print the resulting list without extra character. I recommend this:
print(' '.join(mergelist))

How to remove the single quotation mark from a list in Python

I am trying to remove the single quotation marks from this list:
list = ['amazed, 10']
and convert it to
list = ['amazed', 10]
I used list= [x.strip('') for x in list] but it does not work.
Is there a workaround?
Thanks in advance!
You need to split but not strip, as your list contains a single string 'amazed, 10' that expected to be split into 2 items - 'amazed' and 10:
lst = ['amazed, 10']
lst = [int(i) if i.isdigit() else i for i in lst[0].split(', ')]
print(lst)
The output:
['amazed', 10]
You can try:
>>> l = ['amazed, 10']
>>> l = l[0].split(", ")
>>> l
['amazed', ' 10']
as it is a single item in the list, u can split the string using split() method.
list=list[0].split(', ')
it will give two separate strings.
First you need to split your list to two elements. Next, strip white space and than convert the second element (a string of number) to number (Iv'e converted it to integer but you can convert to float or whatever).
ll = ['amazed, 10']
ll = ll[0].split(",")
ll[1] = int(ll[1].strip())
Try:
lst = ['amazed, 10']
lst = [int(i) if i.isdigit() else i for i in lst[0].replace(',', '').split()]

Convert a list into a string and allow for a separator

please be aware, im new to python:
i'm trying to create a defined function that can convert a list into a string, and allows me to put a separator in. The separator has to be ', '.
My current thought process is to add each item from a list to an empty string variable, and then I'm trying to make use of the range function to add a separator in. I'm only wanting to use str() and range().
def list2Str(lisConv, sep = ', '):
var = ''
for i in lisConv:
var = var + str(i)
#test line
print(var, "test line")
var1 = int(var)
for a in range(var1):
print(str(var1)[a], sep = ', ')
list1 = [2,0,1,6]
result = list2Str(list1, ', ')
print(result)
First you need to convert the list of int to a list of string.
You can use list comprehension : https://docs.python.org/3/tutorial/datastructures.html
str_list = [str(x) for x in list1]
Then, join the list of string with the separator you want.
sep = ', '
print(sep.join(str_list))
In a more concise way:
print(', '.join([str(x) for x in [1, 2, 3]))
More information about join here: http://www.diveintopython.net/native_data_types/joining_lists.html
list=['asdf', '123', 'more items...']
print ', '.join([str(x) for x in list])
If you wanted to create your own function to convert you could do the following.
def convert(list, sep):
n_str = ''
for index, I in enumerate(list): #enumerate(list) returns (current position, list[current position]) so if we need to know the current position we use enumerate
if index != len(list)-1:
n_str += str(i) + sep #we don't apply the seperator if we're at the end of the list
else:
n_str += str(i)
return n_str
If no string methods (like join) are allowed, reduce should offer the shortest solution:
def list2Str(lisConv, sep = ', '):
return reduce(lambda x, y: str(x) + sep + str(y), lisConv)
print(list2Str([2, 0, 1, 6], ', '))
# 2, 0, 1, 6

Categories