How to unpack input in Leetcode - python-3.x

I'm a newbie to programming and have solved a few questions in codechef and hackerrank. In those platforms,generally lists or elements in a list/array are given as a string of integers with spaces in them
eg: '5 4 6 7'
I can unpack them using an input().split() method in python
But in leetcode, I'm given an input of type
'[1,2,3,4], target=7'
I'm finding it hard to unpack these values from a string into a meaningful datatype. Could someone help me out here? [Context: Two sum problem in leetcode https://leetcode.com/problems/two-sum/]
I tried appending the odd indices of the string into a list
Input: nums = [2,7,11,15], target = 9
a=input()
l=[]
for i in range(len(a)):
if i%2!=0:
l.append(a[i])
print(l)
But I got the following output and the following error
Stdout ['2', '7', '1', ',', '5']
Runtime error
TypeError: 'int' object is not iterable
Line 19 in _deserialize (./python3/__deserializer__.py)
param_1 = des._deserialize(line, 'integer[]')
Line 25 in _driver (Solution.py)
_driver()
Line 43 in <module> (Solution.py)

I think what you're looking for is .split's sep keyword argument, which allows you to split from any character. This is usually defaulted to " " which is why you don't need to put it in every time.
Also as some others mentioned, you don't need to take any inputs, as the function is already taking inputs.
nums = nums[1:-1].split(sep=",")
If you did have to process an input like nums = [2,7,11,15], target = 9 my approach would be:
inp = input() # get input
inp = inp.replace("nums = ", "").replace("target = ", "") # remove the value names
nums, target = inp.split(sep=", ") # unpack items from list: [nums, target]
nums = nums[1:-1].split(sep=", ")
or just condense it down to:
nums, target = input().replace("nums = ", "").replace("target = ", "").split(sep=", ")
nums = nums[1:-1].split(sep=",")

Related

Alien Dictionary Python

Alien Dictionary
Link to the online judge -> LINK
Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary. Find the order of characters in the alien language.
Note: Many orders may be possible for a particular test case, thus you may return any valid order and output will be 1 if the order of string returned by the function is correct else 0 denoting incorrect string returned.
Example 1:
Input:
N = 5, K = 4
dict = {"baa","abcd","abca","cab","cad"}
Output:
1
Explanation:
Here order of characters is
'b', 'd', 'a', 'c' Note that words are sorted
and in the given language "baa" comes before
"abcd", therefore 'b' is before 'a' in output.
Similarly we can find other orders.
My working code:
from collections import defaultdict
class Solution:
def __init__(self):
self.vertList = defaultdict(list)
def addEdge(self,u,v):
self.vertList[u].append(v)
def topologicalSortDFS(self,givenV,visited,stack):
visited.add(givenV)
for nbr in self.vertList[givenV]:
if nbr not in visited:
self.topologicalSortDFS(nbr,visited,stack)
stack.append(givenV)
def findOrder(self,dict, N, K):
list1 = dict
for i in range(len(list1)-1):
word1 = list1[i]
word2 = list1[i+1]
rangej = min(len(word1),len(word2))
for j in range(rangej):
if word1[j] != word2[j]:
u = word1[j]
v = word2[j]
self.addEdge(u,v)
break
stack = []
visited = set()
vlist = [v for v in self.vertList]
for v in vlist:
if v not in visited:
self.topologicalSortDFS(v,visited,stack)
result = " ".join(stack[::-1])
return result
#{
# Driver Code Starts
#Initial Template for Python 3
class sort_by_order:
def __init__(self,s):
self.priority = {}
for i in range(len(s)):
self.priority[s[i]] = i
def transform(self,word):
new_word = ''
for c in word:
new_word += chr( ord('a') + self.priority[c] )
return new_word
def sort_this_list(self,lst):
lst.sort(key = self.transform)
if __name__ == '__main__':
t=int(input())
for _ in range(t):
line=input().strip().split()
n=int(line[0])
k=int(line[1])
alien_dict = [x for x in input().strip().split()]
duplicate_dict = alien_dict.copy()
ob=Solution()
order = ob.findOrder(alien_dict,n,k)
x = sort_by_order(order)
x.sort_this_list(duplicate_dict)
if duplicate_dict == alien_dict:
print(1)
else:
print(0)
My problem:
The code runs fine for the test cases that are given in the example but fails for ["baa", "abcd", "abca", "cab", "cad"]
It throws the following error for this input:
Runtime Error:
Runtime ErrorTraceback (most recent call last):
File "/home/e2beefe97937f518a410813879a35789.py", line 73, in <module>
x.sort_this_list(duplicate_dict)
File "/home/e2beefe97937f518a410813879a35789.py", line 58, in sort_this_list
lst.sort(key = self.transform)
File "/home/e2beefe97937f518a410813879a35789.py", line 54, in transform
new_word += chr( ord('a') + self.priority[c] )
KeyError: 'f'
Running in some other IDE:
If I explicitly give this input using some other IDE then the output I'm getting is b d a c
Interesting problem. Your idea is correct, it is a partially ordered set you can build a directed acyclcic graph and find an ordered list of vertices using topological sort.
The reason for your program to fail is because not all the letters that possibly some letters will not be added to your vertList.
Spoiler: adding the following line somewhere in your code solves the issue
vlist = [chr(ord('a') + v) for v in range(K)]
A simple failing example
Consider the input
2 4
baa abd
This will determine the following vertList
{"b": ["a"]}
The only constraint is that b must come before a in this alphabet. Your code returns the alphabet b a, since the letter d is not present you the driver code will produce an error when trying to check your solution. In my opinion it should simply output 0 in this situation.

