blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
db02d5e7754d9d50693569b4f47a6a6dc043daed
darshan3899/darshan_python
/OOP/heirarchical_inheritance.py
804
4.15625
4
#WAP to demonstrate Heirarchical Inheritance #!/usr/bin/python import inspect class A(object): #class A(object): inheriting with object->then 2.7 works like 3.x def m(self): print("Inside A's m()") def k(self): print("Inside A's k()") class B(A): def l(self): pint("Inside B's l()") class C(A): def n(self): print("Inside C's n()") def m(self): print("Inside C's m()") class D(B,C): def __call__(self): print("Invoked") def main(): print(inspect.getmro(D)) obj=D() obj.n() obj.m() obj() if __name__=='__main__': main() ''' OUTPUT without class(object) 3.x darshan@darshan:~/Python/Class/OOP$ python3 heirarchical_inheritance.py Inside C's n() Inside C's m() 2.7 darshan@darshan:~/Python/Class/OOP$ python heirarchical_inheritance.py Inside C's n() Inside A's m() '''
false
9b2a2defcd7de9eed65db08d994e64c294be78f0
darshan3899/darshan_python
/Basics/factorial_recursive.py
266
4.1875
4
#WAP recursive program to find factorial def recursiveFactorial(a): if a==0 or a==1: return 1 if a==2: return 2 return(a*recursiveFactorial(a-1)) def main(): a=int(input("Enter A Number\n")) print(recursiveFactorial(a)) if __name__=='__main__': main()
false
f750fcb08ee76632c21571ed05f15116fe8555eb
Anirban2404/LeetCodePractice
/Q2degreeOfArray.py
1,493
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 7 13:33:16 2019 @author: anirban-mac """ """ Q2 Degree of an Array Given an array of n integers, we define its degree as the maximum frequency of any element in the array. For example, the array [1,2,2,4,3,3,2] has a degree of 3 because the number 2 occurs three times (which is more than any other number in the array). We want to know the size of the smallest subarray of our array such that the subarray's degree is equal to the array's degree. Complete the function in the editor below. It has one parameter: an array of n integers, arr. The function must return an integer denoting the minimum size of the subarray such that the degree of the subarray is equal to the degree of the array. Sample Input 0 5 1 2 2 3 1 Sample Output 0 2 """ #!/bin/python3 import sys from collections import Counter def degreeOfArray(arr): # Complete this function left, right, count = {}, {}, {} for i, x in enumerate(nums): if x not in left: left[x] = i right[x] = i count[x] = count.get(x, 0) + 1 ans = len(nums) degree = max(count.values()) for x in count: if count[x] == degree: ans = min(ans, right[x] - left[x] + 1) return ans if __name__ == "__main__": size = int(input().strip()) arr = [] arr_i = 0 for arr_i in range(size): arr_t = int(input().strip()) arr.append(arr_t) res = degreeOfArray(arr)
true
3e3a34dd60166a15fb3e664affdec8470734c4dd
Anirban2404/LeetCodePractice
/48_rotate.py
1,533
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 3 20:14:29 2019 @author: anirban-mac """ """ 48. Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ] Example 2: Given input matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], rotate the input matrix in-place such that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ] """ class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ cols = len(matrix) rows = len(matrix[0]) for row in range(rows): for col in range(row, cols): #print (matrix[row][col],matrix[col][row], matrix[col][row],matrix[row][col]) matrix[col][row],matrix[row][col] = matrix[row][col],matrix[col][row] print(matrix) for j in range(cols): matrix[j] = (list(reversed(matrix[j]))) print(matrix) matrix = [[1,2,3], [4,5,6], [7,8,9]] print(Solution().rotate(matrix))
true
49bd38532f2177a13af8b47f5d7a917bf4ed2d78
Anirban2404/LeetCodePractice
/123_maxProfit.py
1,999
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 10 18:15:08 2019 @author: anirban-mac """ """ 123. Best Time to Buy and Sell Stock III Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. """ class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ maxProfit = [0] * len(prices) min_price = float('inf') maxProfit_local = 0 for i, price in enumerate(prices): min_price = min(min_price, price) maxProfit_local = max(maxProfit_local, price - min_price) maxProfit[i] = maxProfit_local print(maxProfit) max_price = float('-inf') for i, price in reversed(list(enumerate(prices[1:], 1))): #print(price) max_price = max(max_price, price) maxProfit_local = max(maxProfit_local, max_price - price + maxProfit[i - 1]) return (maxProfit_local) prices = [3,3,5,0,0,3,1,4] print(Solution().maxProfit(prices))
true
351876b0981aa5abee7a233d29a2098c65955ee9
Anirban2404/LeetCodePractice
/374_guessNumber.py
1,511
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 23 19:35:54 2019 @author: anirban-mac """ """ We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number is higher or lower. You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): -1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! Example : Input: n = 10, pick = 6 Output: 6 """ # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution: def guessNumber(self, n): """ :type n: int :rtype: int """ #for i in range(n): # if self.guess(i) == 0: # return i start = 0 end = n while start <= end: mid = (start + end)//2 print(mid, start, end, self.guess(mid)) if self.guess(mid) == 0: return mid elif self.guess(mid) == -1: start = mid + 1 else: end =mid - 1 def guess(self, n): pick = 6 print (n) if n == pick: return 0 elif n > pick: return 1 else: return -1 n = 10 pick = 10 print(Solution().guessNumber(n))
true
8c0de92e51136f93391a825a3f65898148d1980d
Anirban2404/LeetCodePractice
/rotateArray.py
2,682
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 4 12:22:03 2019 @author: anirban-mac """ """ Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? """ class Solution: def rotate1(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ length = len(nums) if len(nums) == 1 or len(nums) == 0: pass else: for i in range(k): temp = nums[0] nums[0] = nums[length-1] for j in range(len(nums)-2,-1,-1): nums[j+1] = nums[j] nums[1] = temp print(nums) def rotate2(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ length = len(nums) if length == 1 or length == 0: pass else: k = k % length nums[:] = nums[length-k:] + nums[:length-k] print(nums) def reverse(self, nums, start, end): i = start #print("1:", nums) while end > start: #print(i) temp = nums[end] nums[end] = nums[start] nums[start] = temp i = i + 1 end = end - 1 start = start + 1 #print("2:", nums) def rotate3(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ length = len(nums) if length == 1 or length == 0: pass else: k = k % length Solution().reverse(nums,0,length-1) Solution().reverse(nums,0,k-1) Solution().reverse(nums,k,length-1 ) print(nums) nums = [1,2,3,4,5,6,7] k = 3 #print(Solution().rotate1(nums,k)) #print(Solution().rotate2(nums,k)) print(Solution().rotate3(nums,k))
true
3bf55a9675e2f415df1d3b8c15c7a41e5823bb7c
Anirban2404/LeetCodePractice
/56_mergeIntervals.py
1,477
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 6 18:01:08 2019 @author: anirban-mac """ """ Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. """ class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ newIntervals = [] for interval in intervals: #print (interval) interval = Interval(interval[0],interval[1]) newIntervals.append(interval) if not newIntervals: return None newIntervals.sort(key = lambda x: x.start) merged = [] for interval in newIntervals: if not merged or merged[-1].end < interval.start: merged.append(interval) else: merged[-1].end = max(merged[-1].end, interval.end) ret = [] for merge in merged: ret.append([merge.start, merge.end]) return ret intervals = [[1,3],[2,6],[8,10],[15,18]] print(Solution().merge(intervals))
true
ce501c178364e36eed7a81c99112d3f43b1916fa
Anirban2404/LeetCodePractice
/977_sortedSquares.py
1,251
4.125
4
""" Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] """ class Solution(object): def sortedSquares(self, nums): """ :type nums: List[int] :rtype: List[int] """ squaredArr = [] for num in nums: squaredArr.append(num * num) return sorted(squaredArr) def sortedSquares_2(self, nums): left = 0 right = len(nums) - 1 squaredArr = [0] * len(nums) for i in range(right,-1,-1): if abs(nums[left]) < abs(nums[right]): squaredArr[i] = nums[right] * nums[right] right -= 1 else: squaredArr[i] = nums[left] * nums[left] left += 1 return squaredArr if __name__=="__main__": nums = [-5,-4,-3,-2,-1,3,20] print(Solution().sortedSquares(nums)) print(Solution().sortedSquares_2(nums))
true
e07b057be9dbc80bdcff0f87facf4ad65c89d063
Anirban2404/LeetCodePractice
/683_kEmptySlots.py
1,685
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 1 17:55:46 2019 @author: anirban-mac """ """ 683. K Empty Slots There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then. Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day. For example, flowers[i] = x means that the unique flower that blooms at day i will be at position x, where i and x will be in the range from 1 to N. Also given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming. If there isn't such day, output -1. Example 1: Input: flowers: [1,3,2] k: 1 Output: 2 Explanation: In the second day, the first and the third flower have become blooming. Example 2: Input: flowers: [1,2,3] k: 1 Output: -1 Note: The given array will be in the range [1, 20000]. """ class Solution: def kEmptySlots(self, flowers, k): """ :type flowers: List[int] :type k: int :rtype: int """ days = [0] * len(flowers) for day, position in enumerate(flowers, 1): days[position - 1] = day print (days) ans = 0 left, right = 0, k + 1 #while right < len(days): #for i in range(left + 1, right): flowers = [2, 3, 4, 5, 10, 6, 7, 1, 8, 9] k = 4 print(Solution().kEmptySlots(flowers, k))
true
4ac13a04779a3de7cc48aa8f0e39963dc3e3db8d
kevinherman1104/ITP_Assignments
/13_practice_2.py
706
4.125
4
#13 verb = str(input("enter a word=")) def makeForms(verb): if verb[-1:] == "y": verb = verb[:-1] + "ies" elif verb[-1:] == ["o","s","x","z"] or verb[-2:] == ["ch","sh"]: verb = verb + "es" else: verb = verb + "s" print(verb) makeForms(verb) verbs = [ "try","brush","run","fix"] def makeFormwithS(verbs): new_verb = [] for element in verbs: if element [-1:] == "y": new_verb.append(element[:-1] + "ies") elif element [-1:] in ["o","s","x","z"] or element[-2:] in ["ch","sh"]: new_verb.append(element + "es") else: new_verb.append(element + "s") print(new_verb) makeFormwithS(verbs)
false
e3af6fcfe07420a009bc744aab92d94343c624f0
Red-Ir-Mogician/Picture-storage
/FelixHan_Main.py
2,132
4.28125
4
import Account from Account import theAccount # Prevents the program's termination never = 0 # To keep track: new account created count = 0 newAccount = [] checkSuccess = 0 # Keep the program running forever ("quit" is available for testing purposes) while never == 0: # Main Screen print("\n----------------------------" "\n Welcome to Shanghai Bank " "\n----------------------------\n") print("You can ") firstOption = input("> 1. create a new account \n" "> 2. login to an already existing account \n" "(Input the number) Your choice: ") # User decides to create a new account if firstOption == "1": print("\n ... NEW ACCOUNT ... \n" "You are about to create a new account. \n" "Please input all the required information.") myName = input("Your full name (last, first): ") myBirthday = input("Your birthday (month/day/year): ") myID = input("Create an ID for your account: ") myPassword = input("Create a password to secure your account: ") newAccount.append(theAccount(myID, myPassword, myName, myBirthday)) count += 1 print("You have successfully created a new account.") # User decides to log into an account elif firstOption == "2": print("\n ... LOGIN ...") enterID = input("Enter your ID: ") enterPassword = input("Enter your password: ") for each in newAccount: if each.ID == enterID and each.password == enterPassword: print("\n ... \n logging in \n ...") Account.myAccount_Screen(each) checkSuccess += 1 else: continue if checkSuccess == 0: print("You have entered an invalid ID or an incorrect password.") else: checkSuccess == 0 # User decides to quit the program (hidden option) elif firstOption == "quit": never += 1 else: print("Wrong input. Please try again.")
true
46735dd415e34c9bab8172348debda65755b67ae
ablaza04/m03
/ejercicio-bucle-sumar-pares.py
254
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- numero = 2 total = 0 salir = False while (salir == False): print numero if (numero %2==0): if (numero == 6): salir = True total = total+numero numero = numero+1 print "----" print total
false
4e81c2f13b9ae5eedc3aeb15d4c82d5e5c04a175
ablaza04/m03
/Deberes17.03.2017/ejercicio-menu-calc.py
734
4.125
4
#coding: utf8 #Menu de una Calculadora print "Qué desea hacer el amo? " print "0) Salir" print "1) Sumar" print "2) Restar" print "3) Multiplicar" print "4) Dividir" opcion = raw_input ("Elija una opción ") numero1 =int(raw_input ("Primer numero ")) numero2 =int(raw_input ("Segundo numero ")) if opcion == "1": suma = numero1 + numero2 print "El resultado es ", suma elif opcion == "2": resta = numero1 - numero2 print "El resultado es", resta elif opcion == "3": multiplicar = numero1 * numero2 print "El resultado es", multiplicar elif opcion == "4": dividir = numero1 / numero2 print "El resultado es", dividir elif opcion == "0": print "Hasta Luego!" else: print "ERROR : Esa Opción no existe !!! "
false
e3373a391dabf6a6895ce571bd80ec7d7ec35a69
ShreyaAgrawal-jp/fibonacci
/fibonacci2.py
213
4.15625
4
#fibonacci using recursive function def fib(n): if n<=1: return n else: return (fib(n-1)+fib(n-2)) n=int(input('enter a number: ')) for i in range(n): print(fib(i),end='')
false
f4d4c689a600f6d1adf119dd78c97a1c276496cd
minjookim1223/ITP-449-Machine-Learning
/ITP 449 HW 1/HW1_Kim_Minjoo_Q8.py
1,769
4.28125
4
# ITP 449 HW 1 # Minjoo Kim # Q8. Write a program to ask the user to enter a password. # Then check to see if it is a valid password based on these requirements - # # 1) Must be at least 8 characters long # 2) Must contain both uppercase and lowercase letters # 3) Must contain at least one number between 0-9 # 4) Must contain a special character -!,@,#,$ # # If the password is not valid, ask the user to re-enter. # This should continue until the user enters a valid password. # After a valid password is entered, print Access Granted! print("Please enter a password. Follow these requirements - ") print("a. Must be at least 8 characters long") print("b. Must contain both uppercase and lowercase letters") print("c. Must contain at least one number between 0-9") print("d. Must contain a special character -!,@,#,$") granted = False while not granted: password = input("Password: ") length = len(password) >= 8 num, special, upper, lower = False, False, False, False for i in password: if i.isupper(): upper = True if i.islower(): lower = True if i.isdigit(): num = True if i in ["!", "@", "#", "$"]: special = True # if not length: # print("Your password is less than 8 characters.") # if not upper: # print("Your password does not have an upper case") # if not lower: # print("Your password does not have a lower case") # if not num: # print("Your password does not have a number") # if not special: # print("Your character does not have a special character.") if num and special and length and upper and lower: break else: print("Invalid Password. Try again!") print("Access Granted!")
true
f08f55cc9a42c116e9a74c8f8dac6b21914d9e4e
greenfox-velox/szepnapot
/week-03/day-3/circle.py
394
4.3125
4
import math class Circle: """Calculate area, and circumference for given radius""" def __init__(self, radius): self.radius = radius def get_circumference(self): return math.pi * 2 * self.radius def get_area(self): return math.pi * self.radius**2 radius = int(input("Enter radius: ")) c = Circle(radius) print("Circumference:",c.get_circumference()) print("Area:",c.get_area())
true
fe65ab0771e1263b38dcab5d6e09311bd822578d
rlhodgson/Assignments
/COSC121/Lab 9/character_set_counts.py
454
4.40625
4
def character_set_counts(string_1, string_2, string_3): """Returns the number of characters that are in string1 and in string2 but not in string3""" string1 = set(string_1) string2 = set(string_2) string3 = set(string_3) string1_2 = string1.intersection(string2) not_string3 = string1_2.difference(string3) return (len(not_string3)) answer = character_set_counts('abcdef', 'bcd', 'ace') print(answer)
true
39b8caf62f5ecc7a41252cd45724c73e35fec868
rlhodgson/Assignments
/COSC121/birthday_function.py
468
4.3125
4
def get_birthday_weekday(): """calculating the day of the week a birthday will be on""" current_day = int(input("Enter the number corresponding to the day of the week ")) day_of_year = int(input("Enter day of the year ")) day_of_birthday = int(input("Enter the day of the year your birthday is ")) day_diff = (day_of_birthday - day_of_year) birthday_weekday = (day_diff + current_day) % 7 print(birthday_weekday) get_birthday_weekday()
false
dac74b7e2c039bde407b84ebbc3ed7c796200352
rlhodgson/Assignments
/COSC121/Self Assessment Quizzes/selfassessment3.py
1,437
4.125
4
def silly(i, j): """Does something silly""" return (j <= i and i > 3 and j < 12) def re_at_either_end(string): """returns a boolean""" if string[0:2] == "re" or string[-2:] == "re": return True else: return False def divisible_by_6(number): """Returns true if something is divisible by 6""" num = number / 6 nums = int(num) if num == nums: return True else: return False def is_trendy(socks_colour, tie_colour): """Returns if something is trendy or not""" socks = socks_colour.lower() tie = tie_colour.lower() if socks == "black" and tie == "cream": return True elif socks == "pinkish" and tie == "cream": return True else: return False def is_viable(angle): """Returns true or false""" angles = float(angle) if angles > 93.011: return True else: return False def level_of_danger(speed, temperature): """Returns the level of danger""" speeds = float(speed) temp = float(temperature) danger = 0 if speeds <= 60 and temp > 67: danger += 6 return danger elif speeds <=60 and temp <= 67: danger += 3 return danger elif speeds > 60 and temp <= 67: danger += 4 return danger elif speeds > 60 and temp > 67: danger += 10 return danger print(level_of_danger(59, 65))
true
b4db8ba8f907e1881ff79235b6fb6fdf775a7e18
rlhodgson/Assignments
/COSC121/Lab 8/rainfall_refactoring.py
2,148
4.5625
5
"""A program to read a CSV file of rainfalls and print the totals for each month. """ def read_data(filename): """Opens and reads the data within the given filename then closes it""" datafile = open(filename) data = datafile.readlines() datafile.close() return data def get_month(columns): """Returns the month number from the column given""" month = int(columns[0]) return month def get_num_days(columns): """Returns the number of days in the given month within the columns""" num_days = int(columns[1]) return num_days def get_month_and_days(columns): """Returns the month and day as a tuple for further use in the main block""" month_and_days = get_month(columns), get_num_days(columns) return month_and_days def get_results(results, columns, month_days): """Appends the results of the total rainfall with the month to a list and returns it""" month, num_days = month_days total_rainfall = 0 for col in columns[2:2 + num_days]: total_rainfall += float(col) results.append((month, total_rainfall)) return results def print_outcome(results): """Prints the monthly rainfall output""" print('Monthly rainfalls') for (month, total_rainfall) in results: print('Month {:2}: {:.1f}'.format(month, total_rainfall)) def print_monthly_rainfalls(input_csv_filename): """Process the given csv file of rainfall data and print the monthly rainfall totals. input_csv_filename is the name of the input file, which is assumed to have the month number in column 1, the number of days in the month in column 2 and the floating point rainfalls (in mm) for each month in the remaining columns of the row. """ data = read_data(input_csv_filename) results = [] # A list of (month, rainfall) tuples for line in data: columns = line.split(',') month_days = get_month_and_days(columns) result = get_results(results, columns, month_days) print_outcome(result) def main(): """The main function""" print_monthly_rainfalls("rainfalls2011.csv") main()
true
b48a98be635b10f7d0277e2443388e3b5164c8fd
rlhodgson/Assignments
/COSC121/Lab 9/word_counter.py
487
4.125
4
def word_counter(input_str): """Returns a dictionary of the words and their counts in the string""" word_list = input_str.split(' ') empty = '' for words in word_list: if words == empty: word_list.remove(words) word_count = {} for word in word_list: word = word.lower() word_count[word] = word_count.get(word, 0) + 1 return word_count word_count_dict = word_counter(" A a a a B B ") print(word_count_dict)
true
4974bce812fd85980b6cc847e766bcbcbcebd9e0
rlhodgson/Assignments
/COSC121/Lab 8/rainfalldata_refactoring.py
1,187
4.34375
4
"""A program to read a CSV file of rainfalls and print the totals for each month. """ def print_monthly_rainfalls(input_csv_filename): """Process the given csv file of rainfall data and print the monthly rainfall totals. input_csv_filename is the name of the input file, which is assumed to have the month number in column 1, the number of days in the month in column 2 and the floating point rainfalls (in mm) for each month in the remaining columns of the row. """ datafile = open(input_csv_filename) data = datafile.readlines() datafile.close() results = [] # A list of (month, rainfall) tuples for line in data: columns = line.split(',') month = int(columns[0]) num_days = int(columns[1]) total_rainfall = 0 for col in columns[2:2 + num_days]: total_rainfall += float(col) results.append((month, total_rainfall)) print('Monthly rainfalls') for (month, total_rainfall) in results: print('Month {:2}: {:.1f}'.format(month, total_rainfall)) def main(): """The main function""" print_monthly_rainfalls("rainfalls2011.csv") main()
true
f65a8f1d01e8bd0501a54ce37d4d294f74372481
chamodi08jaya/MachineLearning
/17020387.py
1,664
4.1875
4
#import numpy and matplotlib import numpy as np import matplotlib.pyplot as plt import random import time #load the dataset train_data = np.genfromtxt('dataset.csv', delimiter=',') #remove the header row train_data = np.delete(train_data,0,0) #take SAT Score as X vector X = train_data[:,0] #take GPA as Y vector Y = train_data[:,1] #visualize data using matplotlib plt.scatter(X,Y) plt.xlabel('SAT Score') plt.ylabel('GPA') #plt.show() #initialize m and c #m=0 #c=0 m = random.random() c = random.random() L = 0.0001 # The learning Rate iterations = 1000 # The number of iterations to perform gradient descent n = float(len(X)) # Number of elements in X # Performing Gradient Descent for i in range(iterations): Y_pred = m*X + c # The current predicted value of Y #D_m = (-2/n) * sum(X * (Y - Y_pred)) # Derivative with respect to m #D_c = (-2/n) * sum(Y - Y_pred) # Derivative with respect to c D_m =(-1/n)*sum(X*(Y-Y_pred)/abs(Y - Y_pred)) #Derivative with respect to m D_c=(-1/n)*sum((Y-Y_pred)/abs(Y - Y_pred))# Derivative with respect to c m = m - L * D_m # Update m c = c - L * D_c # Update c print ("m = ",m) print ("c = ",c) plt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color='red') plt.pause(1e-17) time.sleep(0.1) #output m and c #print ("m = ",m) #print ("c = ",c) #Final predictions Y_pred = m*X + c #Draw the best fitting line #plt.scatter(X, Y) plt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color='green') #plot the best line with green color #plt.xlabel('SAT Score') #plt.ylabel('GPA') plt.show()
true
b4554731ed095286c2bce91fe71cd67c22a46c67
allenphilip93/ML-projects
/03-neural-network/neural-network.py
2,438
4.125
4
import numpy as np import matplotlib.pyplot as plt class NeuralNetwork: def __init__(self, num_attr, num_neurons): # seed the random generator to give same numbers every run np.random.seed(1) # Modelling a single neuron with 3 input connections # and 1 output connection # Weights will be assigned to a 3x1 matrix with values [-1, 1] mean 0 self.synaptic_weights = 2 * np.random.random((num_attr, num_neurons)) - 1 # error logs self.mean_error_log = [] # Activation function to normalize the results to [-1, 1] def __sigmoid(self, x): return 1 / (1 + np.exp(-x)) # Derivative of the activation function for weights adjustments def __sigmoid_derivative(self, x): return x * (1 -x) def train(self, training_input, training_output, num_iters): for iteration in xrange(num_iters): # Pass the training set through our neural network model_output = self.think(training_input) # Calculate the error error = training_output - model_output # Gradient descent for weight adjustments adj = np.dot(training_input.T, self.__sigmoid_derivative(model_output) * error) # Adjust the weights self.synaptic_weights += adj # print "Epoch #{0}: Error = {1}".format(iteration+1, np.mean(error)) self.mean_error_log.append(np.mean(error)) # Output processing def think(self, training_input): # Pass inputs through our neural network return self.__sigmoid(np.dot(training_input, self.synaptic_weights)) # Plot the error logs def plot_error(self): print "Trained Weights: " + str(self.synaptic_weights) plt.plot(range(len(self.mean_error_log)), self.mean_error_log, color='blue') plt.show() def run(): # training data with input and output - price = func(rooms, baths, floors) points = np.genfromtxt('zoo_data.csv', delimiter=",", dtype=float) # points = np.array([[0, 0, 1, 0], [1, 1, 1, 1], [1, 0, 1, 1], [0, 1, 1, 0]]) # Set basic [params num_iters = 5000 num_attr = 14 num_neurons = 1 print "Loaded zoo dataset for animal type classification" # Initialize the neural network neural_network = NeuralNetwork(num_attr, num_neurons) # Random initializing the synaptic weights print "Initializing the synaptic weights" print neural_network.synaptic_weights # Traing the neural network neural_network.train(points[:,:num_attr], points[:,num_attr:num_attr+1], num_iters) # Plot error neural_network.plot_error() if __name__ == "__main__": run()
true
30b3f813b32ddab1eec02a91d3b7b10d43d8761f
regenalgrant/datastructures
/src/link_list.py
2,592
4.1875
4
"""Implementing LinkList.""" class Node(object): """Creating a template for a Node.""" def __init__(self, data): """Providing attribute to Node.""" self.data = data self.next_node = None class LinkedList(object): """Creating a template for Link List.""" def __init__(self, data=None): """ Attribute of head available upon intitialization. If iterable date is available. Iters through data. """ self.head = None if data: try: for info in data: self.push(info) except TypeError: raise TypeError("data must be iterable") def push(self, data): """Push data to head of list.""" new_node = Node(data) new_node.next_node = self.head self.head = new_node def pop(self): """Pop head from linklist.""" pop_old_node = self.head try: self.head = self.head.next_node except AttributeError: raise AttributeError("Cannot pop from empty list") return pop_old_node.data def size(self): """Size method finds length of linklist.""" counter = 0 current = self.head while current is not None: counter += 1 current = current.next_node return counter def search(self, data): """Searching for Node with a value.""" current = self.head try: while data != current.data: current = current.next_node return current except AttributeError: return def remove(self, node): """Remove node from link list.""" if self.head is None: raise IndexError("list is empty") current = self.head if current == node and current.next_node is not None: self.head = current.next_node current = None return self.head try: while current.next_node != node: current = current.next_node current.next_node = current.next_node.next_node except AttributeError: raise IndexError("Value not found in list") def display(self): """Display unicode string of a tuple.""" link_list_string = "(" current = self.head while current: link_list_string = link_list_string + str(current.data) + ", " current = current.next_node link_list_string = link_list_string[:-2] + ")" return link_list_string
true
84676b959775fcbf53560a5f01342ef628050bda
laetrid/learning
/First_course/ex6_2.py
697
4.21875
4
#!/usr/bin/env python ''' 2. Write a function that converts a list to a dictionary where the index of the list is used as the key to the new dictionary (the function should return the new dictionary). ''' # Func defenition def list2dic(a_list): a_dic = {} i = 1 for s in a_list: a_dic[i] = s i += 1 return a_dic # Main body text = ''' 2. Write a function that converts a list to a dictionary where the index of the list is used as the key to the new dictionary (the function should return the new dictionary). ''' words = text.split() word_dic = list2dic(words) print "" for key in word_dic: print "%-3d.%-20s" % (key, word_dic[key]) print "" # The END
true
715e4335ed7a2de466be81869ecbbbfddbcd6826
laetrid/learning
/First_course/ex6_1.py
1,025
4.8125
5
#!/usr/bin/env python ''' 1. Create a function that returns the multiplication product of three parameters--x, y, and z. z should have a default value of 1. a. Call the function with all positional arguments. b. Call the function with all named arguments. c. Call the function with a mix of positional and named arguments. d. Call the function with only two arguments and use the default value for z. ''' # Func defenition def multi_three(x, y, z = 30): return x * y * z # Main prigram a = 10 b = 20 c = 30 multipl = multi_three(10, 20, 30) print "A. Call the function with all positional arguments. ==> %d" % multipl multipl = multi_three(a, b, c) print "B. Call the function with all named arguments. ==> %d" % multipl multipl = multi_three(a, z = c, y = 20) print "C. Call the function with a mix of positional and named arguments. ==> %d" % multipl multipl = multi_three(a, b) print "D. Call the function with only two arguments and use the default value for z. ==> %d" % multipl # The END
true
6d4ec546f948c35f94afcf289bbea29b3fbaf620
chandansgowda/basic-python-projects
/circle.py
899
4.40625
4
import text_to_speech as speech def square(x): return x * x def cube(x) : return x * x * x def half(x) : return x / 2 def area(x): return 3.14 * x * x def circumference(c): return 2 * 3.14 * x def examples(x): print("Examples: Eyes, Wheels, Bottle Cap, Ring etc. ") return #speech.speak("Give me the radius of the circle", "en") x = int(input("Give me the radius of the circle>> ")) print(''' 1.Area 2.Circumference 3.Examples ''') function = int(input("Select any function >> ")) if function == 1: a = area(x) elif function == 2: a = circumference(x) elif function == 3: a = examples(x) else : print("It was an invalid function request.Try Again") print(a) print("Thank you for using Chandan Softwares")
true
f4ad715caeee0428fb9c4e0c7782d34722572764
LucP33/Python
/Ex3-2.py
481
4.21875
4
#!/usr/bin/env python3 ################################################# # Name: Avihu # # Sum higher then 30 or number bigger then 10 # # 2 - 6 - 2018 # ################################################# i=0 num_sum = 0 while i < 11: num_sum = num_sum + i if num_sum > 30: break i = int ( input ( 'Enter a number: ') ) print ( 'The sum of the numbers is:' + str ( num_sum ) )
false
edd3b56f3d93e3136b51aa8d849445b2fc66e167
ddinesh89/python
/sqrtCalculation.py
612
4.21875
4
#newton-rhapson formulae for finding sqrt inputNum = float(raw_input("Enter the input number: ")) negative = False if (inputNum < 0): negative = True; inputNum = abs(inputNum) epsilon = 0.001 guess = inputNum/2.0 while (abs(guess**2 - inputNum) >= epsilon): guess = guess - ((guess**2)-inputNum)/(2*guess) if (abs(guess**2 - inputNum) >= epsilon): print "Could not find the square root of "+str(inputNum) else: if (negative): print str(guess) +"i is the approximate square root of "+str(inputNum) else: print str(guess) +" is the approximate square root of "+str(inputNum)
true
53532ed1e09a9ecea73149fa0af8e380872eedc8
ddinesh89/python
/strCombinations.py
1,190
4.21875
4
def shiftPrint(tempStr, inputStr, results) : """ Recursively rotates the strings and returns a list of combinations """ newStr = tempStr[1:] + tempStr[0] if newStr == inputStr : if newStr not in results : results.append(newStr) else : if newStr not in results : results.append(newStr) shiftPrint(newStr, inputStr, results) def rotateStr(inputStr, iterator) : """ Gets an input string and integer iterator and rotates the first char and iterator character within the string and returns the string """ tempStr = inputStr[iterator] + inputStr[1:iterator] + inputStr[0] + inputStr[iterator+1:] return tempStr def allcombinations() : """ Gets a string from user and prints a list of all possible combinations of the string""" inputStr = raw_input("Enter the string for which you want all the combinations : ") iterator = 0 results = [] while iterator < len(inputStr)-1 : shiftPrint(inputStr, inputStr, results) iterator += 1 inputStr = rotateStr(inputStr, iterator) print results #call the function to start the program automatically allcombinations()
true
c5b94ca14fbc29ec1d60d7e45135bd8dc6613b85
RodrigoGM/algebra
/operations.py
294
4.125
4
def sum(num1, num2): """ This function takes the sum of two numbers Parameters ---------- num1 -- the first number num2 """ return num1 + num2 def product(num1, num2): """ This function takes the product of two numbers """ return num1 * num2
true
e3dac4af4153b239001ccf1019e7e038e93b6b23
sarathrasher/Python_Exercises
/exercises103/tipcalc2.py
732
4.21875
4
bill_input = raw_input("How much was the bill? \n") bill = float(bill_input) service_rating = raw_input("How was your service? \n") rating = service_rating.lower() split = raw_input("Split how many ways?") def tip_calc(): if rating == "good": tip = bill * 0.20 elif rating== "fair": tip = bill * 0.15 elif rating == "bad": tip = bill * 0.10 else: print "Please input either 'good' or 'fair' or 'bad'." return total = bill + tip adjust_total = total / split print "Tip amount: %.2f" % tip print "Total amount: %.2f" % total print "Total amount per person: %.2f" % adjust_total return tip return total return adjust_total tip_calc()
true
b7b6ab700ce1a7ed3b39b9833252a0fc5a1d15d6
Reyoth/python
/variables.py
1,462
4.125
4
# une variable est une "boite" qui contient une valeur # celle ci peut changer au cours du programme maVariable1 = 15 # nombre entier ( int ) maVariable2 = "Bonjour" # lettres ( str ) maVariable3 = 0.5 # nombre decimal ( float ) maListe = ["Bonsoir","Salut", 42] # une liste contenant 3 valeurs # un dictionnaire contenant 3 valeurs # sa particularite c'est que les indexes sont choisi par nous meme monDico = { "a" : "rate", "b" : 42, "c" : 0.15} # Ici, on affiche dans le terminal les valeurs et les types # de chaque variable (attention aux listes et dictionnaires) print(maVariable1, type(maVariable1)) print(maVariable2, type(maVariable2)) print(maVariable3, type(maVariable3)) print(maListe[0], type(maListe)) print(monDico["a"], type(monDico)) print("-------------------------") # operateurs arithmetique # + : addition # - : soustraction # / : division # * : multiplication # ** : exposant # // : division entiere # % : modulo print(maVariable1**2) print(maVariable1//2) print(maVariable1%2) autreVariable = maVariable1%2 # on stock le resultat dans une autre varaibale print("-------------------") # operateurs de comparaison # > : plus grand que # < : plus petit que # >= : plus grand ou egale a # <= : plus petit ou egale a # == : est egale a # != : est different que if (5<10): print("vrai") if(maVariable1 == 15): print("vrai") if (15 != maVariable1): #celui ci sera ignore car ils sont egaux print("vrai")
false
91f34a75f118c1dd22f0c2e3ca31d76eea86df1c
sunilray1326/Python
/PythonSamples/FunctionSample.py
2,983
4.375
4
# # Function and loop examples # # just to print message def fun1(): print("I am fun1") # calculate power of given number, if no power given then default to 1 # the dafault value parameters must come after all non-default parameters def power(num, pw=1): print("\nInside power() function") result = 1 # If only one range is given then range starts from 0 # For example range(4) means 0 to 4 and loop will iterate through 0 to 3 print("Given power is", range(pw)) for i in range(pw): #print(i) result = result * num return result # Add multiple numbers passed and return result def add(*num): print("\nInside add function") print(num) result = 0 # the for loop works as iterator and iterate through each value in list for i in num: #print(i) result = result + i return result # we can pass variable argumemts to function but it shuold be last parameter # we can either pass one value or none to this parameter and it works def add_multi(num1, num2, *args): print("\ninside add_multi() function") # while printing string and number, we need to convert number to string print("num1:", str(num1), "num2:", str(num2), "*args:", str(args)) result = num1 + num2 # If there is no value in list, the loop will not execute # Even if value is 0 in case it is number, loop will execute # for (0,0,0,0) as values, loop will execute 4 times for i in args: print(i) result = result + i return result def whileTest(num, pw): print("\ninside whileTest function") result = 1; while (pw >= 1): #print(pw) result = result * num pw = pw - 1 return result # will print mesasge inside fun1() fun1() # fun1() will print message and print() will print "none" since function doesnt # return any value print(fun1()) print(fun1) print(power(2)) print(power(2,4)) print("Result of add() => {}".format(add())) print("Result of add(2,3) => {}".format(add(2,3))) print("Result of add(4,5,6) => {}".format(add(4,5,6))) print("Result of add(7,8,9,10) => {}".format(add(7,8,9,10))) print(add_multi(9,8,7)) print(add_multi(9,8,7,6)) # even if we don't pass any value to *args parameter, it still works print(add_multi(9,8)) print(add_multi(9,8,0)) print(add_multi(9,8,0,0,0,0)) print(whileTest(4,3)) # see how range() works print("\nrunnig range() function with for loop") for i in range(4,8): print(i) #using the enumerate() function to get index print("\nlist to iterate for \"for loop\"") days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] # enumerate function returns object stored in memory and not any readable value #print(enumerate(days)) for index, day in enumerate(days): print (index, day) # We can also access list using index as show below # so if we have any number available, we can use that as idex to get value from list print("\naccessing days[] using index") print(days[2])
true
ed9239f841d2d4de620ee09a13b09efdd264b4d5
sunilray1326/Python
/PythonSamples/comprehensionSamples3.py
1,545
4.1875
4
## we can initialize list while declaring it itself and faster way to do it testList1 = list(range(1,20)) testList2 = [i for i in range(1,20)] #[i for i in range(1,20) ] print("List1 => ", testList1) print("List2 => ", testList2) ## create a list of tuple testList3 = [(i, i**2) for i in range(1,10)] print("List3 => ", testList3) print("List3 3rd element => ", testList3[2]) print("List3 tuple first element => ", testList3[2][0]) print("List3 tuple second element", testList3[2][1]) try: testList3[2][1] = 12 except TypeError: print("\n**** WARNING : We cannnot modify tuple ****\n") ## we can even use some conditional statement while initializing it testList1 = [i for i in range(1,20) if i % 2 == 0] print("List1 => ", testList1) testList1 = [i1 for i in range(1,20) if i % 2 == 0 for i1 in range(i, i+2)] print("List1 => ", testList1) print("---------------------------------------------------------------") str1 = "I am test sentence" ## below string include one space before a and it is used to match with a space inside any other string str2 = " aeiou" list1 = [i for i in str1 if i not in str2] set1 = {i for i in str1 if i not in str2} print("List1 => ", list1) print("Set1 => ", set1) print("---------------------------------------------------------------") list1 = {i for i in range(1,21)} list2 = {i for i in range(11,31)} print("List1 => ", list1) print("List2 => ", list2) list3 = [i for i in list1 if i not in list2] list4 = [i for i in list1 if i in list2] print("List3 => ", list3) print("List4 => ", list4)
true
9fc4d31d5844b68cb52b125c71f9cd4a8ba69177
unix2dos/pythonTest
/grammar/generate.py
822
4.1875
4
g = (x for x in range(1, 11)) for n in g: print(n) # 另外一种形式 python3 # 如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator: def odd(): yield 1 yield 3 yield 5 for n in odd(): print(n) print(type((x for x in range(1, 11)))) print(type([x for x in range(1, 11)])) # 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。 # Python的Iterator对象表示的是一个数据流, # Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。 # 凡是可作用于for循环的对象都是Iterable类型; # 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
false
7f3121afdc8db6077ac8049c10508fd42f32d3a8
dandanzhe/Learnpython
/类方法.py
718
4.15625
4
# -*-coding:UTF-8 -*- # 要在class中定义类方法,需要这么写: class Person(object): count = 0 @classmethod def how_many(cls): return cls.count def __init__(self, name): self.name = name Person.count = Person.count + 1 print Person.how_many() p1 = Person('Bob') print Person.how_many() # 通过标记一个 @classmethod,该方法将绑定到 Person 类上,而非类的实例。类方法的第一个参数将传入类本身,通常将参数名命名为 cls,上面的 cls.count 实际上相当于 Person.count。 # 因为是在类上调用,而非实例上调用,因此类方法无法获得任何实例变量,只能获得类的引用。
false
eb487cc46ad2df066c548da45e4c89be25ff2254
jonfisik/ScriptsPython
/Scripts1/Script05.py
902
4.40625
4
'''Autor: Jonatan Paschoal, 22/04/2020. Operadores com o função: pow(x,y)=x**y''' print('--------------------------------------------') print('Resolva a seguinte expressão numérica.') print('a {[ b + c ( d x e )] f + (g - h)}') a = int(input('Digite o valor de a: ')) b = int(input('Digite o valor de b: ')) c = int(input('Digite o valor de c: ')) d = int(input('Digite o valor de d: ')) e = int(input('Digite o valor de e: ')) f = int(input('Digite o valor de f: ')) g = int(input('Digite o valor de g: ')) h = int(input('Digite o valor de h: ')) resultado = a*(( b + c * ( d * e )) * f + (g - h)) print('O resultado da expressão.', end=' --> ') print(a,'{[',b,'+',c,'(',d,'x',e,')]',f,'+ (',g,'-',h,')} é: ', resultado) #print("{} {[ {} + {} ( {} x {} )] {} + ( {} - {} )} é {}".format(a, b, c, d, e, f, g, h, resultado)) """<-corrigir essa linha""" print('--------------------------------------------')
false
4fd643ca4fad4507750b5ebfa5a3db5c018834c2
jonfisik/ScriptsPython
/Scripts8/Script72v2.py
988
4.1875
4
'''Exercício Python 072: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.''' #---------------------------------------------------- tupla20 = ('zero','um', 'dois','três','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','quartoze','quinze','dezesseis','dezessete','dezoito','dezenove','vinte') print('-'*40) while True: numero = int(input('Digite um número entre 0 e 20. >>> ')) if 0 <= numero <=20: print(f'Você digitou o número "{tupla20[numero]}".') resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0] print('-'*40) while resp not in 'SN': resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if resp == 'N': break else: print('Tente novamente. ', end = '') print('Saindo do programa...')
false
2322ca4d98cbf414001e571c5711674e5bbe8a14
jonfisik/ScriptsPython
/Scripts11/testeDic2.py
823
4.125
4
brasil = [] estado1 = {'UF': 'Rio de Janeiro', 'sigla': 'RJ'} estado2 = {'UF': 'São Paulo', 'sigla': 'SP'} brasil.append(estado1) brasil.append(estado2) print(estado1) print(estado1) print(brasil) print(brasil[1]) print(brasil[0]) print(brasil[1]['UF']) print(brasil[1]['sigla']) print('---'*15) estado = dict() brasil = list() for c in range(0,3): estado['uf'] = str(input('Unidade Federativa: ')) estado['sigla'] = str(input('Sigla do estado: ')) brasil.append(estado.copy()) print(brasil) print('---'*15) for e in brasil: print(e) print('---'*15) for e in brasil: # for da lista for k, v in e.items(): #for do dicionario print(f'O Campo {k} tem valor {v}.') print('---'*15) for e in brasil: # for da lista for v in e.values(): #for do dicionario print(v, end='') print()
false
4485cf20ccb7bb460e17f1c3de0e6627122b5e70
jonfisik/ScriptsPython
/Scripts7/Script71.py
1,168
4.1875
4
#### # Exercício Python 071: Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao # usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão # entregues. OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. #### print('='*40) titulo = 'BANCO JA' print(f'{titulo:^40}') print('='*40) #------------------------------------ valores = 'Notas de R$ 50, R$ 20, R$ 10 e R$ 1.' print(f'{valores:^40}') print('-'*40) saque = int(input('Que valor você quer sacar? R$ ')) total = saque cedulaValor = 50 totalCedula = 0 while True: if total >= cedulaValor: total -= cedulaValor totalCedula += 1 else: if totalCedula > 0: print(f'Total de {totalCedula} cédula de R$ {cedulaValor}.') if cedulaValor == 50: cedulaValor = 20 elif cedulaValor == 20: cedulaValor = 10 elif cedulaValor == 10: cedulaValor = 1 totalCedula = 0 if total == 0: break print('-'*40) print('{:^40}'.format('Volte sempre ao BANCO JA.')) print('='*40)
false
e95cfade54a3145be73d950fe802f72fe1958e9f
jonfisik/ScriptsPython
/Scripts6/Script54.py
890
4.1875
4
'''Exercício Python 054: Crie um programa que leia o ano de nascimento de sete pessoas. No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.''' from datetime import date print('=+=+=+=+=+=+=+=+='*3) titulo = str('GRUPO DA MAIOR IDADE') print('{:^51}'.format(titulo)) print('=+=+=+=+=+=+=+=+='*3) #---------------------------------------------------------------- totmaior = 0 totmenor = 0 anoAtual = date.today().year for c in range(1,8): n = int(input('Digite o ano de nascimento da {}º pessoa: '.format(c))) idade = anoAtual - n if idade >= 21: totmaior = totmaior + 1 else: totmenor = totmenor + 1 print('-----------------'*3) print('Ao todo tivemos {} pessoa(s) com maior idade.'.format(totmaior)) print('E também tivemos {} pessoa(s) com menor idade.'.format(totmenor)) print('=+=+=+=+=+=+=+=+='*3)
false
cac6064f72bc2d63e035d203434c99869540abad
jonfisik/ScriptsPython
/Scripts7/Script58.py
1,038
4.3125
4
'''Exercício Python 058: Melhore o jogo do DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.''' import random print('x-x-x-x-x-x'*4) titulo = 'ADVINHAÇÃO' print('{:^44}'.format(titulo)) print('x-x-x-x-x-x'*4) num = random.choice([0,1,2,3,4,5,6,7,8,9,10]) print('''Sou seu computador... Acabei de pensar em um número entre 0 e 10. Será que consegue adivinhar?''') palpite = int(input('Qual seu palpite? ')) x = y = z = 0 print('------------'*4) while palpite != num: if palpite > num: print('Menos... Tente mais uma vez.') palpite = int(input('Qual seu palpite? ')) x = x + 1 if palpite < num: print('Mais... Tente mais uma vez.') palpite = int(input('Qual seu palpite? ')) y = y + 1 z = x + y + 1 print('------------'*4) print('Acertou com {} tentativas. PARABÉNS!!!'.format(z)) #print(num, palpite,z,x,y) print('x-x-x-x-x-x'*4)
false
d57a7cd47bae3ce00f742fc274d32d8572a3a1e6
chotmat/learnpythongroup
/LearnPythonTheHardWayToPython3/projects/ex48/ex48/lexicon.py
935
4.125
4
def scan(sentence): """ Scan through each word of a sentence and then turn them into lexicon tuples """ words = sentence.split() lexicons = [] directions = ['north', 'south', 'east','west', 'down', 'up', 'left', 'right', 'back'] verbs = ['go', 'stop', 'kill', 'eat'] stops = ['the', 'in', 'of', 'from', 'at', 'it'] nouns = ['door', 'bear', 'princess', 'cabinet'] for word in words: lWord = word.lower() if lWord in directions: lexicons.append(('direction', word)) elif lWord in verbs: lexicons.append(('verb', word)) elif lWord in stops: lexicons.append(('stop', word)) elif lWord in nouns: lexicons.append(('noun', word)) elif lWord.isdigit(): lexicons.append(('number', int(word))) else: lexicons.append(('error', word)) return lexicons
false
6dbd3677675aac4bb62ad1bd300588a739a22cb4
DominusDrow/Curso_Python
/2-POO/poo_5(super).py
1,049
4.21875
4
#pondremos en practica el uso del metodo super class persona(): def __init__(self,nombre,edad,localidad): self.nom=nombre self.edad=edad #la primera clase es de persona self.loc=localidad def info(self): print("nombre: ",self.nom," edad: ",self.edad," localidad: ",self.loc) class empleado(persona): def __init__(self,sul,anti,nombre,edad,localidad): super().__init__(nombre,edad,localidad) #super llama a la clase padre para poder usar sus metodos self.sueldo=sul self.antiguedad=anti def info_empleado(self): super().info() print("sueldo: ",self.sueldo," antiguedad: ",self.antiguedad) print("\n**********Persona**********") persona1=persona("antonio",22,"Mexico") #aqui creamos una persona cualquiera persona1.info() print("\n**********Empleado**********") #un empleado siempre es una persona, pero una persona no simpre es un empleado empleadoP=empleado(3000,"3 anios","Julio",33,"Sonora") empleadoP.info_empleado() isinstance()
false
8a2cd692f69cca84618db2c4a0fec1016b881d5d
ievagaj/2021-09-22
/main.py
2,941
4.1875
4
import sqlite3 import sys connection = sqlite3.connect("people.db") cursor = connection.cursor() try: cursor.execute("CREATE TABLE people (name TEXT, age INTEGER, skills STRING)") except Exception as e: pass def user_is_unique(name): rows = cursor.execute("SELECT name, age, skills FROM people").fetchall() for user in rows: if user[0] == name: return False return True def insert_db(): name = input("Name >>") if user_is_unique(str(name)): age = input("Age >>") skills = input("Skills >") if name != "" and age != "" and skills != "": cursor.execute(f"INSERT INTO people VALUES ('{name}', '{age}', '{skills}')") connection.commit() print(name + " has been added to the database!") else: print("One of the fields are empty! Please try again!") insert_db() else: print("Name is already in the database!") def edit_db(): name = input("Type the name of the person you'd like to edit >>") field = input("Which field would you like to edit: nme, age or skills? >>") updated_field = input("What would you like to update it to? >>") try: cursor.execute(f"UPDATE people SET {field} = ? WHERE name = ?", (updated_field, name)) connection.commit() print("Successfully updated user!") except Exception as e: print(e) def get_user_info_db(): target_name = input("Who do you want to see information about? >>") rows = cursor.execute("SELECT name, age, skills FROM people WHERE name = ?", (target_name,),).fetchall() name = rows[0][0] age = rows[0][1] # rows [(name, age, skills)] skills = rows[0][2] print(f"{name} is {age} years old, and works as a {skills}.") def delete_db(): name = input("Type the name of the person that you would like to delete >>") if name != "": cursor.execute("DELETE FROM people WHERE name = ?", (name,)) connection.commit() print("User sucessfully deleted!") def display_db(): rows = cursor.execute("SELECT name, age, skills FROM people ORDER BY name ASC").fetchall() print("Users: ") for user in rows: print(f"- {user[0]} - {user[1]} - {user[2]}") def exit_db(): cursor.close() connection.close() sys.exit() def select_options(): options = input(""" ----------------------- Type "0" to exit Type "1" to insert new user Type "2" to display users Type "3" to delete user Type "4" to edit user Type "5" to get user information ------------------------ >>""") if options == "0": exit_db() if options == "1": insert_db() if options == "2": display_db() if options == "3": delete_db() if options == "4": edit_db() if options == "5": get_user_info_db() # Infinite loop while True: select_options()
true
41c40e3fa60f670ce951ed4f4b0a441a5b1ea108
wangminli/codes
/python/str.py
211
4.125
4
#! /usr/bin/env python # -*-coding:utf-8 -*- # str是不可变对象,虽然有个replace方法,但是它的值依然不可改变 str = 'abc' str1=str.replace('a', 'A') print str1 print str ''' Abc abc '''
false
916db100ad564f07a538158cfdaa740a785ed5c6
kimonjo67/py-notes
/dict.py
1,000
4.4375
4
''' Created a menu that will calculate cost of your meal and print a recept with change ''' prices = { "beef": 3.0, "chicken": 3.5, "cheese" : 1.5, "veggie" : 2.0, "salad" : 1.5, "soup" : 2.0, "garlic bread" : 1.0, "fries" : 0.5, "juice" : 2.0, "soda" : 1.5, "bottled water" : 1.0 } print(prices) #User input from the menu sandwich = input("Choose a sandwich from : [beef, chicken, cheese, veggie]: ") side_dish = input("Choose a side dish from : [salad, soup, garlic bread, fries]: ") drink = input("Choose a drink from: [juice,soda, bottled water ]: ") cash = int(input("Please enter cash in $: ")) #Computation of the recept total = prices.get(sandwich) + prices.get(side_dish) + prices.get(drink) print("Your Total is: ", total) change = cash - total print("Your Change is: ", change) #Receipt print("You chose ", sandwich, " $$ " , prices.get(sandwich), " ," , side_dish, " $$ ", prices.get(side_dish), " $$ ", drink , " $$ " , prices.get(drink))
true
b573c497cecf15c354a56e848a018e02be9d29a1
FireNoddles/-offer-
/033. 数值的整数次方.py
2,097
4.3125
4
# 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 # # 保证base和exponent不同时为0 # 快速幂 class Solution: def Power(self, base, exponent): if exponent<0: e = -exponent elif exponent==0: if base == 0: return False else: return 1 else: e = exponent re = 1 t = base while e>0: if e & 1 == 1: re = re * t print(re) t = t * t e = e >> 1 if exponent<0: return 1/re else: return re a = Solution() print(a.Power(2,4)) # 递归 # 链接:https://www.nowcoder.com/questionTerminal/1a834e5e3e1a4b7ba251417554e07c00?answerType=1&f=discussion # 来源:牛客网 # # 解法 3: 二分法 # 为了方便讨论,假设指数exponent是正数。那么递归式如下: # # 如果exponent是偶数,Power(base, exponent) = Power(base, exponent / 2) * Power(base, exponent / 2) # 如果exponent是奇数,Power(base, exponent) = base * Power(base, exponent / 2) * Power(base, exponent / 2) # 对于负指数exponent的情况,取其绝对值先计算。将最后结果取倒数即可。 # # 时间复杂度是 O(logN);由于采用递归结构,空间复杂度是 O(logN)。 # # // 原文地址:https://xxoo521.com/2019-12-31-pow/ # // ac地址:https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00 # # function Power(base, exponent) { # const isNegative = exponent < 0; // 是否是负指数 # const result = absPower(base, Math.abs(exponent)); # return isNegative ? 1 / result : result; # } # # function absPower(base, exponent) { # if (exponent === 0) { # return 1; # } # # if (exponent === 1) { # return base; # } # # const subResult = absPower(base, Math.floor(exponent / 2)); # return exponent % 2 ? subResult * subResult * base : subResult * subResult; # }
false
42010761508897cb345eb23a9701676583d69f9e
IfDougelseSa/cursoIntensivoPython
/exercicios_capitulo4/pizzaTwo.py
284
4.125
4
pizzas = ["palmito", "calabresa", "frango"] friend_pizzas = pizzas[:] pizzas.append("queijo") friend_pizzas.append("brocolis") for pizza in pizzas: print(f"My favorite pizzas are {pizza}") for pizza in friend_pizzas: print(f"My friends favorite pizzas are {pizza}")
false
b9c607f34001d7b66a35bb585784f2d48fdfd8ca
IfDougelseSa/cursoIntensivoPython
/capitulo9.py
1,077
4.15625
4
""" Classes A programação orientada a objetos é uma das abordagens mais eficientes para escrever software. Na programação orientada a objetos, escrevemos classes que representam entidades e situações do mundo real, e criamos objetos com base nessas classes. Quando escrevemos uma classe, definimos o comportamento geral que toda uma categoria de objetos pode ter. -> Criar um objeto a partir de uma classe é uma operação conhecida como instanciação, e trabalhamos com instâncias de uma classe. Por convenção, nomes com a primeira letra maiúscula referem-se a classes em Python. Uma função que faz parte de uma classe é um método. O método __init__() é um método especial que Python executa automaticamente sempre que criamos uma nova instância baseada na classe Dog. O parâmetros self é obrigatório na definição do método e deve estar antes dos demais parâmetros. Acessando atributos nome_instancia.atributo Chamando métodos nome_instancia.metodo() Trabalhando com classes e instâncias Definindo um valor default para um atributo """
false
8c30858295726f3af7b740fbb700520fa9e3795d
shuxiaying/python3
/day1/day1.py
1,341
4.3125
4
# -*- coding:utf8 -*- # #----------------------------------------------------------------------------------- # ProjectName: python3 # FileName: day1 # Author: TangJianjun # Date: 2020/7/6 # Description:Notes for the study of Python3, day 1st. #----------------------------------------------------------------------------------- # python学习第一天 """ 1. pycharm 使用: 快速复制粘贴行:ctrl + d 快速换行:shift + Enter 注释快捷键:ctrl + / 2.赋值: 单个变量赋值: a="变量1" b=1 c=2.12 批量赋值: a,b,c=1,"a","法国红酒" 3.打印输出:print() 输出字符串:print("你好") 输出变量:print(a) 计算输出: print("正"*5)'执行5次输出操作' print("2+3=",2+3) 打印不换行: print("第一行",end='') print("第二行") 4. 格式化字符串: %s 格式化为str类型 %d 格式化为int类型 %f 格式化为float类型 三个一起用时,需要一一对应 import math print("今天7月%d日,天气%s,PM2.5指数%0.2f" %(6,"",100.00)) """ print("hello Monday!") a, b, c = 1, "a", "法国红酒" print(a) print(b) print(c) print("今天7月%d日,天气%s,PM2.5指数%0.2f" %(6,"",100.00)) print("第一行",end='') print("第二行")
false
9a0d476c13517ad5e093e5cd05025eae8928b39b
cybersaksham/Python-Tutorials
/54_object_introspection.py
831
4.125
4
class Employee: leaves = 8 def __init__(self, name, salary, role): self.name = name self.salary = salary self.role = role def emp_det(self): return f"Name is {self.name}, Salary is {self.salary}, Role is {self.role} & leaevs are {self.leaves}" @classmethod # This is class method i.e. it is applied to all instances def change_leaves(cls, newleaves): # Takes first argument as cls by default cls.leaves = newleaves saksham = Employee("Saksham", 5000, "Programmer") harry = Employee("Harry", 2500, "Instructor") # Printing name of class of object print(type(saksham)) # Printing id of object print(id(saksham)) # Printing functions & variables of class of object print(dir(saksham)) import inspect # Printing all information print(inspect.getmembers(saksham))
true
220ff786caebf28a7f6f9336ecd353894309f4f4
filipeclopes/courses
/AzeroPython/python-do-zero-master/python-do-zero-master/exercicios_resolvidos/exercicio3.py
984
4.25
4
""" Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total. """ metros = input("Digite a quantidade de metros quadrados a serem pintados: ") litros = int(metros)/3 preço = 80.0 capacidadeL = 18 latas = litros / capacidadeL preço_total = latas * preço print(f'Você usara {latas}, latas de tinta') print(f'O preco total é de: R$ {preço_total}') """ Caso você queira fazer o arredondamento correto No python, a biblioteca interna te matemática tem uma função chamada ceil que faz esse arredondamento """ from math import ceil print(""" medidas arredondadas """) print(f'Você usara {ceil(latas)}, latas de tinta') print(f'O preco total é de: R$ {ceil(preço_total)}')
false
9d602db515f92d23566521be59078ee92ef2c5bb
filipeclopes/courses
/AzeroPython/python-do-zero-master/python-do-zero-master/exercicios_resolvidos/exercicio12.py
405
4.1875
4
""" Exercício # 12 Faça um programa que receba uma string, com um número de ponto flutuante, e imprima qual a parte dele que não é inteira EX: n = ‘3.14’ responsta: 14 """ numero = input('Digite um número de ponto flutuante: ') # Maneira rápida print(numero.split('.')[1]) # Maneira com for ponto = False for c in numero: if ponto: print(c) if c == '.': ponto = True
false
76b628773ce30088b3ad7625051d3ce38d2e2fc5
jerryhwg/Python
/foundation/recursion/fibonnaci3.py
375
4.34375
4
# Python 3.7.2 # # Module 102 # # Implement a Fibonnaci Sequences Iteratively # # a function will accept a number n and return the nth number of the fibonacci sequence def fib_iter(n): a = 0 b = 1 for i in range(n): a,b = b,a+b # iterate, python way print('a',a) print('b',b) return a """ Test fib_iter(10) result: 55 """
true
4b31dd8849435e3425372ef62fe2b3f8497de085
jerryhwg/Python
/foundation/linked_lists/nth_to_last_node.py
1,335
4.25
4
# Python 3.7.2 # a function that takes a head node and an integer value n # and returns the nth to last node in the linked list # a bunch of nodes # a block = n-wide nodes ex. n=2, 2-wide nodes # once the front of the block reaches the end, the other end of the block is the Nth node def nth_to_last_node(n, head): # head = a left_pointer = head right_pointer = head # set right pointer for i in range(n-1): if not right_pointer.nextnode: raise LookupError('Error: n is larger than the linked list') right_pointer = right_pointer.nextnode # set the block (left_pointer = head, right_pointer = right_pointer.nextnode) while right_pointer.nextnode: # continue to loop (slide the block) until 'right_pointer.nextnode' reaching the tail left_pointer = left_pointer.nextnode # ex. n =2, d right_pointer = right_pointer.nextnode # ex. e return left_pointer # when the end is e, the Nth pointer is d and d.value is 4 """ class Node: def __init__(self,value): self.value = value self.nextnode = None """ """ Test a = Node(1) b = Node(2) c = Node(3) d = Node(4) e = Node(5) a.nextnode = b b.nextnode = c c.nextnode = d d.nextnode = e target_node = nth_to_lst_node(2, a) # 2nd to last node = d with a value of 4 target_node.value 4 """
true
e1e2e48c74e5a31f9956ac349d54c838c6de9c2a
jerryhwg/Python
/function_methods/old_macdonald.py
318
4.1875
4
# Python 3.7.2 # Level 1 # Capitalize the first and fourth letters of a name def old_macdonald(name): first_half = name[:3] second_half = name[3:] return first_half.capitalize() + second_half.capitalize() if __name__ == "__main__": print(old_macdonald('macdonald')) # key: split name into two parts
true
16785e09a7d71341feff6b7ff07985964d1b0231
jerryhwg/Python
/foundation/array_sequences/rev_word1.py
432
4.4375
4
# Python 3.7.2 # Module 59 # Given a string of words, reverse all the *words* # Usage: rev_word1('words') def rev_word1(s): return " ".join(reversed(s.split())) # split() words per space in string # s.split() # ['space', 'before'] # # reversed: reverse the words order # ['before', 'space'] # # join (put them together into a sentence) # before space """ Test: s = ' space before' rev_word1(s) Output: 'before space' """
true
1f3b5649ea2a65e2898aafeff32df9ccf6b87a75
jerryhwg/Python
/foundation/sorting/insertion_sort.py
408
4.15625
4
def insertion_sort(arr): for i in range(1,len(arr)): # 1 2 3 4 currentvalue = arr[i] # arr[1] position = i # 1 while position > 0 and arr[position-1] > currentvalue: # arr[0] > arr[1] arr[position] = arr[position-1] # swap arr[0] moves to arr[1]; insert position = position-1 # position = 0 arr[position] = currentvalue # arr[0] = currentvalue
false
6e1f2c55b354d9cbf9aefede5b768fc6ef7ccc18
pVilmos/Ciphers
/deciphers/substitution_decipher.py
835
4.25
4
#note that this code is basically ../ciphers/substitution_cipher.py #This reason for making another file is purely for from itertools import permutations from random import random from math import floor from constants import CHARACHTERS, LENGTH def decrypt_message_substitution(message, alphabet, decryption_table): decrypted_message = "" #looping through the message for letter in message: if letter not in alphabet: decrypted_message += letter #leaving the the charachters the same that are not in the alphabet else: decrypted_message += decryption_table[alphabet.index(letter)] return decrypted_message if(__name__=="__main__"): message = input() encryption_table = input() print(encrypt_message_substitution(message, CHARACHTERS, encryption_table))
true
e6db2ffd8038ee13228a297003eeb21fcbb218fb
AtulPhirke95/Data-Structures
/LinkedList/double_linked_list.py
2,156
4.15625
4
class Node: def __init__(self,data): self.data = data self.prev = None self.next = None class LinkedList: def __init__(self): self.head = None def traversal(self): temp = self.head while temp!=None: print(temp.data) temp = temp.next def push(self,key): temp = self.head if temp == None: new_node = Node(key) new_node.next = None new_node.prev = None self.head = new_node else: while temp.next!=None: temp = temp.next new_node = Node(key) new_node.next = None temp.next = new_node new_node.prev = temp def insertion_at_beginning(self,key): temp = self.head if temp == None: self.push(key) else: new_node = Node(key) new_node.next = self.head new_node.prev = None new_node.next.prev = new_node self.head=new_node def insertion_in_between(self,key,new_key): temp = self.head if temp == None: self.push(new_key) else: while temp.data !=key: temp = temp.next new_node = Node(new_key) new_node.next = temp.next new_node.prev = temp temp.next = new_node new_node.next.prev = new_node def pop(self): temp = self.head if temp == None: print("Can not delete. List is empty.") return else: if temp.next ==None: self.head.next = None self.head.prev = None else: while(temp.next!=None): temp = temp.next temp.prev.next=None temp.prev = None def pop_at(self,key): temp = self.head flag = False while temp!=None: if temp.data ==key: flag=True temp = temp.next if flag == False: print("Serached key not found.") return else: temp = self.head while temp.data != key: temp = temp.next temp.prev.next = temp.next temp.next.prev = temp.prev temp.next=None temp.prev = None def reversed(self): p1 = self.head p2 = p1.next p1.next = None p1.prev = p2 while p2!=None: p2.prev = p2.next p2.next = p1 p1 = p2 p2 = p2.prev self.head = p1 if __name__== "__main__": lobj = LinkedList() for i in range(1,11): lobj.push(i) #pass #lobj.insertion_in_between(5,60) #lobj.pop() #lobj.pop_at(9) lobj.reversed() lobj.traversal()
false
448d806f1e6d6277cfe6d801a8edb0c7e18d4a09
Bioviking/SU_comparative_genomics
/templates/check_if_protein.py
474
4.1875
4
############################################### #(*) Given a string of characters, write a function is_protein(seq) that returns True if it is a valid protein sequence, else False. We consider a a valid protein something that contains only valid aminoacids: ACDEFGHIKLMNPQRSTVWY in capital letters. def is_protein(seq): for i in seq: if i not in 'ACDEFGHIKLMNPQRSTVWY': return False return True #print(is_protein('ACDEFGHIKLMNPQRSTVWY'))
true
f498776516b019702f5d35305359163e6ac17a89
raiscreative/100-days-of-python-code
/day_003/pizza_order.py
913
4.125
4
choice = input('Welcome to Pizza Hot! Do you want to place a new order? y/n\n') order = 0 if choice.lower().startswith('y'): order = 1 else: print('Very well then, come another time!') while order: size = input('Would you like a small, medium or large pizza? s/m/l/\n') pepperoni = input('Would you like pepperoni on your pizza? y/n\n') cheese = input('Would you like extra cheese on your pizza? y/n\n') if size.lower().startswith('s'): price = 15 if pepperoni.lower().startswith('y'): price += 2 elif size.lower().startswith('m'): price = 20 if pepperoni.lower().startswith('y'): price += 3 else: price = 25 if pepperoni.lower().startswith('y'): price += 3 if cheese.lower().startswith('y'): price += 1 print(f'Your pizza is ${price}, please. Enjoy!')
true
e97ea7a14a597a4c7b41963a123638b32990e102
Deivid-Araujo/Python-programs
/Guess_the_number.py
1,229
4.40625
4
'''The idea behind the code The computer choose a number between 1 and 100, try to know what number is it. Don't worry, the computer will give you some clues to help. ''' import random #Creating the variable that saves the value of user! user = [] #Computer choose the random number number = random.randint(1,100) #Loop while user doesn't got the right number while user!= number: #User try to discover the number by the input user = int(input('What number you think it is?')) #Conditional if number is even if number % 2 == 0: print('The number is even!') #Conditional if number is odd else: print('The number is odd!') #Conditional to know if number that user tried is multiple of the number computer choose if number % user == 0: print(f'{user} is a multiple of the number') #Conditional to know if number that user tried is lower than the number computer choose if user < number: print('The number is higher! Give it another try! ') #Conditional to know if number that user tried is higher than the number computer choose else: print('The number is smaller! Give it another try! ') if user == number: print('Congratulations!')
true
5ca86bdb41f503e86f72804c16b7c28185ac988e
siblackburn/sentence_analysis
/sentence_analysis.py
1,016
4.3125
4
user_input = input("enter something nice: ") #Finding the number of lower case characters based on using a count of the lower function count = 0 for i in user_input: if(i.islower()): count = count + 1 print("The number of lower case characters is: ") print(count) #Finding the number of upper case characters based on using a count of the upper function upcount = 0 for j in user_input: if(j.isupper()): upcount = upcount + 1 print("the number of upper case characters is:") print(upcount) #How to count the special characters in a sentence specials = ['!', ',', " \ ", ";", " \ ", ".", "-", "?", "*", "(", ")"] special_count = 0 for k in user_input: if user_input in specials: special_count = special_count + 1 print("The number of special characters is:") print(special_count) print("Therefore the total number of characters is ", count + upcount + special_count) Dict = {"Upper case" : upcount, "lower case" : count, "Special characters" : special_count} Print(Dict)
true
c8160b5a90962ad5338a9ccce8a5b3b6a616c762
ewoodworth/calculator-2
/arithmetic.py
1,380
4.3125
4
def add(numbers): """Add variable amount of numbers Add content of list numbers to get an integer output""" return reduce(lambda x, y: x + y, numbers) def subtract(numbers): """Find the difference between variable amount of numbers Subtract contents of list numbers to get an integer output""" return reduce(lambda x, y: x - y, numbers) def multiply(numbers): """Find the product of variable amount of numbers Multiply contents of list numbers to get an integer output """ return reduce(lambda x, y: x * y, numbers) def divide(numbers): """Find the quotient of variable amount of numbers Divide initial list item by all following list contents to get a float """ return reduce(lambda x, y: x / y, numbers) def square(numbers): """ Square a number. Square num1 to get an integer output """ return numbers[0] ** 2 def cube(numbers): """ Cube a number Cube num1 to get an integer output """ return numbers[0] ** 3 def power(numbers): """Find the nth power of a number Raise num1 to the power of num2 to get an integer output """ return reduce(lambda x, y: x ** y, numbers) def mod(numbers): """Find the remainder after the division of two numbers Returns the remainder integer after dividing num1 by num2 """ return reduce(lambda x, y: x % y, numbers)
true
6e8c336d53332bc5a619f21c9845fd2e94dce434
hollsmarie/Python
/MultiplesSumAverage_Assignment/multiplesSumsAverage.py
1,112
4.5
4
# Multiples # Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise. for count in range(1, 1001): #creates a variable called Count to hold all of the numbers between 1 and 10001 print count #prints the variable # Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000. for count in range (5, 1000000): #creates a variable called count and assigns it a range of 5 to 10000000 print count * 5 #prints the numbers in the range that are a multiple of 5 #Sum List #Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3] a = [1, 2, 5, 10, 255, 3] #Creates a variable called a, and assigns it the values inside b = sum(a) #creates a variable called b and assigns it the sum of a print b #prints variable b #Average List # Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3] c = [1, 2, 5, 10, 255, 3] #creates a variable called c and assigns it values print sum(c)/len(c) #prints the sum of c divided by the length of c
true
e41d8b3c0d73aad233fae3e2daeed64b257d08cf
Lingann/PythonSamples
/07_OOP/Encapsulation.py
1,179
4.4375
4
# python中,基本上封装是要靠规范来进行的,实际上就靠约定进行能不能访问成员 # python 中,对于私有变量有一下约定 # * 不应该直接访问以下划线为前缀的类的变量 如 class._variable 或class.__variable (实际上可以访问得到) # * 由于python中没有private,所以对于私有变量,以下划线为开头进行命名,约定该变量为私有变量 # * 单下划线的变量,我们约定为只有子类可以访问,类似protected关键字,双下划线表示只有当前类可以访问,类似private关键字 # 构造函数类 class Teacher(object): # 类似 private __motto __motto = "留取丹心照汗青" # 类似 protected _age _age = 0 def __init__(self, name, age): self.name = name self._age = age def say(self): self.__after_one_year() self._say_name() print(self.__motto, self._age) # 类似 private __after_one_year() def __after_one_year(self): self._age += 1 # 类似protected _say_name() def _say_name(self): print(self.name) tea = Teacher('琳', 18) tea.say() tea.say() tea.say()
false
b2a567c54cbc6498f7c3d79200b791b68c525daf
YashKarthik/20_queens
/N_queens.py
2,266
4.125
4
from copy import deepcopy class N_queens: def __init__(self, N): self.N = N self.K = 1 self.Outputs = {} def print_sol(self, board): print(f'On {self.K}th Solution') self.Outputs[self.K] = [] self.Outputs[self.K] += deepcopy(board) self.K += 1 def is_safe(self, board, row, col): for i in range(col): # Checking if that particular cell already has a queen. if board[row][i]: return False i = row j = col # checking if there is a queen on upper diagonal on left side while i >= 0 and j >= 0: if board[i][j]: # Again checking if there's a queen return False j -= 1 i -= 1 i = row j = col while j >= 0 and i < self.N: if board[i][j]: return False i += 1 j -= 1 # Finally, that place is safe to place our beautiful queen! return True def solve_util(self, board, col): """ First, it checks if all the queens are placed, and then returns true... """ try: if col == self.N: self.print_sol(board) return True # Trying to place this queen in all rows one by one res = False for i in range(self.N): if self.is_safe(board, i, col): board[i][col] = 1 res = self.solve_util(board, col + 1) or res if type(res) == dict: return res board[i][col] = 0 # Backtracking... # if queen cannot be placed in any row in this col, then alas # we return false.. return res except KeyboardInterrupt: print('Keyboard Interrupted!') return self.Outputs def solve(self): board = [[0 for j in range(self.N)] for i in range(self.N)] outputs = self.solve_util(board, 0) if not outputs: print('No solution exists.') return False return outputs def main(): N_queens(20).solve() if __name__ == "__main__": main()
false
14e180e0d40fc63b29e4f8e5a7a1c2367ea66d0b
owlrana/cpp
/rahulrana/python/Leetcode/#037 String Matching in an Array/v37.0.py
429
4.125
4
# https://leetcode.com/problems/string-matching-in-an-array/ def stringMatching(words): substring_list = [] for word1 in words: for word2 in words: if word1 in word2 and word1 != word2 and word1 not in substring_list: substring_list.append(word1) return substring_list words = ["leetcode","et","code"] print(stringMatching(words)) # 24ms; faster than 99% # 14.3MB; less than 25%
true
314e27b3c3b1e18aef8fb78f30cae3c8e6923dbd
zhaobingwang/python-samples
/30-Days-Of-Python/30-Days-Of-Python/11_function.py
2,474
4.1875
4
print('---------- Function without Parameters ----------') def add_two_numbers(): num_1 = 1 num_2 = 2 total = num_1 + num_2 print(total) add_two_numbers() print('---------- Function Returning a Value Part 1 ----------') def add_two_numbers(): num_1 = 1 num_2 = 2 total = num_1 + num_2 return total print(add_two_numbers()) print('---------- Function with Parameters ----------') def greeting(name): return 'Hi,' + name print(greeting('ZhangSan')) def sum_two(num1, num2): total = num1 + num2 return total print(sum_two(1, 3)) print('---------- Passing Arguments with Key and Value ----------') def sub_two(num1, num2): total = num1 - num2 print(total) sub_two(num2=5, num1=3) # -2 print('---------- Function Returning a Value Part 2 ----------') print('\t---------- Returning a string ----------') def get_full_name(firstname, lastname): space = ' ' full_name = firstname + space + lastname return full_name print(get_full_name('San', 'Zhang')) print('\t---------- Returning a numbers ----------') def calculate_age(current_year, birth_year): age = current_year - birth_year return age print(calculate_age(2021, 2000)) print('\t---------- Returning a boolean ----------') def is_even(num): if num % 2 == 0: return True return False print(is_even(6)) # True print(is_even(5)) # False print('\t---------- Returning a list ----------') def find_even_numbers(n): evens = [] for i in range(n + 1): if i % 2 == 0: evens.append(i) return evens print(find_even_numbers(10)) print('---------- Function with Default Parameters ----------') def calculate_age(birth_year, current_year=2021): age = current_year - birth_year return age print(calculate_age(2000)) print('---------- Arbitrary Number of Arguments ----------') def sum_all_nums(*nums): total = 0 for num in nums: total += num return total print(sum_all_nums(1, 2, 3, 4, 5)) print('---------- Default and Arbitrary Number of Parameters in Functions ----------') def generate_groups(team, *args): print(team + ':') for i in args: print(' ', i) generate_groups('Team-1', 'Zhang San', 'Li Si', 'Wang Wu') print('---------- Function as a Parameter of Another Function ----------') def square_number(n): return n * n def do_something(f, x): return f(x) print(do_something(square_number, 3))
true
10f6180e99549404ca713314237cbc58d4da5fa6
zhaobingwang/python-samples
/30-Days-Of-Python/30-Days-Of-Python/16_datetime.py
2,316
4.625
5
from datetime import datetime print('---------- Getting datetime Information ----------') now = datetime.now() print(now) print(now.year) print(now.month) print(now.day) print(now.hour) print(now.minute) print(now.second) print(now.timestamp()) # Timestamp or Unix timestamp is the number of seconds elapsed from 1st of January 1970 UTC. print('---------- Formating Date Output Using strftime ----------') new_year = datetime(2021, 1, 1) print(new_year) year = new_year.year month = new_year.month day = new_year.day hour = new_year.hour minute = new_year.minute second = new_year.second print(year, month, day, hour, minute, second) print(f'{year}/{month}/{day}, {hour}:{minute}:{second}') # Time formating print('\t---------- Time formating ----------') now = datetime.now() t = now.strftime('%Y-%m-%d %H:%M:%S') print(t) print('---------- String to Time Using strptime ----------') date_string = "2021-01-01" print("date_string =", date_string) date_object = datetime.strptime(date_string, "%Y-%m-%d") print("date_object =", date_object) print('---------- Using date from datetime ----------') from datetime import date d = date(2021, 2, 7) print(d) # 2021-02-07 print(d.day) # 7 print(d.today()) # date object of today's date print('---------- Time Objects to Represent Time ----------') from datetime import time print(time()) # 00:00:00 print(time(12, 00, 00)) # 12:00:00 print(time(hour=12, second=0, minute=30)) # 12:30:00 print('---------- Difference Between Two Points in Time Using ----------') today = date(year=2021, month=2, day=7) new_year = date(2022, 1, 1) time_remaining_of_new_year = new_year - today print('Remaining time of New Year:', time_remaining_of_new_year) today = datetime(year=2021, month=2, day=7, hour=0, minute=0, second=0) new_year = datetime(year=2022, month=1, day=1, hour=0, minute=0, second=0) time_remaining_of_new_year = new_year - today print('Remaining time of New Year:', time_remaining_of_new_year) print('---------- Difference Between Two Points in Time Using timedelta ----------') # 更多信息参见:https://docs.python.org/zh-cn/3/library/datetime.html#timedelta-objects from datetime import timedelta t1 = timedelta(weeks=12, days=10, hours=4, seconds=20) t2 = timedelta(days=7, hours=5, minutes=3, seconds=30) t3 = t1 - t2 print("t3 =", t3)
false
30c8b979906116480ad330b169ceed811360e7e9
pz325/codeeval
/fizzbuzz.py
1,759
4.28125
4
''' https://www.codeeval.com/open_challenges/1/ INPUT SAMPLE: Your program should read an input file (provided on the command line) which contains multiple newline separated lines. Each line will contain 3 numbers which are space delimited. The first number is first number to divide by ('A' in this example), the second number is the second number to divide by ('B' in this example) and the third number is where you should count till ('N' in this example). You may assume that the input file is formatted correctly and is the numbers are valid positive integers. E.g. 3 5 10 2 7 15 OUTPUT SAMPLE: Print out the series 1 through N replacing numbers divisible by 'A' by F, numbers divisible by 'B' by B and numbers divisible by both as 'FB'. Since the input file contains multiple sets of values, your output will print out one line per set. Ensure that there are no trailing empty spaces on each line you print. E.g. 1 2 F 4 B F 7 8 F B 1 F 3 F 5 F B F 9 F 11 F 13 FB 15 Constraints: The number of test cases <= 20 "A" is in range [1, 20] "B" is in range [1, 20] "N" is in range [21, 100] ''' def fizzbuzz(test): (A, B, N) = test.split(' ') A, B, N = int(A), int(B), int(N) seq = [] for i in range(1, N+1): if i % A == 0 and i % B == 0: seq.append('FB') else: if i % A == 0: seq.append('F') elif i % B == 0: seq.append('B') else: seq.append(str(i)) print(' '.join(seq)) import sys test_cases = open(sys.argv[1], 'r') for test in test_cases: # ignore test if it is an empty line # 'test' represents the test case, do something with it fizzbuzz(test) # ... test_cases.close() # fizzbuzz('10 1 58')
true
db98727279e99087fe86f229e52993e2ceafc701
claire1234995/code
/tools/py_python/list_remove.py
295
4.25
4
# 显然下面的结果是错的 l = ['1', '2', 'c', 'a'] print(l) # ['1', '2', 'c', 'a'] for i in l: if i in ['1', '2']: l.remove(i) print(l) # ['2', 'c', 'a'] l = ['1', '2', 'c', 'a'] print(l) # ['1', '2', 'c', 'a'] l = [i for i in l if i not in ['1', '2']] print(l) # ['c', 'a']
false
6eb6ea765e33e5dea1419c3a92c3c4f8d03cee8b
tanyag330/PyGame
/sample/Step3.py
1,706
4.15625
4
# Make the Bunny Move #2 (after you set the screen height and width): keys = [False, False, False, False] playerpos=[100,100] # Use the "playerpos" variable to draw the player # Change the following line in section #6: screen.blit(player, (100,100)) # To: screen.blit(player, playerpos) # Update the keys array based on which keys are being pressed. # PyGame makes detecting key presses easy by adding event.key functions. # At the end of section #8, right after the block checking for event.type==pygame.QUIT, put this code (at the same indentation level as the pygame.QUIT if block): if event.type == pygame.KEYDOWN: if event.key==K_w: keys[0]=True elif event.key==K_a: keys[1]=True elif event.key==K_s: keys[2]=True elif event.key==K_d: keys[3]=True if event.type == pygame.KEYUP: if event.key==pygame.K_w: keys[0]=False elif event.key==pygame.K_a: keys[1]=False elif event.key==pygame.K_s: keys[2]=False elif event.key==pygame.K_d: keys[3]=False # Add the following code to the end of game.py (with one indentation level, putting it at the same level as the for loop): # 9 - Move player if keys[0]: playerpos[1]-=5 elif keys[2]: playerpos[1]+=5 if keys[1]: playerpos[0]-=5 elif keys[3]: playerpos[0]+=5 # This code simply checks which of the keys are being pressed and adds or subtracts from the player’s x or y position # (depending on the key pressed) to move the player.
true
1b6e5a5c275369f9e073a946136d7fb59b2d8039
favanso/Python_Projects
/M9 Assignment.py
1,204
4.5
4
##Create the PYTHON program allowing the user to enter a value for one edge of a cube(A box-shaped solid object that has six identical square faces). ## ##Prompt the user for the value. ##There should be a function created for each calculation: ##One function should calculate the surface area of one side of the cube. The value calculated is printed within the function. ##One function should calculate the surface area of the whole cube. ##The user value is passed as an argument to this function. It should be returned to the calling statement and printed. ##One function should calculate the volume of the cube and print the results within in the function. ''' Fernando Branco CIS 129 M9 Assignment ''' value = float(input('Enter a value for one edge of a cube: ')) def oneside(): os = value*value print ('The area of each cube side is ', os,'\n') print ('The side lenght you inputed is ',value,'\n') def surfacearea(value): surf = value*6 return surf result = surfacearea(value) print ('The Surface area of the cube is ', result,'\n') def volume(): vol = value**3 print ('The volume of the cube is ', vol,'\n') oneside() volume()
true
adfe17a6eb9c35a697329f25ca0c934cbe2fee54
scm2nycotx/python-exercises
/guess_the_number.py
2,835
4.28125
4
# Step 1 print("I am thinking of a number between 1 and 10.") secret_number = 5 while True: answer = int(input("What is the number of your guess? ")) if answer == secret_number: print("Yes! You Win!!") break else: print("Nope, try again!") # Step 2: Give High-Low Hint print("I am thinking of a number between 1 and 10.") secret_number = 5 while True: answer = int(input("What is the number of your guess? ")) if answer == secret_number: print("Yes! You Win!!") break elif answer > secret_number: print("{} is too high! Try a lower one!".format(answer)) else: print("{} is too low! Try a higher one!".format(answer)) # Step 3: Randomly Generated Secret Number import random my_random_number = random.randint(1, 10) print("A random number is generated between 1 and 10.") while True: answer = int(input("What is the number of your guess? ")) if answer == my_random_number: print("Yes! You got it!!") break elif answer > my_random_number: print("{} is too high! Try a lower one!".format(answer)) else: print("{} is too low! Try a higher one!".format(answer)) # Step 4: Limit Number of Guesses import random my_random_number = random.randint(1, 10) print("A random number is generated between 1 and 10.") print("You have five guesses left.") count = 5 while count > 0: answer = int(input("What is the number of your guess? ")) if answer == my_random_number: print("Yes! You got it!!") break elif answer > my_random_number: print("{} is too high! Try a lower one!".format(answer)) count -= 1 else: print("{} is too low! Try a higher one!".format(answer)) count -= 1 print("You ran out of guesses!") # Bonus: Play Again import random def play(): my_random_number = random.randint(1, 10) print("A random number is generated between 1 and 10.") print("You have five guesses left.") count = 5 while count > 0: answer = int(input("What is the number of your guess? ")) if answer == my_random_number: print("Yes! You got it!!") againOrnot = input("Do you want to play again (Yes or No)? ") if againOrnot.lower() == "yes": play() if againOrnot.lower() == "no": print("See you!") elif answer > my_random_number: print("{} is too high! Try a lower one!".format(answer)) count -= 1 else: print("{} is too low! Try a higher one!".format(answer)) count -= 1 print("You ran out of guesses!") againOrnot = input("Do you want to play again (Yes or No)? ") if againOrnot.lower() == "yes": play() if againOrnot.lower() == "no": print("See you!")
true
09ccd0b835ba4f8ee0ab5e81fbaca60f176e64f8
debdutgoswami/anonymous-coding-problems
/Question 21-30/Q22/Q22.py
481
4.34375
4
def first_recurring_char(s: str) -> str: """python program to find the first repeated character in a string. Arguments: s {str} -- the string on which the search is to be performed. Returns: str -- first occuring character else None """ h = {} # using dictionary as hash for ch in s: if ch in h: return ch h[ch] = 0 return None print(first_recurring_char('qwertty')) print(first_recurring_char('qwerty'))
true
f43a7c857c14a77388a9cce5a68854570e486ee5
ramneek008/Python-Exercise
/String.py
1,051
4.34375
4
string = "Python practice going on" print(string) print("First character of string is: ") print(string[0]) print("Last character of string is: ") print(string[-1]) print("slicing elements from 3-14: ") print(string[3:14]) string1 = '''Hi, I'm "Ramneek"''' print("String1: ") print(string1) string2 = "{} {} {}".format('Be', 'Honest', 'always') print("String2 in default order: ") print(string2) string3 = "{1} {0} {2}".format('Be', 'Honest', 'always') print("String3 in positional order: ") print(string3) s = "We are learning python" print(s.upper()) print(s.lower()) s='We are learning python ' print(s.strip()) #removes extra spaces s = 'We are learning python' print(s.find('are')) print(s.find('java')) b = s.replace("learning",'teaching') print(b) split_string = s.split(' ') print(split_string) print(type(split_string)) #list print(' '.join(split_string)) joined_string = ','.join(split_string) print(joined_string) print(s) print(s[0]) s='programming' print(s[-7:-3]) print(s[::2]) s = 'ha@ha@ha@' print(s[::3])
true
a5d64a16015de7afa30e42e2774731c33fdd8a1e
Farooqut21/my-work
/assignment from 3 .1 to 3.13/3.5/a.py
426
4.125
4
#Implement a program that requests from the user a list of words (i.e., strings) and then prints on the screen, one per line, all four-letter strings in the list. list=[] # create empty list first_word = input('Enter first word: ') second_word = input('Enter second word: ') third_word= input('Enter third word: ') list.append(first_word) list.append(second_word) list.append(third_word) for i in list: print(i)
true
9c07517278e89d815c1d918bcd01ddc949116e85
Farooqut21/my-work
/LAB 04 Muhammad Farooq section b cs 021/program 9.py
469
4.46875
4
#program 9Write a program to convert digital number from 0 to 16 into binary, octal and hexa-decimal number system. print("python program to convert decimal number into binary,octal and hexadecimal number system") for a in range(0,17): print("the decimal value of ",a,"is:","in binary its:",bin(a),"in ovtal its:",oct(a),"and in hexadeciaml its:",hex(a)) print("thats the end of the program with range from 1 to 16")
true
d209fe0d08ce94f09f7b9614dd4b219496bd0d3c
puku6/MyExercises
/Python Exercises/ex21.py
953
4.125
4
def add(a,b): print "ADDING %d to %d" % (a,b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a,b) return a - b def multiply(a, b): print "MULTIPLYING %d * %d" % (a,b) return a * b def divide (a, b): print "DIVIDING %d / %d" % (a,b) return a / b print "Let's do some math with just functions!" age = add(30,5) height = subtract(78,4) weight = multiply(90,2) iq = divide (100, 2) print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) # the same as age + height - weight * (iq/20) = 35+74-180*(50/2) print "that becomes: ", what, "Can you do it by hand?" print "here comes my own puzzle" puzzle = divide(multiply((subtract(age, weight)),(add(height, iq))),2) print " = ", puzzle print "and now to the normal calculation" puzzle_easy = divide(multiply(add(1,2),4),5) print " = ", puzzle_easy
false
2a11f217d07548dc2ffc6a2edcf5bbb1931094be
yusrakaya/GlobalAIHubPythonHomework
/PROJECT.py
2,043
4.3125
4
student_list = ["Yüsra Kaya", "Sibel Erman", "Şevval Önder", "Nebo Genç","Elif Küçükkaya"] lessons = ["Calculus", "Algorithm", "OPP", "Data Structure", "Electronic Circuits", "Psychology"] def lesson_selection(): lessons_input = input("\nPlease enter lessons do you want to choose: ") lessons_list = list(lessons_input.split(",")) if len(lessons_list) < 3: return print("\nYou failed, you must take a minimum 3 and maximum 5 lessons.") else: lesson = input("Please enter the lesson's name you want to learn passed or not: ") if lesson in lessons_list: grades = {"midterm": 0, "final": 0, "project": 0} midterm = int(input("\nEnter your midterm grade: ")) grades["midterm"] = midterm final = int(input("Enter your final grade: ")) grades["final"] = final project = int(input("Enter your project grade: ")) grades["project"] = project grade = (midterm * 30 + final * 50 + project * 20) / 100 if grade >= 90: return print("\nYour grade is AA.", "you passed the lesson") if grade >= 70 and grade < 90: return print("\nYour grade is BB.", "you passed the lesson") if grade >= 50 and grade < 70: return print("\nYour grade is CC.", "you passed the lesson") if grade >= 30 and grade < 50: return print("\nYour grade is DD.", "you passed the lesson") else: return print("\nYour grade is FF.", 'You have failed') for i in range(3): name = input("Please enter your name: ") surname = input("Please enter your surname: ") student = name + " " + surname if student in student_list: print("\n", student, ",", "Welcome") lesson_selection() break if i <= 2: print("İnvalid username, Try again.") else: print("Please try again later.")
false
86fe98b062e2f1cb30ee027fbb6a1f2d166c4c2c
razmanika/My-Work-Python-
/Udemy/udemy-5.py
536
4.25
4
def count_primes(num): # check for 0 or 1 input if num < 2: return 0 # 2 or greater #store our prime numbers primes = [2] #Counter going up to the input num x = 3 # x is going throught every numbver up to input num while x <= num: #check if x is prime for y in range(3,x,2): if x % y == 0: x += 2 break else: primes.append(x) x += 2 print(primes) return len(primes) print(count_primes(100))
true
ef6b0796f160c2782e59a9b88239358c254df13c
patompong995/unittestlab
/testinglab/listutil.py
686
4.53125
5
def count_unique(list): """Count the number of distinct elements in a list. The list can contain any kind of elements, including duplicates and nulls in any order. (In PyDoc there are different formats for parameters and returns. Use what you prefer.) :param list: list of elements to find distinct elements of :return: the number of distinct elements in list Examples: >>> count_unique(['a','b','b','b','a','c','c']) 3 >>> count_unique(['a','a','a','a']) 1 >>> count_unique([ ]) 0 """ check=[ ] count=0 for i in list: if(i not in check): check.append(i) count=count+1 return count
true
30dfbff52236a7fe7a13859a0ef596ffd94cbf4d
MostFunGuy/SpringboardProjectsPublic
/python-ds-practice/33_sum_range/sum_range.py
1,141
4.1875
4
def sum_range(nums, start=0, end=None): """Return sum of numbers from start...end. - start: where to start (if not provided, start at list start) - end: where to stop (include this index) (if not provided, go through end) >>> nums = [1, 2, 3, 4] >>> sum_range(nums) 10 >>> sum_range(nums, 1) 9 >>> sum_range(nums, end=2) 6 >>> sum_range(nums, 1, 3) 9 If end is after end of list, just go to end of list: >>> sum_range(nums, 1, 99) 9 """ return_num = 0 i = -1 for num in nums: i = i + 1 if (i >= start) and (end == None or i <= end): return_num = return_num + num return return_num nums = [1, 2, 3, 4] print(F"sum_range.py: sum_range(nums) = 10 = {sum_range(nums)}") print(F"sum_range.py: sum_range(nums, 1) = 9 = {sum_range(nums, 1)}") print(F"sum_range.py: sum_range(nums, end=2) = 6 = {sum_range(nums, end=2)}") print(F"sum_range.py: sum_range(nums, 1, 3) = 9 = {sum_range(nums, 1, 3)}") print(F"sum_range.py: sum_range(nums, 1, 99) = 9 = {sum_range(nums, 1, 99)}")
true
c260034379d7934d0469bf84ee5dab3fbe49cb0d
MostFunGuy/SpringboardProjectsPublic
/python-ds-practice/fs_3_three_odd_numbers/three_odd_numbers.py
946
4.375
4
def three_odd_numbers(nums): """Is the sum of any 3 sequential numbers odd?" >>> three_odd_numbers([1, 2, 3, 4, 5]) True >>> three_odd_numbers([0, -2, 4, 1, 9, 12, 4, 1, 0]) True >>> three_odd_numbers([5, 2, 1]) False >>> three_odd_numbers([1, 2, 3, 3, 2]) False """ for i in range(0, len(nums)-2): if (nums[i] + nums[i+1] + nums[i+2]) % 2 != 0: return True return False print(F"three_odd_numbers.py: three_odd_numbers([1, 2, 3, 4, 5]) = True = {three_odd_numbers([1, 2, 3, 4, 5])}") print(F"three_odd_numbers.py: three_odd_numbers([0, -2, 4, 1, 9, 12, 4, 1, 0]) = True = {three_odd_numbers([0, -2, 4, 1, 9, 12, 4, 1, 0])}") print(F"three_odd_numbers.py: three_odd_numbers([5, 2, 1]) = False = {three_odd_numbers([5, 2, 1])}") print(F"three_odd_numbers.py: three_odd_numbers([1, 2, 3, 3, 2]) = False = {three_odd_numbers([1, 2, 3, 3, 2])}")
false
b870decfadf16702b26323faf5a50d5f2cd61676
JSidat/python-practice
/automate the boring stuff with python/collections_deque.py
1,476
4.25
4
# Perform append, pop, popleft and appendleft methods on an empty deque ''' # actions used on the deque 6 append 1 append 2 append 3 appendleft 4 pop popleft ''' from collections import deque # import deque function from collections module n = int(input()) # input for the number of actions being carried out on deque d= deque() # create an empty deque for i in range(n): # for each action in range n command = input().split() # input the action being carried out, but seperate the command from the number in a list action = command[0] # the actual action (append, pop, popleft, appendleft) will be the first element of the list if len(command) > 1: # if the list is longer then 1 element, i.e. the list has an action and a number element = command[1] # the number will be at index 1 of the list if action == 'append': # if the action is 'append': d.append(element) # append the number in the list to the deque elif action == 'pop': # if the action is 'pop': d.pop() # this will remove the element to the right of the deque elif action == 'appendleft': # if the action is 'appendleft': d.appendleft(e) # this will append the number specified to the left of the deque elif action == 'popleft': # if the action is 'popleft': d.popleft() # this will remove the element to the left of the deque print(*d) # print the deque with the unpack operator removing all the brackets to give just the numbers
true
fedba2dd26079e1e9787a2cde55680d8069226dd
JSidat/python-practice
/automate the boring stuff with python/company_logo.py
385
4.125
4
from collections import Counter s = sorted(input()) # sorted function converts the string to a list of characters in alphabetical order c = Counter(s).most_common(3) # Counter funcion will count the occurences of each character, most_common will give the top 3 for i, j in c: # for each character and number in list, print(i, j) # print character and number next to each other
true
778e0e8ad438ef0fc2fa27ef4fabd59ed8121ffd
santoshtbhosale/Python-String
/string6.py
349
4.1875
4
""" Write a Python program to count the number of characters (character frequency) in a string. Sample String : google.com' Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1} """ s = 'google.com' d = {} for i in s: key = d.keys() if i in key: d[i] = d[i] + 1 else: d[i] = 1 print(d)
true
bb827be044aa6bdddec5f8e4a58c1ba1fa9badb7
danilsu/1
/Курсовая.Ч2/30.py
802
4.15625
4
# Создать прямоугольную матрицу A, имеющую N строк и M столбцов со # случайными элементами. Добавить к элементам каждого столбца такой # новый элемент, чтобы сумма положительных элементов стала бы равна # модулю суммы отрицательных элементов. Результат оформить в виде # матрицы из N + 1 строк и M столбцов. import numpy as np import random N = random.randint(2, 5) M = random.randint(2, 5) print("N =", str(N), " - ", "M =", str(M)) A = np.random.randint(-50, 50, (N, M)) print(str(A) + "\n") M_n = np.sum(A, axis=0) * (-1) A = np.vstack((A, M_n)) print(A)
false
0807cb34da8e282b520ec9a01f1eebaa75b6f16f
bernblend/Python_Data_Structures
/multiples_three_n_five.py
485
4.1875
4
print "\nProject Euler - Problem 1" print "\nMultiples of 3 and 5\n" print "If we list all the natural numbers below 10" print "that are multiples of 3 or 5, we get 3, 5, 6 and 9." print "The sum of these multiples is 23." print "\nFind the sum of all the multiples of 3 or 5" print "below 1000.\n" def multiples_three_n_five(): sum = 0 for num in range(1000): if num % 3 == 0 or num % 5 == 0: sum += num return sum print multiples_three_n_five()
true
01b5dddc139c981ca065b722b5de69db9dfd5874
Yogessh3/FANG-Challenge
/BubbleSort_Sorting.py
412
4.15625
4
def bubbleSort(array): isSorted=False counter=0 while not isSorted: isSorted=True for i in range(len(array)-1-counter): if(array[i]>array[i+1]): swap(i,i+1,array) isSorted=False counter+=1 return array def swap(i,j,array): array[i],array[j]=array[j],array[i] array=[56,45,12,35,69,1] print(bubbleSort(array))
true
8085245eeacd4ab799416f860310e9cd6f2a6bc6
SoraiaTeixeiraCanelas/livro_python
/ex18.py
617
4.125
4
#esta linha é funciona como os scripts eo argv def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2:{arg2}") #*args nao serve para nada, em vez disso fazemos: def print_two_again(arg1, arg2): #definção de função print_two_again com dois argumentos arg1, arg2 print(f"arg1: {arg1}, arg2: {arg2}") #esta só lega 1 argumento def print_one(arg1): print(f"arg1: {arg1}") #esta não leva argumentos def print_none(): print("I got nothin'.") print_two("Soraia","Teixeira Canelas") print_two_again("Soraia","Teixeira Canelas") print_one("first!") print_none()
false
187ca0e1b717fea28be50c305fedaa9cbc714ee9
caolxw/python_work
/函数式编程/高阶函数/filter.py
619
4.15625
4
#filter用于过滤序列 #参数:函数和序列 #返回:Iterator #用filter求素数 def _odd_iter():#构造从3开始的奇数序列 n = 1 while True: n = n + 2 yield n #定义一个筛选函数 def _not_divisible(n): return lambda x: x % n > 0 #lambda 定义了一个匿名函数 冒号前为参数,冒号后为函数体。可读性不高。 #定义一个生成器,不断返回下一个素数 def primes(): yield 2 it = _odd_iter() while True: n = next(it) yield n it = filter(_not_divisible(n), it) #打印1000以内的素数 for n in primes(): if n < 1000: print(n) else: break
false
e117853ab77fc04aecae33feb875d1a8053e7d12
thekhazal/python
/Ch2/functions_start.py
798
4.375
4
# # Example file for working with functions # # define a basic function def func1(): print("I am a function") return "haci" # function that takes arguments def func2(arg1, arg2): print(arg1, " test ", arg2) # function that returns a value def func3(): return "abok" # function with default value for an argument def power(num,x=1): result = 1 for i in range(x): result = result * num return result #function with variable number of arguments def multiAdd(*args): result = 0 for x in args: result = result + x return result func1() print (func1()) print(func1) a="andra" b="tredje" func2("första",a ) print (func2(a,b)) print (func2) print (power(2)) print (power(2,3)) print (power(x=3, num=2)) print (multiAdd(2,3,4,5,6,7))
true
09c5d79f160efe145a211d035c8e999737cacde3
tarunbhatt8/PythonL15
/2.py
794
4.125
4
''' Q2. Write a python program to in the same interface as above and create a action when the button is click it will display some text. ''' from tkinter import * def display(): hwL2.configure(text='Submitted!!', bg='blue',\ font='Times 20 italic underline') root = Tk() root.title('My App') root.configure(background='blue') hwL1 = Label(root) hwL2 = Label(root) hwL1.configure(text='Hello World!!', bg='blue',\ font='Times 25 bold underline') submitB = Button(root, text='Submit', bg='green',\ activebackground='yellow', \ activeforeground='white',\ command=display) exitB = Button(root, text='exit', width=25, \ command=root.destroy) hwL1.pack() hwL2.pack() submitB.pack() exitB.pack() root.mainloop()
true