How the looping with for in Python really works? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm learning python and in a test, I made a class that have a list of numbers, in other class, a list of previous class. In the second class, I wrote a method for put the numbers dinamically but it put the numbers x times for the length of the list of previous class.
def make_connection(self, number):
if not self.__has_con:
for i in range(number):
self.__weight.append(1)
self.__has_con = True
The method above is from the first class, to get n numbers.
inp = len(self.__inputs)
for n in self.__hidden:
n.make_connection(inp)
This is from the second class. If __hidden has 9 objects, it put the inp 9 times for all the 9 elements.
init of second class
def __init__(self, array):
if isinstance(array, list):
if len(array) > 2:
inps = []
hidd = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[len(array)-1]):
k = kn(kn.OUTPUT)
outs.append(k)
a = array[1:]
h = a[:len(a)-1]
if len(h) > 1:
for i in h:
hd = []
for p in range(i):
k = kn(kn.HIDDEN)
hd.append(k)
hidd.append(hd)
else:
for p in range(h[0]):
k = kn(kn.HIDDEN)
hidd.append(k)
self.__inputs = inps
self.__hidden = hidd
self.__output = outs
else:
inps = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[0]):
k = kn(kn.OUTPUT)
outs.append(k)
self.__inputs = inps
self.__output = outs

The for var in collection syntax in Python uses an iterator. Instead of a for loop where you specify a starting value, an increment and a terminating value, it says iterate over all the values in the collection.
So when you say this in Python:
for x in range(4):
print x
it's like saying this in other languages:
for (x = 0; x < 4; ++x) {
print(x);
}
Python's range returns a iterator over 0..4 in this case. In your example, Python gives you each element of your collection.
See, for more details: https://www.w3schools.com/python/python_iterators.asp

In python Use the for loop like that:
for str in str_list
print (str)

Related

Perfect number function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 days ago.
Improve this question
Write a program in Python that exercises the functional higher order functions via Python list comprehensions to determine if a number is perfect or not. Write a function named perfect(num) that returns true/false if the given number is/is not perfect.
Use the built in Python function called range(n) that returns a list of integers between 0 and n-1 inclusive.
Use map implemented as a Python List Comprehension to add one to each element of the list.
Use filter implemented as a Python List Comprehension to generate a list of proper factors of n.
Use the Python reduce to generate a sum of those factors
Not more than 4-5 lines of code
def is_perfect(num):
sum = 0
for x in range(0, num-1):
if num % x == 0:
sum += x
return sum == num
print(Is_perfect(28))
Here you go:
def is_perfect(num):
sum = 0
for i in range(1, num):
if num % i == 0:
sum += i
if sum == num:
return True
else:
return False
Now to test it:
x = 8
print(is_perfect(x))
This returns False.
x = 28
print(is_perfect(x))
This returns True.
Some correction in your code
You calling not a correct function name Is_perfect(),
There is also error of modulo by zero,
As written you would inclusive (n-1) in your for loop it is running till (n-2) not till (n-1),
Code:
from functools import reduce
def is_perfect(num):
# List comprehension which store all the number which can be divisible.
list_comprehension = [x for x in range(0, num) if x == 0 or num % x == 0]
print(list_comprehension)
# [0, 1, 2, 4, 7, 14] for number 28
# [0, 1, 2, 4] for number 8
# sum of list using reduce.
sum_of_divisible_numbers = reduce(lambda x, y: x + y, list_comprehension)
return sum_of_divisible_numbers == num
print(is_perfect(28)) # True
print(is_perfect(8)) # False

