Cartesian product from list of Strings - string

To answer this question you need to write code that will produce
a list of strings that contains all combinations that can be made
from two input lists by taking an element from the first list and
following it by an element of the second list (with a space in between).
The ordering of elements in the new list should be determined
primarily the the ordering in the first list and secondarily
(for elements with the same same first part) by the ordering
of the second list.
So, if the first input is of the form: A, B, .. X
and the second is of the form: 1, 2, .. n
the output would be of the form:
["A 1", "A 2", .. "An", "B 1", "B 2", .. "Bn", .. "X 1", "X 2", .. "Xn"]
(where the ".." indicates there can be more elements in between).
NOTES:
1. There can be different numbers of elements in the two lists.
2. If the first list has M elements and the second list has N elements,
then the output list should have M*N elements.
""" )
print("INPUT:")
listA=[] #Creating a list
listB=[]#Creating a second list
listC=[]
while True:
print("add element y to continue")
if input()!='y':
break
else:
print("keep adding or x to break" )
while True:
if input=='x':
break
else:
input_listA = input( "Enter first comma separated list of strings: " )
print(n)
listA.append(input_listA)
print(input_listA)
print(listA)
if input=='x':
break
else:
input_listB=input( "Enter second comma separated list of int: " )
input_listB.split()
listB.append(input_listB)
break
however when i right words it for instance ["black ham ", "twice mouse", "floating cheese", "blue elf", "electric elf", "floating elf"] in the calculation for the cartesian product will be calculatin characters not words like 'b', 'l','a','c','k' how can i make the strings words inside the list and also how can i print it in the form of i mean without commas because as you can see i input delimiter along the strings

Try this:
import itertools
a = input("Enter first comma separated list of strings: ")
b = input("Enter second comma separated list of strings: ")
result = []
for i in itertools.product(a.split(","), b.split(",")):
result.append("".join(map(str, i)))
print(result)
Result:
~ $ python3 test.py
Enter first comma separated list of strings: aa,bb
Enter second comma separated list of strings: 1,2,3
['aa1', 'aa2', 'aa3', 'bb1', 'bb2', 'bb3']
If you'd rather like a space between the two words in each pair, change
result.append("".join(map(str, i)))
to
result.append(" ".join(map(str, i)))
Output:
['aa 1', 'aa 2', 'aa 3', 'bb 1', 'bb 2', 'bb 3']

Related

Suppose we have a list of 3-letter words with 3 elements, but each word is also a list. The function return the character at the given index

Suppose we have a list of 3-letter words with 3 elements, but each word is also a list. See example below:
word_list = [ ['r','e','d'] , ['p','e','a'] , ['z','i','p'] ]
Create a function named getCharacterAt that accepts 2 arguments - word_list and index_of_character. The function should be able to return the character at the given index. (If index_of_character is 3, we get 3rd letter in the whole list which is 'd'. If it is 5, we get 'e'. If 9, we get 'p'.
word_list = [ ['r','e','d'] , ['p','e','a'] , ['z','i','p'] ]
new_word_list = []
for i in word_list:
new_word_list = new_word_list + i
def getCharacterAt(word_list: list, index_of_character: int):
return word_list[index_of_character - 1]
print(getCharacterAt(new_word_list, 3))
# Output: d
In this case, I have created a 'new_word_list' with the union of each element of 'word_list'. Then, following your description, you just return the index - 1 element of the request (remember that first list index is 0)

How to modify list of lists using str.format() so floats are 3 decimals and other data types remain the same

I have a list of lists that is very big, and looks like this:
list_of_lists = [[0,'pan', 17.892, 4.6555], [4, 'dogs', 19.2324, 1.4564], ...]
I need to modify it using the str.format() so the floats go to 3 decimal places and the rest of the data stays in its correct format. I also need to add a tab between each list entry so it looks organized and somewhat like this:
0 'pan' 17.892 4.655
4 'dogs' 19.232 1.456
...
And so on.
My problem is that I keep getting the error in my for loop and gow to fix it.
for x in list_of_lists:
print ("{:.2f}".format(x))
TypeError: unsupported format string passed to list.__format__
In your loop you are iterating through a nested list. This means that x is also a list itself, and not a valid argument to the format() function.
If the number of elements in the inner lists are small and it makes sense in the context of the problem, you can simply list all of them as arguments:
list_of_lists = [[0,'pan', 17.892, 4.6555], [4, 'dogs', 19.2324, 1.4564]]
for x in list_of_lists:
print ("{:d}\t{:s}\t{:.3f}\t{:.3f}".format(x[0], x[1], x[2], x[3]))
These are now tab delimited, and the floats have three decimal places.
for x in list_of_lists:
print ("{:.2f}".format(x))
This is only looping over the top level array - not the elements inside - therefore you are getting the error.
Try addressing the element individually
# build manually, join with tab-char and print on loop
for i in s:
result = []
result.append( f'{i[0]}' )
result.append( f'{i[1]}' )
result.append( f'{i[2]:.3f}' )
result.append( f'{i[3]:.3f}' )
print( '\t'.join(result) )
# build in one line and print
for i in s:
print( f'{i[0]}\t\'{i[1]}\'\t{i[2]:.3f}\t{i[3]:.3f}'
Or as a list comprehension
# build whole line from list comprehension, join on new-line chat
result = [f'{i[0]}\t\'{i[1]}\'\t{i[2]:.3f}\t{i[3]:.3f}' for i in s]
result = '\n'.join(result)
print(result
# all in one line
print( '\n'.join([f'{i[0]}\t\'{i[1]}\'\t{i[2]:.3f}\t{i[3]:.3f}' for i in s]))

Python inputs using list comprehensions

n = int(input("Enter the size of the list "))
print("\n")
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:n]
print("User list: ", num_list)
can anyone explain this ...... i.e how it will work.THANKYOU
The workflow is once you enter the size of the list value will be stored in variable 'n' and n printed in the interpreter.
n = int(input("Enter the size of the list "))
print("\n")
In the list comprehension input().strip().split() is executed first i.e once you entered data is striped(removed leading and trailing spaces) and split data by space(default behavior) . then you entered data is iterated by iter variable (num) and num was converted into an integer as well as stored in num_list. Then finally you got num_list contains elements as int type.
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())
finally, list slicing as before n elements are returned into num_list.
num_list[:n]
Without list comprehension of how the above code works like......
num_list=[]
n = int(input("Enter the size of the list "))
print("\n")
for num in input("Enter the list items separated by space ").strip().split()):
num_list.append(int(num))
num_list=num_list[:n]
in one short in list comprehension every element in input is iterated by loop and typecasting it into int and before nth index elements are stored into num_list.

Sort a list of strings and numbers in Python

I am trying to sort a list of strings. Each string contains numbers and letters and they are separated by space. I want to sort the list based on the numbers.
Example code:
list=["x 10","y 20"]
You may sort with the help of a lambda:
list = ["x 10", "y 20", "z 15"]
list_sorted = sorted(list, key=lambda x: int(x.split()[1]))
print(list_sorted) # ['x 10', 'z 15', 'y 20']
In the snippet above, the lambda expression splits each list element by space, and then casts the second element to an integer. It is this value which is then used to sort the list.
l=["x 10","y 20","z 15"]
n=len(l)
for i in range(n-1):
for j in range(n-i-1):
if int(l[j].split()[1])>int(l[j+1].split()[1]):
l[j],l[j+1]=l[j+1],l[j]
print(f"sorted{l}")

Keeping tracks of the first digit of similar items in a list Python

For example,
lst = ['120 abc','123 abc','256 abc','125 bcd','326 bcd','426 bcd']
I want to count how many time 2 is the second digit in each item.
In the lst above:
2 occurs 2 times for items ending in abc
2 occurs 3 times for itmes ending in bcd
My question is related to an assignment on Benford's law. The text file given is structured similar to the lst above. The numbers represent ballots count and the letters represent name of cities.
My program reads the file and put each ballots count and the corresponding city as an item in a list.
Since each item in the list is a string, i know to to index through each item for the desired digit, and count the number of occurrences. But i don't know how to separate each item into similar group of items.
I'm an absolute beginner to programming. I'm not looking for actual codes but ideas on how to approach the problem.
Indexing helps you to rapidly retrieve an element of a sequence. First item has always the zero index. Both list and string are sequences, so:
>>> lst[2]
'256 abc'
>>> lst[2][1]
'5'
With the knowledge of indexing you can easily get all the second characters of a list in a new list with a generator expression:
>>> [x[1] for x in lst]
['2', '2', '5', '2', '2', '2']
Now you only have to count the twos there:
>>> [x[1] for x in lst].count('2')
5
If you only want those which ends witha a specific string, use this genexp:
>>> [x[1] for x in lst if x.endswith('abc')]
['2', '2', '5']
What you want to do is to just itterate the list and when you find an index that matches more then once just add to it's place in the list. This snippet should give you the idea of how it is done.
lst = ['120 abc','123 abc','256 abc','125 bcd','326 bcd','426 bcd']
list2 = {}
for listItem in lst:
if listItem.index('2') == 1:
t = listItem.split()
if t[1] in list2:
list2[t[1]] = list2[t[1]] + 1
else:
list2[t[1]] = 1
print(list2)
listItem.split() is a standard function that divides the string on a whitespace, after that we can use "abc" as a key and place the value in a dictionary and sum up the number of times that any particular string occured.

Resources