NBD NTL  
alberty111 | Aug. 22, 2021, 9:32 a.m.
PythonLearning python for like a few weeks. I'm used to code with fortran. So there is certain way of coding style for me to adjust from fortran to python. One example for doing a loop in python (the use of enumerate):
#not like python, more like a fortran
for i in range(len(some_list)):
j=some_list[i]
do_some(i,j)
#more like python
for i,j in enumerate(some_list):
do_some(i,j)
#if just want to use indexes(under score is a habbit):
for i, _ in enumerate(some_list): do_some(i)
Another interesting zip function, transforms multiple lists into a single list of tuples of corresponding element.
Another tricky thing is when we creating a function which takes another function as input, or say a higher order function. Normally I would do this:
def function_over_f(f):
def g(x):
return 2*f(x)
return g
#this would go wrong when your f takes 2 or more arguments
def f(x,y):
return x+y
g=function_over_f(f)
print g(1,2)
This can be solved by adding **kwargs for receiving a dictionary or *args receiving a tuple when your function can be called with an arbitrary number of arguments.
def g(*args,**kwargs):
...
--------------------------------------------------------------------
Permutation Problem in leetcode
The problem from leetcode in here
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3 Output: “213”
class Solution:
def getPermutation(self, n: int, k: int) -> str:
fact = lambda n:1 if n==0 else n*fact(n-1)
l1=[]
slt=[]
for i in range(1,n+1): #define list=[1,2,..,n]
l1.append(i)
n1=n #counter
for i in reversed(range(1,n)):
if n1==2:
slt.append(l1[k-1])
del l1[k-1]
else:
a1=k//fact(n1-1)
k=k%fact(n1-1)
if k==0:
a1=a1-1
k=fact(n1-1)
slt.append(l1[a1])
del l1[a1]
n1=n1-1
slt.append(l1[0])
return ''.join(map(str, slt))
tags: python | programmming |
Just a guy who likes to go to gym, play Texas hold'em and bouldering.
Know more!