A simple Python program to study classes

For the sake of studying the concept of classes in Python, I have written a program which is meant to calculate the average of a tuple of numbers. However, the program returns an error message which is quoted.
#!/usr/bin/python3
"""
Python program to calculate the average value of
a set of integers or float numbers.
Input format: a tuple, e.g. (1,2,3)
When run, the program generates an error message in line 27
"""
class Mean_value():
def __init__(self, operand):
self.operand = operand
def calculate_average(self, operand):
self.operand = operand
all_in_all = sum(operand)
nmbr = len(operand)
average = all_in_all/nmbr
self.average = average
return self.average
operand = input("Key in numbers as a tuple: ")
print(operand) #temp, the operand is taken in by the program
x = Mean_value.calculate_average(operand) #line 27
print(x)
The error message:
Traceback (most recent call last):
File "D:\Python\Exercise76a.py", line 27, in <module>
x = Mean_value.calculate_average(operand)
TypeError: calculate_average() missing 1 required positional argument: 'operand'
I would highly appreciate any hints from members more experienced than myself.
Any method in your class with self as the first parameter is an instance method, meaning it's supposed to be called on an instance of the class and not on the class itself.
In other words, the self parameter isn't just for show. When you do this:
x = Mean_value(operand)
x.calculate_average(operand)
the python interpreter actually takes x and passes it through to the function as the first parameter (i.e. self). Hence, when you try to call calculate_average() on the class Mean_value instead of on an object of that type, it only passes one of the two required parameters (there's no instance to pass automatically as self, so it just passes the one argument you've given it, leaving the second argument unspecified).
If you want to have a method be static (called on the class instead of on an instance of the class), you should use the #staticmethod decorator on the method in question, and omit the self parameter.
Another way to fix this error is to make your calculate_average method static. Like this:
#staticmethod
def calculate_average(operand):
# but be careful here as you can't access properties with self here.
all_in_all = sum(operand)
nmbr = len(operand)
average = all_in_all/nmbr
return average
The program contains comments
#!/usr/bin/python3
"""
The program computes the average value of a sequence of positive integers,
keyed in as a tuple.
After entering the tuple, the input function returns a string,
e.g.(1,2,3) (tuple) --> (1,2,3) (string).
On screen the two objects look the same.
The major code block deals with reversing the type of the input,
i.e. string --> tuple,
e.g. (1,2,3) (string) --> (1,2,3) (tuple).
The maths is dealt with by the class Average.
"""
class Average:
def __init__(self, tup):
self.tup = tup
def calculate(self):
return sum(self.tup)/len(self.tup)
"""Major code block begins ----------"""
#create containers
L_orig_lst = []
S_str = ""
print("The program computes the average value of")
print("a sequence of positive integers, input as a tuple.\n")
#in orig_str store the string-type of the tuple keyed in
orig_str = input("Key in the numbers as a tuple:\n")
lnth = len(orig_str)
#copy each character from orig_str into the list L_orig_lst (the original list)
for i in range(lnth):
if orig_str[i] in ['(', '.', ',' , ')', '1', '2', '3','4', '5', '6', '7', '8', '9', '0']:
#if one of the characters left parenthesis, period, comma, right parenthesis or a digit
#is found in orig_str, then S_str is extended with that character
S_str = S_str + orig_str[i]
L_orig_lst.append(S_str)
#set S_str to be empty
S_str = ""
elif orig_str[i] == " ":
pass
else:
print("Error in input")
break
#at this stage the following transformation has taken place,
#tuple (string) --> tuple (list)
#e.g. (1,2,3) (string) --> ['(' , '1' , ',' , '2' , ',' , '3' , ')'], L_orig_lst
#create new container
#and set S_str to be empty
L_rev_lst = []
S_str = ""
lnth = len(L_orig_lst)
#from the original list, L_orig_lst, copy those elements which are digits (type string)
#and append them to the revised list, L_rev_lst.
for i in range(lnth):
if L_orig_lst[i] in ['1', '2', '3','4', '5', '6', '7', '8', '9', '0']:
#if the element in the original list is a digit (type string),
#then extend S_str with this element
S_str = S_str + L_orig_lst[i]
elif L_orig_lst[i] == ',':
#if the element in the original list is a comma, then finalize the reading of the number,
#convert the current number (type string) into an integer
S_int = int(S_str)
#and append the integer to the revised list
L_rev_lst.append(S_int)
#set S_str to be empty
S_str = ""
else:
pass
#also convert the last number (type string) to an integer,
S_int = int(S_str)
#and also append the last integer to the revised list
L_rev_lst.append(S_int)
#now convert the revised list into a tuple
T_tpl = tuple(L_rev_lst)
"""Major code block ends --------"""
#calculate the average for the tuple T_tpl
#call the class
x = Average(T_tpl)
#instantiate the class
y = x.calculate()
print("Average value: ", y)

