how do i write this code (easy way), python problem? - python-3.x

I am very new in Python, and I am really surprised at the following line of code.
p, q = [int(x) for x in input().split()]
how to write basic??

You can make a loop instead to understand better, but the code won't work because the logic is false:
your_input = input().split()
list_ = []
for x in your_input:
list_.append(int(x))
p, q = list_
The .split() put the str in input in a list so you just have one element and one loop. But the p,q = at the end suggests it waits two elements in the list. So it can't work. Maybe you can delete the .split() if you want each digit of a number less than 100. Depends on the result you want.

Related

Python Compare Two lists with a loop and if a match is found run a few codes, and return back to the loop to test if there is another match

I am building a program in python. I have two lists and I want to loop through each of them to see if the elements are equal if they are I want to remove the one element from the list and I want to run a few codes. When this is done I want to return back to the loop to compare the lists again. until one list is empty and the program will continue.
I tried this but just can not get my mind to unblock it! Thank you.
x = [1,2,3,4,5,6,7]
y = [28,1,2,3,4,5,6]
for i in x:
for a in y:
while i == a:
x.remove(i)
How do I tell python to return to the first loop??
Use flag approch
x = [1,2,3,4,5,6,7]
y = [28,1,2,3,4,5,6]
flag=False
for i in x:
flag=False
for a in y:
while i == a:
x.remove(i)
flag=True
if(flag==True):
break

how to add characters from array into one string python

I'm trying to change characters from x into upper or lower character depending whether they are in r or c. And the problem is that i can't get all the changed characters into one string.
import unittest
def fun_exercise_6(x):
y = []
r = 'abcdefghijkl'
c = 'mnopqrstuvwxz'
for i in range(len(x)):
if(x[i] in r):
y += x[i].lower()
elif(x[i] in c):
y += x[i].upper()
return y
class TestAssignment1(unittest.TestCase):
def test1_exercise_6(self):
self.assertTrue(fun_exercise_6("osso") == "OSSO")
def test2_exercise_6(self):
self.assertTrue(fun_exercise_6("goat") == "gOaT")
def test3_exercise_6(self):
self.assertTrue(fun_exercise_6("bag") == "bag")
def test4_exercise_6(self):
self.assertTrue(fun_exercise_6("boat") == "bOaT" )
if __name__ == '__main__':
unittest.main()
Using a list as you are using is probably the best approach while you are figuring out whether or not each character should be uppered or lowered. You can join your list using str's join method. In your case, you could have your return statement look like this:
return ''.join(y)
What this would do is join a collection of strings (your individual characters into one new string using the string you join on ('').
For example, ''.join(['a', 'b', 'c']) will turn into 'abc'
This is a much better solution than making y a string as strings are immutable data types. If you make y a string when you are constructing it, you would have to redefine and reallocate the ENTIRE string each time you appended a character. Using a list, as you are doing, and joining it at the end would allow you to accumulate the characters and then join them all at once, which is comparatively very efficient.
If you define y as an empty string y = "" instead of an empty list you will get y as one string. Since when you declare y = [] and add an item to the list, you add a string to a list of string not a character to a string.
You can't compare a list and a string.
"abc" == ["a", "b", "c'] # False
The initial value of y in the fun_exercise_6 function must be ""

Can we change for loop result into list with index?

I am currently learning python, I just have one little question over here.
I used for loop and getting a result below.
Here is my code:
def psuedo_random(multiplier, modulus, X_0, x_try):
for i in range(x_try):
place_holder = []
count = []
next_x = multiplier * X_0 % modulus
place_holder.append(next_x)
X_0 = next_x
for j in place_holder:
j = j/modulus
count.append(j)
print(count)
Result:
[0.22021484375]
[0.75439453125]
[0.54443359375]
[0.47705078125]
Can we somehow change it into something like this?
[0.22021484375, 0.75439453125, 0.54443359375, 0.47705078125]
After you initialized a list, you can use append function in the loop.
initialize a list where you want to list these numbers
mylist = []
use this function in your for loop
for i in .....:
mylist.append(i)
It's simple. Do not initialize your list inside the loop. Just place it outside.

How can i optimise my code and make it readable?

The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))

What does this input via list-comprehension do?

You know when you find a solution via trial and error but you stumbled so much thtat you can't understand the answer now?
Well this is happening to me with this piece:
entr = [list(int(x) for x in input().split()) for i in range(int(input()))]
The input is done by copying and pasting this whole block:
9
8327 0
0070 0
2681 2
1767 0
3976 0
9214 2
2271 2
4633 0
9500 1
What is my list comprehension exactly doing in each step? And taking into account this: How can I rewrite it using for loops?
In fact, your code is not a nested list-comprehension, beause you use list construtor rather than mere list-comprehension.
This line serves as same as your code:
entr = [[int(x) for x in input().split()] for i in range(int(input()))]
To understand this line, you must remember the basic structure of list-comprehension in python, it consists of two component obj and condition with a square brackets surrounding:
lst = [obj condition]
it can be converted to a loop like this:
lst = []
condition:
lst.append(obj)
So, back to this question.
What you need to do now is to break the nested list-comprehension into loop in loop, usually you begin from the condition in latter part, from outer space to inner space. You got:
entr = []
for i in range(int(input())):
entr.append([int(x) for x in input().split()])) # the obj is a list in this case.
And now, you can break the list-comprehension in line 3.
entr = []
for i in range(int(input())):
entry = []
for x in input().split():
entry.append(int(x))
entr.append(entry)
So, now the stuff the original line can be easily understand.
the program construct a entry list named entr;
the program ask for user input and convert the input string into an int, which is the number of the entrys you want to input(assume it is num);
the program ask for user input for num times, each time you should input something seperate with spaces.
The program split every string into a list (named entry in above code) you input with str.split() method (with parameter sep default to space). And append each entry list in every loop.
for every element in the entry list, it converted to int.
My English may be poor, feel free to improve my answer:)
That is equivalent to this:
entr = []
for i in range(int(input())):
row = []
for x in input().split():
row.append(int(x))
entr.append(row)
You can copy-paste that into a list comprehension in a couple steps. First the inner loop/list:
entr = []
for i in range(int(input())):
row = [int(x) for x in input().split()]
entr.append(row)
Without the row variable:
entr = []
for i in range(int(input())):
entr.append([int(x) for x in input().split()])
Then the outer loop/list (copied over multiple lines for clarity):
entr = [
[int(x) for x in input().split()]
for i in range(int(input()))
]
You have that same nested comprehension except that the inner one has been written as a generator passed to the list constructor so it looks like list(int(x) for x in input().split()) instead of [int(x) for x in input().split()]. That's a little more confusing than using a list comprehension.
I hope that explanation helps!

Resources