blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
e516f72d59516fa7c4b19e4e54f8db01d7427ab1
wh2per/Programmers-Algorithm
/Programmers/Lv3/Lv3_타일장식물.py
170
3.625
4
def solution(N): d = [0]*(N*2) d[1] = 1 d[2] = 1 for i in range(3,N+2): d[i] = d[i-2] + d[i-1] return d[N]*2 + d[N+1]*2 print(solution(5))
fc9b0f8e4e162b7194deac8834064c76458555d2
wh2per/Programmers-Algorithm
/Programmers/Lv1/Lv1_자연수뒤집어배열로만들기.py
124
3.546875
4
def solution(n): answer = [] s = reversed(str(n)) for i in s: answer.append(int(i)) return answer
9000f77994c2cb607a822d4bf3980a9c4d4a0200
gchriswill/METCS521-HW3
/chriswgm_hw_3_4_2.py
714
4.09375
4
""" Student: Christopher W Gonzalez Melendez Class: CS 521 - Summer 2 Date: 07/27/2020 Homework Problem: #2 Description: A program to demonstrate the usage of method that ease string manipulation. """ # Constants for the odd string and the relevant message ODD_STR = "Christopher" RELEVANT_MSG = "This odd string is not odd at all" # Checks if the string is not odd if len(ODD_STR) % 2 == 0: exit("\n\t" + "\033[91m" + RELEVANT_MSG + "\033[0m" + "\n") # Prints the required statements print("\"{}\", \"{}\"".format(ODD_STR, len(ODD_STR))) print("\"{}\"".format(ODD_STR[int(len(ODD_STR)/2)::int(len(ODD_STR)/2)+1])) print("\"{}\"".format(ODD_STR[:int(len(ODD_STR)/2)])) print("\"{}\"".format(ODD_STR[int(len(ODD_STR)/2)+1:]))
8ae9e4c2915d771cf5f3a4802153ccc4b9ba3f4a
sainihimanshu1999/Arrays-LeetCode
/MaximumProductSubarray.py
361
3.71875
4
''' In this question we hav to find the contigous subarray with maxproduct, we just take product forward and backwards then combine those array to get the maximum product out of them ''' def maxProductsubarray(self,nums): a = nums[::-1] for i in range(1,len(nums)): nums[i] *= nums[i-1] or 1 a[i] *= a[i-1] or 1 return max(nums+a)
651a036ce80c3f728e8bdcb28d3c94c644f5e5ca
sainihimanshu1999/Arrays-LeetCode
/SetMatrixtoZero.py
794
3.96875
4
''' In this question we have to set the matrix element(boht row and col zero) where zero is originally present we make two list rl and cl and same row and col coordinate where zero appears, and then remove duplicates from them and make every element of row and col zero there ''' def setmatrixzero(self,matrix): m = len(matrix) n = len(matrix[0]) rl = [] cl = [] for i in range(m): for j in range(n): if matrix[i][j]==0: rl.append(i) cl.append(j) rs = list(set(rl)) cs = list(set(cl)) while len(rs)>0: row = rs.pop() for j in range(n): matrix[row][j] = 0 while len(cs)>0: col = cs.pop() for i in range(m): matrix[i][col] = 0 return matrix
beaece7dfc9fedf95354e3362827b805ac1a0dc1
sainihimanshu1999/Arrays-LeetCode
/LongestConsecutiveSubsequence.py
343
3.796875
4
''' In this question we have to find the longest consecutive subsequence of numbers from the given numbers. ''' def LCS(self,nums): nums = set(nums) length = 0 for x in nums: if x-1 not in nums: y = x+1 while y in nums: y+=1 length = max(length,y-x) return length
e86f62f6229d5166113d3dcfe8456e456f3ef610
sainihimanshu1999/Arrays-LeetCode
/MergeTwoSortedArrays.py
270
3.859375
4
''' This is an easy question, just remember you can in place edit the array if you know the index and all ''' def mergeTwoSortedArrays(self,nums1,m,nums2,n): if n == 0: return nums1 for num in nums2: nums1[m] = num m+=1 nums1.sort()
310310bfeacd00c2af7a6a0bc315f0832f17e3ca
sainihimanshu1999/Arrays-LeetCode
/ValidTriangle.py
429
3.953125
4
''' A triangle i said to be valid when the sum of any two sides is greated than third side ''' def validTriangle(self,nums): count = 0 nums.sort() n = len(nums) for i in range(n-1,1,-1): low = 0 high = i-1 while low<high: if nums[low]+nums[high]>nums[i]: count += low-high high -=1 else: low +=1 return count
7f6593cacf560b64b556593943ff5bcf9415c20b
sainihimanshu1999/Arrays-LeetCode
/JumpGame2.py
598
3.640625
4
''' In thid question we take two variable, curr_cover and last_jump_index, curr_cover maintains the distance we travelled and last_jump_index maintains the current index we are on. ''' def jumpGame(self,nums): n = len(nums) if n ==1: return 0 destination = n-1 curr_cover = 0 last_jump_index = 0 count = 0 for i in range(n): curr_cover = max(curr_cover,i+nums[i]) if i == last_jump_index: last_jump_index = curr_cover count +=1 if curr_cover>=destination: return count return count
dd83fa66ba7d7d8cb42d37725ceed62d4c5a22a5
sainihimanshu1999/Arrays-LeetCode
/ContainerwithMostWater.py
473
3.859375
4
''' In this question two pointer approach is used, and always remember that in two pointer approach, both pointers does not move simultaneously, rather there is a condition to move them ''' def maxArea(self,height): start = 0 end = len(height)-1 water = 0 while start<=end: water = max(water, (end-start)*min(height[start],height[end])) if height[start]<height[end]: start+=1 else: end-=1 return water
489bcc0cd405e007cde01bc22c15dffbc82fdb8b
Manish9718/Python
/Function file till Loop.py
35,036
4.46875
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 20:28:37 2020 @author: yamanish """ '''Starting of function:''' ========================= We have 3 type of function: 1) Build in Function: Len(), Print(), Count(), shuffle, randint, enumerate, min max, zip 2) User defined Function: Which are defined by user. 3) Anonymou's Function: lambda ========================= So we are doing user defined function. Q) How we define a function? Ans By using DEF before the name of that function. EX: '''def add(enter the parameter like: x,y):''' '''add(5,6): adding to values''' Q1) Make a formula to add variables. def add(x,y): c=x+y print(c) add(5,6) So we can call add any where at any time by entering the value. Q) Why we need it? Ans Bcz while doing a project we need to perform certain task and for avoiding to write the same code we create a function of that code. -------------------- for ex: def greet(): print("Hello") print("welcome") greet() ------------------- #We can also return a value. '''what is RETURN and what's its use.''' Ans Return does not print a value however it gives a result as a total output and sane it. Q) Use a formula to add 2 arguments and use Return function. for ex: def fun(x,y): c=x+y return c fun(5,6) or def afs(x,y): c=x+y return c result=afs(3,4) '''here function does not return a value.''' '''so here it just saved a value in c''' def afs(x,y): c=x+y return c result=afs(3,4) print(result) '''here function return a value''' Q can we return 2 arguments? Ans yes we can, use sum and sub ex: def afs_sub(x,y): a=x+y b=x-y return a,b result1,result2=afs_sub(5,3) print(result1,result2) Q. 1)Define a function, user input his name. 2)If the user name contain vowel than print "Your name contain vowals" 3)In Result name should be printed in Series. def name(): name=input("Please enter the name: ") if set('aeiou').intersection(name.lower()): print('Your name contains vowal') else: print('Your name does not contain vowal') for x in name: print(x) #This is used for series. name() Q Use a function range(0,20) but stop when it is equal's to 5. So Ans should be 0 1 2 3 4 5 Ans def loop_five(): for x in range(0,20): print(x) if x==5: return loop_five() ========================= Factorial: 5!=5*4*3*2*1=120 ========================= def fact(n): y=1 for i in range(1,n+1): y=y*i return y result=fact(5) print(result) Concept of using y Here y=1 and i is 1, so 1*1=y and now Y value is 1 Then i value is 2 and Y vale is 1(1*1), now Y*i(1*2)=3(Y) Y*i(2*3)=Y(6) Y*i(6*4)=Y(24) Y*i(24*5)=Y(120) So that is the reason we have called Y. ========================= Recursion function: Means calling a function itself. ========================= Recursion basically means calling the same function in the function you created. For ex: def greet(): print("Hello") greet() #Here we have called this function in the same function. greet() #Result an error # The result will be infanite time print hello. ========================= Recursive factorail function: Instead of using a Loop use Recursive function. =========================== def fac(x): if x==1: #This is used since factorial of 1 is 1 and we need more than that. return 1 #This is used so that it will not run infinity times. else: return (x*fac(x-1)) #6*6-1,6*5-1 and so on. result=fac(6) print(result) or def calc_factorial(x): if x == 1: return 1 else: return (x * calc_factorial(x - 1)) num =int(input("Please enter the value: ")) print("The factorial of" , num , "is ", calc_factorial(num)) ----------------------------- ====================== Arguments in Python ====================== Ther are 2 type of Arugument: 1) Formal argument: Ex: def sum(x,y) --> This is formal Argument. 2) Actual Argument: Ex: sum(6,7) --> While calling the value in the Arugment. Now Actual argument are of 4 type: 1) Poition Argument 2) Keyword argument 3) Default argument 4) Variable Argument Explain - 1) Position Argument: ------------------ When the position of the argument is same while giving the perameter and calling the same. For ex: def person(name,age): print(name) print(age) person('manish',25) Here the postion of manish and name is 1st. Position od 25 and age is 2nd so it give the result however when we are not sure about position than what we can do. For ex if we want to call person function however we are not sure where the name position is. Ans So to resolve this problem, keyword Argument comes to our mind. 2) Keyword Argument: -------------------- We assign a key to our values at the time of calling. For ex: def person(name,age): print(name) print(age) person(age=25,name='manish') Here we have changed the position however assigned a key to the value. 3) Default Argument: -------------------- Q Now the question arises that if we will not provide a value to an argument then what will happen. Ans We can give a default value to an argument so that if we are not providing a value while calling an argument then even we will get it. For ex: def person(name,age=25): print(name) print(age) person('manish') def profile_info(name,followers=1): print("username:",name) print("Followers:",followers) profile_info("Manish") profile_info(name='kapil',followers=235) Q) if we change the age then what happen? Ans: Yes we can change and it will provide the updated one. def person(name,age=25): print(name) print(age) person('manish',36) 4) Variable Argument: --------------------- When we are not sure that how many arguments we need to enter in the function than we use this function. So we want to eneter multiple argument in the function than we use this function. 1) Variable length argument = * 2) Keyword variable length argument. = ** (*= Key, *= value) So we can * and **kwargs ------------------------ 1) use of * def sum(a,*b): c=a for i in b: c=c+i print(c) sum(23,36,75,45) or single use of Argument def sum(*b): c=0 for i in b: c=c+i print(c) sum(1,2,3,4,5,6) ----------------- Try it with string and number def sing(name,*b): print(name) print(b) sing('mani',27,'xyz','70 kg') So here in the result we have seen that, we have enter multiple argument: 27,'xyz','70 kg') However we are not sure what is 27, xyz or 70 kg. So to assign a key them so that we can understand that why we use it and what is this vale. Here we use ** keyword variable length argument. ------------------- 2) use of **kwargs 'Keyworded Variable Length Arguments in Python ,pass the mutiple keyword/data' def detail(name,**kwargs): print(name) print(kwargs) detail('manish',age=25,address='xyz',mob=9718) 'Now how to print them in a series and how to use it properly. def detail1(name,**kwargs): print(name) for i,j in kwargs.items(): print(i,j) detail1('manish',age=25,address='xyz',mob=9718) Q) How use this with input: def detail(**b): n=input("enter the data") detail(n) Q) Use a function to input how many arguments you need. Than make the user to input arguments. def add(**b): a=int(input("Enter how many times u want to enter:")) for i in range(a): if i<=a: d=input("Enter the Details") for n,m in b.items(): print(n,m) add() Q If a user use both *args and **kwargs def n(*args,**kwargs): if 'Fruits' and 'Juice' in kwargs: print("I like: {} and in fruits i like to eat: {}".format(" , ".join(args),kwargs)) else: pass n('butter','egg',Fruits='Mango',Juice='Lichi') ================================================= Scope ================================================= Scope are of 2 type: 1) Global 2) Local Global: When variables are declared outside the function and can be used anywhere in the function than it is called Global Local: When variables are declared inside the function than these are called local. Q Is it possible to use 2 variable in the same code. Ans. Yes Ex: a=10 #Global Var def AKG(): a=15 #Local Var print("In fun ",a) AKG() print("Out funct ",a) Q can we use the Global var inside the function or call it inside a function. Ans yes we can 'for ex': a=10 def AKG(): print("inside",a) AKG() print("outside",a) Q can we update/change the value of Global variable in the function. Ans Yes we can do that by changing the value by using global before variable. or Q can we convert a local variable into a global Ans. Yes we can do it by using global before the variable. 'for ex': a=10 def AKG(): global a a=15 print("inside",a) AKG() print("outside",a) #Here we dont have a local var. QCan we change the value into a list: Ans a=10 def AKG(): global a a=[1,2,3,4,5,6,7] print("inside",a) AKG() print("outside",a) Q can we use local variable outside a function. And. No we cannot use. Q can we update a value of golbal var. and also use a local var with the same name. Yes we can do this with the help of Globals #main part: x = globals()['a'] #globals()['a'] = 15 For Ex: a=10 def AKG(): a=9 #Local print("inside",a) x = globals()['a'] globals()['a'] = 15 #[here we have not used x=15 bcz it means a new var is created whose value is 15] AKG() print(a) or we can use different variable name for local and global x=10 def AKG1(): a=9 #local print("Inside",a) global x x=x+10 AKG1() print("Outside",x) ======================== Fibonacci Sequence: ======================= 0 1 1 2 3 5 8 13 21 #Here is a patten that first no + second No. #than 2nd no with 3rd no. ans so on. def fib(n): a=0 b=1 if n==1: print(a) else: for i in range(2,n): c=a+b a=b #Here we are just swapping a with b and b with c. b=c print(c) fib(10) -------------------------------------------- Q1) How to use a list in the function and provide the no of Odd and Even? def count(lst): even=0 odd=0 for i in lst: if i%2==0: even+=1 else: odd+=1 return even,odd lst=[23,23,4,5,6,3,2,2,4,32,5,6,6,33] even,odd=count(lst) print(even) print(odd) ------------------------------------------- list=[] c=int(input("enter the details")) for i in range(c): if i<=c: data=input() list.append(data) print(list) =============================================================================== This is 3rd function in Python: Anonymou's Function. No need to define variables Automatically iteration No need to return No parameters. lambda =============================================================================== 1)Multiplication f=lambda a: a*a result=f(4) print(result) 2) Add f=lambda a,b: a+b result=f(2,3) print(result) 3)Substract f=lambda a,b: a-b result=f(5,2) print(result) 4)Exponent f=lambda a: a**4 result=f(5) print(result) ------------------ =============== lambda has 3 function: 1)filter() 2)map() 3)reduce() These 3 are basically used to 1st filter the data and than map(change as per our need) and than reduce it to single result. ============== 1) Filter : It takes 2 Arguments: 1st one is function/logic and 2nd is list/sequence. 'lambda use' '''def is_even(n): if n%2==0: return n or return n%2==0 nums=[3,2,6,8,10,11,13] evens=list(filter(is_even,nums)) print(evens)''' nums=[3,2,6,8,10,11,13] evens=list(filter(lambda n:n%2==0,nums)) print(evens) ------------------ 2) Map : It means change the value by doing an operation. It takes 2 Arguments: 1st one is function/logic and 2nd is list/sequence/iteration. """Always Remember that for using REDUCE we have import thsi function: --FROM FUNCTOOLS IMPORT REDUCE--""" '''def update(n): return n*2 nums=[3,2,6,8,10,11,13] evens=list(filter(is_even,nums)) double=list(map(update,evens)) print(double)''' num=[3,2,5,6,7,89,456,345] evens=list(filter(lambda n: n%2==0,num)) double=list(map(lambda n: n*2,evens)) print(double) ---------------------- 3) Reduce: It help in getting a result form the map list We can onlu use by doing the below operation. from functools import reduce '''def sum_all(n,b): return n+b from funtools import return num=[2,3,4,5,6,7,8,9,6,6,5,5,45,4,4,4,2342,4,3,3,322,234] even=list(filter(lambda n: n%2==0,num)) double=list(map(lambda n: n*2,num)) sum=reduce(sum_all,double) print(sum)''' from functools import reduce num=[2,3,4,5,6,7,8,9,6,6,5,5,45,4,4,4,2342,4,3,3,322,234] even=list(filter(lambda n: n%2==0,num)) double=list(map(lambda n: n*2, num)) sum=reduce(lambda n,m: n+m,num) print(sum) or from functools import reduce nums=[3,2,6,8,10,11,13] even=list(filter(lambda a:a%2==0,nums)) print(even) double=list(map(lambda a:a*2,even)) print(double) sum=reduce(lambda a,b: a+b,double) print(sum) ========================================================================================================================= Decoraters ========================================================================================================================= Decorators can be thought of as functions which modify the functionality of another function. They help to make your code shorter and more "Pythonic". Decoraters basically follows Scope(Global and Local). In python eveything is a object so a function is also an object and can be used inside another function. ------------------------------------ ***IMP : when we use parentheses () def hello(name): return 'Hello '+name hello('John') #here we have used () because we are calling the function. So we call a function then we use parenthese and when we assign a function to a variable then not. greet=hello greet '''when we call without parenthese then it will direct us towards "<function __main__.hello>"''' greet() '''it will give us the result''' Now what happen we delete hello function? Ans Even though we deleted the name hello, the name greet still points to our original function object. It is important to know that functions are objects that can be passed to other objects! ----------------------------------- Functions within functions Great! So we've seen how we can treat functions as objects, now let's see how we can define functions inside of other functions: Ex1. def hello(name): print('The hello() function has been executed') def greet(): return '\t This is inside the greet() function' def welcome(): return "\t This is inside the welcome() function" greet() hello('josh') Ans if we exicute the above function: The hello() function has been executed So if we are calling greet without print it is not working. ************ Ex2. use of greet with print def hello(name): print('The hello() function has been executed') def greet(): return '\t This is inside the greet() function' def welcome(): return "\t This is inside the welcome() function" print(greet()) hello('josh') Ans for the above function: The hello() function has been executed This is inside the greet() function So here we have seen that when we use a function inside a function then we have to use print while calling that. ********AND WE CANNOT RUN GREET AND WELCOME INDIPENDENTLY WITHOUT MAIN FUNCTION HELLO. ************ Ex3. def hello(name): print('The hello() function has been executed') def greet(): return '\t This is inside the greet() function' def welcome(): return "\t This is inside the welcome() function" print(greet()) print(welcome()) hello('josh') Now the problem is if we exicute the function hello both function work and we need it to run as per the situation. ---------------------- with return statement: ---------------------- def hello(name): print('The hello() function has been executed') def greet(): return '\t This is inside the greet() function' def welcome(): return "\t This is inside the welcome() function" if name=='josh': return greet() else: return welcome() hello('sam') ----------------------- Functions as Arguments ----------------------- def hello(): return 'Hi josh' def other(fun): print('other code would go there') print(fun()) other(hello) ----------------------- How to create Decorator ----------------------- def new_decorator(func): def wrap_func(): print("Code would be here, before executing the func") func() print("Code here will execute after the func()") return wrap_func def func_need_decorator(): print("This function is in need of a Decorator") func_need_decorator=new_decorator(func_need_decorator) func_need_decorator() or def new(fun): def wrap(): print('inside wrap') fun() print('outside wrap') return wrap def new_fun(): print('gift') new_fun=new(new_fun) new1() ***************** So an alternative way of doing that is: @ @new_decorator def func_need_decorator(): print("This function is in need of a Decorator") func_need_decorator() Q) When we enters a number for division. The numerator should be bigger than the denominator. Even if num is enter smaller. def div(a,b): if a<b: a,b=b,a print(a/b) #Here the problem is Num is less and den is more. div(5,6) So the problem is when you don't have the code or you do not want to change the function. Ans Than Decorator comes to the picture. 'Decorators' def div(a,b): print(a/b) #here we are creating a new function as decorative or add on. def smart_div(func): def inner (a,b): if a<b: a,b=b,a return func(a,b) return inner div1=smart_div(div) div1(2,4) ========================================================================== Questions for Function. ========================================================================== This is an example of using Function in other function. 1. Write a Python function to find the Max of three numbers. Ans def max_of_two(x,y): if x>y: return x else: return y def max_of_three(x,y,z): return max_of_two(x,max_of_two(y,z)) x=int(input("Please enter the 1st value: ")) y=int(input("Please enter the 2nd value: ")) z=int(input("Please enter the 3rd value: ")) print(max_of_three(x,y,z)) #Here the consept we have use is: Step 1. max_of_two(y,z) : max_of_two(8,-10) Step 2. max_of_two(x,(result from previous: Y)) : max_of_two(2,8): 8 So Y = 8 and we get Max value. """We create a function and than we use that function in other function""" """We have used bracket concept: First Inner bracket will give result: (y,z):(8,10)""" """Now by using first formula we get a result of Y and now same will be applied to outer formula between (x,result:Y) (2,8)= 8""" 2. Write a Python function to sum all the numbers in a list. Ans def sum(n): total=0 for x in n: total+=x return total print(sum((8,7,3,4,0,9))) or def manish(n): a=0 for x in n: a+=x return a n=[1,2,3,4,5,56,6,7] manish(n) 3. Write a Python function to multiply all the numbers in a list. Ans def Mult(n): a=1 for x in n: a*=x return a print(Mult((8, 2, 3, -1, 7))) or def manish(n): a=1 for x in n: a*=x return a n=[2,3,4,5,6] manish(n) 4. Write a Python program to reverse a string? Ans def reverse_string(str1): rvstr1='' index=len(str1) """Here we have taken length of str in Index""" while index>0: rvstr1+=str1[index-1] """when we use indexing we need result of 3 position then we write: print(list[3])""" """In the same wayn we are using indexing where we need print(n[7]): 7th Position""" """This will give a result of 7 which we are using as Indexing=0,1,2,3,4,5,6,7""" index=index-1 return rvstr1 print(reverse_string('abcd1234')) or def rev1(n): rev2='' index=len(n) while index>0: rev2+=n[index-1] index=index-1 return rev2 n=input("Please enter a string: ") rev1(n) 5. Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. Ans def fac(n): if n==1: return 1 else: #for x in range(2,n+1): # y=y*x #return y return (n*fac(n-1)) n=int(input("Enter the value of Factorial: ")) result=fac(n) print(result) 6. Write a Python function to check whether a number is in a given range. Ans def test(n): if n in range(3,9): print("number %s is in the range"%str(n)) """ Use of %s: We can use this where we want to print the value and then at last declare the source: %str(n)""" else: print("Number is not in the list") test(6) 7. Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. Sample String : 'The quick Brow Fox' Expected Output : No. of Upper case characters : 3 No. of Lower case Characters : 12 Ans def test_string(n): d={'UPPER CASE':0, 'lower case':0} for x in n: if x.isupper(): d['UPPER CASE']+=1 elif x.islower(): d['lower case']+=1 else: pass print("Original string is: ",n) print("No of upper case: ",d['UPPER CASE']) print("No of lower case: ",d['lower case']) test_string('The quick BrowseR Fox') or Q)Tell: 'The Kapil SharMA ShoW' def tes(n): a=0 b=0 for x in n: if x.isupper(): a+=1 elif x.islower(): b+=1 else: pass print("Original String:",n) print("No. of Upper case characters :",a) print("No. of lower case characters :",b) n=input("Please enter the String: ") tes(n) 8. Write a Python function that takes a list and returns a new list with unique elements of the first list. Sample List : [1,2,3,3,3,3,4,5] Unique List : [1, 2, 3, 4, 5] def old_lst(n): new_lst=[] for x in n: if x not in new_lst: new_lst.append(x) print(new_lst) n=[1,2,3,3,3,3,4,5] sample(n) =============== if want the user to input than input should be like a string without comma: def old(n): lst=[] for x in n: if x not in lst: lst.append(x) print("New list is: ",lst) n=input() old(n) 9. Write a Python function that takes a number as a parameter and check the number is prime or not? Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself. Ans **In this question we have to keep in mind that : No even number is prime so we are dividing it with 3. import math def pr(num): if num%2==0 and num>2: return False for i in range(3,int(math.sqrt(num))+1,2): '''Why we use this range: it is doing range(start (3): stop: step(2)) then we have: math.sqrt(num)+1: It means we are taking the square root of like(100): 10. So 10+1 = 11 So this means: range(3,math.sqrt(num)+1,2) num= 100 range(3,11,2)''' if num%i==0: return False return True num=int(input("Please enter the value: ")) pr(num) or def test_prime(n): if (n==1): return False elif (n==2): return True; else: for x in range(2,n): if(n % x==0): """This means till if we will get just one 0 as a remainder that means it is divisible by other no. and not a prime""" """secondly we have not included 1 """ return False else: return True print(test_prime(9)) or: if negative value or zero is input then we can also use absolute: num=abs(num) for negative values. def prime(n): if n<=1: return False elif n==2: return True else: for x in range(2,n): if n%x==0: return False else: return True n=int(input("Please enter the value: ")) prime(n) 10. Write a Python program to print the even numbers from a given list. Go to the editor Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9] Expected Result : [2, 4, 6, 8] Ans num=[1, 2, 3, 4, 5, 6, 7, 8, 9] even=list(filter(lambda a: a%2==0,num)) print(even) or def even(n): lst=[] for x in n: if x%2==0: lst.append(x) return lst n=[1, 2, 3, 4, 5, 6, 7, 8, 9] print(even(n)) 11. Write a Python function to check whether a number is perfect or not. Go to the editor According to Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of al l of its positive divisors (including itself). Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128. Ans def perfect_number(n): sum = 0 for x in range(1, n): if n % x == 0: sum += x return sum == n print(perfect_number(6)) 12. Write a Python function that checks whether a passed string is palindrome or not. def poli(n): n=input("Enter the String: ") if n==n[::-1]: def perfect(n): sum=0 for x in range(1,n): if n%x==0: sum+=x return sum==n print("True") else: print("False") poli(n) 13.Write a Python function to check whether a string is a pangram or not. Go to the editor Note : Pangrams are words or sentences containing every letter of the alphabet at least once. For example : "The quick brown fox jumps over the lazy dog" Ans """string.ascii_lowercase or uppercase is used for ('abcdefghijklmnopqrstuvqxyz')""" """to use string we have import string""" import string def Pangrams(n,alphabets=string.ascii_lowercase): alphaset=set(alphabets) return alphaset<=set(n.lower()) Pangrams("The quick brown fox jumps over the lazy dog") 14. Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included). Ans def square(): list=[] for x in range(1,31): x=x**2 list.append(x) return list print(square()) 15. Check weather a Integer is a Palindrome or not? Ans def pali(n): original1=n reverse1=0 while n>0: d = original1 % 10 reverse1 = reverse1*10 + d n = n//10 if original1==reverse1: print("yes") else: print("no") n=int(input("Please enter the no : ")) pali(n) 16. Write a function that returns the number of prime numbers that exist up to and including a given number for num in range(2,101): prime = True for i in range(2,num): if (num%i==0): prime = False if prime: print (num) or def prime(n): lst=[] for x in range(2,n+1): if x%2==0 or x%3==0 or x%5==0: continue else: lst.append(x) print(lst) n=int(input("Please enter the value: ")) prime(n) 17. Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd¶ lesser_of_two_evens(2,4) --> 2 lesser_of_two_evens(2,5) --> 5 def lesser_of_two_evens(a,b): if a%2 == 0 and b%2 == 0: return min(a,b) else: return max(a,b) lesser_of_two_evens(2,3) 18. Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False¶ makes_twenty(20,10) --> True makes_twenty(12,8) --> True makes_twenty(2,3) --> False def m(a,b): if a+b==20: return True elif a==20 or b==20: return True else: return False a=int(input()) b=int(input()) m(a,b) 19. ***This is Important: How we can use" f,s = text.split(" ") " to getb the data from the same string with different words Write a function takes a two-word string and returns True if both words begin with same letter animal_crackers('Levelheaded Llama') --> True animal_crackers('Crazy Kangaroo') --> False def animal_crackers(text): f,s = text.split(" ") #basically we are splitting the text in the same line. if f[0]==s[0]: return True else: return False text=input("Please enter the string: ") animal_crackers(text) or def animal_crackers(text): wordlist = text.split() return wordlist[0][0] == wordlist[1][0] animal_crackers('Levelheaded Llama') 20. ***IMP Write a function that takes in a list of integers and returns True if it contains 007 in order spy_game([1,2,4,0,0,7,5]) --> True spy_game([1,0,2,4,0,5,7]) --> True spy_game([1,7,2,0,4,5,0]) --> False def spygame1(n): return '007' in ''.join(str(i) for i in n) spygame1([1,2,4,0,0,7,5]) 21. Given a list of ints, return True if the array contains a 3 next to a 3 somewhere. has_33([1, 3, 3]) → True has_33([1, 3, 1, 3]) → False has_33([3, 1, 3]) → False def check1(n): return '33' in "".join(str(i) for i in n) n=[3, 3, 3] check1(n) 22.Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False makes_twenty(20,10) --> True makes_twenty(12,8) --> True makes_twenty(2,3) --> False def makes_twenty(n1,n2): return (n1+n2)==20 or n1==20 or n2==20 makes_twenty(20,10) 23. OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name old_macdonald('macdonald') --> MacDonald Note: 'macdonald'.capitalize() returns 'Macdonald' def old_macdonald(name): if len(name) > 3: return name[:3].capitalize() + name[3:].capitalize() else: return 'Name is too short!' old_macdonald('macdonald') 24. Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.¶ summer_69([1, 3, 5]) --> 9 summer_69([4, 5, 6, 7, 8, 9]) --> 9 summer_69([2, 1, 6, 9, 11]) --> 14 def summer_69(arr): total = 0 add = True for num in arr: while add: if num != 6: total += num break else: add = False while not add: if num != 9: break else: add = True break return total summer_69([4, 5, 6, 7, 8, 9]) 25. Guessing Game Challenge Let's use while loops to create a guessing game. The Challenge: Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are: If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS" On a player's first turn, if their guess is within 10 of the number, return "WARM!" further than 10 away from the number, return "COLD!" On all subsequent turns, if a guess is closer to the number than the previous guess return "WARMER!" farther from the number than the previous guess, return "COLDER!" When the player's guess equals the number, tell them they've guessed correctly and how many guesses it took! You can try this from scratch, or follow the steps outlined below. A separate Solution notebook has been provided. Good luck! Ans def Game(): print("Here are the rules: \n'Guess a number between 1 and 100.' \n 'Hint will be provided if required.'") from random import randint Random_no=randint(0,100) Random_no1=Random_no-10 Random_no2=Random_no+10 print(Random_no) Guess=int(input("Please try a no: ")) if Guess==Random_no: print("WOW Correctly Guessed the number :",Guess) elif Guess >= Random_no1 and Guess <= Random_no2: print("WARM") else: print("COLD") previous = Guess guess_list=int(1) while Guess!=Random_no: guess_list=guess_list+1 Guess=int(input("Try again! ")) if Guess==Random_no: print("Now you guessed the correct no %s"%(Guess)) print("You took %s chances"%(guess_list)) break if Guess<0 or Guess>100: print("Out of Bounds, try again") break current = abs(Guess-Random_no) old = abs(previous-Random_no) if current <= old: print("Warmer: You are closer to the number" ) else: print("Colder: You number is further away from the previous number") previous=Guess Game()
be045bc27bf57fdebf319266babaacb851387e46
anupbharade09/Algorithms-Data_Structures
/CS_6114/linked_list.py
646
3.921875
4
class Node: def __init__(self,data=None): self.data=data self.next=None class linked_list: def __init__(self): self.head= Node() def append(self,data): new_node= Node(data) cur = self.head while cur.next != None: cur = cur.next cur.next = new_node def display(self): elems= [] cur_node = self.head while cur_node.next != None: cur_node= cur_node.next elems.append(cur_node.data) print(elems) my_linked_list = linked_list() my_linked_list.display() my_linked_list.append('1') my_linked_list.display()
05ac42b6a7ad86bed47988f4fc004a332c805800
JenteOttie/Avian_tRNAs
/tRNA_Clusters.py
6,497
3.765625
4
# Python script to check the distribution of tRNAs across the genome # The genomic locations for each tRNA are extracted from a overview file # To check whether the tRNAs cluster in the genome, the user is asked to provide a threshold of distance between tRNAs (in this case the genome-wide median - see R-script) import os.path # Ask user which species they want to focus on species = raw_input("Which species would you like to use: ") threshold = int(raw_input("Which threshold would you like to use for the cluster analysis: ")) # Open Overview file input_file = open("private/tRNA_Overview/" + species + "_tRNA.txt", "r") #################################### ##### STEP 1 - Collecting data ##### #################################### # Extract locations of tRNAs per scaffold and save them in temporary files # These temporary files will be used in the next step number_of_tRNA = 1 scaffold_name = "X" list_of_scaffolds = [] for line in input_file: if "Sequence" in line or "Name" in line or "-" in line or "Pseudo" in line or "Undet" in line: # Ignore first three lines of the tRNA file and ignore pseudogenes next else: line_contents = line.split('\t') # Split line according by tab position_1 = line_contents[2] # Beginning of tRNA position_2 = line_contents[3] # End of tRNA tRNA_type = line_contents[4] # AA coded by tRNA anticodon = line_contents[5] # Anticodon of tRNA if scaffold_name == line_contents[0]: # Compare scaffold names. If the same, collect tRNA information # Collect information and save to temporary file position_1 = line_contents[2] # Beginning of tRNA position_2 = line_contents[3] # End of tRNA tRNA_type = line_contents[4] # AA coded by tRNA anticodon = line_contents[5] # Anticodon of tRNA temp = open("temp_" + scaffold_name + ".txt", "a") temp.write(scaffold_name + "\t" + position_1 + "\t" + position_2 + "\t" + tRNA_type + "\t" + anticodon + "\n") temp.close() # Counting number of tRNAs per scaffold number_of_tRNA = number_of_tRNA + 1 else: #print(scaffold_name + " contains " + str(number_of_tRNA) + " tRNAs") scaffold_name = line_contents[0] # Set new scaffold_name list_of_scaffolds.append(scaffold_name) number_of_tRNA = 1 # Reset tRNA counter temp = open("temp_" + scaffold_name + ".txt", "a") temp.write(scaffold_name + "\t" + position_1 + "\t" + position_2 + "\t" + tRNA_type + "\t" + anticodon + "\n") # Add first line to file temp.close() ######################################### ##### STEP 2 - Check for clustering ##### ######################################### print("Data collected and stored in temporary files") print(str(len(list_of_scaffolds)) + " scaffolds will now be analyzed") no_tRNA = 0 begin_end_list = [] # Empty list to store begin and end locations AA = [] # Empty list to store amino acids # Prepare header for results file results = open("results_cluster_analysis_" + species + ".txt", "a") results.write("Scaffold\tDistance\tAA1\tbegin1\tend1\tAA2\tbegin2\tend2\n") results.close() for i in list_of_scaffolds: location_file = open("temp_" + i + ".txt") # Open file with tRNA locations made in Step 1 num_lines = sum(1 for line in location_file) # Get number of lines in file location_file.close() # Remove files with just one tRNA if (num_lines == 1): # If the file contains only one tRNA discard it. print("scaffold " + i + " contains only one tRNA and will be removed") os.remove("temp_" + i + ".txt") # Remove file no_tRNA = no_tRNA + 1 # Keep track of files with only one tRNA else: print("Analyzing scaffold " + i + ", which contains " + str(num_lines) + " tRNAs" ) location_file = open("temp_" + i + ".txt") # Re-open file for data in location_file: data_contents = data.split('\t') # Split line according by tab begin = int(data_contents[1]) # Beginning of tRNA end = int(data_contents[2]) # End of tRNA amino = data_contents[3] # Amino Acid anticodon = data_contents[4].rstrip("\n") # Anticodon with function rstrip() to remove newline (\n) at the end begin_end_list.append(begin) # Add begin and end locations to list begin_end_list.append(end) AA.append(amino) # Save amino acids in list AA. Do it twice to make extracting easier in later stage AA.append(amino) # Analyzing files with more than one tRNA if len(begin_end_list) == 0: next else: [x for y,x in sorted(zip(AA,begin_end_list))] # Sort lists for amino acids and locations at the same time # They have to be sorted together, otherwise the order of the AAs gets lost! # Calculate distance between end of one tRNA and beginning of the next one x = 1 y = 2 while y < len(begin_end_list): distance = begin_end_list[y] - begin_end_list[x] if (distance < threshold and distance > -threshold): # Save tRNA genes that are less than 1000 bp apart results = open("results_cluster_analysis_" + species + ".txt", "a") results.write(i + "\t" + str(distance) + "\t" + AA[x] + "\t" + str(begin_end_list[x-1]) + "\t" + str(begin_end_list[x]) + "\t" + AA[y] + "\t" + str(begin_end_list[y]) + "\t" + str(begin_end_list[y+1]) + "\n") results.close() else: next y = y + 2 x = x + 2 begin_end_list = [] # Reset lists for next scaffold AA = [] # Delete temporary files os.system("rm temp_*")
3c564afb5b2ffd328e44cca9a36f929ab63c7edf
DeepakM2001/python_intern
/d7/Ex2.py
352
3.96875
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 18 22:11:07 2021 @author: Deepak Murugesan """ def covid(name,btemp): print("patient name is :",name,"\tbody temperature:",btemp) name = input("enter patients name:\n") btemp = input("enter temperature :") if btemp.isalpha() == True: weight = 98 else: weight = btemp covid(name,btemp)
769c3e591bd78805c7b3799d4ce876d91bc23877
DeepakM2001/python_intern
/d14/try_except.py
323
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 27 18:05:23 2021 @author: Deepak Murugesan """ try: a = 123 if a==123: print(b) raise NameError("Name error") if a >0: raise ValueError("Value error") except NameError as ne: print(ne) except ValueError as ve: print(ve)
49a165df2abe6456b1d37ae472814ed0c6a1eeeb
DeepakM2001/python_intern
/d9/Ex5.py
242
3.828125
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 21 21:57:39 2021 @author: Deepak Murugesan """ n_156 = int(9) mul_2 = 0 print("multiplication table of : 9",) for p in range(1,10+1): mul_2 = n_156*p print(n_156 ,"x", p ,"=", mul_2 )
d4da079c380e87ca07ddbc542294584baea9b9a5
DeepakM2001/python_intern
/d8/Ex8.py
774
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 20 21:29:08 2021 @author: Deepak Murugesan """ from collections import Counter def MMM(n_num): n = len(n_num) get_sum = sum(n_num) mean = get_sum / n print("Mean / Average is: " + str(mean)) n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2 else: median = n_num[n//2] print("Median is: " + str(median)) data = Counter(n_num) get_mode = dict(data) mode = [k for k, v in get_mode.items() if v == max(list(data.values()))] if len(mode) == n: get_mode = "No mode found" else: get_mode = "Mode is / are: " + ', '.join(map(str, mode)) print(get_mode)
22c783941ab9c04aa44de1d1cc9f2a5ca6c371ba
DeepakM2001/python_intern
/d21/Ex1_1.py
271
3.984375
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 6 21:33:24 2021 @author: Deepak Murugesan """ def merge(list1, list2): merged_list = list(zip(list1, list2)) return merged_list list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] print(merge(list1, list2))
5eceee81798a9b02229cfda471037eb023c35c31
DeepakM2001/python_intern
/d5/Ex2.py
174
3.65625
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 14 17:06:19 2021 @author: Deepak Murugesan """ my_tuple = ("I am kapeeD") my_tuple = tuple(reversed(my_tuple)) print(my_tuple)
33b02513df20dd4cbe00720afbf3886781875d66
KKraan/Mailbox
/mimp.py
1,933
3.671875
4
# -*- coding: utf-8 -*- """This file contains functions to import the data. With "readdata", the data is imported and a dataframe is returned. @author: Kraan """ import pandas as pd Maildata = 'Mailgegevens.xlsx' textfilename = 'mailtekst.txt' # DEFINE FUNCTIONS def definenumber(textpart): """Based on "checklist" this function gives every item (in "textpart") a number coresponding with the position in the list. Input: a string Output: a number""" checklist = ['Sent Items', 'Inhuurprotocollen', 'Niet aangeboden', 'Intakes', 'Contracten', 'Aangeboden'] for i in range(len(checklist)): if checklist[i] in textpart: return i+1 return 0 def readdata(sourcefile=Maildata): # read data dfxls = pd.read_excel(sourcefile, encoding='utf-8', errors='ignore') # Use only mail from the KZA mailbox dfxls = dfxls[dfxls['Persoon'] == 'KZAPlanning@kza.nl'] # create indicator for in or outgoing mail dfxls['Inkomend'] = (dfxls['afzendernaam'] != 'KZA Planning') # als de afzender "KZA planning" is komt hier dus "FALSE" # dfxls['status']=(definenumber(dfxls['Map'])) status = [definenumber(row) for row in dfxls['Map']] dfxls['status'] = status # select relevant columns dfxls = dfxls[['Inkomend', 'status', 'afzendernaam', 'Ontvanger', 'Verzenddatum', 'Onderwerp', 'tekst', 'conversationID']] # little bit of cleaning dfxls['tekst'] = dfxls['tekst'].replace({'\n': ' '}, regex=True).replace({'\r': ' '}, regex=True).replace({'#': ' '}, regex=True) dfxls['tekst'] = dfxls['tekst'].replace({' +': ' '}, regex=True) dfxls['tekst'] = dfxls['tekst'].replace({'ë': 'e'}, regex=True).replace({'è': 'e'}, regex=True).replace({'é': 'e'}, regex=True).replace({'ü': 'u'}, regex=True).replace({'ó': 'o'}, regex=True).replace({'ö': 'o'}, regex=True).replace({'ï': 'i'}, regex=True) dfxls['ID'] = dfxls.index # add ID return(dfxls)
613b47f563a9143c8cb1a3a2469228ae45bc1f4a
sagard21/descriptive_statistics_project
/q02_plot/build.py
690
3.75
4
# Default Imports import pandas as pd import matplotlib.pyplot as plt from greyatomlib.descriptive_stats.q01_calculate_statistics.build import calculate_statistics dataframe = pd.read_csv('data/house_prices_multivariate.csv') sale_price = dataframe.loc[:, 'SalePrice'] # Draw the plot for the mean, median and mode for the dataset def plot(): plt.hist(sale_price) plt.axvline(sale_price.mean(), color = 'r', label = 'Mean') plt.axvline(sale_price.median(), color = 'g', label = 'Median') plt.axvline(sale_price.mode()[0], color = 'y', label = 'Mode') plt.xlabel('Prices') plt.ylabel('Frequencies') plt.title('Price Histogram') plt.legend() plt.show()
fb9b299eff93179ac097d797c7e5ce59bc20f63a
yugin96/cpy5python
/practical04/q5_count_letter.py
796
4.1875
4
#name: q5_count_letter.py #author: YuGin, 5C23 #created: 26/02/13 #modified: 26/02/13 #objective: Write a recursive function count_letter(str, ch) that finds the # number of occurences of a specified leter, ch, in a string, str. #main #function def count_letter(str, ch): #terminating case when string is empty if len(str) == 0: return 0 #add 1 to result if ch is equal to first character of str if str[0] == ch: return 1 + count_letter(str[1:], ch) #add 0 to result if ch is not equal to first character of str if str[0] != ch: return 0 + count_letter(str[1:], ch) #prompt user input of string and character string = str(input('Enter a string: ')) character = str(input('Enter a character: ')) print(count_letter(string, character))
599df5c53d26902da3f2f16cb892a0ae6501be78
yugin96/cpy5python
/practical04/q6_sum_digits.py
482
4.28125
4
#name: q6_sum_digits.py #author: YuGin, 5C23 #created: 26/02/13 #modified: 26/02/13 #objective: Write a recursive function sum_digits(n) that computes the sum of # the digits in an integer n. #main #function def sum_digits(n): #terminating case when integer is 0 if len(str(n)) == 0: return 0 else: return int(str(n)[0]) + sum_digits(str(n)[1:]) #prompt user input of integer integer = input('Enter an integer: ') print(sum_digits(integer))
f0d3f474dfb9c4c893a79b8f7d6c3d8ccbc29078
yugin96/cpy5python
/practical02/q08_top2_scores.py
6,220
4.25
4
#filename: q08_top2_scores.py #author: YuGin, 5C23 #created: 29/01/13 #modified: 30/01/13 #objective: Take as input a number of students' names and their scores, and return the names of the students with the two highest scores. #additional objective: If multiple students have either the top or second-from-top score, return all their names, up to a maximum of five joint-top or # joint-second-from-top scorers #main #prompt input of number of students n = int(input('Enter number of students: ')) #prompt input of individual students and their scores i = 1 student_list_1 = [] student_list_2 = [] unsorted_score_list = [] sorted_score_list = [] #compile student names and score into separate lists while i <= n: student_i = input('Enter name of student ' + str(i) + ' : ') score_i = int(input('Enter score of student ' + str(i) + ' : ')) student_list_1.append(student_i) student_list_2.append(student_i) unsorted_score_list.append(score_i) sorted_score_list.append(score_i) i = i + 1 #sort scores in increasing order sorted_score_list.sort() #extract top scores highest_score = sorted_score_list.pop() #if multiple students have the same top score, find the number of students with that score number_joint_top = (1 + sorted_score_list.count(highest_score)) #remove top score(s) from list i = 1 while i < number_joint_top: sorted_score_list.pop() i = i + 1 #extract second-from-top score second_highest_score = sorted_score_list.pop() #if multiple students have the same second-from-top score, find the number of students with that score number_joint_second_top = (1 + sorted_score_list.count(second_highest_score)) #if there is only one student with the top score, return name of student if number_joint_top == 1: highest_score_position = unsorted_score_list.index(highest_score) top_scorer = student_list_1.pop(highest_score_position) print('Top scorer is ' + top_scorer + '.') #if there are multiple students with the top score, return names of all such students if 1 < number_joint_top <= 5: highest_score_position_1 = unsorted_score_list.index(highest_score) highest_score_position_2 = unsorted_score_list.index(highest_score, highest_score_position_1 + 1) top_scorer_1 = student_list_1.pop(highest_score_position_1) top_scorer_2 = student_list_1.pop(highest_score_position_2 - 1) if number_joint_top > 2: highest_score_position_3 = unsorted_score_list.index(highest_score, highest_score_position_2 + 1) top_scorer_3 = student_list_1.pop(highest_score_position_3 - 2) if number_joint_top > 3: highest_score_position_4 = unsorted_score_list.index(highest_score, highest_score_position_3 + 1) top_scorer_4 = student_list_1.pop(highest_score_position_4 - 3) if number_joint_top > 4: highest_score_position_5 = unsorted_score_list.index(highest_score, highest_score_position_4 + 1) top_scorer_5 = student_list_1.pop(highest_score_position_5 - 4) if number_joint_top == 2: print('Joint-top scorers are ' + top_scorer_1 + ' and ' + top_scorer_2 + '.') if number_joint_top == 3: print('Joint-top scorers are ' + top_scorer_1 + ', ' + top_scorer_2 + ' and ' + top_scorer_3 + '.') if number_joint_top == 4: print('Joint-top scorers are ' + top_scorer_1 + ', ' + top_scorer_2 + ', ' + top_scorer_3 + ' and ' + top_scorer_4 + '.') if number_joint_top == 5: print('Joint-top scorers are ' + top_scorer_1 + ', ' + top_scorer_2 + ', ' + top_scorer_3 + ', ' + top_scorer_4 + ' and ' + top_scorer_5 + '.') if number_joint_top > 5: print('Error: Too many joint-top scorers!') #if there is only one student with the joint-second-from-top score, return name of student if number_joint_second_top == 1: second_highest_score_position = unsorted_score_list.index(second_highest_score) second_top_scorer = student_list_2.pop(second_highest_score_position) print('Second-from-top scorer is ' + second_top_scorer + '.') #if there are multiple students with the second-from-top score, return names of all such students if 1 < number_joint_second_top <= 5: second_highest_score_position_1 = unsorted_score_list.index(second_highest_score) second_highest_score_position_2 = unsorted_score_list.index(second_highest_score, second_highest_score_position_1 + 1) second_top_scorer_1 = student_list_2.pop(second_highest_score_position_1) second_top_scorer_2 = student_list_2.pop(second_highest_score_position_2 - 1) if number_joint_second_top > 2: second_highest_score_position_3 = unsorted_score_list.index(second_highest_score, second_highest_score_position_2 + 1) second_top_scorer_3 = student_list_2.pop(second_highest_score_position_3 - 2) if number_joint_second_top > 3: second_highest_score_position_4 = unsorted_score_list.index(second_highest_score, second_highest_score_position_3 + 1) second_top_scorer_4 = student_list_2.pop(second_highest_score_position_4 - 3) if number_joint_second_top > 4: second_highest_score_position_5 = unsorted_score_list.index(second_highest_score, second_highest_score_position_4 + 1) second_top_scorer_5 = student_list_2.pop(second_highest_score_position_5 - 4) if number_joint_second_top == 2: print('Joint-second-from-top scorers are ' + second_top_scorer_1 + ' and ' + second_top_scorer_2 + '.') if number_joint_second_top == 3: print('Joint-second-from-top scorers are ' + second_top_scorer_1 + ', ' + second_top_scorer_2 + ' and ' + second_top_scorer_3 + '.') if number_joint_second_top == 4: print('Joint-second-from-top scorers are ' + second_top_scorer_1 + ', ' + second_top_scorer_2 + ', ' + second_top_scorer_3 + ' and ' + second_top_scorer_4 + '.') if number_joint_second_top == 5: print('Joint-second-from-top scorers are ' + second_top_scorer_1 + ', ' + second_top_scorer_2 + ', ' + second_top_scorer_3 + ', ' + second_top_scorer_4 + ' and ' + second_top_scorer_5 + '.') if number_joint_second_top > 5: print('Error: Too many joint-second-from-top scorers!')
7315634187176a683570d3abfa829d47f483cf3d
yugin96/cpy5python
/practical02/q07_miles_to_kilometres.py
635
3.84375
4
#filename: q07_miles_to_kilometres.py #author: YuGin, 5C23 #created: 29/01/13 #modified: 29/01/13 #objective: Display two tables side by side: One shows values of 1-10 miles and their corresponding values in kilometres; the other shows values of 20-65 kilometres # in intervals of 5 km and their corresponding values in miles. #main #print heading print('Miles Kilometres Kilometres Miles') #print values in table i = 1 j = 20 while i <= 10: print("{0:<6s}".format(str(i)) + str("{0:<12.3f}".format(i * 1.609)) + "{0:<11s}".format(str(j)) + str("{0:3f}".format(i / 1.609))) i = i + 1 j = j + 5
78baf00a600d84297b1f2abac7d09470fce0638f
hechtermach/ML
/untitled2.py
218
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 01:27:35 2019 @author: mach0 """ import itertools list_step=['R','L','U','D'] list_all=[] for item in itertools.product(list_step,repeat=3): print (item)
17ba89a7ead84c24761240540961cc4559e31ab7
Silverutm/Concursos-Algoritmia
/XV Semana 0ct 2016/alreves/SolutionLittle.py
312
3.5625
4
def es_palindromo(m): for i in list(range(len(m))): if m[i] != m[len(m)-i-1] : return False return True n = int(input()) for x in range(n): a, b = [int(x) for x in input().split()] tot = 0 for i in list(range(a, b+1)): #print(i, end = ' ') tot += es_palindromo(str(i)) #print(tot) print(tot)
ed4d02e186bbd711f970ae29fd5a3a5828b4dbdb
1997priyam/Data-Structures
/arrays&mix/pyramid_number.py
260
4.03125
4
#!/usr/bin/python3 num = int(input("Enter a number: ")) for i in range(num,-1,-1): for j in range(i): print("", end=" ") for k in range(num-i+1): print(k, end="") for l in range(num-i-1,-1,-1): print(l, end="") print("")
105f437782b818e66122b84088377d775b1b04a8
1997priyam/Data-Structures
/arrays&mix/countandsay.py
633
3.953125
4
""" The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... """ def countAndSay(A): num = "1" for i in range(A-1): count = 0 prev = num[0] new_num = "" for j in range(len(num)): if num[j] == prev: count+=1 else: new_num = new_num + str(count) + prev prev = num[j] count = 1 if j == len(num)-1: new_num = new_num + str(count) + prev num = new_num return num a = int(input("Enter a number: ")) print(countAndSay(a))
0d6af4582b3165cf5947c4ba1fc539fc96322677
vpythonfcfm/Coordenadas
/coordenadas.py
1,695
3.75
4
from vpython import * from math import * def es_numero(valor): """ Indica si un valor es numérico o no. """ return isinstance(valor, (int, float, long, complex) ) class Punto(object): def __init__(self, x=0, y=0, z=0): """ Constructor de Punto, x e y deben ser numéricos, de no ser así, se levanta una excepción TypeError """ if es_numero(x) and es_numero(y) and es_numero(z): self.x=x self.y=y self.z=z else: raise TypeError("x e y deben ser valores numéricos") """ Devuelve la norma del vector que va desde el origen hasta el punto. """ def norma(self): return (self.x*self.x + self.y*self.y + self.z*self.z)**0.5 def __str__(self): """ Muestra el punto como un par ordenado. """ return "(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")" def __add__(self, otro): return Punto(self.x + otro.x, self.y + otro.y, self.z + otro.z) def __sub__(self,otro): return Punto(self.x - otro.x, self.y - otro.y, self.z - otro.z) def distancia(self, otro): """ Devuelve la distancia entre ambos puntos. """ r = Punto(self.x - otro.x, self.y - otro.y, self.z - otro.z) return r.norma() class Cilindricas: def __init__(self, radio = 0, azimutal = 0, altura = 0): if es_numero(radio) and es_numero(azimutal) and es_numero(altura): self.radio=radio self.azimutal=azimutal self.altura=altura else: raise TypeError("no son numeros") def Pasar_A_Cilindricas_A_Cartesianas(self): radio = self.radio azimutal = self.azimutal altura = self.altura punto = Punto() punto.x = radio*cos(azimutal) punto.y = radio*sin(azimutal) punto.z = altura return punto
595fdebab1b1dc92ba2f123073b5e42bf258e309
qdev-dk/qdev-wrappers
/qdev_wrappers/configreader.py
2,629
3.53125
4
# Module containing the config file reader class from configparser import ConfigParser class Config: """ Object to be used for interacting with the config file. The ConfigFile is constantly synced with the config file on disk (provided that only this object was used to change the file). Args: filename (str): The path to the configuration file on disk isdefault (Optional[bool]): Whether this is the default Config object. Default: True. Attributes: default (Union[None, Config]): A reference to the default Config object, if it exists. Else None. """ default = None def __init__(self, filename, isdefault=True): # If this is the default config object, we make it available as a # class method. if isdefault: Config.default = self self._filename = filename self._cfg = ConfigParser() self._load() def _load(self): self._cfg.read(self._filename) def reload(self): """ Reload the file from disk. """ self._load() def get(self, section, field=None): """ Gets the value of the specified section/field. If no field is specified, the entire section is returned as a dict. Example: Config.get('QDac Channel Labels', '2') Args: section (str): Name of the section field (Optional[str]): The field to return. If omitted, the entire section is returned as a dict """ # Try to be really clever about the input if not isinstance(field, str) and (field is not None): field = '{}'.format(field) if field is None: output = dict(zip(self._cfg[section].keys(), self._cfg[section].values())) else: output = self._cfg[section][field] return output def set(self, section, field, value): """ Set a value in the config file. Immediately writes to disk. Args: section (str): The name of the section to write to field (str): The name of the field to write value (Union[str, float, int]): The value to write """ if not isinstance(value, str): value = '{}'.format(value) self._cfg[section][field] = value with open(self._filename, 'w') as configfile: self._cfg.write(configfile) def sections(self): """ Gets the sections in the config file """ return self._cfg.sections()
e6a09452aa1308100af09ea215edb35fb88368a3
Adriskk/FakeIDGeneratorApp
/random_identity/identity.py
2,890
3.515625
4
from random import randrange from random import choice from faker import Faker import datetime # - FILES from random_identity.data.data import * fake = Faker() minimum_age = 19 now = datetime.datetime.now() current_year = now.year - minimum_age years = [] year = 1940 for i in range(0, (current_year - 1940)): years.append(year) year += 1 # born_year = choice(years) # age = now.year - born_year # print(age) # print(years) def full_name(): global fullname fullname = choice(first_names) + ' ' + choice(surnames) return fullname def leap_year(year): if year % 4 == 0 and year % 100 != 0: if year % 400 == 0: return True elif year % 4 != 0: return False def birthday(): global born_year, born_month, born_day birthday_date = '' rand_month = choice(months) rand_year = choice(years) born_year = rand_year born_month = rand_month if rand_month != 'February': x = 29 while len(days) < 30: days.append(str(x)) x += 1 else: if not leap_year(rand_year): days.remove('29') rand_day = choice(days) born_day = rand_day return rand_day + ' ' + rand_month + ' ' + str(rand_year) def age(): year_age = now.year - born_year if now.month > months.index(born_month): return year_age elif now.month <= months.index(born_month): if now.day > days.index(born_day): return year_age else: return year_age - 1 def phone_number(): phone_num = '' for num in range(0, 10): number = choice(numbers) if num == 3 or num == 6: phone_num += '-' phone_num += number return phone_num def email_address(): email = '' chars = [ '-', '_', '.', '' ] email_page = [ '@gmail.com', '@yahoo.com', '@hotmail.com', '@aol.com' ] fullname_list = fullname.split() [name.lower() for name in fullname_list] email += fullname_list[0].lower() + choice(chars) + fullname_list[1].lower() + choice(chars) + choice(email_page) return email def phone_nr(): return "+ " + str(country_code) + " " + phone_number() def address(): return fake.address() def identity(): print("Full name: {}".format(full_name())) print("Birthday: {}".format(birthday())) print("Age: {}".format(age())) print("Phone number: {}".format('+' + str(country_code) + ' ' + phone_number())) print("Nationality: {}".format(nationality)) print("Address: ") print(fake.address()) print("Workplace: {}".format(choice(workers))) print("E-mail: {}".format(email_address())) # identity()
e8761af386686f370f8f828e018ff1daf757e072
league-python-student/level0-module1-danatheprincess
/_03_if_else/_3_secret_message_box/secret message box.py
410
3.875
4
from tkinter import messagebox, simpledialog, Tk window=Tk() window.withdraw() secret= "birthday" message=simpledialog.askstring("","Enter SECRET MESSAGE") messagebox.showinfo("","if you want to see the secret message you should guess the password first") password=simpledialog.askstring("","Enter password") if password==secret: messagebox.showinfo("",message) else: messagebox.showinfo("","INTRUDER")
ab4ed3e4cf03888fb88f478170102e9d67b7d351
holdeelocks/Sorting
/src/recursive_sorting/recursive_sorting.py
1,297
4.0625
4
def merge(arrA, arrB): merged_arr = [] while (len(arrA) and len(arrB)): if (arrA[0] < arrB[0]): merged_arr.append(arrA.pop(0)) else: merged_arr.append(arrB.pop(0)) merged_arr.extend(arrA + arrB) return merged_arr def merge_sort(arr): if len(arr) <= 1: return arr else: mid = len(arr) // 2 left = merge_sort(arr[0:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge_in_place(arr, start, mid, end): left = arr[start:mid] right = arr[mid:end] i = j = 0 k = start for l in range(k, end): if j >= len(right) or (i < len(left) and left[i] < right[j]): arr[l] = left[i] i += 1 else: arr[l] = right[j] j += 1 return arr def merge_sort_in_place(arr, l, r): if r - 1 > 1: midpt = (l + r) // 2 merge_sort_in_place(arr, l, midpt) merge_sort_in_place(arr, midpt, r) merge_in_place(arr, l, midpt, r) arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7] merge_sort_in_place(arr1, 0, len(arr1) - 1) # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort(arr): return arr
998d801f7de31fa23c006bd082c33a9474236cf7
Monsieurvishal/Peers-learning-python-3
/programs/list_sum.py
195
4.1875
4
# Program to find the sum of all numbers stored in a list sum=0 numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] for val in numbers: sum = sum+val print("The sum is", sum) #output: The sum is 48.
fbd7624f47d4e14b47722923fd568c31e082d91d
Monsieurvishal/Peers-learning-python-3
/programs/for loop.py
236
4.59375
5
>>for Loops #The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects. for i in range(5): print("hello!") Output: hello! hello! hello! hello! hello!
c56cc5a285093da9ca9cc2265e344bfdbf03f929
Monsieurvishal/Peers-learning-python-3
/programs/for loop_p3.py
282
4.3125
4
>>Write a python script to take input from the user and print till that number. #Ex: if input is 10 print from 1 till 10. n=int(input("enter the number:")) i=0 for i in range(n): print(i) i=i+1 print("finished") #output: enter the number: 0 1 2 3 4 5 6 7 8 9 finished
02d08829f1f1b03c3db9bdfe4d9d696ab4afca7c
joao-conde/advents-of-code
/2017/src/day01.py
1,017
3.59375
4
input_file = open("input/day01") puzzle_input = input_file.read() input_file.close() puzzle_len = len(puzzle_input) # PART1 captcha1 = 0 for i in range(0, puzzle_len): # last element has to check the first (circular list) if i == puzzle_len - 1: if puzzle_input[i] == puzzle_input[0]: captcha1 = captcha1 + int(puzzle_input[i]) break if puzzle_input[i] == puzzle_input[i + 1]: captcha1 = captcha1 + int(puzzle_input[i]) print("Captcha1 sum is " + str(captcha1)) # PART2 captcha2 = 0 step = puzzle_len / 2 for i in range(0, puzzle_len): # past the last element check has to loop from beginning if i + step > puzzle_len - 1: if puzzle_input[i] == puzzle_input[int((i + step) % puzzle_len)]: captcha2 = captcha2 + int(puzzle_input[i]) else: if puzzle_input[i] == puzzle_input[int(i + step)]: captcha2 = captcha2 + int(puzzle_input[i]) print("Captcha2 sum is " + str(captcha2))
220c81cc277241645a50b8ac92eec106563e6cdf
kaitlavs/REDCap_Data_Transformation
/version2.py
21,734
3.75
4
import pandas as pd # import sys def create_df(file_name): """ Returns a DataFrame from a cvs file """ return pd.read_csv(file_name) def return_matches_between_data_and_metadata(data_list, metadata_list): """ Returns a list of all items common to both metadata lists and data lists. data_list is either a list of the field names in the data_df or a list of values in a specified column in the data_df. metadata_list is either the values under the Variable / Field Name column in the metadata DataFrame or the choices found in the Choices, calculations, etc. column of the metadata DataFrame.""" matches = list(set(metadata_list).intersection(data_list)) return matches def return_difference_between_data_and_metadata(data_list, metadata_list): """ Returns a list of all items found in the data list that is not found in the metadata list. data_list is either a list of the field names in the data_df or a list of values in a specified column in the data_df. metadata list is either the values under the Variable / Field Name column in the metadata DataFrame or the choices found in the Choices, calculations, etc. column of the metadata DataFrame.""" difference = list(set(data_list).difference(metadata_list)) return difference def return_value_and_index_dict(data_values, source_list): """ Returns a dictionary that contains values in data_values as keys, and their index + 1 in source_list. This function is used to return erroneous data values (data values that do not match choices found in the metadata_df's column 'Choices, Calculations, OR Slider Labels Choices, Calculations, OR Slider Labels' and their index in the data_df. It is also used to return correct data values (data values that match choices found in the metadata_df's column: 'Choices, Calculations, OR Slider Labels Choices, Calculations, OR Slider Labels' and their index within this metadata column.""" index_list = [] for item in data_values: index_list.append(str(source_list.index(item)+1)) error_values_and_index_dict = dict(zip(data_values, index_list)) return error_values_and_index_dict def error_message(ix_dict): """ Outputs an error message and a dictionary containing the value and the index of the difference in values between two lists.""" print("These data field names do not match options found in the metadata:") print(ix_dict) def return_data_df_containing_only_matching_cols(orig_data_df, matches_between_data_and_metadata): """ Returns a data DataFrame that only contains the columns that matched with the metadata_df's column 'Variable / Field Name'.""" data_matches_df = orig_data_df[matches_between_data_and_metadata] return data_matches_df def return_cleaned_data_values(data_values_list): """ Returns a list of strings with whitespace removed and all lowercase letters.""" cleaned_data_values_list = [] for count in range(len(data_values_list)): if type(data_values_list[count]) != str: v1 = str(data_values_list[count]) else: v1 = data_values_list[count] v1 = v1.replace(' ', '') v1 = v1.lower() cleaned_data_values_list.append(v1) return cleaned_data_values_list def parse_metadata_choices(metadata_choices_string, separator): """ Returns a list of strings parsed around the separator in metadata_choice_string""" pipe_num = metadata_choices_string.count(separator) parsed_list = [] for count in range(pipe_num + 1): v1 = metadata_choices_string.split(separator)[count] v1 = v1.split(',')[1] v1 = v1.replace(' ', '') v1 = v1.lower() parsed_list.append(v1) return parsed_list def return_index_of_data_values_in_metadata(data_values_list, all_meta_choices_and_their_index): """ Returns a list of number strings that replaces keys with their value in a dictionary. This list is used to update the values of the columns in the data DataFrame. data_values_list is a list of all the values in the data_df of a specified column. all_choices_and_their_index is a dictionary containing the metadata_df choices as keys and the index of these choices as values.""" string_list = ', '.join(data_values_list) for i, j in all_meta_choices_and_their_index.items(): string_list = string_list.replace(i, j) back2list = string_list.split(',') return back2list def date_validation(data_values_list, date_format_string): """ Validates the format of a list of strings and returns a new list with correct date formats.""" import datetime import dateutil.parser new_list = [] if date_format_string == 'date_mdy': for str_date in data_values_list: str_date = str(str_date) try: formatted_date = datetime.datetime.strptime(str_date, '%m/%d/%Y').strftime('%m/%d/%Y') new_list.append(formatted_date) except: parsed_str_date = dateutil.parser.parse(str_date) reformatted_date = str(parsed_str_date.month).rjust(2, '0') + '/' + str( parsed_str_date.day).rjust(2, '0') + '/' + str(parsed_str_date.year) new_list.append(reformatted_date) elif date_format_string == 'date_dmy': for str_date in data_values_list: str_date = str(str_date) try: formatted_date = datetime.datetime.strptime(str_date, '%d/%m/%Y').strftime('%d/%m/%Y') new_list.append(formatted_date) except: parsed_str_date = dateutil.parser.parse(str_date) reformatted_date = str(parsed_str_date.day).rjust(2, '0') + '/' + str( parsed_str_date.month).rjust(2, '0') + '/' + str(parsed_str_date.year) new_list.append(reformatted_date) elif date_format_string == 'date_ymd': for str_date in data_values_list: str_date = str(str_date) try: formatted_date = datetime.datetime.strptime(str_date, '%Y/%m/%d').strftime('%Y/%m/%d') new_list.append(formatted_date) except: parsed_str_date = dateutil.parser.parse(str_date) reformatted_date = str(parsed_str_date.year) + '/' + str(parsed_str_date.month).rjust(2, '0') + '/' + str( parsed_str_date.day).rjust(2, '0') new_list.append(reformatted_date) return new_list def decimal_point_validation(data_values_list): """ Changes the format of a float or an integer to two decimal places.""" new_list = ["{:.2f}".format(num) for num in data_values_list] return new_list def integer_validation(data_values_list, data_field_name): """ Validates the format of a list of numbers and returns and a new list containing only integers.""" new_list = [] for x in data_values_list: if type(x) != int and type(x) != float: print(str(data_field_name) + ": Error. Value " + str(x) + " must be an integer") elif type(x) == float: new_x = int(x) new_list.append(new_x) else: new_list.append(x) return new_list def return_checkbox_col_field_names(data_field_name, metadata_choices_list): """ Returns a list of the new column names for the checkbox columns. These new column names are named with the convention 'data field name'___'choice from metadata'.""" new_list = [] for count in range(len(metadata_choices_list)): name = data_field_name + '___' + metadata_choices_list[count] new_list.append(name) return new_list def return_checkbox_col_values(metadata_choice, checkbox_data_values): """ Returns a list of 0s and 1 based on whether the metadata_choice passed in is found in each row of the checkbox_data_values. 1 is added if the metadata_choice is found, 0 if not.""" new_list = [] for choice in checkbox_data_values: if choice.find(metadata_choice) != -1: new_list.append(1) else: new_list.append(0) return new_list def update_data_df_with_checkbox_cols(orig_data_df, col_field_names, col_values): """ Adds the checkbox columns to the existing data_df naming them with col_field_names and fills the columns with col_values""" for i, j in zip(col_field_names, col_values): orig_data_df[i] = j def return_list_of_properly_formatted_field_names(field_names): """ Returns a list of properly formatted field names. White space is removed, and replaced with '_'. '/' and ',' are removed as well.""" new_list = [] for name in field_names: v1 = name.lower() v1 = v1.replace(' ', '_') v1 = v1.replace(',', '') if v1.find('/') != -1: v1 = v1.replace('/', '') v1 = v1.replace('__', '_') new_list.append(v1) else: new_list.append(v1) return new_list def return_list_containing_only_data_values_that_match_metadata_choices( difference_list, source_list): """ Returns a list of data values that have had all the mismatches between metadata choices and data_values removed.""" diff_list = source_list[:] for item in difference_list: diff_list.remove(item) return diff_list # data_source = sys.argv[1] # metadata_source = sys.arg[2] # variable names for the files data_source = 'G:\\My Documents\Python Scripts\\fake.csv' metadata_source = 'G:\My Documents\Python Scripts\\breastDMT.csv' # Creates DataFrames from the data_source and metadata_source data_df = create_df(data_source) metadata_df = create_df(metadata_source) # converts column field names from data_df to a list to be compared to values in first column of metadata_df data_field_names = list(data_df.columns) # checks data_field_names and changes to proper format data_field_names = return_list_of_properly_formatted_field_names(data_field_names) # changes data_df's field names to the list of properly formatted field names data_df.columns = data_field_names # converts column field names from metadata_df to a list metadata_field_names = list(metadata_df.columns) # checks metadata_field_names and changes to proper format (metadata_df field names are referenced throughout the code) metadata_field_names = return_list_of_properly_formatted_field_names(metadata_field_names) # changes metadata_df's field names to the list of properly formatted field names metadata_df.columns = metadata_field_names # converts values from metadata_df's first column to a list to be compared to column field names in data_df values_in_first_col_of_metadata_df = metadata_df.variable_field_name.tolist() # list containing all the items in common between data_field_names and values_in_first_col_of_metadata_df matches_between_data_field_names_and_metadata_first_col_values = return_matches_between_data_and_metadata( data_field_names, values_in_first_col_of_metadata_df) # list containing items that were found in data_field_names but not the values_in_first_col_of_metadata_df data_field_names_not_found_in_metadata_values = return_difference_between_data_and_metadata( data_field_names, values_in_first_col_of_metadata_df) # a new data DataFrame that holds only the columns that matched the metadata_source data_df_containing_only_matching_cols = return_data_df_containing_only_matching_cols( data_df, matches_between_data_field_names_and_metadata_first_col_values) # a new metadata_source DataFrame that holds only the columns that matched the data metadata_df_containing_only_matched_rows = \ metadata_df.loc[metadata_df['variable_field_name'].isin( matches_between_data_field_names_and_metadata_first_col_values)] # creates a list of all fields that are field type 'text' in the metadata_df list_of_field_names_that_have_field_type_text_from_metadata_df = \ list(metadata_df_containing_only_matched_rows.loc [metadata_df_containing_only_matched_rows['field_type'] == 'text', 'variable_field_name']) # creates a list of all fields that are field type 'checkbox' in the metadata_df list_of_field_names_that_have_field_type_checkbox_from_metadata_df = list( metadata_df_containing_only_matched_rows.loc[metadata_df_containing_only_matched_rows['field_type'] == 'checkbox', 'variable_field_name']) # Error reporting # dictionary containing data_field_names that did not match the values_in_first_col_of_metadata_df # and the index at which they are found in the data_df data_dictionary_containing_error_value_and_index = return_value_and_index_dict( data_field_names_not_found_in_metadata_values, data_field_names) if data_dictionary_containing_error_value_and_index: print('Field Name Errors') print('-----------------') # error message for fields that did not match between the data fields and metadata_source values error_message(data_dictionary_containing_error_value_and_index) print() print() print('Value Errors') print('---------------') print("These values are not options found in the metadata_source:") # iterates over the columns in the data_df that matched the first column of the metadata_df for current_data_field_name in matches_between_data_field_names_and_metadata_first_col_values: # validate format of field type 'text' # Represents a list of items that are only 'text' field type and checks to make sure that the list is not empty if current_data_field_name in list_of_field_names_that_have_field_type_text_from_metadata_df: # Creates a series to check if the the text validation column is empty text_validation_values_series = \ metadata_df_containing_only_matched_rows.loc[ metadata_df_containing_only_matched_rows['variable_field_name'] == current_data_field_name, 'text_validation_type_or_show_slider_number'] # if the check validation column is not empty, format validation is needed if text_validation_values_series.any(): text_validation_values_that_are_not_NaN_list = list( metadata_df_containing_only_matched_rows.loc[metadata_df_containing_only_matched_rows[ 'variable_field_name'] == current_data_field_name, 'text_validation_type_or_show_slider_number']) # Checks valid format for date if 'date' in text_validation_values_that_are_not_NaN_list[0]: date_data_values_list = list( data_df_containing_only_matching_cols[current_data_field_name]) updated_date_format_values = date_validation( date_data_values_list, text_validation_values_that_are_not_NaN_list[0]) data_df[current_data_field_name] = updated_date_format_values continue # checks and changes format to two decimal places elif text_validation_values_that_are_not_NaN_list[0] == 'number_2dp': data_values_with_decimal_point_text_validation_required = list( data_df_containing_only_matching_cols[current_data_field_name]) if all(isinstance(x, (int, float)) for x in data_values_with_decimal_point_text_validation_required): updated_data_values_with_correct_decimal_point_format = decimal_point_validation( data_values_with_decimal_point_text_validation_required) data_df[current_data_field_name] = updated_data_values_with_correct_decimal_point_format continue else: print("error ") # Validates if value is an integer elif text_validation_values_that_are_not_NaN_list[0] == 'integer': data_values_with_int_text_validation_required = list( data_df_containing_only_matching_cols[current_data_field_name]) updated_data_values_as_integers = integer_validation( data_values_with_int_text_validation_required, current_data_field_name) data_df[current_data_field_name] = updated_data_values_as_integers continue else: pass else: # creates list of values found in the current_field_name column of the data_df orig_data_values_from_current_field_name_col = list( data_df_containing_only_matching_cols[current_data_field_name]) # cleans data_values_from_current_field_name_col for comparison metadata_source choices cleaned_data_values_from_current_field_name_col = return_cleaned_data_values( orig_data_values_from_current_field_name_col) # creates a DataFrame to check if cell is empty metadata_df_to_check_for_null_choices = metadata_df.loc[metadata_df['variable_field_name'] == current_data_field_name, 'choices_calculations_or_slider_labels'] # if cell is empty, metadata_source data comparison list becomes ['no', 'yes'] # if it is not empty, than the choices must be parsed and cleaned so that # each item in the list is an individual choice if pd.isna(metadata_df_to_check_for_null_choices).bool(): parsed_metadata_choices_list = ['no', 'yes'] else: metadata_choices_for_one_row = list(metadata_df.loc[metadata_df['variable_field_name'] == current_data_field_name, 'choices_calculations_or_slider_labels']) parsed_metadata_choices_list = parse_metadata_choices(metadata_choices_for_one_row[0], '|') # list of data values found in the metadata_df choices data_values_that_match_metadata_choices = return_matches_between_data_and_metadata( parsed_metadata_choices_list, cleaned_data_values_from_current_field_name_col) # list of data values not found in the metadata_df choices data_values_that_do_not_match_metadata_choices = return_difference_between_data_and_metadata( cleaned_data_values_from_current_field_name_col, parsed_metadata_choices_list) # checkbox if current_data_field_name in list_of_field_names_that_have_field_type_checkbox_from_metadata_df: # creates a list of column names that will be added to the target df col_names_for_new_checkbox_cols = return_checkbox_col_field_names( current_data_field_name, parsed_metadata_choices_list) values_for_new_checkbox_cols = [] counter = 0 # while loop loops through the parsed metadata_source choices # and checks if that choice is an option in the data while counter < len(parsed_metadata_choices_list): values_for_new_checkbox_cols.append( return_checkbox_col_values(parsed_metadata_choices_list[counter], cleaned_data_values_from_current_field_name_col)) counter = counter + 1 # updates data_df with the new checkbox columns update_data_df_with_checkbox_cols( data_df, col_names_for_new_checkbox_cols, values_for_new_checkbox_cols) # drops the current_data_field_name column in the new DataFrame data_df = data_df.drop(current_data_field_name, 1) else: list_of_data_values_that_only_contain_matches_with_metadata_choices = \ return_list_containing_only_data_values_that_match_metadata_choices( data_values_that_do_not_match_metadata_choices, cleaned_data_values_from_current_field_name_col) # if there are mismatches, then an error message is needed if data_values_that_do_not_match_metadata_choices: data_error_values_and_index_dict = return_value_and_index_dict( data_values_that_do_not_match_metadata_choices, cleaned_data_values_from_current_field_name_col) print(current_data_field_name + ": " + str(data_error_values_and_index_dict)) # indexing # dictionary containing the matched data values and their index from the metadata_source matched_data_values_and_position_in_metadata_choices_dict = return_value_and_index_dict( list_of_data_values_that_only_contain_matches_with_metadata_choices, parsed_metadata_choices_list) # replace list of values with the indexes from the metadata_source list data_values_index_in_metadata_choices = return_index_of_data_values_in_metadata( cleaned_data_values_from_current_field_name_col, matched_data_values_and_position_in_metadata_choices_dict) # update data DataFrame column values data_df[current_data_field_name] = data_values_index_in_metadata_choices # create new csv file from the updated data DataFrame containing the data transformations data_df.to_csv('G:\My Documents\Python Scripts\\new_test_patient1.csv', index=False)
bfb3f73a402bf3d98775a80bcbe7cbde8875826d
RSAkidinUSA/ctf
/guess_sha256/flag_guess.py
656
3.625
4
#!/usr/bin/python3 # This script is used to generate random guess from the charset and check # if they are the flag of the ctf competition import random from flag_vars import charset, flaglen from flag_test import test def gen_guess(): guess = '' for i in range(flaglen): c = charset[random.randint(0, len(charset) - 1)] guess = guess + c return guess def main(): while True: guess = 'flag{' + gen_guess() + '}' retval = test(guess) print('%s%s is %sthe correct flag!' % ('Sorry, ' if retval else '', '\'' + guess + '\'', 'not ' if retval else '')) if (not retval): exit(0) if __name__ == '__main__': main()
4c9ffe29f4245e08e5128fb4cabe35f7b2b8d101
Nita-Boni/my-first-blog
/prueba.py
189
3.71875
4
# Miralo bien name = 'Ana' if name == 'Ola': print('Hey Ola!') elif name == 'Sonja': print('Hey Sonja!') elif name == 'Ana': print('yessss!') else: print('Hey anonymous!')
5cfa6e114552a027ba32243fecaeb69ac3242402
dell-ai-engineering/BigDL4CDSW
/2_deeplearning/autoencoder_mnist.py
5,225
3.625
4
# Using an auto encoder on MNIST handwritten digits. # In this tutorial, we are going to learn how to compress handwritten digit images from MNIST dataset # and reconstruct them by using [autoencoder](https://en.wikipedia.org/wiki/Autoencoder) algorithm. # The autoencoder model is mainly composed of an ***encoder*** and a ***decoder***. As you can see in the following diagram # (*credit to this* [blog](https://blog.keras.io/building-autoencoders-in-keras.html)) of the model architecture, # after the original input is fed through the encoder and decoder layer, the target output is expected to be the same # as the input although there could be lost information actually after reconstruction***, which is the key point of autoencoder. # It's a very basic and limited data compression algorithm but still good enough for practical applications such as data denoising # and dimensionality reduction for data visualization. # ![model_architecture](jumpstart/images/autoencoder/autoencoder_schema.jpg) # Without further ado, let's finish some imports and setups before the experiment and then delve into the code illustration. %cd "/home/cdsw/2_deeplearning" from sys import path sys.path.append('/home/cdsw/2_deeplearning/resources') import matplotlib # matplotlib.use('Agg') import numpy as np import datetime as dt import matplotlib.pyplot as plt from bigdl.nn.layer import * from bigdl.nn.criterion import * from bigdl.optim.optimizer import * from bigdl.util.common import * from bigdl.dataset.transformer import * from bigdl.dataset import mnist from utils import get_mnist, generate_summaries from pyspark import SparkContext from matplotlib.pyplot import imshow sc=SparkContext.getOrCreate(conf=create_spark_conf().setMaster("yarn").set("spark.driver.memory","8g")) init_engine() # 1. Load MNIST dataset # Read the training data and test data from our designated dataset path by using `get_mnist` method. It also pre-processes # the data by standardizing the image pixel values for better neural network performance. # Please edit the "mnist_path" accordingly. If the "mnist_path" directory does not consist of the mnist data, # the `get_mnist` method will download the dataset directly to the directory. # Get and store MNIST into RDD of Sample, please edit the "mnist_path" accordingly. mnist_path = "/home/cdsw/tmp/mnist" (train_data, test_data) = get_mnist(sc, mnist_path) train_data = train_data.map(lambda sample: Sample.from_ndarray(np.resize(sample.features[0].to_ndarray(), (28*28,)), np.resize(sample.features[0].to_ndarray(), (28*28,)))) test_data = test_data.map(lambda sample: Sample.from_ndarray(np.resize(sample.features[0].to_ndarray(), (28*28,)), np.resize(sample.features[0].to_ndarray(), (28*28,)))) print train_data.count() print test_data.count() # 2. Model setup # Specify the initial hyperparameters prior to the training. # Parameters training_epochs = 10 batch_size = 128 display_step = 1 # Network Parameters n_hidden = 32 n_input = 784 # MNIST data input (img shape: 28*28) # 3. Model creation # By introducing non-lineararity into our autoencoder model, the activation layer ***ReLU*** and ***Sigmoid*** # are added into encoder and decoder respectively. # Create Model def build_autoencoder(n_input, n_hidden): # Initialize a sequential container model = Sequential() # encoder model.add(Linear(n_input, n_hidden)) model.add(ReLU()) # decoder model.add(Linear(n_hidden, n_input)) model.add(Sigmoid()) return model model = build_autoencoder(n_input, n_hidden) # 4. Optimizer setup # Create an Optimizer optimizer = Optimizer( model=model, training_rdd=train_data, criterion=MSECriterion(), optim_method=Adam(), end_trigger=MaxEpoch(2), batch_size=batch_size) # generate summaries and start tensortboard if needed (train_summary, val_summary) = generate_summaries('/home/cdsw/tmp/bigdl_summaries', 'autoencoder') optimizer.set_train_summary(train_summary) optimizer.set_val_summary(val_summary) #Train model trained_model = optimizer.optimize() # 5. Loss visualization # Let's draw the performance curve during optimization. loss = np.array(train_summary.read_scalar("Loss")) plt.figure(figsize = (12,12)) plt.plot(loss[:,0],loss[:,1],label='loss') plt.xlim(0,loss.shape[0]+10) plt.grid(True) plt.title("loss") # 6. Prediction on test dataset # Then we test our autoencoder from the previous loaded dataset, compress and reconstruct the digit images # then compare the results with the original inputs, which are also our target outputs. We are going to use # only 10 examples to demonstrate our created and trained autoencoder is working. (images, labels) = mnist.read_data_sets(mnist_path, "test") examples_to_show = 10 examples = trained_model.predict(test_data).take(examples_to_show) f, a = plt.subplots(2, examples_to_show, figsize=(examples_to_show, 2)) for i in range(examples_to_show): a[0][i].imshow(np.reshape(images[i], (28, 28))) a[1][i].imshow(np.reshape(examples[i], (28, 28)))
24b146a3e423fd413124b988150d4e1ee01b4204
dell-ai-engineering/BigDL4CDSW
/1_sparkbasics/1_rdd.py
1,467
4.25
4
# In this tutorial, we are going to introduce the resilient distributed datasets (RDDs) # which is Spark's core abstraction when working with data. An RDD is a distributed collection # of elements which can be operated on in parallel. Users can create RDD in two ways: # parallelizing an existing collection in your driver program, or loading a dataset in an external storage system. # RDDs support two types of operations: transformations and actions. Transformations construct a new RDD from a previous one and # actions compute a result based on an RDD,. We introduce the basic operations of RDDs by the following simple word count example: from pyspark import SparkContext from pyspark.sql import SparkSession sc = SparkContext.getOrCreate() spark = SparkSession.builder \ .appName("Spark_Basics") \ .getOrCreate() text_file = sc.parallelize(["hello","hello world"]) counts = text_file.flatMap(lambda line: line.split(" ")) \ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b) for line in counts.collect(): print line # The first line defines a base RDD by parallelizing an existing Python list. # The second line defines counts as the result of a few transformations. # In the third line and fourth line, the program print all elements from counts by calling collect(). # collect() is used to retrieve the entire RDD if the data are expected to fit in memory.
9fe4fba829899ac04b1366c8425db8f3c46dc8f1
PavelSlepushkin/fizzbuzz
/fizzbuzz.py
367
3.84375
4
#!/usr/bin/env python3 # Standard boilerplate to call the main() function to begin # the program. def main(): for i in range(1,101): if 0 == i%15 : print ('FizzBuzz') elif 0 == i%5 : print ('Buzz') elif 0 == i%3 : print ('Fizz') else: print(i) if __name__ == '__main__': main()
c1f5e291411edf4edac9addaeee960c0dcc7d371
uyennguyen87/python
/metaprogramming/MyList.py
265
3.640625
4
# Metaprograming/MyList.py def howdy(self, you): print "Howdy, " + you MyList = type('MyList', (list, ), dict(x=42, howdy=howdy)) myList = MyList() myList.append("Camembert") print myList print myList.x myList.howdy("Uyen") print(myList.__class__.__class__)
e084db566617188aaf2e46123e4ff2debd444e95
uyennguyen87/python
/network/1_1_local_machine_info.py
427
3.5
4
# python3 import socket def get_machine_info(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) return { 'host_name': host_name, 'ip_address': ip_address } def print_machine_info(): info = get_machine_info() print("Host name: %s" % info['host_name']) print("IP address: %s" % info['ip_address']) if __name__ == '__main__': print_machine_info()
8438dc1c4416d68bf54b351503c13fc56bf0b90e
nguyenla/Sugar-spelling-activity
/Speak.py
632
3.625
4
# @author: Angel Shiwakoti # @createdOn: 02/06/2017 # This class uses threading to spell the word # using Espeak Library. It prevents the UI Blocking # while Espeak is spelling a word. import threading import gobject import os import espeak gobject.threads_init() class Speak(threading.Thread): def __init__(self, word): super(Speak, self).__init__() self._stop = threading.Event() self.word = word self.es = espeak.ESpeak(voice="en+f1", speed = 230) def stop(self): self._stop.set() def run(self): self.es.say(self.word) # os.system("espeak '{}'".format(self.word))
c53d3807f4b997baf6033cc1c54be0038b593a23
Vladimir-82/code_wars
/Does_my_number_look_big_in_this.py
543
4.09375
4
def narcissistic(value): ''' A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10). 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938 ''' lst = [str(i) for i in list(str(value))] list_extet = sum([int(i) ** len(str(value)) for i in lst]) return True if value == list_extet else False print(narcissistic(1938))
0431501bbf49d95208fb0df853a83ce3f8aa3ad9
Vladimir-82/code_wars
/Recreation_One.py
1,645
3.65625
4
def list_squared(m, n): '''1, 246, 2, 123, 3, 82, 6, 41 - делители числа 246.Возводя эти делители в квадрат, получаем: 1, 60516, 4, 15129, 9, 6724, 36, 1681. Сумма этих квадратов равна 84100, чтосоставляет 290 * 290. Задача Найдите все целые числа от m до n (m и n целые числа, такие как 1 <= m <= n), такие, что сумма их квадратов делителей сама по себе является квадратом. Мы вернем массив подмассивов или кортежей (в C массив Pair) или строку. Подмассивы (или кортежи, или пары) будут иметь два элемента: сначала число, квадрат делителей которого является квадратом, а затем сумма квадратов делителей. Пример: list_squared(1, 250) -> [[1, 1], [42, 2500], [246, 84100]] list_squared(42, 250) -> [[42, 2500], [246, 84100]]''' sqr = [[i**2 for i in range(m, n + 1) if n % i == 0] for n in range(m, n + 1)] print(sqr) sum_squear = [] number = [] filter_list = list(filter(lambda x: sum(x)**0.5 % 1 == 0, sqr)) print(filter_list) # for i in filter_list: # if sum(i)**0.5 % 1 == 0: # number.append(sqr.index(i) + 1) # sum_squear.append(sum(i)) # print(sum_squear) # answer = list(zip(number, sum_squear)) # return answer list_squared(42, 250)
d6a6c132a0c34e2cec3f26a4f72c984843b24143
isrusin/lab-tools
/make_site_list.py
2,660
3.515625
4
#! /usr/bin/env python2 """Site list generator. The tool generates a list of all sites of the given length or all sites matching the specified template. """ import argparse from itertools import product import re import signal import sys def mask_type(value): """Site template type.""" length = value.count("X") if not 0 < length < 11: raise ap.ArgumentTypeError( "Bad site mask!\nThere should be 1 to 10 'X's in the mask." ) mask = value.replace("%", "%%").replace("X", "%c") mask = mask.replace("{", "{{").replace("}", "}}") mask = re.sub(r"\d", lambda x: "{%s}" % x.group(0), mask) return mask, length def main(argv=None): """Main function.""" parser = argparse.ArgumentParser( description="Make list of all sites of the given length or mask." ) parser.add_argument( "-o", dest="oustl", metavar="FILE", type=argparse.FileType("w"), default=sys.stdout, help="output file, default STDOUT" ) parser.add_argument( "--with-n", dest="with_n", action="store_true", help="""use 5-letter alphabet [A, C, G, T, N]; leading and trailing N symbols will be removed if LENGTH is specified, but will not with --mask option""" ) desc_group = parser.add_mutually_exclusive_group(required=True) desc_group.add_argument( "-m", "--mask", type=mask_type, default=(None, 0), help="""site template with X instead of any nucleotide (e.g. XXNNXX); digit from 1 to number of 'X's means complement to according 'X' position (e.g. XXNN21 is a palindrome)""" ) desc_group.add_argument( "length", metavar="LENGTH", type=int, choices=range(1, 11), nargs="?", help="site length, from 1 to 10, including both" ) args = parser.parse_args(argv) mask = args.mask[0] length = args.length or args.mask[1] nucls = "ACGTN" if args.with_n else "ACGT" site_gen = product(nucls, repeat=length) sites = set() if mask: compls = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N"} for site_tuple in site_gen: site = mask % site_tuple if "{" in site: site = site.format("", *(compls[x] for x in site_tuple)) sites.add(site) else: sites = set("".join(site).strip("N") for site in site_gen) sites.discard("") with args.oustl as oustl: oustl.write("\n".join(sorted(sites)) + "\n") if __name__ == "__main__": try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: pass # no signal.SIGPIPE on Windows sys.exit(main())
cd127e3a4d0a4d1413c118abb1170a07c7358567
hoangqwe159/DoVietHoang-C4T5
/Homework 2/Turtle ex2.py
228
3.75
4
from turtle import * speed(0) n = 3 while n < 7: if n % 2 == 1: color("blue") else: color("red") for i in range (n): forward(100) left(180 - 180 * (n - 2) / n) n = n + 1 mainloop()
c767555ee9c73ae671ed7d37c5951dbe943c3635
hoangqwe159/DoVietHoang-C4T5
/Homework 2/session 2.py
258
4.21875
4
from turtle import * shape("turtle") speed(0) # draw circles circle(50) for i in range(4): for i in range (360): forward(2) left(1) left(90) #draw triangle # = ctrl + / for i in range (3): forward(100) left(120) mainloop()
f9e6948812fefcfd9aba9a25a7479f06ad779e75
NoemiFlores/TestingSistemas
/ene-jun-2019/NoemiEstherFloresPardo/Practica7/Mascotas.py
2,118
3.5
4
import sqlite3 class Mascota(): def __init__(self, nombre, especie, edad): self.nombre = nombre self.especie = especie self.edad = edad def __str__(self): return "Nombre de la mascota: {} Especie: {} Edad: {}".format(self.nombre, self.especie, self.edad) def __eq__(self, taco): if Mascota.nombre != self.nombre: return False if Mascota.especie != self.especie: return False if Mascota.edad != self.edad: return False return True class sqlite(): def __init__(self, archivo): self.conn = sqlite3.connect(archivo) def save(self, Mascota): cur = self.conn.cursor() values = (Mascota.nombre, Mascota.especie, Mascota.edad) cur.execute("INSERT INTO mascotas (id,nombre, especie, edad) VALUES (null,?,?,?)", values) self.connection.commit() def getAllMascota(self): cur = self.conn.cursor() mm = cur.execute("SELECT * FROM MASCOTA").fetchall() mascota = [] for m in mm: mascota.append(Mascota(m[1], m[2], m[3])) return mascota def saveMascota(Mascota, db): db.save(Mascota) def showMascota(db): mascota = db.getAllMascotas() return mascota if __name__ == "__main__": mascota1 = Mascota("Sorullo", "perro", 10) mascota2 = Mascota("Sorulla", "perro", 2) mascota3 = Mascota("Gigio", "perro", 18) mascota4 = Mascota("Rex", "perro", 10) mascota5 = Mascota("Gigin", "perro", 12) mascota6 = Mascota("Taco", "perro", 3) mascota7 = Mascota("Zeus", "perro", 3) mascota8 = Mascota("Bodoque", "perro", 3) db = sqlite("Mascotas.db") # cur = db.conn.cursor() # cur.execute("CREATE TABLE TACOS (id INTEGER PRIMARY KEY AUTOINCREMENT,tortilla TEXT, guiso TEXT, salsa TEXT)") saveMascota(mascota1, db) saveMascota(mascota2, db) saveMascota(mascota3, db) saveMascota(mascota4, db) saveMascota(mascota5, db) saveMascota(mascota6, db) saveMascota(mascota7, db) saveMascota(mascota8, db) print(*showMascota(db), sep="\n")
a072f2d30088a42a3a3098806d0e9884e9840d77
adamantiumaurora/MLExcercises
/ml_exercises/supervised_learning/cost_functions.py
1,747
3.890625
4
def mean_absolute_error(predictions, observations): ''' Mean absolute error expressing the arithmetic average of the absolute errors. All individual deviations have even importance. Parameters: predictions (array): array of double values representing predicted values observations (array): array of double values representing observed values Returns: (double): single, cumulative value representing the average of the absolute errors ''' number_of_points = len(predictions) sum_of_errors = 0 for predicted, observed in zip(predictions, observations): sum_of_errors += abs(predicted - observed) mae = (1.0 / number_of_points) * sum_of_errors return mae def mean_squared_error(predictions, observations): ''' Average squared error expressing the arithmetic squared value of difference between the predictions and expected results. Each individual deviation is equivalent to the area of the square created out of the geometrical distance between the measured points. Parameters: predictions (array): array of double values representing predicted values observations (array): array of double values representing observed values Returns: (double): single, cumulative value representing the average of the squared errors ''' number_of_points = len(predictions) sum_of_squared_errors = 0 for predicted, observed in zip(predictions, observations): sum_of_squared_errors += abs(predicted - observed) **2 # division by two in the averaging denominator as its presence makes MSE derivation calculus cleaner mse = (1.0 / (number_of_points * 2)) * sum_of_squared_errors return mse
810b58cdc7bd68bc54369515bfb0d5390b910ede
abhishekkolli/assignment-4
/problem8.py
1,523
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 26 11:54:59 2021 @author: kolliabhishek """ """play hangman""" import random #def hangman(): if __name__=="__main__": f=open("common_words.txt","r") entirefile=f.read() f.close() common_words=entirefile.split() #print(common_array) play="y" guesses=5 while play=="y": computerchoice=random.choice(common_words) # computerchoice="kite" chars=[] while guesses>0: userinput = input("Guess a letter?") guesses = guesses - 1 if userinput in computerchoice: print(userinput,"is in the word:",end="") chars.append(userinput) for char in computerchoice: if char in chars: print(char,end="") else: print("_ ",end="") userguess = input("Try and guess the word?") if userguess.lower() == computerchoice: print("Congratulations!") print("The word was",computerchoice) break else: print("That is not the word") continue else: print(userinput," is not in the word") print("You have {} guesses remaining".format(guesses)) play = input("would you like to play again?") guesses = 5
9db3cfe54657040160ba8fedb87b7eb3beb4a9ef
frank217/Summer-Coding-2018
/CODEChef June Challenge 2018/ Sheokand and String.py
3,908
3.609375
4
""" Sheokand and String Problem Code: SHKSTR https://www.codechef.com/JUNE18B/problems/SHKSTR """ """ Naive version : for each querie run through all the possible string and find the word with longest common prefix that is lexicographically smallest. Runtime : O(q * n * 10) = O(10^11) This only passes on the samll inputcase """ def sheokand(strings,r, querie): # print (strings,r,querie) maxl = 0 word = strings[0] for i in range(r): string = strings[i] index = 0 while index < len(string) and index < len(querie): if string[index] == querie[index]: index +=1 else: break # print(string, index) if maxl == index+1: word = min(string, word) elif maxl < index+1: maxl = index + 1 word = string return word # strings = ["abcd","abce","abcdex","abcde"] # print(sheokand(strings,3,"abcy" )) # print(sheokand(strings,3,"abcde" )) # print(sheokand(strings,4,"abcde" )) # print(sheokand(strings,4,"ab" )) # 3 abcy # 3 abcde # 4 abcde """ **** Only works on cases : WA Better version: Stores each string in to dictionary so that we can decrease search space as we proceed with the given value. Since limit is Strings : 1≤N≤100,000 length of string : 1≤|Si|≤10 for each valid i Queries : 1≤Q≤100,000 R = upto what index we can use in strings to search. 1≤R≤N P = word given to search for longest common prefix 1≤|P|≤10 creating each dictionary will O(n*si) = O(n) *** if dictionary is created every time it will be O(n * q) = 10 ^ 10 which will be too slow *** only create dictionary once. Search will be O(Si) because depth of dictionary will be Si. And bfs on the remain dictionary to find lexicographically smallest one will take O(n*Si) = O(n) Which should be fast enough for large input as well. """ def sheokand2(dic, querie): # print(querie,strings) # print(querie,dic) #search for queries curdic = dic word = "" for i in querie: if i in curdic : word += i curdic = curdic[i] else: break # print(word,curdic) # print("GETREM") word += getrem(curdic) return word def getrem(curdic): if "end" in curdic: return "" key = list(curdic.keys()) # print("key", key[0]) word = key[0] + getrem(curdic[key[0]]) # print (word, curdic) for i in key[1:]: newword = i + getrem(curdic[i]) # print(word, newword) word = min(word, newword) return word import copy def makedic(strings, queries): # Use set because look up takes O(1) where as list is O(n) dic = {} listdic = [] for i in range(len(strings)): string = strings[i] curdic = dic for j in string: if j in curdic: curdic = curdic[j] else: curdic[j] = {} curdic = curdic[j] curdic["end"] = i listdic.append(copy.deepcopy(dic)) for qq in queries: r , q = qq print (sheokand2(listdic[r-1],q)) return # strings = ["abcd","abce","abcdex","abcde"] # queries = [(3,"abcy"),(3,"abcde"),(4,"abcde"),(4,"ab"),(4,"a"),(4,"aa"),(4,"b")] # print("ANSWER :",makedic(strings,queries )) # print("ANSWER :",input(strings,3,"abcde" )) # print("ANSWER :",input(strings,4,"abcde" )) # print("ANSWER :",input(strings,4,"ab" )) # print("ANSWER :",input(strings,4,"a" )) # print("ANSWER :",input(strings,4,"aa" )) # print("ANSWER :",input(strings,4,"b" )) # 4 # abcd # abce # abcdex # abcde # 3 # 3 abcy # 3 abcde # 4 abcde # n = int(input()) # strings = [] # for i in range(n): # strings.append((input())) # q = int(input()) # queries = [] # for i in range(q): # r, querie = input().split(" ") # queries.append((int(r),querie)) # makedic(strings,queries)
464fd20db57c94a62710ba9697a9d64abfe7f323
frank217/Summer-Coding-2018
/CODEChef June Challenge 2018/NAICHEF.py
8,348
3.625
4
# Conquer and divide """ Naive Chef https://www.codechef.com/JUNE18B/problems/NAICHEF Input : """ def naichef(dice ,a,b): countA = 0 countB = 0 for i in dice: if a == i: countA+=1 if b == i: countB+=1 return (countA/len(dice))*(countB/len(dice)) # n = int(input()) # for i in range(n): # s,a,b = list(map(int, input().split(" "))) # dice = list(map(int, input().split(" "))) # result = naichef(dice, a,b) # print(result) """ Binary Shuffle Problem Code: BINSHFFL https://www.codechef.com/JUNE18B/problems/BINSHFFL Explanation : ------------------------------------------------------ There is certain formula for this problem. With the 1 set of operation we can do two things. 1) increase number of 1 bits by 1. 2) decrease number of 1 bits from current value any value between current value and 1. With this speculation we can notice that this problem should be solved using number 1 bits in A and B. c1A(count of 1bits in A) c2B(count of 1bits in B) Inorder to make a certain number into B we know that we have to reach a number B-1 because operation always require plus to a value. So if the B is odd. All we need to do is make A into the c2B-1 number of 1bits. Therefor if c1A < c2B -1 we only need to do (c2B-1) - c1A to add that many 1 bits to A. If c1A > c2B-1 we only need one operation to decrease c1A 1bits to c2B-1 number of 1bits. After this we only need to do 1 operation(add 1) to reach B. If the B is even it's a we need one more thing to consider. Since B is even if we -1 to B, it will create 1 bits equal to how many tailing 0 bits it have. So now it is same as making odd bits with (c1B-1) + tailing 0 bits. ------------------------------------------------------ Number of operation c1B-1 >= c1A : odd = (c1B-1) - c1A + 1 = c1B - c1A : even = ((c1B-1) + tz) - c1A + 1 = c1B + tz - c1A odd only needs to add 1 bits with difference of c1B -1 and c1A because c1B -1 > c1A. Then add 1 to reach from B-1 to B Even does same. Get c1B-1 + tz number of 1 bits from c1A then add 1 to reach from B-1 to B. c1B-1 < c1A : odd = 1 + 1 = 2 : (even) if (c1B-1 + tz)-1 >= c1A needs to add 1bits (ec1B =(c1B-1 + tz)-1) ((ec1B - c1A + 1) + 1 = c1B + tz - c1A (even) otherwise needs to delete 1bits and and 1 + 1 = 2 (delete, add 1) odd needs only deleting 1bits to c1B-1 and adding 1 which is only 2 operation. even is complecated because of tailing zero. B-1 has (c1B-1 + tz) = ec1B 1 bits and B-1 is odd. If ec1B -1 <= c1A we need to add 1 bits. which is same operation we did above. otherwise we delete 1 bits to make this B-1 then add 1 once more to make it B. Rumtime : O(T) ------------------------------------------------------ T =10^5 0 < A,B ≤ 10^18 for each task it takes constant time operation because it is all discrete mathematic that all depends on number of digits of A and B so O(T) * O(1) = O(T) So lets implements this. """ def binaryShuffle(a,b): # print("a",a,"b",b) if a == b : return 0 if b <= 1: return -1 binA = bin(a)[2:] binB = bin(b)[2:] tz = 0 index = len(binB)-1 while True: if binB[index] == "0": tz +=1 index -=1 else: break c1A = binA.count("1") c1B = binB.count("1") # print (binA,binB,c1A,c1B,tz) if c1B - 1 >= c1A: if binA[-1] == "1": return c1B-c1A else: return c1B-c1A + tz else: if binB[-1] == "1": return 2 else: ec1B = c1B - 1 + tz if ec1B == c1A: return 1 elif ec1B > c1A: return c1B + tz - c1A else: return 2 print (1,5,binaryShuffle(1,5),1) print (2,4,binaryShuffle(2,4),2) print (5,1,binaryShuffle(5,1),-1) print (4,1,binaryShuffle(4,1),-1) print (5,1,binaryShuffle(3,1),-1) print (5,3,binaryShuffle(5,3),2) print (2,7,binaryShuffle(2,7),2) print (7,2,binaryShuffle(7,2),2) print (2,7,binaryShuffle(2,7),2) print (15,12,binaryShuffle(15,12),2) print (15,24,binaryShuffle(15,24),1) print (6,28,binaryShuffle(6,28),3) print (15,16,binaryShuffle(15,16),1) print (16,15,binaryShuffle(16,15),3) print (12,3,binaryShuffle(12,3),2) # n = int(input()) # for i in range(n): # a,b = list(map(int, input().split(" "))) # result = binaryShuffle(a,b) # print(result) """ Naive version : for each querie run through all the possible string and find the word with longest common prefix that is lexicographically smallest. Runtime : O(q * n * 10) = O(10^11) This only passes on the samll inputcase """ def sheokand(strings,r, querie): # print (strings,r,querie) maxl = 0 word = strings[0] for i in range(r): string = strings[i] index = 0 while index < len(string) and index < len(querie): if string[index] == querie[index]: index +=1 else: break # print(string, index) if maxl == index+1: word = min(string, word) elif maxl < index+1: maxl = index + 1 word = string return word # strings = ["abcd","abce","abcdex","abcde"] # print(sheokand(strings,3,"abcy" )) # print(sheokand(strings,3,"abcde" )) # print(sheokand(strings,4,"abcde" )) # print(sheokand(strings,4,"ab" )) # 3 abcy # 3 abcde # 4 abcde """ **** Only works on cases : WA Better version: Stores each string in to dictionary so that we can decrease search space as we proceed with the given value. Since limit is Strings : 1≤N≤100,000 length of string : 1≤|Si|≤10 for each valid i Queries : 1≤Q≤100,000 R = upto what index we can use in strings to search. 1≤R≤N P = word given to search for longest common prefix 1≤|P|≤10 creating each dictionary will O(n*si) = O(n) *** if dictionary is created every time it will be O(n * q) = 10 ^ 10 which will be too slow *** only create dictionary once. Search will be O(Si) because depth of dictionary will be Si. And bfs on the remain dictionary to find lexicographically smallest one will take O(n*Si) = O(n) Which should be fast enough for large input as well. """ def sheokand2(dic, querie): # print(querie,strings) # print(querie,dic) #search for queries curdic = dic word = "" for i in querie: if i in curdic : word += i curdic = curdic[i] else: break # print(word,curdic) # print("GETREM") word += getrem(curdic) return word def getrem(curdic): if "end" in curdic: return "" key = list(curdic.keys()) # print("key", key[0]) word = key[0] + getrem(curdic[key[0]]) # print (word, curdic) for i in key[1:]: newword = i + getrem(curdic[i]) # print(word, newword) word = min(word, newword) return word import copy def makedic(strings, queries): # Use set because look up takes O(1) where as list is O(n) dic = {} listdic = [] for i in range(len(strings)): string = strings[i] curdic = dic for j in string: if j in curdic: curdic = curdic[j] else: curdic[j] = {} curdic = curdic[j] curdic["end"] = i listdic.append(copy.deepcopy(dic)) for qq in queries: r , q = qq print (sheokand2(listdic[r-1],q)) return # strings = ["abcd","abce","abcdex","abcde"] # queries = [(3,"abcy"),(3,"abcde"),(4,"abcde"),(4,"ab"),(4,"a"),(4,"aa"),(4,"b")] # print("ANSWER :",makedic(strings,queries )) # print("ANSWER :",input(strings,3,"abcde" )) # print("ANSWER :",input(strings,4,"abcde" )) # print("ANSWER :",input(strings,4,"ab" )) # print("ANSWER :",input(strings,4,"a" )) # print("ANSWER :",input(strings,4,"aa" )) # print("ANSWER :",input(strings,4,"b" )) # 4 # abcd # abce # abcdex # abcde # 3 # 3 abcy # 3 abcde # 4 abcde # n = int(input()) # strings = [] # for i in range(n): # strings.append((input())) # q = int(input()) # queries = [] # for i in range(q): # r, querie = input().split(" ") # queries.append((int(r),querie)) # makedic(strings,queries)
a64975b07f4e72045250ce1bc94a801e62967094
anuvazhayil/Python-Programs
/RotationCipher.py
533
3.59375
4
class RotationCipher(object): def __init__(self): self.plain = '' def rot_cipher(self, rot, cipher): for elem in cipher: if elem.isalpha(): if elem.isupper(): if ord(elem) + rot > 90: self.plain += chr(ord(elem) + rot - 26) else: self.plain += chr(ord(elem) + rot) if elem.islower(): if ord(elem) + rot > 122: self.plain += chr(ord(elem) + rot - 26) else: self.plain += chr(ord(elem) + rot) else: self.plain += elem return self.plain
bbbacf8c3dc58f10eec1b4904bf2267ce6f61554
ryankynor/Final-Project
/Finalproject.py
1,220
4.09375
4
""" Ryan Kynor Geostationary orbit calculator """ import math deltav = 0 #parameters of rocket staticmass = int(input("What is the dry mass of the rocket in kg? ")) fuelmass = int(input("What is the mass of the fuel in the rocket in kg? ")) thrustvelocity = int(input("What is the thrust velocity of the engine used in the rocket in meters per second? ")) #calculating the total mass of the rocket in kg totalmass = fuelmass + staticmass #calculation using Tsiolkovsky rocket equation deltav = thrustvelocity * math.log(totalmass/staticmass) if deltav >= 13500: print("Yay! Your rocket made it to geostatonary orbit!") print("Your Delta-V was {0}",deltav) print("You need 13,500 meters per second of acceleration to reach geostationary orbit.") else: print("Your rocket didn't make it to geostationary orbit.") print("Your Delta-V was {0}",deltav) print("You need 13,500 meters per second of Delta-V to reach geostationary orbit.") #program written with idea of optimal orbital trajectory and average amount of aerodynamics """ Planning to take into account different launch tragectories and basic orbital maneuvers in the future This would be based on date and coordinates """
682abfb3f19fe60bde02a455a448110bfe5b5073
joachimds/raspberry
/square_fixer.py
804
3.859375
4
from sys import exit from math import sqrt # Read A variable try: getal1 = float(input('A ')) except ValueError: print ("Het is geen getalletje") exit() # Read B variable try: getal2 = float(input('B ')) except ValueError: print ("Het is geen getalletje") exit() # Read C variable try: getal3 = float(input('C ')) except ValueError: print ("Het is geen getalletje") exit() if (getal2**2 - 4*getal1*getal3 < 0): print ("No solutions") elif getal1 == 0: print ("1 solution") print (-getal3/getal2) else: print ("2 solutions") sol1 = (-getal2 + sqrt(getal2**2 - 4*getal1*getal3))/(2*getal1) sol2 = (-getal2 - sqrt(getal2**2 - 4*getal1*getal3))/(2*getal1) print (sol1) print (sol2)
fe892de04ecbf1e806c4669f14b582fd1a801564
qodzero/icsv
/icsv/csv
578
4.15625
4
#!/usr/bin/env python3 import csv class reader(obj): ''' A simple class used to perform read operations on a csv file. ''' def read(self, csv_file): ''' simply read a csv file and return its contents ''' with open(csv_file, 'r') as f: cs = csv.reader(f) cs = [row for row in cs] df = dict() for key in cs[0]: df[key] = [] df_keys = [key for key in df.keys()] for row in cs[1: ]: for i, col in enumerate(row): df[df_keys[i]].append(col) return df
58c8bf3e951488c0cf961ab4b4aadead3f204cd4
Dmitri00/hackerrank_problems
/week 1/swop.py
1,506
3.96875
4
def swap(arr,i,j): t = arr[i] arr[i] = arr[j] arr[j] = t return arr def bubble_sort(arr, foutput): if n < 2: foutput.write('No more swaps needed.\n') #return ['No more swaps needed.\n'] return left = 0 strs = [] while left < len(arr) : minim = arr[left] min_index = left right = left + 1 while right < len(arr): if arr[right] < minim: minim = arr[right] min_index = right right += 1 if left != min_index: swap(arr,left, min_index) #strs.append('Swap elements at indices {0:} and {1:}.\n'.format(left+1,min_index+1)) foutput.write('Swap elements at indices {0:} and {1:}.\n'.format(left+1,min_index+1)) left += 1 #strs.append('No more swaps needed.\n') foutput.write('No more swaps needed.\n') return strs if __name__ == '__main__': with open('input.txt','r') as finput: n = int(finput.readline()) arr = list(map(int, finput.readline().rstrip().split())) #n = int(input()) #arr = list(map(int, input().rstrip().split())) #for x,y in zip(arr, sorted(arr)): # assert x == y with open('output.txt','w') as fouput: #strs = bubble_sort(arr) bubble_sort(arr, fouput) #for line in strs: # fouput.write(line) for x in arr[:-1]: fouput.write('{:} '.format(x)) fouput.write('{:}'.format(arr[-1]))
dad76c97b4d6171816b64e56021b15c562dfad5b
anand004/hackerrank
/Python/Introduction to Sets.py
333
3.859375
4
def average(array): new_array=set(array) count=0 sum1=0 for i in new_array: sum1+=i count+=1 average=sum1/count return average # your code goes here if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
9c5588b50f93ef2de4605638cab3e829c621ca3b
anand004/hackerrank
/Python/String Split and Join.py
183
3.609375
4
def split_and_join(line): x= line.split(" ") y= "-".join(x) return y if __name__ == '__main__': line = input() result = split_and_join(line) print(result)
f26dcd75d3de055c2cd65d3c6c54e04c899714ba
akhawaja98/RobotPython
/GUI.py
634
3.671875
4
from tkinter import * class gui: def __init__(self, master): self.master = master master.title("Virtual simulator") self.label = Label(master, text="Welcome to our virtual simulator") self.label.pack() self.greet_button = Button(master, text="Start", command=self.greet) self.greet_button.pack() self.close_button = Button(master, text="Quit", command=master.quit) self.close_button.pack() def greet(self): print("Let's start") def quit(self): exit() root = Tk() my_gui = gui(root) root.mainloop()
c29b3d17cf6ccafb9c6f22b26057824745eb1ea1
Arko-p-Moitra/TicTacToe
/Tic tac Toe.py
4,418
4.34375
4
#This function will display the board def display_board(board): i=0 while i < len(board): print ('{} | {} | {}'.format(board[i],board[i+1],board[i+2])) print('---------') i = i +3 #This function will take input from user regarding the mark def player_input(): marker='' while marker !='X' and marker !='x' and marker != 'O' and marker !='o' : marker=input('Player 1.....Please select "X" or "O" : ') if marker =='X'or marker =='x': return('X','O') else: return('O','X') #This section will place the marker in the board based on the user's input def place_marker(board, marker, position): i=0 pos=int(position) pp=pos-1 while i<len(board): board[pp]=marker i=i+1 #This section will check if a player won the match def win_check(board, mark): return ((board[6] == board[7] == board[8] == mark) or # across the top (board[3] == board[4] == board[5] == mark) or # across the middle (board[0] == board[1] == board[2] == mark) or # across the bottom (board[6] == board[3] == board[0] == mark) or # down the middle (board[7] == board[4] == board[1] == mark) or # down the middle (board[8] == board[5] == board[2] == mark) or # down the right side (board[6] == board[4] == board[2] == mark) or # diagonal (board[8] == board[4] == board[0] == mark)) # diagonal #This section will choose which player will go first import random def choose_first(): random_player=random.randint(1, 2) return random_player #This section will check if a position is empty or not def space_check(board, position): marks=['X','x','O','o'] pos=int(position) if board[pos] in marks: return print('this poisition is occupied') else: return print('This position is free') #This section will check if the board is full or not def full_board_check(board): marks=['X','x','O','o'] creck=all(elem in marks for elem in board) if creck: return True #This section will take the input from user def player_choice(board): position=input('Enter the next position = ') #space_check(board, position) return position #From here the actual code is started print('Welcome to Tic Tac Toe') theBoard = [1,2,3,4,5,6,7,8,9] display_board(theBoard) print('\n') #player_input() player1_mark,player2_mark=player_input() print("Player 1's mark is this = {} and Player 2's mark is this = {}".format(player1_mark,player2_mark)) print('\n \n') player=choose_first() player_SecondPart= player print('Player {} will go first'.format(player)) counter = 0 game_on=True #while game_on==True: i=0 while i<5: if player==1: pos=player_choice(theBoard) place_marker(theBoard, player1_mark, pos) player=2 else: pos=player_choice(theBoard) place_marker(theBoard, player2_mark, pos) player=1 newBoard=theBoard display_board(newBoard) i=i+1 if win_check(newBoard, player1_mark)==True: print('Player 1 Won') elif win_check(newBoard, player2_mark)==True: print('Player 2 Won') elif win_check(newBoard, player2_mark)==False: j=0 win='' while j<5: if player_SecondPart==1: pos=player_choice(newBoard) place_marker(theBoard,player2_mark,pos) if win_check(newBoard, player2_mark)==True: display_board(newBoard) win='Player 2 win' print(win) break else: if full_board_check(newBoard)==True: display_board(newBoard) print("It's a draw") break else: display_board(newBoard) player_SecondPart=2 elif player_SecondPart==2: pos=player_choice(newBoard) place_marker(newBoard,player1_mark,pos) if win_check(newBoard, player1_mark)==True: display_board(newBoard) win='Player 1 win' print(win) break else: if full_board_check(newBoard)==True: display_board(newBoard) print("It's a draw") break else: display_board(newBoard) player_SecondPart=1 j=j+1
95bab4811ba29854a3b44d32a2aee725866cdce7
mrmittag/Introduction-to-Programing
/Projects/project_6/rock_paper_scissors_0.py
1,092
4.0625
4
from random import randint play = True moves = ["rock","paper","scissors"] while play == True: user_choice = input("What is your choice: rock, paper or scissor") random_number = randint(0,2) computer_choice = moves[random_number] if user_choice == "rock": if computer_choice == "rock": win = False tie = True elif computer_choice =="scissors": win = True tie = False elif computer_choice =="paper": win = False tie = False elif user_choice == "paper": if computer_choice == "paper": win = False tie = True elif computer_choice =="rock": win = True tie = False elif computer_choice =="scissors": win = False tie = False elif user_choice == "scissors": if computer_choice == "scissors": win = False tie = True elif computer_choice =="paper": win = True tie = False elif computer_choice =="rock": win = False tie = False print("I chose ",computer_choice) print("You chose ", user_choice ) if win == True: print("You won!") elif win == False: print("You lost!") elif tie == True: print("We tied!")
2f10aa6c85ff0c353531e1c965c41b140a1e7a51
mrmittag/Introduction-to-Programing
/Projects/project_2/snake_4b.py
1,665
3.890625
4
import curses import time screen = curses.initscr() screen.border() screen.nodelay(1) screen.keypad(1) direction =0 game_over =False head=[1,1] def processInput(direction): """This function processes any user input""" userinput = screen.getch() if userinput == curses.KEY_UP: direction = 3 elif userinput == curses.KEY_DOWN: direction = 2 elif userinput == curses.KEY_LEFT: direction = 1 elif userinput == curses.KEY_RIGHT: direction = 0 return direction def update(direction): """This function updates the state of the game. It advances the game one step. Performs AI and Physics""" if direction == 3: head[0] -=1 elif direction == 2: head[0] += 1 elif direction == 1: head[1] -= 1 elif direction == 0: head[1] += 1 screen.refresh() time.sleep(0.1) def collison(direction): """This function is used to detect a collision""" if direction == 3 and screen.inch(head[0]-1,head[1]) !=ord(' '): return True elif direction == 2 and screen.inch(head[0]+1,head[1]) !=ord(' '): return True elif direction == 1 and screen.inch(head[0],head[1]-1) !=ord(' '): return True elif direction == 0 and screen.inch(head[0],head[1]+1) !=ord(' '): return True else: return False def display(): """This function draws all of the stuff in the game""" screen.addch(head[0],head[1],'x') while game_over == False: direction = processInput(direction) update(direction) display() game_over = collison(direction) curses.endwin()
32a16495f550cabcab3ce799921e458b7d0e939f
manishadhakal/manu
/if_statement.py
101
4
4
age=input("enter your name:") age=int(age) if age>=18: print("your are eligible for dance party")
b81f9f1046ed75b5f84f8578913b48fd08fe77e4
stickhero23/CS313E
/Triangle.py
2,499
3.8125
4
# returns the greatest path sum using exhaustive search def exhaustive_search (triangle, index, i, b, c): if i == (len(triangle)): b.append(c) else: c += triangle[i][index] return exhaustive_search(triangle, index, i + 1, b, c) or exhaustive_search(triangle, index + 1, i + 1, b, c) # returns the greatest path sum using greedy approach def greedy (triangle): index = 0 c = 0 for i in range(len(triangle) - 1): c += triangle[i][index] if (triangle[i + 1][index] > triangle[i + 1][index + 1]): index = index else: index = index + 1 c += triangle[i + 1][index] return c # returns the greatest path sum using divide and conquer (recursive) approach def rec_search (triangle, c, b): if len(triangle) == 1: b.append(c + triangle[0][0]) else: triangle1 = [] triangle2 = [] for line in triangle[1:]: triangle1.append(line[1:]) triangle2.append(line[:-1]) c = c + triangle[0][0] return (rec_search(triangle1, c, b)) or (rec_search(triangle2, c, b)) # returns the greatest path sum using dynamic programming def dynamic_prog (triangle): total = triangle[-1] for i in range(len(triangle) - 1, 0, -1): line1 = triangle[i - 1] line2 = total total = [] for j in range(len(line1)): total.append(max((line1[j] + line2[j]), (line1[j] + line2[j + 1]))) return total[0] # reads the file and returns a 2-D list that represents the triangle def readFile (file): triangle=[] file.readline() for line in file: line = line.split() line = [int(i) for i in line] triangle.append(line) return triangle def main (): # read triangular triangle from file triangle = [] in_file = open("triangle.txt","r") triangle = readFile(in_file) # output greates path from exhaustive search b = [] exhaustive_search (triangle, 0, 0, b, 0) print("The greatest path sum through exhaustive search is " + str(max(b)) + ".") # output greates path from greedy approach print("The greatest path sum through greedy search is " + str(greedy(triangle)) + ".") # output greates path from divide-and-conquer approach a = [] rec_search(triangle, 0, a) print("The greatest path sum through recursive search is " + str(max(a)) + ".") # output greates path from dynamic programming print("The greatest path sum through exhaustive search is " + str(dynamic_prog(triangle)) + ".") main()
fb923903d9aadc71cb40c9200c3ca0dafdd066c1
stickhero23/CS313E
/Nim.py
1,204
3.734375
4
#helper functions in order to get nim_sum def nim_sum(list_nums): exclusive_sum = 0 for i in list_nums: exclusive_sum = exclusive_sum^i return exclusive_sum def nim_sum_heaps(nim_sum, list_nums): for i in list_nums: num_sum_heaps = nim_sum^i if num_sum_heaps< i: move = i - num_sum_heaps num_heap = list_nums.index(i)+1 return move, num_heap #file processing for data def main(): import string # open file for reading in_file = open ("./nim.txt", "r") # read number of games num_games = in_file.readline() num_games = num_games.strip() num_games = int (num_games) #get heap numbers within each game and append as ints for i in range (num_games): heap_nums = in_file.readline() heap_nums = heap_nums.strip() heap_nums = heap_nums.split(" ") list_nums = [] for j in (heap_nums): list_nums.append(int(j)) #find nim_sum nim_sum_1 = nim_sum(list_nums) if nim_sum_1 == 0: print("Lose Game") else: move, num_heap = nim_sum_heaps(nim_sum_1, list_nums) print ("Remove "+str(move)+" counters from Heap "+str(num_heap)) in_file.close() main()
a549bd64dc0b726d9aa8b8e0f08e7411700fa9fa
aha1464/lpthw
/ex19.py
1,537
4
4
# LPTHW EX19 # comment out 1 line """ comment out multiple lines""" """ Variables in the function are not connected to the variables in the script defined variables below """ def cheese_and_crackers(cheese_count, boxes_of_crackers): print(">>> cheese_count=", cheese_count, "boxes_of_crackers=", boxes_of_crackers) print(f"You have {cheese_count} packets of cheese!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man that's enough for a party!") print("Get a blanket.") print("<<<< exit cheese_and_crackers\n") # make sure that the indentation is removed otherwise python doesn't seem to want to run # Commented out to try input values below """print("We can just give the function numbers directly:") cheese_and_crackers(20, 30)""" print("We can give the inputs directly into the teminal:\n") print(f"How many packets of cheese do you have?\n") cheese = input () print(f"How many boxes of crackers do you have?\n") crackers = input () cheese_and_crackers(cheese, crackers) print("OR, we can use variables from our script:") amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print("We can even do math inside too:") #print(f"How many packets of cheese do you have?") #cheese = input () #print(f"How many boxes of crackers do you have?") #crackers = input () cheese_and_crackers(100 + 10, 5 + 6) print("And we can combine the two, variables and math:") cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
8b9059649cbaad48bb6b53fa8a4624eb9b5819a9
aha1464/lpthw
/ex21.py
2,137
4.15625
4
# LPTHW EX21 # defining the function of add with 2 arguments. I add a and b then return them def add(a, b): print(f"ADDING {a} + {b}") return a + b # defining the function of subtract def subtract(a, b): print(f"SUBTRACKTING {a} - {b}") return a - b # defining the function of multiply def multiply(a, b): print(f"MULTIPLING {a} * {b}") return a * b # defining the function of divide def divide(a, b): print(f"DIVIDING {a} / {b}") return a / b # print the text in the string and add a new line print(f"let's do some math with just functions!\n") # defining age, height, weight & iq by addition, subraction, multiplying and # dividing with the (the values, required) age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) # print the text with their {variable} print(f"Age: {age}, Height {height}, Weight {weight}, IQ {iq}\n") # a puzzle for the extra credit, type it in anyway # print the text below in the terminal print(f"Here is the puzzle.") # WTF, I have no idea??? Inside out: (iq, 2)(/ weight)(multiply by height) #(subtract age) add # 50/2 = 25 # 180 * 24 = 4500 # 74 - 4500 # 35 + -4426 = -4391 # what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print("That becomes: ", what, "Can you do it by hand?") print("24 + 34 / 100 - 1023") # Extra Credit: # 1. If you aren't really sure what return does, try writing a few of your own # functions and have them return some values. You can return anything that you # can put to the reight of an = # 2. At the end of hte script is a puzzle. I'm taking th return value of one # function and using it as the argument of an other funtion. I'm doing this in # a chain so that I'm kind of creating a formula using the function. It looks # really weird, but if you run the sript, you can see the results. # 3. Once you have the formula worked out for the puzzle, get in there and see # what happens when you modify the parts of the functions. Try to change it on # purpose to make another value. # 4. Do the inverse. Write a simsple forumula and use the functions in the # same way to calculate it.
6345bac40a37f7811ffd2cf6b011e339bdd072f7
aha1464/lpthw
/ex16.py
1,371
4.25
4
# import = the feature argv = argument variables sys = package from sys import argv # script, filename = argv # printed text that is shown to the user when running the program print(f"We're going to erase (filename).") print("If you don't want that, hit CTRL-C (^c).") print("If you do want that, hit RETURN.") # input = user input required ("prompt text goes here") input("?") # prints ("the text") print("Opening the file...") # target = open(user inputed filename in the terminal) 'W' says open this file in 'write mode' target = open(filename, 'w') # prints ("the text here") print("Truncating the file. Goodbye!") # target command truncate: empties the file. target.truncate() # prints("the text" in the terminal) print("Now I'm going to ask you for three lines.") # # line1 is the id and input gives the command that the user needs to input info line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: " # prints ("the text" in the terminal) print("I'm going to write these to the file.") # target.write(the text the user inputs in the terminal when prompted) target.write(line1) # using ("\n") starts a new line target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") # print the ("text") print("And finally, we close it.") # targer.close() closes and saves the file that has been created target.close()
992a1523de805e2fd0d0716cfb9fe02d8edc5cfc
Sindhu1024/python_28
/Activity_05.py
139
4.1875
4
num = input("Enter 5 numbers") num1 = num.split(' ') sum = 0 for i in num1: sum = sum + int(i) print("The sum of the numbers:",sum)
abe3bad19c62b4a46629664b4b6ced60284e0b7e
taskj/JPyDemo
/Python基础/函数/闭包的概念.py
465
3.75
4
def outer(): x = 10 #在外部函数里定义了一个变量x,是一个局部变量 def inner(): #在函数内部如何修改外部函数的局部变量 #x = 20 不是修改外部的x变量,而是在inner函数内部又创建了一个新的变量x nonlocal x #此时,这里的x不再是新增的变量,而是外部的局部变量x y = x + 1 print('inner里的y=',y) x = 20 return inner() outer()()
516131674444caac28a69e3fef0e891e6dbf4467
taskj/JPyDemo
/Python基础/列表/删除列表中空字符串.py
385
3.890625
4
# 删除列表中的空字符串 words = ['hello','good','','','yes','ok',''] ''' 在用for...in遍历列表时,最好不要进行增加和删除操作,删掉元素后会漏掉 for word in words: if word == '': words.remove(word) print(words) ''' i = 0 while i < len(words): if words[i] == "": words.remove(words[i]) i -= 1 i += 1 print(words)
c8b1f88c16a239d2053e66fb2ede3dd65a3fe141
taskj/JPyDemo
/Python基础/函数/sort方法的使用.py
912
4
4
#有几个内置函数和内置类,用到了匿名函数 nums = [4,8,2,1,7,6] # nums.sort() # print(nums) ints = (5,9,2,1,3,8,7,4) #sorted内置函数,不会改变原有数据,而是生成一个新的结果 x = sorted(ints) print(ints) students = [ {'name':'zhangsan','age':14,'score':98,'height':198}, {'name':'lisi','age':13,'score':38,'height':23}, {'name':'wangwu','age':12,'score':48,'height':131}, {'name':'zhaoliu','age':8,'score':28,'height':129}, ] #字典与字典之间不能使用比较符运算 #students.sort() def foo(ele): print("ele = {}".format(ele)) return ele['age'] #通过返回值告诉sort方法,按照元素的属性进行排序 ''' 需要传递参数key,指定比较规则 key参数类型是一个函数 在sort内部实现的时候,调用了foo方法,并传入了一个参数,参数就是列表里面的元素 ''' students.sort(key=foo)
5e8ef378032daa50cb181e7bbc60f8dfe45578b0
taskj/JPyDemo
/Python基础/字典/集合运算符的使用.py
462
3.5625
4
first = {'李白','白居易','李清照','杜甫','王昌龄','王维','孟浩然','王安石'} second = {'李商隐','杜甫','李白','白居易','岑参','王昌龄'} third = {'李清照','刘禹锡','岑参','王昌龄','苏轼','王维','李白'} ''' set 支持多数运算符 ''' print(first - second) #求 a-b 的差集 print(first & second) #求 a和b 的交集 print(first | second) #求 a和b 的并集 print(first ^ second) #求 a和b差集的并集
b1fbb0504fca2758d7b7f6db9b5b4f4687543fb8
taskj/JPyDemo
/学生教师管理系统GUI/fileoperator.py
1,771
3.75
4
class Files: def __init__(self): #记录学生信息的文件路径 self.student_path = "student.txt" #记录教师信息的文件路径 self.teacher_path = "teacher.txt" #定义学生存储所用的List self.list_student_all = [] #定义老师存储所用的List = [] self.list_teacher_all = [] self.read_from_file() def read_from_file(self): #读取学生信息 try: with open(self.student_path,encoding="utf-8",mode="r") as fd_student: #逐行读取 current_line = fd_student.readline() #判断是否有数据 while current_line: #分割成数组 student_list = current_line.split(",") #直接添加 self.list_student_all.append(student_list) #读取下一行 current_line = fd_student.readline() except Exception as e: raise e #读取教师信息 try: with open(self.teacher_path,encoding="utf-8",mode="r") as fd_teacher: #逐行读取 current_line = fd_teacher.readline() #判断是否有数据 while current_line: #分割成数组 teacher_list = current_line.split(",") #直接添加 self.list_teacher_all.append(teacher_list) #读取下一行 current_line = fd_teacher.readline() except Exception as e: raise e if __name__ == '__main__': file = Files() file.read_from_file() print(file.list_student_all)
1f625f7f2db037ae82f776445e49792cd8afc2ff
jonbugge4/Numpy
/MyArrays2.py
1,703
3.65625
4
import numpy as np #Rows - Each Student (Student0, Student1, Student2, Student3) #Columns - Each Test (Test0, Test1, Test 2) grades = np.array([[87,96,70], [100,87,90], [94,77,90],[100,81,82]]) student1 = grades[1] #row, column student0_Test1 = grades[0,1] #Upper bound is not included so we do 2 instead of 1 students0_1 = grades[0:2] #double brackets represent just rows, not columns allows us to grab two students student1and3 = grades[[1,3]] #grades[row,column] #grades[[1,3], 2] student1and3_test2 = grades[[1,3],2] #just doing a collen, python knows to grab upper and lower bound allstudents_tes1 = grades[:,0] all_students_test1_2 = grades[:, 1:3] all_students_test0_2 = grades[:,[0,2]] import random grades = np.random.randint(60, 101, 12).reshape(3,4) grades.mean() #average by test-score (column) grades.mean(axis=0) #average by student (row) grades.mean(axis = 1) numbers = np.arange(1,6) #shallow copy numbers_view = numbers.view() numbers[1] *= 10 numbers_view[1] /= 10 number_slice = numbers[0:3] numbers[1] *= 20 #Deep Copies- changes to the orginial does NOT affect the deep copy numbers_copy = numbers.copy() numbers[1] *= 10 #reshape method produces a shallow copy grades = np.array ([[87,96,70],[100,87,90]]) grades_reshaped = grades.reshape(1,6) #resize method changes the original array grades.resize(1,6) #flatten creates a deep copy flattened = grades.flatten() #raveled creates a shallow copy raveled = grades.ravel() raveled[0] = 100 flattened[1] = 100 grades = np.array ([[87,96,70],[100,87,90]]) grades.T grades2 = np.array([[94,77,90], [100,81,82]]) h_grades = np.hstack((grades, grades2)) v_grades = np.vstack((grades, grades2)) print()
9305b966fab8a9168824705a1ec00ebe02734b84
cabudies/Python-8-September-2018
/Python/sample_module_addition.py
93
3.5
4
def add(a,b): result = a+b print("Addition result of ", a, " & ", b, " is: ", result)
eedb176bbeb1f4e21c7e4906bff3dd56b51cc3e9
gauravdargan66/Portfolio
/pycrypto/pymysql/main.py
773
3.734375
4
import sqlite3 con = sqlite3.connect("mycompany.db") cObj = con.cursor() cObj.execute("CREATE TABLE IF NOT EXISTS employees(id INTEGER PRIMARY KEY, name TEXT, salary REAL, department TEXT, pposition TEXT)") con.commit() def insert_value(id, name, salary, department, position): cObj.execute("INSERT INTO employees VALUES(?, ?, ?, ?, ?)",(id, name, salary, department, position)) con.commit() def update_value(dep, id): cObj.execute("UPDATE employees SET department=? WHERE id=?",(dep, id)) con.commit() def sql_fetch(): cObj.execute("SELECT * FROM employees") result = cObj.fetchall() print(result) def delete_all(): cObj.execute("Delete from employees") con.commit() cObj.close() con.close()
a354c2e85f0b0e053b84709a7d587fdc466bf723
gauravdubey7/ATM
/ATM_code.py
1,011
3.9375
4
input("Welcome to 'AXIS BANK ATM'. Press 'ENTER' to continue. ") input("Swipe your card. Press 'ENTER'. ") option = ['Balance enquiry','Withdraw money','Quit'] pin_no = 1000 pin_no = input("'ENTER' your pin to proceed:") try: if pin_no = 1000: print('Type your option from the following:') print('1.Balance enquiry') print('2.Withdraw money') print('3.Quit') except Exception: print('You entered the wrong pin.Try again!') opt = input('Type your option here:') if opt == 'Balance enquiry': slip = input('Do you want slip?') if slip == 'Yes': print('Here is your slip!') else: print('Thanks for using AXIS BANK ATM. ') elif opt == 'Withdraw money': amount = input('Enter your amount to proceed:') if amount>0: print('Collect your cash,Thanks!') else: print('Enter valid amount to proceed.') elif opt == 'Quit': quit = input("Type 'Yes' to quit:") if quit == 'Yes': print('You have quit, Thanks!') else: print('Choose any transaction please!')
7c12d040923e2a69f3dfef2ca28c119369cd6963
sebastianfrasic/Arenas-PIMO
/Bono parcial 1/intercambios.py
1,124
3.671875
4
from sys import stdin def unir(low,high,lista): contador_final = 0 if high > low+1: mid = low + ((high-low)//2) contador_final = unir(low,mid,lista) + unir(mid,high,lista) + Merge_Sort(low,high,mid,lista) return contador_final def Merge_Sort(low,high,mid,lista): contador = 0 i = 0 j = 0 first = lista[low:mid] second = lista[mid:high] for x in range(low,high): if -mid + high == j: lista[x] = first[i] i = i + 1 elif (mid-low) == i: lista[x] = second[j] j = j + 1 else: if first[i] > second[j]: lista[x] = second[j] j = j + 1 contador = (-i+(mid-low)) + contador else: lista[x] = first[i] i+=1 return contador def main(): n = int(stdin.readline().strip()) while n!=0: lista = [] for i in range(n): lista.append(int(stdin.readline().strip())) resp = unir(0,n,lista) print(resp) n = int(stdin.readline().strip()) main()
9554510fb037061639b3f9b8441d3be5bf3d7942
huier522/test
/2-input.py
149
3.609375
4
name = input('請輸入名字:') print('Hi,', name) height = input('請輸入身高: ') weight = input('請輸入體重: ') print(height, weight)
2277df744b6ba8dd5a19cb1456ad0b7fc342cdc8
killedman/PythonPracticeQuestions
/write_city_data_to_excel.py
853
3.5
4
#! /usr/bin/env python # -*- coding: utf8 -*- # author: dreampython # date: 2018-10-23 # 第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示: # 请将上述内容写到 city.xls 文件中 # 步骤1: 读取city.txt中的数据 # 步骤2: 创建excel对象 from openpyxl import Workbook import json def read_txt_file(): with open('./city.txt','r',encoding='utf-8-sig') as file: load_dict = json.load(file) return load_dict def create_excel_file(citys): wb = Workbook() sheet = wb.active sheet.title = "citys" i = 0 for city in citys: i = i + 1 sheet["A%d" %i].value = city sheet["B%d" %i].value = citys.get(city) wb.save('./citys.xlsx') if __name__ == "__main__": citys = read_txt_file() create_excel_file(citys)
9ac67c124324b7a64f5378305c7ed9a011485571
killedman/PythonPracticeQuestions
/replace_sensitive_word.py
1,309
3.703125
4
#! /usr/bin/env python # -*- coding: utf8 -*- # author: dreampython # date: 2018-10-23 # 第 0012 题: 敏感词文本文件 filtered_words.txt,当用户输入敏感词语,则用 星号 * 替换, # 例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 def read_senstive_word(): words = [] with open('./filtered_words.txt', 'r', encoding='utf8') as file: content = file.readlines() for line in content: # 去除开头的\ufeff字符 line = line.replace('\ufeff', '') # 去除换行符 line = line.strip() words.append(line) return words def replace_input_word(checked_word, sensitive_word): for word in sensitive_word: if word in checked_word: checked_word = checked_word.replace(word, '*') print(checked_word) def input_word(checked_word, sensitive_word): while checked_word: replace_input_word(checked_word, sensitive_word) checked_word = input('please input word: ') if __name__ == '__main__': print('begin input word...') print('attention: Hit the Enter key will quit this program.') sensitive_word = read_senstive_word() checked_word = input('please input word: ') input_word(checked_word, sensitive_word)
466111f9e693b5b225d344cd59dc0386dbf48313
nhaantran/python
/3.Chuoi~2.py
1,080
3.53125
4
'''chuỗi trần''' print('Haizz, mình thích mấy \ngay này') print(r'Haizz, mình thích mấy \ngay này') #toán tử cộng strA = "Nhân Trần\n" strB = "lớp 12a2" strC = strA + "\n"+ strB print(strC) #toán tử nhân strC = strA*2 + strB*2 print(strC) #toán tử in (true hoặc false) a = "abcdef" b = "g" c = b in a print(c) #indexing và cắt chuỗi (từ 0 đến n-1)*lưu ý nhen! A = "abc def" B = A[0] C = A[-2] print(B) print(C) #lấy ra phần tử cuối cùng D= A[len(A)-1] print(D) #cat chuoi~ E=A[1:5] F=A[3:len(A)] #or F=A[3:None] or F=A[None:2] or F=A[None:] or F=A[:] print(E) print(F) #cat chuoi~ nguoc lai p=A[None:None:-1] g=A[None:None:-2] print(g) print(p) #ép kiểu dữ liệu với cú pháp "kiểu dữ liệu muốn ép ra"(giá trị muốn ép) q= int(6.9) #hoặc float(6) hoặc int("6") print(q) '''số thành chuỗi a= str(69) + "5" kết quả sẽ là 695''' #thay đổi nội dung chuỗi ba = "HowKteam.com" ba = ba[None:1]+ '0'+ ba[2:None] print(ba) print(hash(ba))
19dfc6fe1c4839f0e5828eb46f5535eb071bd5f6
nhaantran/python
/1.Fraction.py
164
3.8125
4
from fractions import* frac=Fraction(1,3) print(frac) print(type(frac)) frac1=Fraction(7,5) frac2=Fraction(6,8) print(frac1 + frac2) a= 3 b= 2 print(a**b)
8744455703ae7e9da09783a887d2c1a82215aa7f
nhaantran/python
/abc.py
608
3.59375
4
waytosucceed= ['learn','relax','enjoy','experience'] print('These are the steps to help you succeed') for steps, advice in enumerate(waytosucceed,1): print(steps,'is', advice) print('------------------------------------------------') List = ['avocado','sweet potato','salmon','chocolate','rice','broccoli'] Lst= [a.capitalize() for a in List] print('Foods that Id to eat on a regular basis:') for numbers, foods in enumerate(Lst,1): print(numbers,'. ',foods,sep='') print('-------------------------------------------------------------') def a6(nameage): print(nameage + '!') a6('Nhan-18')
bd0139736354ec0f30ae72ae2b6ebd865ee52fac
abhinav-garg/Developer
/Project Euler/sumPrime.py
200
3.765625
4
def isPrime(n): for i in range(2, n): if n%i == 0: return False return True count = 0 i = 2 s = 0 while i <= 2000000: if isPrime(i): count += 1 s += i print '#', count, i i += 1 print s
4a0469e2370d8e6b762051f6caa1072170f7c9b1
RanaAqib/pythonclass
/main.py
62
3.65625
4
r=3 area=3.14*r**2 print('Area of Cicle is: '+str(area))
c4e61b7613fabe1e1b2412054b2547e850e6357c
svudya/ML_code
/logisticRegGradDesc.py
1,323
3.625
4
import numpy as np import matplotlib.pyplot as plt def step_gradient(thet, points,learning_rate): thet_grad = 0 new_grad = 0 N = float(len(points)) for i in range(len(points)): y = points[i,0] x = points[i,1] if np.isnan(x) or np.isnan(y) : pass else : thet_grad += -1/N * (np.log(1+np.exp((-y)* thet * x))) new_grad = thet - (learning_rate * thet_grad) return new_grad def compute_y(theta, x_list): y_final= [] for i in range(len(x_list)): y_final.append(1/(1+np.exp((-theta)*x_list[i]))) return y_final def gradient_descent_runner(thet, points, learning_rate, iterations): for i in range(iterations): theta = step_gradient(thet, np.array(points),learning_rate) return theta def run(): points = np.genfromtxt('./titanic_train.csv',delimiter=',',skip_header=1,usecols=(1,4)) learning_rate = 0.0001 thet = 0 iterations = 1000 x_list = [] y_list = [] num_iterations = 1000 print "Logistic Regression" for i in range(len(points)): y = points[i,0] x = points[i,1] if np.isnan(x) or np.isnan(y) : pass else : x_list.append(x) y_list.append(y) print x_list print y_list theta = gradient_descent_runner(thet, points, learning_rate, iterations) plt.scatter(x_list,y_list) plt.plot(x_list, compute_y(theta, x_list)) plt.show() if __name__ == '__main__': run()
a2b20fc074c95160960b3406c6869ff2e33a93d4
smadhuvarsu/Python
/Rock,Paper,Scissors.py
2,104
4.0625
4
import random moves=["r","p","s"] cscore=0 uscore=0 tscore=0 name=input("What is your name:") print() print("Hi",name.title(),"! Are you ready to play rock,paper scissors? Good! If you want to do rock,enter 'r'.If you want to do paper,enter 'p'.If you want to do scissors,enter 's'.Your oppenent will be the computer.") print() rounds=int(input("One minute...please enter how many rounds you want to play:")) print("-------------------------------------------------------------------------------------------------------------") for i in range(rounds): print("Round #",i+1) user=input("What is your move:") computer=random.choice(moves) #Computer Wins if (computer=="s") and (user=="p"): print("Computer wins!") cscore+=1 elif (computer=="r") and (user=="s"): print("Computer wins!") cscore+=1 elif (computer=="p") and (user=="r"): print("Computer wins!") cscore+=1 #User Wins elif (computer=="s") and (user=="r"): print("You win!") uscore+=1 elif (computer=="r") and (user=="p"): print("You win!") uscore+=1 elif (computer=="p") and (user=="s"): print("You win!") uscore+=1 #Tie elif (computer=="r") and user=="r": print("It is a tie!") tscore+=1 elif (computer=="p") and (user=="p"): print("It is a tie!") tscore+=1 elif (computer=="s") and (user=="s"): print("It is a tie!") tscore+=1 else: print("Something went wrong(I think you typed an unknown letter or a number).") print("This means you will have to miss a turn..:(") print("Here are your scores:",uscore) print("Here are the computer's scores:",cscore) print("Here are the number of ties you had:",tscore) if (cscore>uscore): print("The winner of this game is..the Computer!") if (uscore>cscore): print("The winner of this game is..",name.title(),"!")
113476d2e6849d536db1135fe007102d7fb8a444
happyliang20211013/machine-learning-Andrew
/ex1_linear_regression/linear_regression_with_one_variable.py
1,987
3.59375
4
import matplotlib.pyplot as plt if __name__ == "__main__": # Part1:从txt文件中读取数据,绘制成散点图 f = open("ex1data1.txt", 'r') population = [] profit = [] for line in f.readlines(): col1 = line.split(',')[0] col2 = line.split(',')[1].split('\n')[0] population.append(float(col1)) profit.append(float(col2)) plt.subplot(2, 2, 1) plt.title("Scatter plot of training data") plt.xlabel("population of city") plt.ylabel("profit") plt.scatter(population, profit, marker='x') # part2:递归下降,同时记录损失值的变化 m = len(population) alpha = 0.01 iterations = 1500 theta = [0, 0] t = [] cost = [] theta0 = [] theta1 = [] c = 0 for j in range(m): c += 1.0 / (2 * m) * pow(theta[0] + theta[1] * population[j] - profit[j], 2) print(c) for i in range(iterations): t.append(i) temp0 = theta[0] temp1 = theta[1] for j in range(m): temp0 -= (alpha / m) * (theta[0] + theta[1] * population[j] - profit[j]) temp1 -= (alpha / m) * (theta[0] + theta[1] * population[j] - profit[j]) * population[j] theta[0] = temp0 theta[1] = temp1 c = 0 for j in range(m): c += 1.0 / (2 * m) * pow(theta[0] + theta[1] * population[j] - profit[j], 2) cost.append(c) theta0.append(temp0) theta1.append(temp1) # part3:绘制回归直线图,已经损失函数变化图 x = [5.0, 22.5] y = [5.0 * theta[1] + theta[0], 22.5 * theta[1] + theta[0]] plt.subplot(2, 2, 2) plt.plot(x, y, color="red") plt.title("Linear Regression") plt.xlabel("population of city") plt.ylabel("profit") plt.scatter(population, profit, marker='x') plt.subplot(2, 2, 3) plt.title("Visualizing J(θ)") plt.xlabel("iterations") plt.ylabel("cost") plt.plot(t, cost, color="red") plt.show()
b49d797270cc2edd022b4304129cbd42f117f692
dreamofwind1014/gloryroad
/练习题/2020.06.19练习题--赵华恬.py
2,726
3.875
4
# 练习176:写一个函数,识别输入字符串是否是符合 python 语法的变量名 # (不能数字开头、只能使用数字和字母以及‘_’) import string # # def check_var(var): # if var[0] in "0123456789": # isdigit() # return False # for v in var: # if not (v in string.ascii_letters or v in string.digits or v == "_"): # not( v.isalnum() or v == "_"): # return False # return True # print("%s 是合法变量:%s" % ("_abA122", check_var("_abA122"))) # # # print("%s 是合法变量:%s" % ("13abc", check_var("13abc"))) # 练习177:一个句子中的所有数字和标点符号删除 # import string # import re # # s = "i am a boy, my age is 19 years ." # res = "" # for letter in s: # if not letter.isdigit() and letter not in string.punctuation: # res += letter # print(res) # # s = "i am a boy, my age is 19 years." # r = "" # for letter in s: # if letter in string.ascii_letters or letter == " ": # r += letter # # print("333", r) # # for letter in s: # if letter in "0123456789": # s = s.replace(letter, "") # if letter in string.punctuation: # s = s.replace(letter, "") # print(s) # # print(" ".join(re.findall(r"\b[a-z]+\b", s))) # # print("".join(list(filter(lambda x: re.match(r"\b[a-z]+\b", x), s.split(",."))))) # 练习178:自定义实现str.capitalize() # def capitalize(s): # first_letter = s[0] # if (first_letter >= "a") and first_letter <= "z": # first_letter = chr(ord(first_letter) - 32) # return first_letter + s[1:] # # # print(capitalize("abc")) # 练习179:自定义实现str.title() # 方式1: # def title(string): # temp_str1 = "" # temp_str2 = "" # for value in string.split(): # if (value[0] >= "a") and value[0] <= "z": # temp_str1 = chr(ord(value[0]) - 32) + value[1:] # temp_str2 += temp_str1 # return temp_str2 # # # print(title("hu hong qiang")) # 方式2: # def title(s): # result_list = [] # for word in s.split(): # word_first_letter = word[0] # if (word_first_letter >= "a") and word_first_letter <= "z": # word_first_letter = chr(ord(word_first_letter) - 32) # result_list.append(word_first_letter + word[1:]) # return "".join(result_list) # # # print(title("hu hong qiang")) # 练习180:自定义实现str.ljust(numbe) # def ljust(s, n, fill_char=" "): # if (not n >= 1) or (not isinstance(n, int)): # return s # print_length = n - len(s) # if print_length <= 0: # return s # else: # return s + print_length * fill_char # # # print(ljust("abc", 10, "*")) # 共计64行代码
3e9cb9d8ca2c3f1b238e8709bc2922752e716ccb
dreamofwind1014/gloryroad
/练习题/2020.06.17练习题--赵华恬.py
4,077
4.125
4
# 练习166:检测密码强度 """ c1: 长度 >= 8 c2: 包含数字和字母 c3: 其他可见的特殊字符 强:满足c1, c2, c3 中: 只满足任一2个条件 弱:只满足任一1个或0个条件 """ # # import operator # import string # # # def check_len(s): # if len(s) >= 8: # return True # else: # return False # # # def check_digit_letter(s): # digit_flag = False # letter_flag = False # for v in s: # # print(v) # if v in string.ascii_letters: # letter_flag = True # if v in string.digits: # digit_flag = True # # print(digit_flag,letter_flag) # if digit_flag and letter_flag: # return True # else: # return False # # # def check_other(s): # for v in s: # if v in string.punctuation: # return True # # return False # # # passwd_1 = "Hhq123456!" # passwd_2 = "Hhq123456" # # passwd_3 = "Hhq!" # # passwd_4 = "Hhq" # # # def check_password(s): # if check_len(s) and check_digit_letter(s) and check_other(s): # return "强" # elif check_len(s) and check_digit_letter(s): # return "中" # elif check_len(s) and check_other(s): # return "中" # elif check_digit_letter(s) and check_other(s): # return "中" # elif check_len(s) or check_digit_letter(s) or check_other(s): # return "弱" # else: # return "弱" # # # print(check_password(passwd_1)) # print(check_password(passwd_2)) # print(check_password(passwd_3)) # print(check_password(passwd_4)) # # print(check_len(passwd_4)) # # print(check_digit_letter(passwd_4)) # # print(check_other(passwd_4)) # 练习167:求两个集合的交集和并集 # lst_1 = [1, 2, 3, 4] # lst_2 = [1, 4, 2, 6] # in_list = [] # u_list = [] # for v in lst_1: # if v in lst_2: # in_list.append(v) # # for v in lst_1: # if v not in u_list: # u_list.append(v) # for v in lst_2: # if v not in u_list: # u_list.append(v) # print("交集: ", in_list) # print("并集:", u_list) # 练习168:一个包含多个数字的列表,请使用随机的方式,将每个数字 + 1后,生成新列表 # import random # # lst = [1, 4, 2, 6] # rand_list = [] # while 1: # rand_index = random.randint(0, 3) # if rand_index not in rand_list: # lst[rand_index] += 1 # rand_list.append(rand_index) # if len(rand_list) == 4: # break # print(lst) # 练习169:判断一个字符串是否为回文字符串,所谓回文字符串,就是一个字符串, # 从左到右读和从右到左读是完全一样的。比如"level" 、 “aaabbaaa” # def func(s): # if len(s) % 2 == 1: # # print(s[:len(s)//2],s[-1:-len(s)//2:-1]) # if s[:len(s) // 2] == s[-1:-len(s) // 2:-1]: # return True # else: # return False # if len(s) % 2 == 0: # if s[:len(s) // 2 - 1] == s[-1:-len(s) // 2:-1]: # return True # else: # return False # # # s = "level" # s2 = "aaabbaaa" # print("%s是回文:%s " % (s, func(s))) # print("%s是回文:%s " % (s2, func(s2))) # # # def f(s): # if s == s[::-1]: # return True # else: # return False # # # s = "level" # s2 = "aaabbaaa" # print("%s是回文:%s " % (s, f(s))) # print("%s是回文:%s " % (s2, f(s2))) # print(f("1")) # 练习170:实现合并同类型的有序列表算法,要求不能有重复元素 # 方式1: # lst1 = [1, 1, 2, 3, 4] # lst2 = [2, 3, 4, 5, 5, 8] # lst = set(sorted(lst1 + lst2)) # print(lst) # 方式2: # 写算法 # lst1 = [1, 1, 2, 3, 4] # lst2 = [2, 3, 4, 5, 5, 8] # result = [] # while lst1 and lst2: # if lst1[0] < lst2[0]: # item = lst1.pop(0) # if item not in result: # result.append(item) # else: # item = lst2.pop(0) # if item not in result: # result.append(item) # # if lst1: # result.extend(lst1) # elif lst2: # result.extend(lst2) # print(result) # 共计123行代码
82cd3bd561827ba6e8988ac7a7ae18c9680a4665
dreamofwind1014/gloryroad
/练习题/2020.06.21练习题--赵华恬.py
2,471
3.984375
4
# 练习186:将"gloryroad"按照如下规则进行加密:字母对应的asscii码值进行加密, # 并且在码值前面加上码值长度,如g对应的码值为ord("g") = 103, # 则字母g加密结果为31033是ascii的长度。“gloryroad”正确输出加密结果为: # "31033108311131143121311431112973100" # def encode_str(s): # result = [] # for v in s: # item = str(len(str(ord(v)))) + str(ord(v)) # result.append(item) # return "".join(result) # # # s = "gloryroad" # print("%s 加密后: %s" % (s, encode_str(s))) # 练习187:、将上题中的加密字符串进行解密 # 方法1: # 从头遍历每个字符串,当长度为3、2 # 分别取到后面的ascii码,加入列表,最后把列表拼接成字符串 # def decode_str(s): # result = [] # index = 0 # length = len(s) # while index < length: # if s[index] == "3": # # 索引位置加上1后才是下一个要的长度值 # item = s[index + 1: index + 3 + 1] # result.append(chr(int(item))) # index += 4 # else: # item = s[index + 1: index + 2 + 1] # result.append(chr(int(item))) # index += 3 # return "".join(result) # # # s = "31033108311131143121311431112973100" # print("%s 解密后: %s" % (s, decode_str(s))) # 方法2:把上述方法合并成步骤 # # def decode_str(s): # result = [] # index = 0 # length = len(s) # while index < length: # item = s[index + 1:index + int(s[index]) + 1] # result.append(chr(int(item))) # index += (int(s[index]) + 1) # return "".join(result) # # # s = "31033108311131143121311431112973100" # print("%s 解密后: %s" % (s, decode_str(s))) # 练习188:递归 # def decode_str(s, result=[]): # if len(s) == 0: # pass # else: # # length = int(s[0]) # item = chr(int(s[1:length + 1])) # result.append(item) # print(result) # decode_str(s[length + 1:]) # # return "".join(result) # # # s = "31033108311131143121311431112973100" # print("%s 解密后: %s" % (s, decode_str(s))) # 练习189:统计首字母是“a”的单词的个数 # # s = "akk alklk bkk aaddd" # count = 0 # for v in s.split(): # if v[0] == "a": # count += 1 # print(count) # 练习190:单词顺序翻转 # s = "i am a boy" # " ".join(s.split()[::-1]) # 'boy a am i' # 共计56行代码
fd27267b5ea5cfe6c625d03dcecb10f061179f3f
dreamofwind1014/gloryroad
/练习题/2020.06.14练习题--赵华恬.py
2,798
3.734375
4
# 练习151: 用推导列表求所有数字key的和 # d = {1: 'a', 2: "b", "a": 3} # sum([k for k in d if isinstance(k, (int, float))]) # # 3 # 练习152:"abcdefgh"里面挑出3个字母进行组合,一共有多少种组合, # 要求三个字母中不能有任何重复的字母,三个字母的同时出现次数, # 在所有组合中只能出现一次,例如出现abc了,不能出现cab和bca等 # s = "abcdefgh" # result = [] # temp_list = [] # for k in s: # for v in s: # for j in s: # if k != v and k != j and v != j: # # sorted("abc") ==》["a","b","c"] # # [sorted(s) for s in result]每一个元素是一个包含三个字母的列表 # # if sorted(list(k+v+j)) not in [sorted(list(s)) for s in result] # if sorted(list(k + v + j)) not in [sorted(s) for s in result]: # result.append(k + v + j) # # print(result) # print("组合数:", len(result)) # 练习153:复制一个列表,不能使用切片和复制的函数进行赋值,尽可能使用少的内置函数 # 方式1: # lst = ["a", "b", "c", "d", "e"] # # length = 0 # i = 0 # for v in lst: # length += 1 # # result = [None] * length # # while i < length: # result[i] = lst[i] # i += 1 # # print("复制后的列表为:", result) # 方式2: # a = ["a", "b", "c", "d", "e"] # # arr_length = 0 # # for i in a: # arr_length += 1 # # # def iter_arr(n): # arr = [] # i = 0 # while i <= n - 1: # arr += [i] # i += 1 # return arr # # # result = [""] * arr_length # # for i in iter_arr(arr_length): # result[i] = a[i] # # print(result) # 练习154:d = {-1: 100, -2: 200, 0: 300, -3: 200} # 按照key的大小顺序升序进行输出,输出key = value - 3 = 200, -2 = 200, -1 = 100, 0 = 300 # 方法一: # d = {-1: 100, -2: 200, 0: 300, -3: 200} # # for k in sorted(d.keys()): # print("%s=%s" % (k, d[k]), end=",") # 方法二: # d = {-1: 100, -2: 200, 0: 300, -3: 200} # # for k, v in sorted(d.items(), key=lambda x: x[0]): # print(str(k) + "=" + str(v), end="") # 练习155:一个字符串排序,排序规则:小写 < 大写 < 奇数 < 偶数, #  原理:先比较元组的第一个值,FALSE<TRUE,如果相等就比较元组的下一个值,以此类推。 s = '9a13C85c7B24A6b' # 正确的顺序应该为:abcABC135792468 s = sorted(list(s)) lst = sorted(s, key=lambda x: ( x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isalpha() and x.isupper(), x.isalpha() and x.islower())) print("".join(lst)) """ 小写 < 大写 < 奇数 < 偶数 偶数(True, True, False, False) 奇数(True, False, False, False) 大写(False, False, True, False) 小写(False, False, False, True) """ # 共计52行代码