Write a program to take dictionary from the keyboard and print sum of values?

d =dict(input('Enter a dictionary'))
sum = 0
for i in d.values():
sum +=i
print(sum)
outputs: Enter a dictionary{'a': 100, 'b':200, 'c':300}
this is the problem arises:
Traceback (most recent call last):
File "G:/DurgaSoftPython/smath.py", line 2, in <module>
d =dict(input('Enter a dictionary'))
ValueError: dictionary update sequence element #0 has length 1; 2 is required
You can't create a dict from a string using the dict constructor, but you can use ast.literal_eval:
from ast import literal_eval
d = literal_eval(input('Enter a dictionary'))
s = 0 # don't name your variable `sum` (which is a built-in Python function
# you could've used to solve this problem)
for i in d.values():
s +=i
print(s)
Output:
Enter a dictionary{'a': 100, 'b':200, 'c':300}
600
Using sum:
d = literal_eval(input('Enter a dictionary'))
s = sum(d.values())
print(s)
import json
inp = input('Enter a dictionary')
inp = dict(json.loads(inp))
sum = sum(inp.values())
print(sum)
input Enter a dictionary{"a": 100, "b":200, "c":300}
output 600
Actually the return of input function is a string. So, in order to have a valid python dict you need to evaluate the input string and convert it into dict.
One way to do this can be done using literal_eval from ast package.
Here is an example:
from ast import literal_eval as le
d = le(input('Enter a dictionary: '))
_sum = 0
for i in d.values():
_sum +=i
print(_sum)
Demo:
Enter a dictionary: {'a': 100, 'b':200, 'c':300}
600
PS: Another way can be done using eval but it's not recommended.

How to take user input when it is seperated by any number of spaces and line breaks in python?