Deleting max value in set without max() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a working code
task = set()
x = 1
while x != 0:
x = int(input('input your number '))
task.add(x)
print('Just 0 could stop it!')
task.remove(max(task))
print(max(task))
And need to get the same result without using max(). What could be an alternative?
Something like this, unless you have really large sets, I don`t see the advantage
task = set()
x = 1
m = 0
while x != 0:
x = int(input('input your number '))
task.add(x)
if x > m:
m = x
print('Just 0 could stop it!')
task.remove(m)
print(max(task))
Notice this will only work for positive numbers, if you want to the complete int range you should init m like this m = -sys.maxsize - 1
You could use min with a key arg that inverts the element:
>>> task = {1, 2, 3, 4, 5}
>>> max(task)
5
>>> min(task, key=lambda x: -x)
5
Or you could sort it and take the last element...
>>> sorted(task)[-1]
5

I need to create a function that filters a list without a for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
so my function needs to filter a list so that it returns a list of only the values that return a positive value when a function is applied to it without the use of any loops. My code is currently:
def positive_places(f, xs):
"""takes a function f and list xs and returns
a list of the values of xs which satisfy
f>0"""
y = list(map(f, xs))
x = filter(lambda i: i > 0, y)
return x
This currently returns a list of all the positive output values of the function, however I need their corresponding values from the original list xs.
Thanks for any help in advance!
Using a list comprehension:
return [x for x in xs if f(x) > 0]
Without using a list comprehension:
return filter(lambda x: f(x) > 0, xs)
Since you said it should return a list:
return list(filter(lambda x: f(x) > 0, xs))
Two solutions are possible using recursion, which do not use looping or comprehensions - which implement the iteration protocol internally.
Method 1:
lst = list()
def foo(index):
if index < 0 or index >= len(xs):
return
if f(xs[index]) > 0:
lst.append(xs[index])
# print xs[index] or do something else with the value
foo(index + 1)
# call foo with index = 0
Method 2:
lst = list()
def foo(xs):
if len(xs) <= 0:
return
if f(xs[0]) > 0:
lst.append(xs[0])
foo(xs[1:])
# call foo with xs
Both these methods create a new list consisting of the desired values. The second method uses list slicing, which I am not sure whether internally implements iteration protocol or not.

Is it valid to write some code that a bit tricky as long as I get same result (fibonacci in python) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In Pycharm Edu I've encountered with this code:
def fib(n):
"""This is documentation string for function. It'll be available by fib.__doc__()
Return a list containing the Fibonacci series up to n."""
result = []
a = 1
b = 1
while a < n:
result.append(a)
tmp_var = b
b = a+b
a = tmp_var
return result
Since I am still learning I tried to do something similar with lists but the problem is to get a proper fibonacci series I used [-1,1] to start calculation, but results are same. Here is my code:
x = [-1,1]
y = []
for i in range(10):
c = x[0] + x[1]
y.append(c)
x[0] = x[1]
x[1] = c
print(y)
The question is, can I get away with this ?
This question might be too opinion-based for this site, but take into consideration that your code doesn't just need to run, it also needs to be readable. Otherwise, what you have written is entirely valid.
Consider this:
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
print(fibonacci_sequence)
As I said, this may seem like opinion, but make sure you keep the beginning PEP 20 in mind:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts...
As a final note, your code is not a function, but the original code snippet is a function. Here is your code as a function:
def fibonacci():
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
return fibonacci_sequence
print(fibonacci())

Python : Subtracting inside an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to subtract the values in an array with 10 values that the user inputs. So far I can't find how to do that. This is what I have...
g = 0
q = []
for s in range(9):
while g < 10:
n = input()
q.append(int(n))
g = g+1
add = sum(Q)
sub =
There are more succinct ways to do this; I've opted instead for readability:
# get our initial input:
n = input()
result = int(n)
# subtract the rest of the user's inputs:
for x in range(9):
n = input()
result -= int(n)
# ... do something with the result ...
You don't need to assign all of those to individual variables. At each iteration of the loop, you could just append the newly input value to the array:
q = []
g = 0
while g < 10:
n = input()
q.append(int(n))
g = g + 1
At the end of this loop, q will contain the 10 values that the user entered.
It's not clear to me what needs to be subtracted from what, but that might get you a little closer to where you need to be.
Be pythonic
a = [int(input()) for x in range(10)]
Or for python 2.X
a = [int(raw_input()) for x in xrange(10)]
This gives you a list containing 10 integers.
Then you can
q = map(lambda x: x-sum(a), q),
which subtracts the sum of user inputs
Just use python API
li = []
for x in xrage(10):
li.append(input())
result = reduce(lambda x, y: x - y, li)

Categories