I want to learn Python and I took a test. I the test I came across this code and I needed to get it's output.
I put the correct answer which was 6, but I didn't understand the code, I just put it in an online python compiler!
Why does this code output a 6?
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(4))
I thing this will solve your problem buddy
def func(x):
res = 0
for i in range(x):
print "x",i
print "res",res
res += i
print "res out", res
return res
print(func(4))
result:
x 0
res 0
res out 0
x 1
res 0
res out 1
x 2
res 1
res out 3
x 3
res 3
res out 6
6
you're passing number 4 as variable x into the function and printing the result in the end.
in the for loop, i is a temporary variable representing each number in range 0 to 4.
so the steps in the code look like this
for 0 in range 0 to 4
add 0 to variable res = 0 + 0 = 0
now res = 0
next step/loop for 1 in range 0 to 4
add 1 to variable res = 0 + 1 = 1
now res = 1
next step/loop for 2 in range 0 to 4
add 2 to variable res = 1 + 2 = 3
now res = 3
next step/loop for 3 in range 0 to 4
add 3 to variable res = 3 + 3 = 6
now res = 6
and the loop is done, giving you the result 6
You assign the value of i to the res and then res value is added to the value of i and your output is assign to the value of res that is when x=3, res become 3 and added with the value 3 is equal to 6 boom
def is used to define function and range means from start to the end point you want so in your case you passed 4 as variable x into your function that means your loop start with the value of 0 and end when value is 4.
Related
i = 0
def func(x):
global i
sum1 = 0
for ele in x:
minus = ele - data['Mean'][i]
sum1 += np.square(minus)
i += 1
return sum1
data['Std'] = Top15_new.groupby('Continents').agg({"Population":func})
return data
answer_eleven()
NameError: name 'i' is not defined
Since data is not provided, I made up the DataFrames and data. I just indented your code as follows:
i = 0
def func(x):
global i
sum1 = 0
for ele in x:
minus = ele - data['Mean'][i]
sum1 += np.square(minus)
i += 1
return sum1
data['Std'] = Top15_new.groupby('Continents').agg({"Population":func})
data
Here is the output of the above code with out error. Again the data is made up data
Mean Std
0 2 NaN
1 3 NaN
2 4 1.0
3 5 5.0
4 6 NaN
while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
I have a logic-driven flag column and I need to create a column that increments by 1 when the flag is true and decrements by 1 when the flag is false down to a floor of zero.
I've tried a few different methods and I can't get the Accumulator 'shift' to reference the new value created by the process. I know the method below wouldn't stop at zero anyway, but I was just trying to work through the concept before and this is the most to-the-point example to explain the goal. Do I need a for loop to iterate line-by-line?
df = pd.DataFrame(data=np.random.randint(2,size=10), columns=['flag'])
df['accum'] = 0
df['accum'] = np.where(df['flag'] == 1, df['accum'].shift(1) + 1, df['accum'].shift(1) - 1)
df['dOutput'] = [1,0,1,2,1,2,3,2,1,0] #desired output
df
Output
As far as I know, there's no numpy or pandas vectorized operation to do this, so, you should iterate line-by-line:
def cumsum_with_floor(series):
acc = 0
output = []
accum_list = []
for val in series:
val = 1 if val else -1
acc += val
accum_list.append(val)
acc = acc if acc > 0 else 0
output.append(acc)
return pd.Series(output, index=series.index), pd.Series(accum_list, index=series.index)
series = pd.Series([1,0,1,1,0,0,0,1])
dOutput, accum = cumsum_with_floor(series)
dOutput
Out:
0 1
1 0
2 1
3 2
4 1
5 0
6 0
7 1
dtype: int64
accum # shifted by one step forward compared with you example
Out:
0 1
1 -1
2 1
3 1
4 -1
5 -1
6 -1
7 1
dtype: int64
But may be there's somebody who knows suitable combination of pd.clip and pd.cumsum or other vectorized operations.
def sum_2_array(list1):
item = 10
numlist = list()
for i in list1:
num = list1.pop()
diff = item-num
if diff in list1:
return num, diff
print sum_2_array([2,3,5,8,7])
This function computes the minimum absolute diff between the elements of an array.The error is that it is returning just one value .
Can anayone please check and tell me where I am going wrong
Please run below code & see if it works. I have Used simple logic
def sum_2_array(list1):
item = 10
j = 0
for i in list1:
print "this is value of J = ", j
num = list1[j]
print "this is value of num = ", num
diff = item - num
print "this is vale of diff = ", diff
if diff in list1:
print num
print diff
j += 1
print sum_2_array([2, 3, 5, 8, 7])
Code you were running in that when it comes to third item in the list i.e 5. At the same time it pops out this item from the list. Because you are using list1.pop(). So it unable to find 5 in the list that's why you are getting only two values. Use code I gave & check if it works.
I got following result from that
this is value of J = 0
this is value of num = 2
this is vale of diff = 8
2
8
this is value of J = 1
this is value of num = 3
this is vale of diff = 7
3
7
this is value of J = 2
this is value of num = 5
this is vale of diff = 5
5
5
this is value of J = 3
this is value of num = 8
this is vale of diff = 2
8
2
this is value of J = 4
this is value of num = 7
this is vale of diff = 3
7
3
I am quite new to programming (Python) and I am trying to write a script in python that compares the values in two separate files such that if the value is the same it assigns 0, and it the value is different it assigns 1.
Say the both initial files are 4rows by 3 columns, so the final file will be a 4rows by 3 columns file of just 1’s and 0’s.
Also, I'd like to sum all the values in this new file (that is summing all the 1’s together).
I have checked around, and I have come across functions such as 'difflib', however I don't know if that'll be suitable.
I am wondering if anyone can help out with something simple...
Thanks a lot in advance :)
The both files shown below consist of 5rows and 6columns
File 1 (ain.txt)
0 1 0 1 0 0
0 0 0 0 0 0
0 1 0 1 0 0
0 0 0 0 0 0
0 1 0 1 0 0
File 2 (bin.txt)
1 1 1 1 1 0
1 1 1 1 1 0
1 1 1 1 1 0
1 1 1 1 1 0
1 1 1 1 1 0
The script below outputs True and False...
import numpy as np
infile = np.loadtxt('ain.txt')
data = np.array(infile)
infile1 = np.loadtxt('bin.txt')
data1 = np.array(infile1)
index = (data==data1)
np.savetxt('comparrr.txt', (index), delimiter = ' ', fmt='%s')
The output shown below:
comparrr.txt
FALSE TRUE FALSE TRUE FALSE TRUE
FALSE FALSE FALSE FALSE FALSE TRUE
FALSE TRUE FALSE TRUE FALSE TRUE
FALSE FALSE FALSE FALSE FALSE TRUE
FALSE TRUE FALSE TRUE FALSE TRUE
However I would want the "FALSE" to be represented by values of 1, and the "TRUE" by values by 0.
I hope this clarifies my question.
Thanks very much in advance.
Sorry for all the troubles, I found out the issue with the previous script above was the format I chose (fmt='%s')... changing that to (fmt='%d') gives the output as 1's and 0's... however I want to have them flipped (i.e. the 1's become 0's, and the 0's become 1's)
Thanks
The output after the change in format mentioned above, shown below:
0 1 0 1 0 1
0 0 0 0 0 1
0 1 0 1 0 1
0 0 0 0 0 1
0 1 0 1 0 1
EDIT: Ok, updating answer
You don't need to import numpy to solve this problem.
If you open the files in iter() they will be read line by line as strings. You can use split() to make them into a list and then use zip() and list comps to quickly figure out if they're equal or not. Then you can turn it back into a string(with map() and join()) and toss it into the file.
foo1 = iter(open('foo1', 'r'))
foo2 = iter(open('foo2', 'r'))
outArr = [ [0 if p==q else 1 for p,q in zip(i.split(), j.split()) ] for i,j in zip(foo1,foo2) ]
totalSum = sum([ sum(row) for row in outArr ])
with open('outFile', 'w') as out:
for row in outArr:
out.write(' '.join(map(str,row))+'\n')
In regards to your code--while the index = (data==data1) bit technically works because of how numpy arrays work, it isn't very readable in my opinion.
To invert your array, numpy provides invert which can be applied directly to the numpy array as np.invert(index). Also, np.loadtxt() returns an np.ndarray type, you don't need to reassign it. To make your code work as you have outlined I would do the following...
import numpy as np
infile = np.loadtxt('foo1')
infile1 = np.loadtxt('foo2')
index = np.invert(infile==infile1).astype(int)
totalSum = sum(sum(index))
np.savetxt('outFile', index, fmt='%d')
'''
assume file 'a.txt' is:
1 2 3
4 5 6
7 8 9
10 11 12
'''
# 1. read in two file.
with open('a.txt','r') as fa:
a = [map(int, line.split()) for line in fa]
with open('b.txt','r') as fb:
b = [map(int, line.split()) for line in fb]
# 2. compare values in two files.
sum_value = 0
c = []
for i in range(4):
c.append([])
for j in range(3):
if (a[i][j] == b[i][j]):
c[i].append(1)
sum_value += 1
else:
c[i].append(0)
# 3. print comparison array.
print c
# 4. print sum value.
print sum_value