I have been trying to take integer inputs seperated by any number of white spaces or line breaks. I know how to take space seperated outputs and outputs having line breaks. In C based languages we don't have to care about where the input is, it automatically takes the input when found, but I don't think this is the case with Python(correct me if I am wrong). Can anybody help?
I tried using a While statement till True and using a try statement in it. But it doesn't work.
a = []
try:
while(True):
a.append(int(input()))
except:
pass
print(a)
when i input
12 12
12
it returns an empty list. If i remove the int in the input it returns a list [12 12, 12].
Try this: The Shortest way possible
a = []
s=input()
while s != '':
i = s.split()
[a.append(int(j)) for j in i]
s=input()
print(a)
Input:
1 2 3
4 5
6
Output:
[1, 2, 3, 4, 5, 6]
You can also try:
a = []
s=input()
while s != '':
i = s.split()
a.extend(map(lambda s: int(s),i))
s=input()
print(a)
Wait, so I think I understand it now. You want to accept any amount of input, but save each input separated by whitespace as its own entry? There is actually a string method for that. Here's an example script for it. It's not the best, but it demonstrates the method pretty well.
list = []
string = "user input goes here"
splitString = string.split()
for word in splitString:
list.append(word)
print(list)
Output:
["user", "input", "goes", "here"]
The string.split() method uses space by default, but you can specify another delimiter like the # sign.
List = []
String = "Hi#my#name#is#bob"
newString = String.split("#")
for word in newString:
list.append(word)
EDIT: Here is a full working implementation that will work whether the thing separating two inputs is whitespace, newlines, or anything else you'd like.
import re
list = []
while True:
string = input()
if string == "break":
break
splitString = re.split("[\s | \r\n]", string)
for word in splitString:
list.append(word)
cleanList = []
for word in list:
if word != '':
cleanList.append(word)
print(cleanList)
Input:
12 94 17
56
3
Output:
[12, 94, 17, 56, 3]
Functional proof: Click here
Hope you will some insight in this example & have added my personal view of how to code.
Firstly, giving input with multi-spaces is understandable but not multi-lines. Prefer taking input one by one.
For testing & debugging purposes, prefer separate collecting user and processing input data.
Now, say you have collected your user input and stored as data using raw_input, which is handy when you need to collect multiline inputs. Please explore raw_input, it is supported in Python3 and Python2.
>>>
>>> data = '''12
...
... 12 12
...
...
... 12'''
>>> data
'12 \n\n12 12\n\n\n12'
>>> print(data)
12
12 12
12
step1: clear all line separations
>>> double_spaces = ' '
>>> single_space = ' '
>>> data = data.strip().replace('\n', single_space)
>>> data
'12 12 12 12'
step2: Fix multiple spaces
>>> while double_spaces in data:
... data = data.replace(double_spaces, single_space)
...
>>> data
'12 12 12 12'
>>> print(list(map(int, data.split()))
...
... )
[12, 12, 12, 12]
>>>
Problems with you code
>>> a = []
>>> try:
... while(True):
... a.append(int(input()))
... except:
... pass
...
12
1
12 12
>>> a
[12, 1]
>>>
When you enter 12 12, below is supposed to happen.
>>> int('12 12')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12 12'
Since this code had bad exception handling except:, your use case is returning an empty list as expected.
Since I have changed the input, you see this difference.

How to get number values without double quotes in list using python

I'm having lists as shown below.
l = ['22','abc','znijh09nmm','928.2','-98','2018-01-02']
I want those to insert in MySQL using Python, but I want it to get the output as:
l = [22,'abc','znijh09nmm',928.2,-98,2018-01-02]
You could use something like this to convert integers and floats in the list.
mylist = ['22','abc','znijh09nmm','928.2','-98','2018-01-02']
def convert(value):
if str(value).isdigit():
return int(value)
else:
try:
float(value)
return float(value)
except ValueError:
return value
mylist = [convert(i) for i in mylist]
print(mylist)
[22, 'abc', 'znijh09nmm', 928.2, -98.0, '2018-01-02']

Resources