Need help in printing dictionary and adding user prompt to obtain nested list values [Python]

Viewed 228

Am currently working on a function that takes in a list. Each element of this list is a list of integers. This list will then be converted to a list of dictionaries. Where the values in each nested list will be multiplied before being outputted as shown below. All list that contain less than 2 integers will also be skipped. So far I am able to get the desired output using a test list but have run into 2 issues: 1st issue: Desired output:

test_list = [[1,3,3], [2,5,-1],[3,2],[4,5,3],[0,23],[1,2,3,4], [1]]

[{'qns': '1 x 3 x 3', 'ans': 9}, 
 {'qns': '2 x 5 x -1', 'ans': -10}, 
 {'qns': '3 x 2', 'ans': 6}, 
 {'qns': '4 x 5 x 3', 'ans': 60}, 
 {'qns': '0 x 23', 'ans': 0}, 
 {'qns': '1 x 2 x 3 x 4', 'ans': 24}]

Am currently getting this output:

test_list = [[1,3,3], [2,5,-1],[3,2],[4,5,3],[0,23],[1,2,3,4], [1]]

[{'qns': '2 x 5 x -1', 'ans': -10}, {'qns': '3 x 2', 'ans': 6}, {'qns': '4 x 5 x 3', 'ans': 60}, {'qns': '0 x 23', 'ans': 0}, {'qns': '1 x 2 x 3 x 4', 'ans': 24}]

2nd issue: May I know how I can add user input functionality to obtain the numbers for the test_list.

[Current Code]

def generate_qns_from_list(lst):
  Qns_List=[]
  for sumList in lst:
    if(len(sumList)>=2):
      question=""
      question+=str(sumList[0])
      answer=sumList[0]
      for i in range(1,len(sumList)):
        question+=" x "+str(sumList[i])
        answer*=sumList[i]
      subDict={'qns':question,'ans':answer}
      Qns_List.append(subDict)
  return Qns_List

input_list=[[1,3,3],[2,5,-1],[3,2],[4,5,3],[0,23],[1,2,3,4],[1]]


print(generate_qns_from_list(input_list))
4 Answers

You could simplify the logic in your for loops by using map():

import pprint
import math

def generate_qns_from_list(lst):
    qns_list = []
    for sub_list in lst:
        if len(sub_list) < 2:
            continue
        d = {}
        qns = ' x '.join(map(str, sub_list))
        d["qns"] = f"{qns}"
        ans = math.prod(sub_list)
        d["ans"] = ans
        qns_list.append(d)
    return qns_list

test_list = [[1, 3, 3], [2, 5, -1], [3, 2], [4, 5, 3], [0, 23], [1, 2, 3, 4], [1]]
pp = pprint.PrettyPrinter(depth=4, sort_dicts=False)
pp.pprint(generate_qns_from_list(test_list))

Output:

[{'qns': '1 x 3 x 3', 'ans': 9},
 {'qns': '2 x 5 x -1', 'ans': -10},
 {'qns': '3 x 2', 'ans': 6},
 {'qns': '4 x 5 x 3', 'ans': 60},
 {'qns': '0 x 23', 'ans': 0},
 {'qns': '1 x 2 x 3 x 4', 'ans': 24}]

If you can't use math.prod here is a no imported libraries python solution:

def generate_qns_from_list(lst):
    qns_list = []
    for sub_list in lst:
        if len(sub_list) < 2:
            continue
        d = {}
        qns = ' x '.join(map(str, sub_list))
        d["qns"] = f"{qns}"
        ans = 1
        for x in sub_list:
          ans *= x
        d["ans"] = ans
        qns_list.append(d)
    return qns_list

test_list = [[1, 3, 3], [2, 5, -1], [3, 2], [4, 5, 3], [0, 23], [1, 2, 3, 4], [1]]
print(generate_qns_from_list(test_list))

Try it here.

You can cut down few loops and convert normal for loops into list comprehensions in order to shorten your code. Here is a modified, completely working version of your code:

def generate_qns_from_list(lst):
    final = []
    lst = [elem for elem in lst if len(elem)>=2]
    for lstt in lst:
        ans = eval('*'.join(str(item) for item in lstt))
        qns = ' x '.join([str(elem) for elem in lstt])
        dictt = {'qns':qns,'ans':ans}
        final.append(dictt)
    return final

test_list = input("Enter the numbers:").split(';')
test_list = [elem.split(',') for elem in test_list]
test_list = [[int(elem) for elem in lstt] for lstt in test_list]
print(generate_qns_from_list(test_list))

Output:

Enter the numbers (same set separated by comma, different sets separated by semi colon):>? 1,3,3;2,5,-1;3,2;4,5,3;0,23;1,2,3,4;1
[{'qns': '1 x 3 x 3', 'ans': 9}, {'qns': '2 x 5 x -1', 'ans': -10}, {'qns': '3 x 2', 'ans': 6}, {'qns': '4 x 5 x 3', 'ans': 60}, {'qns': '0 x 23', 'ans': 0}, {'qns': '1 x 2 x 3 x 4', 'ans': 24}]

well it seems you forgot in the input list the first element you have [1] instead of [1,3,3]. You can check the input() function for your needs

My solution to add user input functionality

One can enter the number of child lists they want and can enter comma-separated values for each list.

def takeUserInput():
    parentList = []
    length = int(input("Enter the number of lists you want : "))
    for l in range(length):
        childList = []
        element = input("Enter the values : ")
        for e in element.split(","):
            childList.append(int(e))
        parentList.append(childList)
    return parentList

takeUserInput()

Output:

Enter the number of lists you want : 7
Enter the values : 1,3,3
Enter the values : 2,5,-1
Enter the values : 3,2
Enter the values : 4,5,3
Enter the values : 0,23
Enter the values : 1,2,3,4
Enter the values : 1

[[1, 3, 3], [2, 5, -1], [3, 2], [4, 5, 3], [0, 23], [1, 2, 3, 4], [1]]
Related