blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
2c01174a18eddce5acb9c6af4dbe8d3eada0753a
aly50n/Python-Algoritmos-2019.2
/lista01ex06.py
297
3.8125
4
print("Reajuste de salário do funcionário:") s=float(input("Digite o valor do salário atual do funcionário-> ")) p=float(input("Digite de quantos porcento será o reajuste-> ")) ns=print("O novo salário do funcinoário será de:", (s*p)/100+s) ns print("Obrigado por usar este aplicativo :D")
1f48de20b12bbe2fe102b827524497c2b4b95ecd
Abinesh1991/Numpy-tutorial
/NumpyTutorial3.py
1,795
4.4375
4
""" Indexing and Slicing Assigning to and accessing the elements of an array is similar to other sequential data types of Python, i.e. lists and tuples. We have also many options to indexing, which makes indexing in Numpy very powerful and similar to core Python. Arrays of Ones and of Zeros - Intializing Arrays with 0's and 1's """ import numpy as np F = np.array([1, 1, 2, 3, 5, 8, 13, 21]) # print the first element of F, i.e. the element with the index 0 print(F[0]) # print the last element of F print(F[-1]) B = np.array([[[111, 112], [121, 122]], [[211, 212], [221, 222]], [[311, 312], [321, 322]]]) print(B[0][1][0]) # numpy way of getting data print B[0, 0, 1] tmp = B[1] print(tmp) print(tmp[0]) # slicing for multidimentional # output - [[13 14 15][23 24 25][33 34 35]] A = np.array([ [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35], [41, 42, 43, 44, 45], [51, 52, 53, 54, 55]]) print(A[:3, 2:]) """ Arrays of Ones and of Zeros There are two ways of initializing Arrays with Zeros or Ones. The method ones(t) takes a tuple t with the shape of the array and fills the array accordingly with ones. By default it will be filled with Ones of type float. If you need integer Ones, you have to set the optional parameter dtype to int: """ # intializing an array as 1 E = np.ones((2,3)) print(E) F = np.ones((3,4),dtype=int) print(F) # intializing an array as 0 Z = np.zeros((2,4),dtype=int) print(Z) # There is another interesting way to create an array with Ones or with Zeros, # if it has to have the same shape as another existing array 'a'. # Numpy supplies for this purpose the methods ones_like(a) and zeros_like(a) x = np.array([2,5,18,14,4]) E = np.ones_like(x) print(E) Z = np.zeros_like(x) print(Z)
aada49073f0425411e870a18cbde25178ad23d62
kamalsingh-engg/udemy_courses_python
/3. Basic Operation With Data type/string_slice.py
255
4.34375
4
#string slicing is same as the list slicing #e.g. a = "kamal" a1 = a[0] a2 = a[:3] a3 = a[-1] a4 = a[-2:] print(a1) print(a2) print(a3) print(a4) #example of string slicing with list l = ['kamal',2,4,5,6] l1 = l[0] l2 = l[0][3] print(l1) print(l2)
b2b66debb5b4b1150b7bf205b2de2ed978843b70
Josue23/matplotlib
/aula4.py
1,328
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' https://www.udemy.com/making-graphs-in-python-using-matplotlib-for-beginners/learn/v4/t/lecture/6304432 4. Rotating Axis Ticks, Adding Text and Annotations ''' import matplotlib.pyplot as plt with open("Goals.txt", "r") as f: HomeTeamGoals = [ int(x) for x in f.readline().strip("\n").strip(" ").split(" ")] AwayTeamGoals = [ int(x) for x in f.readline().strip("\n").strip(" ").split(" ")] xVariable = [] ticks = ["Game One", "Game Fifty", "Game 100"] for i in range(len(HomeTeamGoals)): xVariable.append(i) # plt.plot(xVariable, AwayTeamGoals, c = "green") plt.plot(xVariable, AwayTeamGoals, c = "green", ls = "--") # ls, line style # add latek to costumize the label plt.title(r"Our first plot $\frac{1}{2}$") # plt.show() # plt.title("Our second plot") plt.plot(xVariable, HomeTeamGoals, c = "red", ls = ":") plt.xlim(0, 145) plt.ylim(-0.5, 6) # add latek to costumize the label plt.xlabel(r"Game Number$_5$") plt.ylabel(r"Goals Scored") plt.xticks([49],["12/12/12"], rotation = 45) plt.yticks([3],["Three Goals"], rotation = 90) plt.text(50, 4, r"Our$^3$ Custom Text", fontsize = 8, color = "blue", rotation = 45) plt.annotate("Text 2", xy = (130, 1), xytext = (65, 5), arrowprops = dict(facecolor = "red",shrink = 65)) plt.show()
6a17114d29abd640bd672696e665d35cbde28b92
NivaLado/Numerical-Methods
/Laboratory work 3/bisection.py
429
3.765625
4
def f(x): return (1/2)*(25/x+x) iteration = 0 a = 1 b = 4 epsilon = 0.01 while abs(b - a) > epsilon: iteration += 1 c = (a + b) / 2 if (f(a) * f(c) > 0): a = c else: b = c print(str(iteration) + ' ' + str(abs(b-a)) + ' ' + str(c)) print('X: ' + str(c)) print('Число Итераций: ' + str(iteration)) print('Параметр сходимости: ' + str((b - a) / iteration))
bfeb140b2abf25fc5d96b65ab18fd915a031702d
Suresh8353/ATM-Work
/ATM.py
5,528
3.6875
4
amount=500 def ATM(): print("========================================================================") print("\t\t A T M O P E R A T I O N") print("========================================================================") print() print("\t\t\t 1. Deposite ") print("\t\t\t 2. Withdrawal") print("\t\t\t 3. Balence Enqury ") print("\t\t\t 4. Generate Pin ") print("\t\t\t 5. Exit") print() print("======================================================================") ch=input("Enter your choice:") if ch in ('1','2','3','4','5'): if ch=='1': Deposite() if ch=='2': Withdrawal() if ch=='3': BalenceEnqury() if ch=='4': GeneratePin() if ch=='5': Exit() #else: #print("Sorry your choice is wrong please try again:") #ATM() else: print("Sorry String/Special Symbols/negative numbers are not allowed here:") print("------------>Try Again") print(end="\n\n") ATM() def Deposite(): global amount dp=int(input("Enter your ammount for Deposite:")) ac=int(input("Enter your pin code of ATM:")) if ac<1000 or ac>10000: print("\n========================================================================") print("Invalid Pin please try again. ATM Pin code must be 4 Digit:") print("\n========================================================================") Deposite() else: amount=amount+dp print("Deposite Succesfully your Deposite balance is:",dp) print("Total balence is in your account:",amount) print() ATM() def Withdrawal(): global amount wd=int(input("Enter your ammount for Withdrawal:")) ac=int(input("Enter your pin code of ATM:")) if ac<1000 or ac>10000: print("\n=========================================================================") print("Invalid Pin please try again. ATM Pin code must be 4 Digit:") print("\n=========================================================================") Withdrawal() if wd>=amount: print("\n========================================================================") print("Sorry you have not sufficient balence in your account:") print("--------------->Try again") print("\n") print("==========================================================================") Withdrawal() else: amount=amount-wd print("Withdrawal Succesfully your Withdrawal balance is:",wd) print("Total balence is in your account:",amount) ATM() def BalenceEnqury(): global amount ac=int(input("Enter your pin code of ATM:")) if ac<1000 or ac>10000: print("\n=========================================================================") print("Invalid Pin please try again. ATM Pin code must be 4 Digit:") print("\n=========================================================================") BalenceEnqury() else: print("Total balence is in your account:",amount) print() ATM() def GeneratePin(): global amount an=int(input("Enter your Account Number:")) if an<1000000000000000 or an>10000000000000000: print("\n=========================================================================") print("Invalid Account Number please try again. A/C number must be 16 Digit:") print("\n=========================================================================") GeneratePin() ac=int(input("Enter pin code for generate ATM pin :")) if ac<1000 or ac>10000: print("\n========================================================================") print("Invalid Pin please try again. ATM Pin code must be 4 Digit:") print("\n========================================================================") GeneratePin() else: print("===========================================================================") print("Your ATM pin has Successfully generate") Exit() def Exit(): print("===================================================================================") print("Thanku for using ATM machine:") ATM()
5b1c9d1ad36af18dbce6a3055a08e37b4864067d
zzwerling/DailyCodingProblemSolutions
/challenge1.py
294
3.78125
4
# Problem 1 # Given a list of numbers and a number k, return whether any two numbers from the list add up to k. def adds_up(list, k): for i in range(len(list)): for j in range(i+1, len(list)): if list[i] + list[j] == k: return True return False
3c318c562d10bf6108e7b17c94e5b5cf8f7a31d5
duniganc1945/CTI110
/P5T2_FeetToInches_DuniganHogan.py
552
4.25
4
#P5T2 - Feet to Inches #CTI-110 #Ciera DuniganHogan #19 April 2019 # choice = 'yes' while choice.lower() == 'yes' : def main(): #Get input feet = int(input('Enter measurement in feet: ')) #Display conversion conversion (feet) def conversion (feet) : #Calculate feet to inches inches = feet * 12 print(inches, 'inches is equal to', feet , 'feet.') main() choice = input("Do you want to run the program again?" + " Enter yes or no. ")
42e7b0f1caced2a97f9b258f5865a83b4db1e630
jjeong723/Algorithm_Practices_Test
/Codeit_Code/Algorithm/4-1. Test_Level1_pro1.py
572
3.546875
4
def sublist_max(profits): # 코드를 작성하세요. size_num = len(profits) list_range = [] max_num = 0 for num in range(size_num): sum_num = 0 for num2 in range(num, size_num): sum_num += profits[num2] if sum_num > max_num: max_num = sum_num list_range = profits[num:num2+1] return max_num # 테스트 print(sublist_max([4, 3, 8, -2, -5, -3, -5, -3])) print(sublist_max([2, 3, 1, -1, -2, 5, -1, -1])) print(sublist_max([7, -3, 14, -8, -5, 6, 8, -5, -4, 10, -1, 8]))
039dd77719356fd2c12665d2e68de239e9b96140
riddhisahu9/hackerrank
/Python/Strings/Find a string/solution.py
705
4.125
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Script: solution.py # @Author: Pradip Patil # @Contact: @pradip__patil # @Created: 2018-02-17 14:56:02 # @Last Modified By: Pradip Patil # @Last Modified: 2018-02-18 13:51:34 # @Description: https://www.hackerrank.com/challenges/find-a-string/problem def count_substring(string, sub_string): start, count = 0, 0 n = string.find(sub_string) while n >= 0: count += 1 start += n+1 n = string[start:].find(sub_string) if n == -1: break return count if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
561966c5f877f78fe6ab28e4e8207f668aaf9eec
anamariagds/primeiroscodigos
/repetições/forteste2.py
523
3.671875
4
def eh_par(n): return n%2 ==0 def pares(inicio, quantidade): if eh_par(inicio): inicio += 2 else: inicio += 1 numeros_pares ='' for n in range(inicio, inicio+(quantidade*2), 2): numeros_pares += str (n) + ' ' return numeros_pares.strip() def main(): inicio = int(input("Inicio do intervalo: ")) qtd = int(input("Quantidade de números: ")) print(f'{qtd} pares após {inicio}: ') print(pares(inicio, qtd)) if __name__=='__main__': main()
269d4b1df449320656cfe6ea653537896729b198
yuchien302/LeetCode
/leetcode146.py
804
3.5
4
from collections import OrderedDict class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.dict = OrderedDict() self.cap = capacity def get(self, key): """ :rtype: int """ if key in self.dict: value = self.dict[key] del self.dict[key] self.dict[key] = value return self.dict[key] return -1 def set(self, key, value): """ :type key: int :type value: int :rtype: nothing """ if key in self.dict: del self.dict[key] self.dict[key] = value if len(self.dict) > self.cap: self.dict.popitem(last=False)
c0aff8e5e706b784f7ad3411323331bacb6c6114
shreyrai99/CP-DSA-Questions
/LeetCode/LinkedList Palindrome/ll palindrome.py
462
3.515625
4
class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ curr = head # This is the key to O(1) space. stringified_list = "" while (curr): stringified_list += str(curr.val) curr = curr.next # Compares string with reversed string to see if they are the same string return stringified_list == stringified_list[::-1]
2827c8423400bfe3d5c7992fd80d1a8d321dbd9f
pmmorris3/Code-Wars-Solutions
/5-kyu/valid-parentheses/python/solution.py
471
4.25
4
def valid_parentheses(string): bool = False open = 0 if len(string) == 0: return True for x in string: if x == "(": if bool == False and open == 0: bool = True open += 1 if x == ")" and bool == True: if open - 1 == 0: bool = False open -= 1 elif x == ")" and (bool == False or open == 0): return False return open == 0
8ee8e96d7bdbbf7d3f182c73eddc93877fc4323e
WckdAwe/SortViz
/SortViz/pysort.py
15,659
3.75
4
from random import shuffle from time import sleep from .display import * import threading x = 0 def bubble_sort(a_list, fig): ''' Performance: Best O(?) || Average O(n^2) || Worse O(n^2) :param a_list: :param fig: :return: ''' for i in range(1, len(a_list)): for j in range(1, len(a_list)): if a_list[j - 1] > a_list[j]: (a_list[j], a_list[j - 1]) = (a_list[j - 1], a_list[j]) x = display(a_list, fig) if x == -1: x = 0 return a_list return a_list # Insertion Sort def insertion_sort(a_list, fig): for i in range(1, len(a_list)): while i > 0 and a_list[i - 1] > a_list[i]: (a_list[i], a_list[i - 1]) = (a_list[i - 1], a_list[i]) i -= 1 x = display(a_list, fig) if x == -1: x = 0 return a_list return a_list # Selection Sort def selection_sort(a_list, fig): for i in range(len(a_list)): min_pos = i for j in range(i + 1, len(a_list)): if a_list[j] < a_list[min_pos]: min_pos = j (a_list[min_pos], a_list[i]) = (a_list[i], a_list[min_pos]) x = display(a_list, fig) if x == -1: x = 0 return a_list return a_list # Quick Sort def quick_sort_exec(some_list, start, stop, fig): if stop - start < 1: return some_list else: pivot = some_list[start] left = start right = stop while left <= right: while some_list[left] < pivot: left += 1 while some_list[right] > pivot: right -= 1 if left <= right: some_list[left], some_list[right] = some_list[right], some_list[left] print("Swapping", some_list[left], "with", some_list[right]) left += 1 right -= 1 display(some_list, fig) quick_sort_exec(some_list, start, right, fig) quick_sort_exec(some_list, left, stop, fig) def quicksort(a_list, fig): low = 0 high = len(a_list) - 1 a_list = quick_sort_exec(a_list, low, high, fig) return a_list # counting sort def counting_sort(a_list, fig): # we need three more lists: # index, count, output temp = a_list.copy() # index has a length equal to the maximum element index = [i for i in range(max(a_list) + 1)] # count has length equal to the index count = [0 for i in range(len(index))] # now we must count the elements for i in range(len(a_list)): count[a_list[i]] += 1 for i in range(1, len(count)): count[i] += count[i -1] for i in range(len(temp)): locate = index.index(temp[i]) print(count) count[locate] -= 1 print(count) a_list[count[locate]] = temp[i] x = display(a_list, fig) if x == -1: return a_list return a_list # Merge Sort def merge_sort(a_list, fig): if len(a_list) > 1: mid = len(a_list) // 2 lefthalf = a_list[:mid] righthalf = a_list[mid:] merge_sort(lefthalf, fig) merge_sort(righthalf, fig) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: a_list[k] = lefthalf[i] i += 1 else: a_list[k] = righthalf[j] j += 1 k += 1 while i < len(lefthalf): a_list[k] = lefthalf[i] i += 1 k += 1 display(a_list, fig) while j < len(righthalf): a_list[k] = righthalf[j] j += 1 k += 1 display(a_list, fig) display(a_list, fig) return a_list # Bogosort def inorder(a_list): i = 0 j = len(a_list) while i + 1 < j: if a_list[i] > a_list[i + 1]: return False i += 1 return True def bogosort(a_list, fig): while not inorder(a_list): shuffle(a_list) x = display(a_list, fig) if x == -1: x = 0 return a_list return a_list # Comb Sort def comb_sort(a_list, fig): gap = len(a_list) swaps = True while gap > 1 or swaps: gap = len(a_list) swaps = True while gap > 1 or swaps: gap = max(1, int(gap / 1.25)) swaps = False for i in range(len(a_list) - gap): j = i + gap if a_list[i] > a_list[j]: (a_list[i], a_list[j]) = (a_list[j], a_list[i]) display(a_list, fig) swaps = True return a_list # Bitonic Sort def isPowerOf2(num): if num == 0: return False while num != 1: if num % 2 != 0: return False num = num // 2 return True def reform(a_list): while isPowerOf2(len(a_list)) != True: a_list.append(0) return a_list def restore(a_list): while 0 in a_list: a_list.remove(0) def compAndSwap( a_list, i, j, direction, ): if direction == 1 and a_list[i] > a_list[j] or direction == 0 \ and a_list[j] > a_list[i]: (a_list[i], a_list[j]) = (a_list[j], a_list[i]) def bitonicMerge(a_list, low, center, direction, fig): if center > 1: k = center // 2 for i in range(low, low + k): compAndSwap(a_list, i, i + k, direction) display(a_list, fig) display(a_list, fig) bitonicMerge(a_list, low, k, direction, fig) bitonicMerge(a_list, low + k, k, direction, fig) def bitonicSort( a_list, low, center, direction, fig ): if center > 1: k = center // 2 bitonicSort(a_list, low, k, 1, fig) bitonicSort(a_list, low + k, k, 0, fig) bitonicMerge(a_list, low, center, direction, fig) return a_list def bitonic_sort(a_list, fig): up = 1 a_list = bitonicSort(reform(a_list), 0, len(a_list), up, fig) return a_list # Stooge Sort def stooge_sort_run(a_list, low, high, fig): if low >= high: return a_list if a_list[low] > a_list[high]: (a_list[low], a_list[high]) = (a_list[high], a_list[low]) display(a_list, fig) if high - low > 1: t = (high - low + 1) // 3 stooge_sort_run(a_list, low, high - t, fig) stooge_sort_run(a_list, low + t, high, fig) stooge_sort_run(a_list, low, high - t, fig) return a_list def stooge_sort(a_list, fig): low = 0 high = len(a_list) - 1 a_list = stooge_sort_run(a_list, low, high, fig) return a_list # Radix Sort def rcounting_sort(a_list, max_value, get_index): counts = [0] * max_value for a in a_list: counts[get_index(a)] += 1 for (i, c) in enumerate(counts): if i == 0: continue else: counts[i] += counts[i - 1] for (i, c) in enumerate(counts[:-1]): if i == 0: counts[i] = 0 counts[i + 1] = c ret = [None] * len(a_list) for a in a_list: index = counts[get_index(a)] ret[index] = a counts[get_index(a)] += 1 # display(a_list) return a_list def get_digit(n, d): for i in range(d - 1): n //= 10 return n % 10 def get_num_digit(n): i = 0 while n > 0: n //= 10 i += 1 return i def check_digits(a_list): cnt = 0 for i in range(len(a_list)): if a_list[i] % 10 == a_list[i]: cnt += 1 else: cnt = 0 if cnt == len(a_list): return True else: return False def radix_sort(a_list, fig): flag = check_digits(a_list) if flag: a_list.append(10) max_value = max(a_list) num_digits = get_num_digit(max_value) for d in range(num_digits): a_list = rcounting_sort(a_list, max_value, lambda a: \ get_digit(a, d + 1)) # display(a_list) if flag: a_list.remove(10) return a_list # Tim Sort def TimInsertionSort(a_list, left, right, fig): for i in range(left + 1, right): temp = a_list[i] j = i - 1 while a_list[j] > temp and j >= left: a_list[j + 1] = a_list[j] display(a_list, fig) j -= 1 a_list[j + 1] = temp def merge( a_list, l, m, r, fig ): len1 = m - l + 1 le2 = r - m left = [0] * len1 right = [0] * len2 for i in range(len1): left[i] = a_list[l + i] for i in range(len2): right[i] = a_list[m + 1 + i] i = 0 j = 0 k = 0 while i < len1 and j < len2: if left[i] <= right[j]: a_list[k] = left[i] i += 1 else: a_list[k] = right[j] j += 1 k += 1 display(a_list, fig) while i < len1: a_list[k] = left[i] k += 1 i += 1 display(a_list, fig) while j < len2: a_list[k] = right[j] k += 1 j += 1 display(a_list, fig) def min(a, b): if a < b: return a else: return b def timsort_run(a_list, n, fig): run = 32 for i in range(0, n, run): TimInsertionSort(a_list, i, min(i + 31, n - 1), fig) size = run left = 0 while size < n: while left < n: mid = left + size - 1 right = min(left + 2 * size - 1, n - 1) merge(a_list, left, mid, right, fig) left += 2 * size size *= 2 def timsort(a_list, fig): size = len(a_list) + 1 timsort_run(a_list, size, fig) return a_list # Binary Insertion Sort def binarySearch( a_list, val, start, end, ): if start == end: if a_list[start] > val: return start else: return start + 1 if start > end: return start mid = (start + end) // 2 if a_list[mid] > val: return binarySearch(a_list, val, start, mid - 1) elif a_list[mid] < val: return binarySearch(a_list, val, mid + 1, end) else: return mid def binary_insertion_sort(a_list, fig): for i in range(1, len(a_list)): val = a_list[i] j = binarySearch(a_list, val, 0, i - 1) a_list = a_list[:j] + [val] + a_list[j:i] + a_list[i + 1:] display(a_list, fig) return a_list # Bucket Sort def numberOfDigits(num): mdiv = num // 10 mmod = mdiv % 10 i = 1 while mdiv != 0: mdiv = mdiv // 10 mmod = mdiv % 10 i += 1 return i def bucket_sort(a_list, fig): buckets = [] for i in range(10): buckets.append([]) for i in range(len(a_list)): h = numberOfDigits(a_list[i]) buckets[h].append(a_list[i]) #display(buckets) for i in range(10): buckets[i] = insertion_sort(buckets[i], fig) #display(buckets) j = 0 for i in range(10): while buckets[i]: a_list[j] = buckets[i].pop(0) display(a_list, fig) j += 1 return a_list # Shell Sort def gapInsertionSort(a_list, start, gap, fig): for i in range(start + gap, len(a_list), gap): currentValue = a_list[i] position = i while position >= gap and a_list[position - gap] > currentValue: a_list[position] = a_list[position - gap] display(a_list, fig) position = position - gap a_list[position] = currentValue def shell_sort(a_list, fig): sublistcount = len(a_list) // 2 while sublistcount > 0: for startposition in range(sublistcount): gapInsertionSort(a_list, startposition, sublistcount, fig) sublistcount = sublistcount // 2 return a_list # Cocktail Sort def cocktail_sort(a_list, fig): swapped = False end = 0 for k in range(len(a_list) - 1, end, -1): for i in range(k, 0, -1): if a_list[i] < a_list[i - 1]: (a_list[i], a_list[i - 1]) = (a_list[i - 1], a_list[i]) x = display(a_list, fig) if x == -1: x = 0 return a_list swapped = True for i in range(k): if a_list[i] > a_list[i + 1]: (a_list[i], a_list[i + 1]) = (a_list[i + 1], a_list[i]) x = display(a_list, fig) if x == -1: x = 0 return a_list swapped = True end = end + 1 if not swapped: return return a_list # Heap Sort def heapify(a_list, count, fig): start = int((count - 2) / 2) while start >= 0: sift_down(a_list, start, count - 1, fig) start -= 1 def sift_down(a_list, start, end, fig): root = start while root * 2 + 1 <= end: child = root * 2 + 1 swap = root if a_list[swap] < a_list[child]: swap = child if child + 1 <= end and a_list[swap] < a_list[child + 1]: swap = child + 1 if swap != root: (a_list[root], a_list[swap]) = (a_list[swap], a_list[root]) display(a_list, fig) root = swap else: return def heap_sort(a_list, fig): heapify(a_list, len(a_list), fig) end = len(a_list) - 1 while end > 0: (a_list[end], a_list[0]) = (a_list[0], a_list[end]) display(a_list, fig) end -= 1 sift_down(a_list, 0, end, fig) return a_list # Gnome Sort def gnome_sort(a_list, fig): i = 0 while i < len(a_list): if i == 0 or a_list[i - 1] <= a_list[i]: i += 1 else: (a_list[i], a_list[i - 1]) = (a_list[i - 1], a_list[i]) x = display(a_list, fig) if x == -1: return a_list i -= 1 return a_list # Sleep Sort def sleep_sort(a_list, fig): def sleepSort(i): sleep(i) a_list.append(i) threads = [] for j in range(len(a_list)): t = threading.Thread(target=sleepSort, args=(a_list.pop(0), )) threads.append(t) t.start() display(a_list, fig) for i in range(len(threads)): display(a_list, fig) threads[i].join() return a_list # Pancake Sort def pancake_sort(a_list, fig): if len(a_list) <= 1: return a_list for size in range(len(a_list), 1, -1): maxindex = max(range(size), key=a_list.__getitem__) if maxindex + 1 != 0: a_list[:maxindex + 1] = reversed(a_list[:maxindex + 1]) display(a_list, fig) a_list[:size] = reversed(a_list[:size]) display(a_list, fig) return a_list # Cycle Sort def cycle_sort(a_list, fig): writes = 0 for (cstart, item) in enumerate(a_list): pos = cstart for item2 in a_list[cstart + 1:]: if item2 < item: pos += 1 if pos == cstart: continue while item == a_list[pos]: pos += 1 (a_list[pos], item) = (item, a_list[pos]) display(a_list, fig) writes += 1 while pos != cstart: pos = cstart for item2 in a_list[cstart + 1:]: if item2 < item: pos += 1 while item == a_list[pos]: pos += 1 (a_list[pos], item) = (item, a_list[pos]) display(a_list, fig) writes += 1 return a_list
71d495e8529cc05b26af0dc346e120271071780f
galkampel/Link_prediction
/link_prediction/cracking_the_code.py
738
3.71875
4
def get_all_paren(n_open,n_close,tmp_s,all_paren = []): if n_open == n_close and n_open == 0: all_paren.append(tmp_s) return all_paren elif n_open == n_close: return get_all_paren(n_open-1,n_close,tmp_s+'(',all_paren ) elif n_open == 0: tmp_s += n_close * ')' all_paren.append(tmp_s) return all_paren elif n_open < n_close: get_all_paren(n_open,n_close-1,tmp_s+')',all_paren) get_all_paren(n_open -1, n_close ,tmp_s+'(',all_paren) return all_paren def all_parens(n): n_open,n_close = n,n return get_all_paren(n_open,n_close,'') def main(): print(all_parens(3)) if __name__ == '__main__': main()
4af24bbfdd17facea513e2d2058613c50c281baf
ellisp97/pythonHR
/bubblesort.py
1,174
3.765625
4
#!/bin/python3 import math import os import random import re import sys """attempt 1 not actually bubble sort """ # def countSwaps(a): # count = 0 # for i in range(len(a)): # if not (a[i] == i+1): # for j in range(i+1,len(a)+1): # if a[j] == i+1: # # print(a) # a[i],a[j] = a[j],a[i] # count+=1 # break # return a,count # pass # {4,2,3,1} # for i ,[0,1,2,3] # for j,[0,1,2] # a[0] =4 > a[1] =2 , count = 1, {2,4,3,1} # a[1] = 4>a[2] = 3, count = 2, {2,3,4,1} # {2,3,1,4} def countSwaps(a): count=0 for i in range(len(a)): for j in range(len(a)-1): if (a[j]>a[j+1]): count+=1 a[j],a[j+1]=a[j+1],a[j] return a,count if __name__ == '__main__': n = int(input()) arr = list(map(int,input().split())) newArr,count = countSwaps(arr) print("Array: {}".format(newArr)) print("Array is sorted in {} swaps.".format(count)) print("First Element: {}".format(newArr[0])) print("Last Element: {}".format(newArr[len(newArr)-1])) # {4,5,1,3,2} # {4,5,1,3,2}
073c1d22430e65a9780a876318bb1dcc600c5b0e
NikaEgorova/goiteens-python3-egorova
/homeworks/hw3/num1.2.py
455
3.578125
4
George_Washington = 2 Thomas_Jefferson = 2 Herbert_Hoover = 1 Barack_Obama = 2 coef = 4 for a in range(1, 3): if a % 2 == 1: print("Herbert Hoover був президентом", a * coef, "роки") if a % 2 == 0: print("George Washington був президентом", a * coef, "років", "\n" "Thomas Jefferson був президентом", a * coef, "років", "\n" "Barack Obama був президентом", a * coef, "років")
fc0e1b7c9aa823f3dba6f8d99b8086d93f31b986
Hasib104/Learning-Python
/Day012/Guess the number.py
1,622
4.0625
4
import random print("Welcome to Guess the number.") print("I am thinking of a number between 1 and 100.") numbers=[] for counter in range(0,101): numbers.append(counter) #print(numbers) def select_number(): chosen_number = random.choice(numbers) return chosen_number lives_easy = 10 lives_hard = 5 chosen_difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") def difficulty_chose(difficulty): if difficulty == "easy": return lives_easy elif difficulty == "hard": return lives_hard else: return 0 def guess_number(): total_lives = difficulty_chose(chosen_difficulty) print(f"You have {total_lives} attempts to guess the number.") end_state = False chosen_number = select_number() print(chosen_number) while not end_state: for lives in range(0, total_lives): guess_number = int(input("Make a guess: ")) if guess_number == chosen_number: end_state = True print("You have guessed the number.") return elif guess_number > chosen_number: total_lives -= 1 print("Too High") print(f"Lives remaining {total_lives}") elif guess_number < chosen_number: total_lives -= 1 print("Too Low") print(f"Lives remaining {total_lives}") if total_lives == 0: end_state = True print("You have ran out of lives") return guess_number()
5645a88eaaec98ce289fe3f6c5d05a1161f2e7b9
prakash-simhandri/Jessie_artificial_intelligence-
/Jessie/Jessie_AI.py
9,115
3.59375
4
import datetime,time import speech_recognition as sr # sudo pip3 install SpeechRecognition % sudo pip3 install SpeechRecognition OR sudo apt-get install python-pyaudio python3-pyaudio import wikipedia,random # sudo pip3 install wikipedia import webbrowser,os,wolframalpha # sudo pip3 install wolframalpha from playsound import playsound # sudo pip3 install playsound from gtts import gTTS client = wolframalpha.Client('') # you Fill up the your wolfromAlpha Id . def speech(Text): tts = gTTS(text=audio, lang='en') tts.save("jessie.mp3") playsound("jessie.mp3") def speak(audio): tts = gTTS(text=audio, lang='en') tts.save("jessie.mp3") playsound("jessie.mp3") def greetMe(hour): if hour >= 0 and hour <=12: speak("Good Morning Sir!") elif hour >= 12 and hour < 18: speak("Good Afternoon Sir!") else: speak('Good Evneing Sir!') speak('I am,Jessie') time.sleep(1) def user_command(): mic = sr.Recognizer() with sr.Microphone() as source: mic.adjust_for_ambient_noise(source)# listen for 1 second to calibrate the energy threshold for ambient noise levels print('Speak Anytgibg :) ') audio = mic.listen(source) # recognize speech using Google Speech Recognition try: text = mic.recognize_google(audio,language="en-in") print("Ok Sir , please wait") print("You said : {}".format(text)) except: print("Sorry could not recognize your voice") return "Nothing" return text if __name__ == "__main__": greetMe(int(datetime.datetime.now().hour)) user_name = "Sir" while True: speak('Please tell me! How can i help you') query = user_command().lower() # Work on what the user asked. if 'wikipedia' in query: try: speak("Searching Wikipedia....") query = query.replace("wikipedia","") W_details = wikipedia.summary(query, sentences=2) speak("According to wikipedia") print(W_details) speech(W_details) time.sleep(5) except Exception as err: print('error: '+str(err)) speech('error '+str(err)) time.sleep(3) elif 'open youtube' in query: speak("ok "+user_name) webbrowser.open('https://www.youtube.com/') speak('please wait') time.sleep(5) elif 'open zoho' in query: speak("ok "+user_name) webbrowser.open('https://cliq.zoho.com/index.do') speak('please wait') time.sleep(6) elif 'open toggl' in query: speak("ok "+user_name) webbrowser.open('https://toggl.com/') speak('please wait') time.sleep(5) elif 'open saral' in query: speak("ok "+user_name) webbrowser.open('http://saral.navgurukul.org/home') speak('please wait') time.sleep(5) elif 'open saavn' in query: speak("ok "+user_name) webbrowser.open('https://www.jiosaavn.com') speak('please wait') time.sleep(5) elif 'open google' in query: speak("ok "+user_name) webbrowser.open('https://www.google.com/') speak('please wait') time.sleep(5) elif 'open facebook' in query: speak('Ok '+user_name) webbrowser.open('https://www.facebook.com/') speak('please wait') time.sleep(5) elif 'play the music' in query or 'play the song' in query: try: music_data = '/home/pandu/Music/Englesh_songs' songs = os.listdir(music_data) one_song = random.choice(songs) speak('Ok %s! Enjoy the Music'%(user_name)) print('The song is running.') playsound("/home/pandu/Music/Englesh_songs/"+one_song) except Exception as err: print('error: '+str(err)) speech('error '+str(err)) time.sleep(3) elif 'hindi music list' in query or 'hindi songs list' in query: speak('ok %s. Choose the number! of your song'%(user_name)) All_songs = "/home/pandu/Music/hindi" songs_list = os.listdir(All_songs) conting = 1 for M_list in songs_list: print(str(conting)+'} '+M_list,"\n") conting+=1 time.sleep(2) speak('How much time will you choose the song') user_time_minten = user_command().lower() user_time_minten = user_time_minten.replace("in","") user_time_minten = user_time_minten.replace('mute',"") user_time_minten = user_time_minten.replace("minute","") timeing = user_time_minten.split() print(timeing) try: meinten=int(timeing[0]) speak("Ok,{}! I am waiting {} minutes".format(user_name,meinten)) time.sleep(60*meinten) speak('please tell me song number') user_music_choes = user_command().lower() except Exception as err: print('error: '+str(err)) speech('error '+str(err)) time.sleep(3) try: one_song = songs_list[int(user_music_choes)-1] speak('Ok %s! Enjoy the Music'%(user_name)) print('The song is running.') playsound('/home/pandu/Music/hindi/'+one_song) except Exception as err: print("error: "+str(err)) speech("error "+str(err)) time.sleep(3) elif 'the time' in query: Time = datetime.datetime.now().strftime("%H! Hour %M! Minute %S! Seconds "+user_name) speak(Time) time.sleep(3) elif 'weather' in query: try: query = query.replace("tell me","") query = query.replace('weather','') speak('Ok,%s! please wait'%(user_name)) user_Aask = ('weather forecast in '+query+', india') res = client.query(user_Aask) output = next(res.results).text print(output) time.sleep(4) except Exception as err: print("error: "+str(err)) speech("error "+str(err)) time.sleep(3) elif "who made you" in query or "created you" in query: speak("I have been created by prakash simhandri.") elif 'what are you doing' in query: Jessie_answer=['Just! remembering you.','i am waiting for you. ', 'i am doing,some work.','Nothing', 'i am talking with you. ','I am thinking something new.', 'i am,wondering with my,friend.','I am trying, to learn, something new.'] speak(random.choice(Jessie_answer)) time.sleep(3) elif 'i love you' in query: speak(random.choice(['I love you to!'+user_name+'.',"i am sorry! i have boyfriend."])) elif 'please wait some time' in query: speak('How many! take the,time %s.'%(user_name)) time_minten = user_command().lower() time_minten = time_minten.replace("in","") time_minten = time_minten.replace('mute',"") time_minten = time_minten.replace("minute","") timeing = time_minten.split() print(timeing) try: meinten=int(timeing[0]) speak("Ok,{} I am waiting {} minutes".format(user_name,meinten)) time.sleep(60*meinten) except Exception as err: print('error: '+str(err)) speech('error '+str(err)) time.sleep(3) elif 'hello madame' in query or 'hello' in query: speak('yes Sir') speak('How canI, hellp you') elif 'who are you' in query or 'what is your name' in query: speak('i am jessie what, is a your name') user_Name = user_command().lower() user_Name = user_Name.replace("my name is","") user_name = user_Name.replace('i am','') speak('OK,%s'%(user_name)) else: if 'quit' in query: speak('nice to meet you %s!'%(user_name)) time.sleep(1) speak('good bye and Thank you') break elif 'nothing' in query: speak('Sorry %s! I could not hear your voice'%(user_name)) time.sleep(2) else: speak(random.choice(['Sorry: These word, are not in my Data,base.','Sorry '+user_name+'! i am not understand, What are you saying.'])) time.sleep(2)
d2606f0d965b8353a6cf5046c313f0806e347142
CodecoolGlobal/lol_erp
/sales/sales.py
5,343
3.8125
4
""" Sales module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * title (string): Title of the game sold * price (number): The actual sale price in USD * month (number): Month of the sale * day (number): Day of the sale * year (number): Year of the sale """ # importing everything you need import os # User interface module import ui # data manager module import data_manager # common module import common def start_module(): """ Starts this module and displays its menu. User can access default special features from here. User can go back to main menu from here. Returns: None """ table = data_manager.get_table_from_file("sales/sales.csv") answer = common.sales_sub_menu() if answer == "0": show_table(table) elif answer == "1": add(table) elif answer == "2": id_ = common.id_table() remove(table, id_) elif answer == "3": id_ = common.id_table() update(table, id_) elif answer == "4": get_lowest_price_item_id(table) elif answer == "5": get_items_sold_between(table, month_from, day_from, year_from, month_to, day_to, year_to) def show_table(table): """ Display a table Args: table: list of lists to be displayed. Returns: None """ common.print_only_table(table) def add(table): """ Asks user for input and adds it into the table. Args: table: table to add new record to Returns: Table with a new record """ new_record = [] sales_records = ["title: ", "price" , "month: ", "day: ","year"] id = common.generate() new_record.append(id) i = 1 title = input(sales_records[0]) new_record.append(title) while i < len(sales_records): integer_inputs = input(sales_records[i]) if integer_inputs.isdigit(): new_record.append(integer_inputs) i += 1 else: print("error!") print(new_record) updated_table = table + [new_record] data_manager.write_table_to_file(file_name="sales/sales.csv", table=updated_table) return updated_table #adding_table = common.add_table() #table.append(adding_table) #return table def remove(table, id_): """ Remove a record with a given id from the table. Args: table: table to remove a record from id_ (str): id of a record to be removed Returns: Table without specified record. """ new_table = [entry for entry in table if entry[0] != id_] # print("frm remove() -> {}".format(new_table)) data_manager.write_table_to_file(file_name="sales/sales.csv", table=new_table) #for i in table: # if id_ in i[0]: # table.remove(i) # ui.print_result() #if id_ != i[0]: # ui.print_error_message('ID not found!') #return table # table.remove(table[id_]) #return table def update(table, id_): """ Updates specified record in the table. Ask users for new data. Args: table: list in which record should be updated id_ (str): id of a record to update Returns: table with updated record """ for i in table: if id_ == i[0]: update_table = ["Title", "Price", "Month", "Day", "Year"] ui.print_menu("What do you want to change?", update_table, "Back to store menu") inputs = ui.get_inputs(["Please enter a number: "], "") option = inputs[0] if option == "0": break updating = ui.get_inputs([update_table[int(option) - 1] + ": "], "") if option == "1": i[1] = updating[0] elif option == "2": i[2] = updating[0] elif option == "3": i[3] = updating[0] elif option == "4": i[4] = updating[0] elif option == "5": i[5] = updating[0] #ui.printresult('Transaction succesfully updated!', '') if id != i[0]: ui.print_error_message("ID do not exist") data_manager.write_table_to_file(file_name="./sales/sales.csv", table=table) return table # special functions: # ------------------ def get_lowest_price_item_id(table): """ Question: What is the id of the item that was sold for the lowest price? if there are more than one item at the lowest price, return the last item by alphabetical order of the title Args: table (list): data table to work on Returns: string: id """ # your code def get_items_sold_between(table, month_from, day_from, year_from, month_to, day_to, year_to): """ Question: Which items are sold between two given dates? (from_date < sale_date < to_date) Args: table (list): data table to work on month_from (int) day_from (int) year_from (int) month_to (int) day_to (int) year_to (int) Returns: list: list of lists (the filtered table) """ # your code
e68c4609833c0e11e448a1b338dd38eb3f5a1e37
luojxxx/Coding-Practice
/hackerrank/interview_prep/comparator_sorting.py
581
3.640625
4
# https://www.hackerrank.com/challenges/ctci-comparator-sorting from functools import cmp_to_key class Player: def __init__(self, name, score): self.name = name self.score = score def __repr__(self): return self.name + ' ' + self.score def comparator(a, b): if a.score != b.score: return b.score - a.score else: if a.name == b.name: return 0 if [a.name, b.name] == sorted([a.name, b.name]): return -1 else: return 1
33f070247da3e66d9830e062bdf2488e45137400
GreatGodApollo/bashbot
/cogs/random.py
1,018
3.546875
4
import discord from discord.ext import commands import random class Random: """Random Cog""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def roll(self, ctx, sides: int = 6): """Roll a die""" if sides >= 2: await self.bot.say(f"You rolled a {sides} sided die.\n> {random.randint(1, sides)}") elif sides == 1: await self.bot.say("Why would you want to roll a 1 sided die?") else: await self.bot.say(f"A number of sides greater than 2 must be specified. You sent:\n>{sides}") @commands.command(pass_context=True) async def choose(self, ctx, *choices): """Get a random choice""" if len(choices) >= 2: choice = choices[random.randint(0, len(choices) - 1)] await self.bot.say(f"I choose\n> {choice}") else: await self.bot.say(":x: At least 2 options must be provided :x:") def setup(bot): bot.add_cog(Random(bot))
48886ec0a33211daa61803553b77b66a50640354
djmar33/python_work
/ex/ex4/ex4.3.3.py
222
3.765625
4
#4.3.3列表统计 digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] #列表中最小的数 print(min(digits)) #列表中最大的数 print(max(digits)) #列表中所有数之和 print(sum(digits)) #列表长度 print(len(digits))
e8bb4ae0457880e7025a93fbccc241b2c23179c2
Jamibaraki/adventOfCode2017
/day13b.py
3,450
3.75
4
#Advent of Code '17 #Day 13a: Packet Scanners #This runs slowly with proper data! #Quicker to optimise than run again #Check 13b2.py for optimized version import platform print ( platform.python_implementation() ) import re #read input file = open('input13.txt','r') input = file.read().split('\n') file.close() #get list of scanners from input #each scanner is array with four values - position, size, current position and direction #direction = 1 for moving down. -1 for moving up scanners = [] furthestScanner = 0 for line in input: line = line.split(' ') #print( str( line[1] ) ) line[0] = re.sub("[^0-9]","",line[0]) scanners.append( [ int(line[0]) ,int( line[1] ),0, 1 ] ) #keep track of the furthest scanner if int(line[0]) > furthestScanner: furthestScanner = int(line[0]) #print( str(scanners) ) #print("furthest scanner " + str(furthestScanner) ) def incPositions(): for scanner in scanners: if scanner[3] == 1: scanner[2] += 1 if scanner[2] >= scanner[1]: scanner[2] -= 2 scanner[3] = -1 elif scanner[3] == -1: scanner[2] -= 1 if scanner[2] < 0: scanner[2] = 1 scanner[3] = 1 #for x in range( 0,5 ): # #print( str(scanners) ) # incPositions() #move through and detect where we are caught #should be 0 and 6 for test #determing largest #def checkSeverity( delay, display ): def checkCaught( delay ): severity = 0 #resetPositions for scanner in scanners: scanner[2] = 0 scanner[3] = 1 #do delay if delay > 0: while delay > 0: incPositions() delay -= 1 #x represents position of moving user in main loup for x in range( 0, furthestScanner+1 ): for y in range( 0, len(scanners) ): if scanners[y][0] == x: #print("hit " + str(x) + " " + str( scanners[y][2] ) ) if scanners[y][2] == 0: #print("scanner caught us. Position: " + str(x) ) return True #if display: # print( str(scanners) + " " + str(x) ) incPositions() #print( "severity: " + str(severity) ) return False # result > following so may as well start from here attempt = 53000 counter = 0 #result = checkSeverity( attempt, False ) result = checkCaught( attempt ) if result == True: while result != False and attempt < 125000: if counter == 1000: print ( "thousand ticks" + str( attempt ) ) counter = 0 counter += 1 attempt += 1 #result = checkSeverity( attempt, False ) result = checkCaught( attempt ) print( str( attempt ) ) #checkSeverity( attempt, True ) #print( "Severity: " + str(severity) )
53fa6c2a34d0dce377597de737455c86dfd0c39e
JulietaCaro/python
/Condicional/ejercicio 6 condicional.py
504
3.828125
4
paginas = int(input("Ingrese la cantidad de paginas: ")) if paginas<300: costo1 = 125 + (paginas*2.20) print("El costo es de ", costo1) else: if paginas>300 and paginas<600: #costo2 = 125 + (paginas * 80) costo2 =int( 125 + 80 + (paginas * 2.20)) print("El costo es de ", costo2) else: if paginas>600: #costo3 = 125 + paginas * 136 costo3 = int(125 + 136 + (paginas * 2.20)) print("El costo es de ", costo3)
4664cf1295e072383d367bedd29c468708deaa8f
maxfeldman14/tools
/permuter.py
819
4
4
#!/usr/bin/env python import sys import enchant import itertools def permute(string, numchars): words = {} count = 0 d = enchant.Dict("en_US") #l = list(string) perms = itertools.permutations(string, int(numchars)) #now have a spellchecker and all permutations #keep only words which are valid and <= numchars and not seen before while True: try: word = perms.next() wd = "".join(word) #convert list to word if len(wd) <= numchars and d.check(wd) and wd not in words: print wd count += 1 words[wd] = 1 except StopIteration: break print count, " possible words" def main(): if not len(sys.argv) == 3: print "usage: ./permuter.py <charstring> <numchars>" return permute(sys.argv[1], sys.argv[2]) if __name__ == "__main__": main()
86fe6020084d15e3141f292ee06f8ff66119b937
whysuman/Hacktoberfest_2020
/Problems/sumanthra problem3.py
334
4.03125
4
a = int(input("Please enter your number a: ")) b = int(input("Please enter your number b: ")) c = int(input("Please enter your number c: ")) if (a**2) == (b**2) + (c**2) : print(f'{a},{b},{c}') elif (b**2) == (a**2) + (c**2): print(f'{b},{a},{c}') elif (c**2) == (a**2) + (b**2) : print(f'{c},{a},{b}')
f3a37f9049674f0c94205583ba34a09af8859511
romebell/python_classes
/inheritance.py
2,648
3.984375
4
# Inheritance class Phone: def __init__(self, phone_number): self.number = phone_number def __str__(self): return f'Phone: {self.number}' def call(self, other_number): print("Calling {} from {}.".format(other_number, self.number)) def text(self, other_number, msg): print("Sending text from {} to {}:".format(self.number, other_number)) print(msg) basic_phone = Phone('333-444-5566') print(basic_phone) class IPhone(Phone): def __init__(self, phone_number): super().__init__(phone_number) self.fingerprint = None def __str__(self): # override this method return f'iPhone {self.number}' def call(self, other_number): print(f'iPhone is calling: {other_number}') def set_fingerprint(self, fingerprint): self.fingerprint = fingerprint def unlock(self, fingerprint=None): if (fingerprint == self.fingerprint and fingerprint == None): print("Phone unlocked because no fingerprint has not been set.") elif (fingerprint == self.fingerprint): print("Phone unlocked. Fingerprint matches.") else: print("Phone locked. Fingerprint doesn't match.") # Iphone Example print('# Iphone Example') iphone_12 = IPhone('555-666-7789') print(iphone_12) iphone_12.call('234-444-5678') iphone_12.set_fingerprint('lskdmalnkaaslfm') print('Fingerprint', iphone_12.fingerprint) iphone_12.unlock('lskdmalnkaaslfm') class IPhoneXI(IPhone): def __init__(self, phone_number, color): super().__init__(phone_number) self.color = color shawn_phone = IPhoneXI('555-888-7789', 'purple') print(shawn_phone) shawn_phone.call('411') class Android(Phone): def __init__(self, phone_number): super().__init__(phone_number) self.keyboard = "Default" def set_keyboard(self, keyboard): self.keyboard = keyboard # Exercise # Make a specfic Android phone # inherit the Android class # Add 2 methods onto class # Test class with using some of the parent methods class SamsungGalaxy(Android): def __init__(self, phone_number, color): super().__init__(phone_number) self.color = color self.apps = [] def __str__(self): return f'Samsung Galaxy: {self.number}' def install_app(self, app): self.apps.append(app) print('Apps:', self.apps) def download_holy_grail(self): print('Download Jay-Z Album: Holy Grail') rome_new_phone = SamsungGalaxy('123-456-7890', 'red') print(rome_new_phone) rome_new_phone.install_app('Slack') rome_new_phone.install_app('Zoom') rome_new_phone.download_holy_grail()
4b68a3139ba368cd6f80caed3349044a40eb9dfe
Mr-StraightFs/Simple_Calculator_with_Tkinter
/Calculator.py
3,434
4.125
4
import tkinter from tkinter import * root = Tk() root.title="Simple Calculator" e=Entry(root , width=35,borderwidth=5) e.grid(row=0,column=0,columnspan=3,padx=10,pady=10) def button_click(number): if number == "clear" : e.delete(0, END) return current= e.get() e.delete(0,END) e.insert(0,str(current)+str(number)) return def button_add(): global operation global f_number operation = "add" f_number = float(e.get()) e.delete(0,END) return second = float(format(5.30, '.2f')) print (type(second)) def button_sub(): global operation global f_number operation = "subs" f_number = float(e.get()) e.delete(0,END) return def button_mult (): global operation global f_number operation = "mult" f_number = float(e.get()) e.delete(0,END) return def button_div(): global operation global f_number operation = "div" f_number = float(e.get()) e.delete(0,END) return def button_equal (): try : second = float(e.get()) e.delete(0, END) if operation == "add": sum = format((f_number + second), '.2f') e.insert(0, sum) elif operation == "mult": multipl = format((f_number * second), '.2f') e.insert(0, multipl) elif operation == "div": divide = f_number / second e.insert(0, format(divide, '.2f')) else : sub = format((f_number - second), '.2f') e.insert(0, sub) except: e.insert(0, "Choose a correct operation , Try again") return button_1 = Button(root,text="1",padx=40,pady=20,command=lambda: button_click(1)) button_2 = Button(root,text="2",padx=40,pady=20,command=lambda: button_click(2)) button_3 = Button(root,text="3",padx=40,pady=20,command=lambda: button_click(3)) button_4 = Button(root,text="4",padx=40,pady=20,command=lambda: button_click(4)) button_5 = Button(root,text="5",padx=40,pady=20,command=lambda: button_click(5)) button_6 = Button(root,text="6",padx=40,pady=20,command=lambda: button_click(6)) button_7 = Button(root,text="7",padx=40,pady=20,command=lambda: button_click(7)) button_8 = Button(root,text="8",padx=40,pady=20,command=lambda: button_click(8)) button_9 = Button(root,text="9",padx=40,pady=20,command=lambda: button_click(9)) button_0 = Button(root,text="0",padx=40,pady=20,command=lambda: button_click(0)) button_sub = Button(root,text="-",padx=38,pady=20,command= button_sub) button_add = Button(root,text="+",padx=38,pady=20,command= button_add) button_mult = Button(root,text="*",padx=38,pady=20,command= button_mult) button_div = Button(root,text="/",padx=38,pady=20,command= button_div) button_equal = Button(root,text="=",padx=91,pady=20,command= button_equal) button_clear = Button(root,text="clear",padx=79,pady=20,command=lambda: button_click("clear")) button_1.grid(row=3,column=0) button_2.grid(row=3,column=1) button_3.grid(row=3,column=2) button_4.grid(row=2,column=0) button_5.grid(row=2,column=1) button_6.grid(row=2,column=2) button_7.grid(row=1,column=0) button_8.grid(row=1,column=1) button_9.grid(row=1,column=2) button_0.grid(row=4,column=0) button_clear.grid(row=4,column=1,columnspan=2) button_add.grid(row=5,column=0) button_sub.grid(row=6,column=0) button_mult.grid(row=5,column=1) button_div.grid(row=5,column=2) button_equal.grid(row=6,column=1,columnspan=2) root.mainloop()
7fe54b433df2a57dc813822950f22a741d7beb97
abid-mehmood/SP_Labs
/Labs/Python_homework/task4.py
260
3.890625
4
def remove_adjacent(name): i=1 while i < (len(name)-1): if name[i-1] == name[i] or name[i+1]== name[i]: del name[i] i-=1 i+=1 return name if __name__=="__main__": TempList=[1,2,2,2,2,3,4,5,5] print TempList print remove_adjacent(TempList)
322aa3bedd4ce2c7bdf80cd7bca5c5bc1b24b743
dhruvag02/Pyhton
/distinctPairs.py
1,030
3.5
4
def isNotEmpty(a): if len(a) == 0: return True else: return False def binarySearch(a, value): low = 0 high = len(a) - 1 while low <= high: mid = (low + high)//2 if a[mid] < value: low = mid+1 elif a[mid] > value: high = mid-1 else: return True return False def distinctPairs(n, a, k): if n == 0: return 0 a.sort() print(a) count = 0 i = 0 while (i < n) or (isNotEmpty(a)): i = i+1 try: item = a[0] except: return count value = k-item if binarySearch(a, value): a.remove(value) a.remove(item) print(a) count = count + 1 else: continue return count n = 6 a = [1, 18, 13, 6, 10, 9] k = 19 pairs = distinctPairs(n, a, k) print(pairs) OUTPUT [1, 6, 9, 10, 13, 18] [6, 9, 10, 13] [9, 10] [] 3
0fc380fd98ecad25e2dc6ee2fa0628d733431714
Pechi77/generate-charts
/nass_weather.py
631
3.5625
4
def weather_by_city(city): weather = Weather(unit=Unit.CELSIUS) location = weather.lookup_by_location(city) condition = location.condition current_condition=condition.text current_temp=location.print_obj["item"]["condition"]["temp"] forecasts = location.forecast weather_df=pd.DataFrame(columns=["Status","Date","High","Low"]) for forecast in forecasts: weather_df=weather_df.append({"Status":forecast.text,"Date":forecast.date,"High":forecast.high,"Low":forecast.low},ignore_index=True) status_json=weather_df.to_json() return current_condition,current_temp,status_json
c777c808594dee47a5500234cecf6628ce096ee6
jjkim110523/flask_tutorial
/flask_Sessions/flask_session.py
1,317
4.0625
4
""" 쿠키랑은 다르게 세션은 서버에 저장되어있는 데이터입니다. 세션은 서버의 임시 디렉토리에 저장되어 작동합니다. 각각의 클라이언트는 세션 ID를 부여받습니다. 암호화가 된 데이터이기 때문에 Flask에서는 SECRET_KEY가 필요합니다. """ from flask import Flask, session, redirect, url_for, escape, request app=Flask(__name__) app.secret_key="asdfsdfg" @app.route("/") def index(): if "username" in session: username=session["username"] return "Logged in as "+username+"<br>"+\ "<b><a href='/logout'>click here to log out</a></b>" return "You are not logged in <br><a href='/login'></b>"+\ "click here to log in</b></a>" @app.route("/login", methods=["GET", "POST"]) def login(): if request.method=="POST": session["username"]=request.form["username"] return redirect(url_for("index")) return """ <form action="" method="POST"> <p><input type="text" name="username"/></p> <p><input type="submit" value="Login"/></p> </form> """ @app.route("/logout") def logout(): #유저가 세션 안에 있으면 삭제한다. session.pop("username", None) return redirect(url_for("index")) if __name__ =="__main__": app.run(debug=True)
a60959075c931679a424838f807b1b8141d8138d
pedroesc123/codigo_python
/complejidad_algoritmica.py
652
3.65625
4
import time import sys sys.setrecursionlimit(2500) print (sys.getrecursionlimit()) #Iterativo def factorial(n): respuesta = 1 while n > 1: respuesta *= n n -= 1 return respuesta #Recursivo def factorial_r(n): if n == 1: return 1 return n * factorial_r(n-1) if __name__ == '__main__': n = 2200 comienzo = time.time() #Significa que se esta ejecutando el modulo time # y adentro hay una función que se llama time factorial(n) final = time.time() print(final - comienzo) comienzo = time.time() factorial_r(n) final = time.time() print(final - comienzo)
65240998e3eee7f8897536256a1be9da535a6944
aaroncsolomon/244proj
/linear_regression2.py
2,331
4.0625
4
import tensorflow as tf import numpy as np # Generate samples of a function we are trying to predict: samples = 100 xs = np.linspace(-5, 5, samples) # We will attempt to fit this function ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, samples) # First, create TensorFlow placeholders for input data (xs) and # output (ys) data. Placeholders are inputs to the computation graph. # When we run the graph, we need to feed values for the placerholders into the graph. # TODO: create placeholders for inputs and outputs # We will try minimzing the mean squared error between our predictions and the # output. Our predictions will take the form X*W + b, where X is input data, # W are ou weights, and b is a bias term: # minimize ||(X*w + b) - y||^2 # To do so, you will need to create some variables for W and b. Variables # need to be initialised; often a normal distribution is used for this. # TODO create weight and bias variables # Next, you need to create a node in the graph combining the variables to predict # the output: Y = X * w + b. Find the appropriate TensorFlow operations to do so. predictions = # TODO prediction # Finally, we need to define a loss that can be minimized using gradient descent: # The loss should be the mean squared difference between predictions # and outputs. loss = # TODO create loss # Use gradient descent to optimize your variables learning_rate = 0.001 optimize_op= tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) # We create a session to use the graph and initialize all variables session = tf.Session() session.run(tf.global_variables_initializer()) # Optimisation loop epochs = 1000 previous_loss = 0.0 for epoch in range(epochs): for (inputs, outputs) in zip(xs, ys): #TODO run the optimize op session.run() # TODO compute the current loss by running the loss operation with the # required inputs loss = session.run() print('Training cost = {}'.format(training_cost)) # Termination condition for the optimization loop if np.abs(previous_loss - loss) < 0.000001: break previous_loss = training_cost # TODO try plotting the predictions by using the model to predict outputs, e.g.: # import matplotlib.pyplot as plt # predictions = #TODO, run the prediction operation # plt.plot(xs, predictions) # plt.show()
5632767ce48d3c89e02549b6799ff2c19ab2a34a
MADMAXITY/cipherschools-june-2021
/Day-1/AlternativeSorting.py
337
3.9375
4
def print_alternative(arr): low, high = 0, len(arr) - 1 while high > low: print(arr[high], arr[low], end=" ") high -= 1 low += 1 if high == low: print(arr[high]) if __name__ == "__main__": arr = [int(x) for x in input("Enter array : ").split()] arr.sort() print_alternative(arr)
1f95dd4e2b26038b1b96b9d1cc70c840d7b104d7
SteveGaleComputingStudies/2020Python2
/classes/shark3.py
264
3.828125
4
class Shark: def __init__(self, name, age): self.name = name self.age = age new_shark = Shark("Sammy", 5) print(new_shark.name) print(new_shark.age) stephan = Shark("Stephan", 8) print("stephan name= ",stephan.name) print("Age = ",stephan.age)
440f5a6d277e4dfc80786e95529aaae5513f8602
jvlazar/mutation
/substitute.py
2,662
3.890625
4
from pathlib import Path import sys try: fName = open(sys.argv[1], "r") oName = open(sys.argv[2], "w+") if len(sys.argv) !=3: print("An input and output file name must be provided") quit() fasta = False target = input("What amino acid do you want to delete?: ") target = target.upper() # converts input to uppercase key = input("What amino acid to you want to replace it with?: ") key = key.upper() position = int(input("What position do you want to delete?: ")) count = 1 # initialize count for the input file total_count = 1 out_count = 1 # initialize count for the output file mutation = 0 substituted = False while True: # loop indefinitely char = fName.read(1) if not char: # if the value of char is null, exit out of the loop break if char == ">": # if the file is in FASTA format read until you reach "]" fasta = True count = 1 # initialize count to 1 for each new organism out_count = 1 # initialize output count to 1 for each new organism while True: if char == "]": oName.write(char) # write the character to the output file char = fName.read(1) break else: oName.write(char) # write the character to the output file char = fName.read(1) total_count = total_count + 1 if count != position: # when not at the desired position, add 1 to count if char != "\n": count = count + 1 out_count = out_count + 1 elif char == "\n": # if the character is a newline, don't change the count pass oName.write(char) # write the character to the output file elif count == position: if char == target: oName.write(key) count = count + 1 # increasing count mutation = mutation + 1 substituted = True else: oName.write(char) count = count + 1 out_count = out_count + 1 if substituted == False: print("There was no mutation at the " + str(count) + " position") total_count = total_count + 1 difference = total_count - mutation print("The amino acids have been substituted") oName.close() except FileNotFoundError: print("File could not be opened") quit()
f1b5956c67d6c94bfec28209faeb3fdeb526208b
Kohdz/Algorithms
/LeetCode/easy/07_mergeTwoList.py
1,346
4.1875
4
# https://leetcode.com/problems/merge-two-sorted-lists/ # Merge two sorted linked lists and return it as a new list. # The new list should be made by splicing together the nodes of the first two lists. # Example: # Input: 1->2->4, 1->3->4 # Output: 1->1->2->3->4->4 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def mergeTwoLists(l1, l2): # curr changes, so we also need to keep refrence to dummy # so when we need to return new list, we can return dummy.next # we dont want to include the 0 curr = dummy = ListNode(0) while l1 and l2: # if list one is smaller, curr.next is list one and l1 pointer moves up 1 if l1.val < l2.val: curr.next = l1 l1 = l1.next else: # else l2 is smaller and l2 is the next item and l2 pointer moves up one curr.next = l2 l2 = l2.next # your updating the refrence of the dummy to the next # for example, if dummy is no longer pointing to null but l1, # well you need to update it to move on to l1 curr = curr.next # remember, one of the lists is goint to equal NULL, so what we d ois refrence # curr.next to the one that is not null curr.next = l1 or l2 return dummy.next
b3366364e4722a046917840396e1c4781ee9aaf3
aleexiisz57/Lessons
/Lesson-1/ex6.py
1,016
4.5625
5
# x is a variable and we giving it a value with strings, we also set the values for "binary" #and "do_not" so that they can be used inside the strings. x = "there are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) #these lines print my variables, where "x" is a statement and "y" too print x print y #here we start a sentence and we use a format character to insert a variable and finish the sentence print "i said: %r." % x print "i also said: '%s'." % y #we set a value for the variables hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" # using only variables we are able to create a sentence print joke_evaluation % hilarious #assigning a value for the variables w = "this is the left side of ..." e = "a string with a right side." #using the variables to create a sentence #we need to use the "+" to add the variables and get strings. if it's removed the console won't reconize them #as variables print w + e
1063dd4961d52b1a7700c7dab58d5545cd8c6162
FerCremonez/College-1st-semester-
/a8e1.py
178
3.875
4
soma=0 #conta quantas entradas foram adicionadas for i in range (0,4): #limite do intervalo num=int(input("insira o número:")) soma+=num print('soma =',soma)
a955c24262b1fbab963100780392ac0c4b875f86
bing1zhi2/algorithmPractice
/pyPractice/algoproblem/kth_largest.py
1,923
4.125
4
''' Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 ''' class Solution(object): def findKthLargest(self, nums, k): """ Runtime: 3040 ms, faster than 5.02% of Python online submissions for Kth Largest Element in an Array. :type nums: List[int] :type k: int :rtype: int """ N = len(nums) for i in range(N): for j in range(i+1, N): if nums[i] < nums[j]: temp = nums[i] nums[i] = nums[j] nums[j] = temp print(i, nums) if i == k -1: break return nums[i] def divid(self,nums,left,right): base = nums[left] while left< right: while left < right and nums[right] >= base: right = right -1 nums[left] = nums[right] while left < right and nums[left] <= base: left = left +1 nums[right] = nums[left] nums[left] = base return left def quik_sort(self, nums,left,right): if left < right: base_idx = self.divid(nums,left,right) self.quik_sort(nums,left,base_idx-1) self.quik_sort(nums,base_idx+1,right) def findKthLargest2(self, nums, k): """ Runtime: 3040 ms, faster than 5.02% of Python online submissions for Kth Largest Element in an Array. :type nums: List[int] :type k: int :rtype: int """ N = len(nums) self.quik_sort(nums,0,N-1) print(nums) return nums[N -k] nu = [3,2,1,5,6,4] a = Solution() a.findKthLargest(nu,2) aaa =a.findKthLargest2(nu,2) print(aaa)
0e9676cf7d639c4ab59bb8ef0e00c8ffd59e53ad
ctc316/algorithm-python
/Lintcode/Ladder_48_Backpack/3_Complete backpack/440. Backpack III.py
1,409
3.5625
4
# Version 1: TLE class Solution: """ @param A: an integer array @param V: an integer array @param m: An integer @return: an array """ def backPackIII(self, A, V, m): dp = [0 for _ in range(m + 1)] for i in range(len(A)): for j in range(1, int(m / A[i]) + 1): for k in range(m, A[i] - 1, -1): dp[k] = max(dp[k], dp[k - A[i]] + V[i]) return dp[m] # Version 2: Time Complexity Optimization # 由於同一種物品的個數無限,所以我們可以在任意容量 j 的背包嘗試裝入當前物品,j 從小向大枚舉可以保證所有包含第 i 種物品,體積不超過 j - A[i] 的狀態被枚舉到。 class Solution: """ @param A: an integer array @param V: an integer array @param m: An integer @return: an array """ ''' size: [2,3,5,7] value:[1,5,2,4] 10 0 5 10 [0,0,0,0,0,0, 0, 0, 0, 0, 0] 2,1 [0,0,1,1,1,1, 1, 1, 1, 1, 1] 3,5 [0,0,1,5,5,6,10,10,11,15,15] 5,2 [0,0,1,5,5,6,10,10,11,15,15] 7,4 [0,0,1,5,5,6,10,10,11,15,15] ''' def backPackIII(self, A, V, m): dp = [0 for _ in range(m + 1)] for i in range(len(A)): for j in range(A[i], m + 1): dp[j] = max(dp[j], dp[j - A[i]] + V[i]) return dp[m]
b8eb0130f6e381a6362e0312e6276bac2a86149f
Weenz/software-QA-hw2
/main.py
2,228
4.21875
4
import math from bmiCalc import * from retirementCalc import * option = 1 while (option != 3): print ("--------------------------------") print ("| |") print ("| Software QA Assignment 2 |") print ("| |") print ("--------------------------------") print ("--------------------------------") print ("| Select an option from below: |") print ("| |") print ("| 1. BMI Calculator |") print ("| 2. Retirement Calculator |") print ("| 3. Exit |") print ("| |") print ("--------------------------------") #These two while statements verify the user input while True: try: option = int(input("Select an option: ")) except: print ("Must be a number value!") continue else: break while ( (option < 1) or (option > 3) ): print ("Must be a valid option choice!") while True: try: option = int(input("Select an option: ")) except: print ("Must be a number value!") continue else: break #Option 1: BMI Calculator if (option == 1): print ("Results: ", bmiCalc()) print ("") input ("Press enter to return to selection screen...") print ("") #Option 2: Retirement Calculator elif (option == 2): age = retirementCalc() if (age >= 100): print ("You died at 100 before reaching your goal.") print ("You would have hit your goal at age", age) elif (age == 0): print ("Error: Annual salary or the percentage saved cannot be zero") else: print ("") print ("You will reach your goal at age", age) print ("") input ("Press enter to return to selection screen...") print ("") print ("") print ("Have a nice day!") input ("Press Enter to close the application...")
f1948a316d199be4c8ee13e55d307a1333957d07
Jackthedowner/My_python_school_programs
/Even_series_program.py
443
3.875
4
def ev(n): listofEven=[] listofall=[] print('ALL NUMBERS:→') for i in range(0,n+1): print(i,end=' ') listofall.append(i) print('List of All Numbers:',listofall) print('EVEN NUMBERS→') for i in range(0,n+1,2): print(i,end=' ') listofEven.append(i) print('List of Even Numbers:', listofEven) print('Sum of list is:',sum(listofEven)) n=int(input('how many times:')) ev(n)
7b44b16d18e00ceb79851b1c848e75d3f33cba0a
joeyscl/Programming_Challenges
/Sorting & Searching/linearSortSequence.py
533
4.125
4
''' given an array of integers from 0 ~ n-1 where (n is the length of the input array) sort the array in-place in linear time ''' ''' We 'sort' by swapping elements directly into where they belong since element value correspond to indices directly ''' def linSort(arr): count = 0 idx = 0 while count < len(arr): print(arr) if idx == arr[idx]: idx += 1 count += 1 else: nextIdx = arr[idx] arr[idx], arr[nextIdx] = arr[nextIdx], arr[idx] count += 1 print(arr) test = [2,4,6,3,8,1,0,5,9,7] linSort(test)
adafc259fcea61f98c3e88aa66081b02a31c3957
chuajunyu/scvu-git-tutorial
/HW5/HW05_Ian.py
3,892
3.90625
4
#QN5 '''def make_counter(): """Return a counter function. >>> c = make_counter() >>> c('a') 1 >>> c('a') 2 >>> c('b') 1 >>> c('a') 3 >>> c2 = make_counter() >>> c2('b') 1 >>> c2('b') 2 >>> c('b') + c2('b') 5 """ "*** YOUR CODE HERE ***" dict = {} def count(i): if i in dict: dict[i] += 1 else: dict[i] = 1 return dict[i] return count ''' #QN6 '''def make_fib(): """Returns a function that returns the next Fibonacci number every time it is called. >>> fib = make_fib() >>> fib() 0 >>> fib() 1 >>> fib() 1 >>> fib() 2 >>> fib() 3 >>> fib2 = make_fib() >>> fib() + sum([fib2() for _ in range(5)]) 12 """ "*** YOUR CODE HERE ***" # 0 1 1 2 3 5 8 13 a, b = 0, 1 def fib_count(): nonlocal a total = a nonlocal b a, b = b, a + b return total return fib_count''' #Q7 '''def make_withdraw(balance, password): """Return a password-protected withdraw function. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> error = w(90, 'hax0r') >>> error 'Insufficient funds' >>> error = w(25, 'hwat') >>> error 'Incorrect password' >>> new_bal = w(25, 'hax0r') >>> new_bal 50 >>> w(75, 'a') 'Incorrect password' >>> w(10, 'hax0r') 40 >>> w(20, 'n00b') 'Incorrect password' >>> w(10, 'hax0r') "Your account is locked. Attempts: ['hwat', 'a', 'n00b']" >>> w(10, 'l33t') "Your account is locked. Attempts: ['hwat', 'a', 'n00b']" >>> type(w(10, 'l33t')) == str True """ "*** YOUR CODE HERE ***" wrong_attempts = [] no_of_attempts = 0 def withdraw(amount, password_attempt): nonlocal no_of_attempts if password_attempt == password and no_of_attempts < 3: nonlocal balance if amount > balance: return 'Insufficient funds' balance = balance - amount return balance elif password_attempt != password and no_of_attempts < 3: wrong_attempts.append(password_attempt) no_of_attempts += 1 return 'Incorrect password' if no_of_attempts >= 3: return "Your account is locked. Attempts: " + str(wrong_attempts) return withdraw''' #QN8 '''def make_joint(withdraw, old_password, new_password): """Return a password-protected withdraw function that has joint access to the balance of withdraw. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> make_joint(w, 'my', 'secret') 'Incorrect password' >>> j = make_joint(w, 'hax0r', 'secret') >>> w(25, 'secret') 'Incorrect password' >>> j(25, 'secret') 50 >>> j(25, 'hax0r') 25 >>> j(100, 'secret') 'Insufficient funds' >>> j2 = make_joint(j, 'secret', 'code') >>> j2(5, 'code') 20 >>> j2(5, 'secret') 15 >>> j2(5, 'hax0r') 10 >>> j2(25, 'password') 'Incorrect password' >>> j2(5, 'secret') "Your account is locked. Attempts: ['my', 'secret', 'password']" >>> j(5, 'secret') "Your account is locked. Attempts: ['my', 'secret', 'password']" >>> w(5, 'hax0r') "Your account is locked. Attempts: ['my', 'secret', 'password']" >>> make_joint(w, 'hax0r', 'hello') "Your account is locked. Attempts: ['my', 'secret', 'password']" """ "*** YOUR CODE HERE ***" passwordcheck = withdraw(0, old_password) if type(passwordcheck) == str: return passwordcheck def jointacct(amount, password): if password == new_password: return withdraw(amount, old_password) else: return withdraw(amount, password) return jointacct'''
9c6eb34fb1be659e26ff04684d88bc939b62ee89
QPaddock/Rubik
/moves.py
7,222
3.5
4
from print_cube import print_cube temp_cube = [["" for i in range(12)] for j in range(9)] def make_moves(mix, cube): if valid_mix(mix) == False: print("Invalid Mix...") exit(0) for twist in mix.split(): if twist == "R": right_turn(cube) if twist == "L": left_turn(cube) if twist == "F": front_turn(cube) if twist == "B": back_turn(cube) if twist == "U": up_turn(cube) if twist == "D": down_turn(cube) if twist == "R2": right_turn(cube) right_turn(cube) if twist == "L2": left_turn(cube) left_turn(cube) if twist == "F2": front_turn(cube) front_turn(cube) if twist == "B2": back_turn(cube) back_turn(cube) if twist == "U2": up_turn(cube) up_turn(cube) if twist == "D2": down_turn(cube) down_turn(cube) if twist == "R'": right_turn(cube) right_turn(cube) right_turn(cube) if twist == "L'": left_turn(cube) left_turn(cube) left_turn(cube) if twist == "F'": front_turn(cube) front_turn(cube) front_turn(cube) if twist == "B'": back_turn(cube) back_turn(cube) back_turn(cube) if twist == "U'": up_turn(cube) up_turn(cube) up_turn(cube) if twist == "D'": down_turn(cube) down_turn(cube) down_turn(cube) def valid_mix(mix): for twist in mix.split(): if (twist != 'R' and twist != "R'" and twist != 'L' and twist != "L'" and twist != 'F' and twist != "F'" and twist != 'B' and twist != "B'" and twist != 'U' and twist != "U'" and twist != 'D' and twist != "D'" and twist != "R2" and twist != "L2" and twist != "F2" and twist != "B2" and twist != "U2" and twist != "D2"): return False return True def right_turn(new_cube): temp_cube = [x[:] for x in new_cube] new_cube[0][8] = temp_cube[3][8] new_cube[1][8] = temp_cube[4][8] new_cube[2][8] = temp_cube[5][8] new_cube[3][0] = temp_cube[2][8] new_cube[3][8] = temp_cube[6][8] new_cube[3][9] = temp_cube[5][9] new_cube[3][10] = temp_cube[4][9] new_cube[3][11] = temp_cube[3][9] new_cube[4][0] = temp_cube[1][8] new_cube[4][8] = temp_cube[7][8] new_cube[4][9] = temp_cube[5][10] new_cube[4][11] = temp_cube[3][10] new_cube[5][0] = temp_cube[0][8] new_cube[5][8] = temp_cube[8][8] new_cube[5][9] = temp_cube[5][11] new_cube[5][10] = temp_cube[4][11] new_cube[5][11] = temp_cube[3][11] new_cube[6][8] = temp_cube[5][0] new_cube[7][8] = temp_cube[4][0] new_cube[8][8] = temp_cube[3][0] def left_turn(new_cube): temp_cube = [x[:] for x in new_cube] new_cube[0][6] = temp_cube[5][2] new_cube[1][6] = temp_cube[4][2] new_cube[2][6] = temp_cube[3][2] new_cube[3][2] = temp_cube[8][6] new_cube[3][3] = temp_cube[5][3] new_cube[3][4] = temp_cube[4][3] new_cube[3][5] = temp_cube[3][3] new_cube[3][6] = temp_cube[0][6] new_cube[4][2] = temp_cube[7][6] new_cube[4][3] = temp_cube[5][4] new_cube[4][5] = temp_cube[3][4] new_cube[4][6] = temp_cube[1][6] new_cube[5][2] = temp_cube[6][6] new_cube[5][3] = temp_cube[5][5] new_cube[5][4] = temp_cube[4][5] new_cube[5][5] = temp_cube[3][5] new_cube[5][6] = temp_cube[2][6] new_cube[6][6] = temp_cube[3][6] new_cube[7][6] = temp_cube[4][6] new_cube[8][6] = temp_cube[5][6] def front_turn(new_cube): temp_cube = [x[:] for x in new_cube] new_cube[2][5] = temp_cube[6][5] new_cube[2][6] = temp_cube[5][5] new_cube[2][7] = temp_cube[4][5] new_cube[2][8] = temp_cube[3][5] new_cube[2][9] = temp_cube[2][5] new_cube[3][5] = temp_cube[6][6] new_cube[3][6] = temp_cube[5][6] new_cube[3][7] = temp_cube[4][6] new_cube[3][8] = temp_cube[3][6] new_cube[3][9] = temp_cube[2][6] new_cube[4][5] = temp_cube[6][7] new_cube[4][6] = temp_cube[5][7] new_cube[4][8] = temp_cube[3][7] new_cube[4][9] = temp_cube[2][7] new_cube[5][5] = temp_cube[6][8] new_cube[5][6] = temp_cube[5][8] new_cube[5][7] = temp_cube[4][8] new_cube[5][8] = temp_cube[3][8] new_cube[5][9] = temp_cube[2][8] new_cube[6][5] = temp_cube[6][9] new_cube[6][6] = temp_cube[5][9] new_cube[6][7] = temp_cube[4][9] new_cube[6][8] = temp_cube[3][9] new_cube[6][9] = temp_cube[2][9] def back_turn(new_cube): temp_cube = [x[:] for x in new_cube] new_cube[0][6] = temp_cube[3][11] new_cube[0][7] = temp_cube[4][11] new_cube[0][8] = temp_cube[5][11] new_cube[3][0] = temp_cube[5][0] new_cube[3][1] = temp_cube[4][0] new_cube[3][2] = temp_cube[3][0] new_cube[3][3] = temp_cube[0][8] new_cube[3][11] = temp_cube[8][8] new_cube[4][0] = temp_cube[5][1] new_cube[4][2] = temp_cube[3][1] new_cube[4][3] = temp_cube[0][7] new_cube[4][11] = temp_cube[8][7] new_cube[5][0] = temp_cube[5][2] new_cube[5][1] = temp_cube[4][2] new_cube[5][2] = temp_cube[3][2] new_cube[5][3] = temp_cube[0][6] new_cube[5][11] = temp_cube[8][6] new_cube[8][6] = temp_cube[3][3] new_cube[8][7] = temp_cube[4][3] new_cube[8][8] = temp_cube[5][3] def up_turn(new_cube): temp_cube = [x[:] for x in new_cube] new_cube[0][6] = temp_cube[2][6] new_cube[0][7] = temp_cube[1][6] new_cube[0][8] = temp_cube[0][6] new_cube[1][6] = temp_cube[2][7] new_cube[1][8] = temp_cube[0][7] new_cube[2][6] = temp_cube[2][8] new_cube[2][7] = temp_cube[1][8] new_cube[2][8] = temp_cube[0][8] new_cube[3][0] = temp_cube[3][3] new_cube[3][1] = temp_cube[3][4] new_cube[3][2] = temp_cube[3][5] new_cube[3][3] = temp_cube[3][6] new_cube[3][4] = temp_cube[3][7] new_cube[3][5] = temp_cube[3][8] new_cube[3][6] = temp_cube[3][9] new_cube[3][7] = temp_cube[3][10] new_cube[3][8] = temp_cube[3][11] new_cube[3][9] = temp_cube[3][0] new_cube[3][10] = temp_cube[3][1] new_cube[3][11] = temp_cube[3][2] def down_turn(new_cube): temp_cube = [x[:] for x in new_cube] new_cube[5][0] = temp_cube[5][9] new_cube[5][1] = temp_cube[5][10] new_cube[5][2] = temp_cube[5][11] new_cube[5][3] = temp_cube[5][0] new_cube[5][4] = temp_cube[5][1] new_cube[5][5] = temp_cube[5][2] new_cube[5][6] = temp_cube[5][3] new_cube[5][7] = temp_cube[5][4] new_cube[5][8] = temp_cube[5][5] new_cube[5][9] = temp_cube[5][6] new_cube[5][10] = temp_cube[5][7] new_cube[5][11] = temp_cube[5][8] new_cube[6][6] = temp_cube[8][6] new_cube[6][7] = temp_cube[7][6] new_cube[6][8] = temp_cube[6][6] new_cube[7][6] = temp_cube[8][7] new_cube[7][8] = temp_cube[6][7] new_cube[8][6] = temp_cube[8][8] new_cube[8][7] = temp_cube[7][8] new_cube[8][8] = temp_cube[6][8]
a684f5bdadaaa7b79376438cc0293b9bfe2c5f22
ugobachi/AtCoder
/ABC162/A.py
330
3.75
4
"""[solution] 入力をリスト化して、フラグを用意 リスト内でfor文を回し、7が含まれていたらフラグをTrueにする フラグによって出力を変える """ N = list(input()) flag = False for i in N: if i == '7': flag = True if flag == True: print('Yes') else: print('No')
bd02d8201908f150a0a7147f4c39f2ea6757c1f6
jmg5219/First-Excercises-in-Python-
/print_a_box.py
609
4.09375
4
width = int(input("Width?"))#prompting user for input on the width of the box height = int(input("Height?"))#prompting user for input on the height of the box i = height#initializing incrementors j = width for i in range(1, i+1) : #cycling through row for j in range(1, j+1) : #cycling through column if (i==1 or i==height or j==1 or j==width):#if at the ends of the box we print print("*", end="") # appending a space after print if at the ends of the box else : print(" ", end="") #printing a blank space if in inside the box print()
be9fc28dd4637c7f132979f6beaee0104208808c
AO-StreetArt/AOWorkflowDeveloper
/Application/src/export/Tree_Iterators.py
6,209
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 18:38:26 2016 Tree Iterators @author: alex """ #Base class which other iterators will inherit from class Tree_Iterator(object): """ :param Tree tree: Internal tree :param String name: Iterator name """ def __init__(self, tree, name): self.tree = tree self.name = name def get_name(self): return self.name """ :param Method function: The function to recurse """ def iterate(self, function): pass #This is implemented and called in each successive iterator to determine how iterations happen #--------Example of passing function down the stack-------- # class Foo(object): # def method1(self): # pass # def method2(self, method): # return method() # # foo = Foo() # foo.method2(foo.method1) # #From http://stackoverflow.com/questions/706721/how-do-i-pass-a-method-as-a-parameter-in-python#706735 #Basic Recursive Operator that supports functions without the actual node or any other parameters class Basic_Recursive_Iterator(Tree_Iterator): """ :param Tree tree: Internal tree """ def __init__(self, tree): super(Basic_Recursive_Iterator, self).__init__(tree, "Basic Recursive Iterator") """ :param Method function: The function to recurse (No parameters passed) """ def iterate(self, function): self.process_node(function, self.tree.root) def process_node(self, function, node): function() if len(node.connections) > 0: for con in node.connections: self.process_node(function, con) else: return True #Advanced Recursive Operator that supports functions with the actual node and a single parameter class Advanced_Recursive_Iterator(Tree_Iterator): """ :param Tree tree: Internal tree """ def __init__(self, tree): super(Advanced_Recursive_Iterator, self).__init__(tree, "Advanced Recursive Iterator") """ :param Method function: The function to recurse (1 parameter passed) """ def iterate(self, function, **kwargs): self.process_node(function, self.tree.root, **kwargs) def process_node(self, function, node, **kwargs): function(node, **kwargs) if len(node.connections) > 0: for con in node.connections: self.process_node(function, con, **kwargs) else: return True #Tail Recursion Iterator that supports functions with the actual node and a single parameter class Tail_Recursion_Iterator(Tree_Iterator): """ :param Tree tree: Internal tree """ def __init__(self, tree): super(Tail_Recursion_Iterator, self).__init__(tree, "Tail Recursion Iterator") """ :param Method function: The function to recurse (1 parameter passed) """ def iterate(self, function, **kwargs): self.process_node(function, self.tree.root, **kwargs) def process_node(self, function, node, **kwargs): while len(node.connections) == 1: function(node, **kwargs) node=node.connections[0] if len(node.connections) > 1: for con in node.connections: self.process_node(function, con, **kwargs) else: return True #Chain Iterator that supports functions with the actual node and a single parameter class Chain_Iterator(Tree_Iterator): """ :param Tree tree: Internal tree """ def __init__(self, tree): super(Chain_Iterator, self).__init__(tree, "Chain Iterator") """ :param Method function: The function to recurse (1 parameter passed) """ def iterate(self, function, **kwargs): chain_list=[] self.process_node(function, self.tree.root, chain_list, **kwargs) for chain in chain_list: for element in chain: function(element, **kwargs) def process_node(self, function, node, chain_list, **kwargs): chain=[] while len(node.connections) == 1: chain.append(node.connections[0]) node=node.connections[0] if len(node.connections) > 1: chain.append(node.connections[0]) node=node.connections[0] chain_list.append(chain) for con in node.connections: self.process_node(function, con, chain_list, **kwargs) else: chain.append(node.connections[0]) node=node.connections[0] chain_list.append(chain) return True #Chain Iterator that supports pre & post functions, #and a main function with the actual node and any number of parameters class Advanced_Chain_Iterator(Tree_Iterator): """ :param Tree tree: Internal tree """ def __init__(self, tree): super(Chain_Iterator, self).__init__(tree, "Advanced Chain Iterator") """ :param Method function: The function to recurse (1 parameter passed) """ def iterate(self, pre_function, function, post_function, **kwargs): chain_list=[] self.process_node(function, self.tree.root, chain_list, **kwargs) for chain in chain_list: pre_function(**kwargs) for element in chain: function(element, **kwargs) post_function(**kwargs) def process_node(self, function, node, chain_list, **kwargs): chain=[] while len(node.connections) == 1: chain.append(node.connections[0]) node=node.connections[0] if len(node.connections) > 1: chain.append(node.connections[0]) node=node.connections[0] chain_list.append(chain) for con in node.connections: self.process_node(function, con, chain_list, **kwargs) else: chain.append(node.connections[0]) node=node.connections[0] chain_list.append(chain) return True
c889c48fc3a4cd71ab3aaa3707c8e3d1a53e6684
xqhu2008/Larva
/src/algorithm/data_structures/heap.py
2,440
4.125
4
#!/usr/bin/env python # -*- encoding:utf-8 -*- ''' Function Name: heap.py heap data structure implementation by python language. Author: Alex Hu Create date: 2020 - 01 - 20 ''' class Heap: def __init__(self, datas = None): self._initialize(datas) def _initialize(self, datas): self._heap = [0] if datas is not None: self._heap.extend(datas) self._build_heap() def size(self): return len(self._heap) - 1 def __str__(self): return str(self._heap[1:]) def is_empty(self): return self.size() == 0 def _build_heap(self): i = self.size() // 2 while i > 0: self._heapify(i) i -= 1 @staticmethod def build_heap(datas): return Heap(datas) def _find_min_branch(self, i): if 2 * i + 1 > self.size(): return 2 * i else: if self._heap[2 * i] < self._heap[2 * i + 1]: return 2 * i else: return 2 * i + 1 def _heapify(self, i): while 2 * i < self.size() + 1: mc = self._find_min_branch(i) if self._heap[mc] < self._heap[i]: self._heap[mc], self._heap[i] = self._heap[i], self._heap[mc] i = mc def insert(self, data): self._heap.append(data) pos = self.size() while pos >= 2: parent = pos // 2 if self._heap[parent] > self._heap[pos]: self._heap[parent], self._heap[pos] = self._heap[pos], self._heap[parent] else: break pos = parent def pop(self): length = self.size() if length == 0: raise ValueError if length == 1: return self._heap.pop() retval = self._heap[1] self._heap[1] = self._heap.pop() self._heapify(1) return retval @staticmethod def heap_sort(datas): heap = Heap.build_heap(datas) datas = [] while not heap.is_empty(): datas.append(heap.pop()) return datas if __name__ == "__main__": import random N = 10 datas = [random.randrange(N) for _ in range(N)] # datas = [1, 3, 5, 2, 4, 8, 6, 7, 9, 10] print(datas) heap = Heap.build_heap(datas) print(heap) heap.insert(12) heap.insert(3) print(heap) print(Heap.heap_sort(datas))
1a70d708e7635ae15c5f67f47408c257a4b9d07c
eMUQI/Python-study
/mooc/week3_BasicDataType/exercises/5.py
3,224
3.71875
4
# -*- coding:utf-8 -*- ''' 1585122477573 恺撒密码 描述 恺撒密码是古罗马恺撒大帝用来对军事情报进行加解密的算法,它采用了替换方法对信息中的每一个英文字符循环替换为字母表序列中该字符后面的第三个字符,即,字母表的对应关系如下:‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬ 原文:A B C D E F G H I J K L M N O P Q R S T U V W X Y Z‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬ 密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B C‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬ 对于原文字符P,其密文字符C满足如下条件:C=(P+3) mod 26‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬ 上述是凯撒密码的加密方法,解密方法反之,即:P=(C-3) mod 26‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬ 假设用户可能使用的输入包含大小写字母a~zA~Z、空格和特殊符号,请编写一个程序,对输入字符串进行恺撒密码加密,直接输出结果,其中空格不用进行加密处理。使用input()获得输入。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬ 输入 示例1: python is good‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬ 输出 示例1: sbwkrq lv jrrg ''' s = input() result = "" for c in s: if ord(c) <= ord('Z') and ord(c) >= ord('A'): result += chr((ord(c)-ord('A') + 3) % 26 + ord('A')) elif ord(c) <= ord('z') and ord(c) >= ord('a'): result += chr((ord(c)-ord('a') + 3) % 26 + ord('a')) else: result += c print(result)
85af3486a59f0e5275e53c2f413232c1fc5c4a81
ShallowAlex/leetcode-py
/1-100/43.py
928
3.53125
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 21 16:40:23 2020 @author: Alex code for windows """ class Solution: def multiply(self, num1, num2): list1 = [int(i) for i in num1[::-1]] list2 = [int(i) for i in num2[::-1]] l1 = len(num1) l2 = len(num2) tmp = [0 for i in range(l1+l2)] for i in range(l1): for j in range(l2): num = list1[i] * list2[j] tmp[i+j] += num print(i,j,tmp) ans = '' for i in range(l1+l2-2): if tmp[i] > 10: tmp[i+1] += tmp[i] // 10 tmp[i] = tmp[i] % 10 while tmp and tmp[-1] == 0: tmp.pop() if not tmp: return '0' for i in tmp[::-1]: ans += str(i) return ans if __name__ == "__main__": s = Solution() a1 = '5' a2 = '12' print(s.multiply(a1, a2))
8f8e72d410c46acfc1255b705a1e4731850ffb2c
timur-qa/leetcode
/26_remove_duplicatest_from_array.py
280
3.609375
4
#https://leetcode.com/problems/remove-duplicates-from-sorted-array/ def removeDuplicates(nums: [int]) -> int: index = 1 while index < len(nums): if nums[index] == nums[index - 1]: nums.pop(index) else: index += 1 return index
d857780687a6d7fa9bbb323fe03d0374e4ae98c5
kmboese/interview-practice
/parsing/extended-csv/parser.py
2,298
4.125
4
''' Given a line of csv input, parse the following inputs: 1. String: a. Always opened with a double quote and closed with a double quote b. Escaped double quotes are allowed as a sequence of two double quotes, i.e. '""' c. Strings may contain commas that should not be treated as a delimiter 2. Integer: a. Integer fields contain only digits 0-9, with no other characters 3. NULL a. NULL fields are fields with nothing in them (comma followed by nothing before the next comma) You can assume that the input is correct, with all strings correctly quoted, all commas in correct places, etc. EXAMPLES: 1. ''' def parseLine(line): tokens = [] string = "" numStr = "" i = 0 while i < len(line): string = "" numStr = "" # Check for a string if line[i] == "\"": string, i = parseString(line, i) tokens.append(string) # If not a string, check for integer elif isInt(line[i]): numStr, i = parseInt(line, i) tokens.append(int(numStr)) # NULL type else: tokens.append(None) # Skip the comma i += 1 return tokens # Parse a line until we see a closing quote # Ex: "a""b," --> "a"b," def parseString(line, i): # Skip the opening quote i += 1 string = "" while i < len(line): if i+1 < len(line) and line[i] == "\"" and line[i+1] != "\"": # Skip the closing quote i += 1 break # If an escaped double quote is seen, append one double quote and skip the next one elif i+1 < len(line) and line[i] == "\"" and line[i+1] == "\"": string += "\"" i += 2 # Otherwise, append a character else: # Skip the closing quote if line[i] == "\"": i += 1 break string += line[i] i += 1 return string, i # Check if a character is an int def isInt(char): return char >= '0' and char <= '9' # Parse an int def parseInt(line, i): numStr = "" while i < len(line): if not isInt(line[i]): return numStr, i else: numStr += line[i] i += 1 return numStr, i
0775a1aedd5d3b53642ddcacc33b778a852211eb
amyfranz/Problem-1-sum-of-multiples
/main.py
222
3.734375
4
def multipleSum(num, multiples): sum = 0 for x in range(1, num): for i in range(0, len(multiples)): if x % multiples[i] == 0 : sum += x break return sum print(multipleSum(1000, [3, 5]))
67f36024a50051775c6fcce30945af9c20e19730
raveltan/itp-git
/01-Introduction/Nathaniel_ALvin - 2440042430/calculator.py
493
4.21875
4
while True: first_Number = int(input('first number: ')) second_Number = int(input('second number: ')) operator = input('operation: ') if operator == '+': print(first_Number + second_Number) elif operator == '-': print(first_Number - second_Number) elif operator == '*': print(first_Number * second_Number) elif operator == '/': print(first_Number / second_Number) else: print('Sorry that action is not yet supported.')
7debbb395eea3094a9d8004aea2b74e3cff2b110
nitzanadut/Exercises
/Python/8 Pirates of the Biss/pirates.py
342
4.09375
4
def dejumble(jumbled_word, words): "Recieves a jumbled_word and a list of fixed words. The function returns the dejumbled word" words_new = [sorted(word) for word in words] return [words[i] for i, word in enumerate(words_new) if word == sorted(jumbled_word)] print(dejumble('ortsp', ['sport', 'parrot', 'ports', 'matey']))
0fa349f2b8e092d00a452ee7daaa919e385104b7
ar90n/lab
/sandbox/tdd_by_example/the_money_example/python/mytest.py
2,324
3.734375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from .money import Money from .bank import Bank from .sum import Sum def test_multiplication(): five = Money.dollar(5) assert five * 2 == Money.dollar(10) assert 2 * five == Money.dollar(10) assert 3 * five == Money.dollar(15) def test_equality(): assert Money.dollar(5) == Money.dollar(5) assert Money.dollar(5) != Money.dollar(6) assert Money.franc(5) != Money.dollar(5) def test_franc_multiplication(): five = Money.franc(5) assert 2 * five == Money.franc(10) assert 3 * five == Money.franc(15) def test_currency(): assert 'USD' == Money.dollar(1).currency assert 'CHF' == Money.franc(1).currency def test_simple_addition(): sum = Money.dollar(5) + Money.dollar(5) bank = Bank() reduced = bank.reduce(sum, 'USD') assert reduced == Money.dollar(10) def test_plug_returns_sum(): five = Money.dollar(5) sum = five + five assert sum.augend == five assert sum.addend == five def test_reduce_sum(): sum = Sum(Money.dollar(3), Money.dollar(4)) bank = Bank() result = bank.reduce(sum, 'USD') assert result == Money.dollar(7) def test_reduce_money(): bank = Bank() result = bank.reduce(Money.dollar(1), 'USD') assert result == Money.dollar(1) def test_reduce_money_different_currency(): bank = Bank() bank.addRate('CHF', 'USD', 2) result = bank.reduce(Money.franc(2), 'USD') assert result == Money.dollar(1) def test_identity_rate(): assert Bank().rate('USD', 'USD') == 1 def test_mixed_addition(): fiveBucks = Money.dollar(5) tenFrancs = Money.franc(10) bank = Bank() bank.addRate('CHF', 'USD', 2) result = bank.reduce(fiveBucks + tenFrancs, 'USD') assert result == Money.dollar(10) def test_sum_plus_money(): fiveBucks = Money.dollar(5) tenFrancs = Money.franc(10) bank = Bank() bank.addRate('CHF', 'USD', 2) sum = Sum(fiveBucks, tenFrancs) + fiveBucks result = bank.reduce(sum, 'USD') assert result == Money.dollar(15) def test_sum_times(): fiveBucks = Money.dollar(5) tenFrancs = Money.franc(10) bank = Bank() bank.addRate('CHF', 'USD', 2) sum = Sum(fiveBucks, tenFrancs) * 2 result = bank.reduce(sum, 'USD') assert result == Money.dollar(20)
9dcb310f50228b38f54e988bfa49f9c2699010d5
thiagolrpinho/solving-problems
/2019_12_31-merge_sorted_lists.py
5,969
4.125
4
''' The question we'll work through is the following: return a new sorted merged list from K sorted lists, each with size N. Before we move on any further, you should take some time to think about the solution! First, go through an example. This buys time, makes sure you understand the problem, and lets you gain some intuition for the problem. For example, if we had [[10, 15, 30], [12, 15, 20], [17, 20, 32]], the result should be [10, 12, 15, 15, 17, 20, 20, 30, 32]. Next, give any solution you can think of (even if it's brute force). It seems obvious that if we just flattened the lists and sorted it, we would get the answer we want. The time complexity for that would be O(KN log KN), since we have K * N total elements. The third step is to think of pseudocode—a high-level solution for the problem. This is where we explore different solutions. The things we are looking for are better space/time complexities but also the difficulty of the implementation. You should be able to finish the solution in 30 minutes. Here, we can see that we only need to look at K elements in each of the lists to find the smallest element initially. Heaps are great for finding the smallest element. Let's say the smallest element is E. Once we get E, we know we're interested in only the next element of the list that held E. Then we'd extract out the second smallest element and etc. The time complexity for this would be O(KN log K), since we remove and append to the heap K * N times. Initialize the heap. In Python this this is just a list. We need K tuples. One for the index for which list among the list of lists the element lives; one for the element index which is where the element lives; and the value of the element. Since we want the key of the heap to be based on the value of the element, we should put that first in the tuple. While the heap is not empty we need to: Extract the minimum element from the heap: (value, list index, element index) If the element index is not at the last index, add the next tuple in the list index. 4. Write the actual code. Ideally, at this point, it should be clear how the code should look like. Here's one example: def merge(lists): merged_list = [] heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst] heapq.heapify(heap) while heap: val, list_ind, element_ind = heapq.heappop(heap) merged_list.append(val) if element_ind + 1 < len(lists[list_ind]): next_tuple = (lists[list_ind][element_ind + 1], list_ind, element_ind + 1) heapq.heappush(heap, next_tuple) return merged_list Think of test cases and run them through your interviewer. This shows that you're willing to test your code and ensure it's robust. I like to think of happy cases and edge cases. Our original example would be a happy case. Edge cases might be. lists is []. lists only contains empty lists: [[], [], []]. lists contains empty lists and non-empty lists: [[], [1], [1,2]]. lists contains one list with one element: [[1]]. lists contains lists of varying size: [[1], [1, 3, 5], [1, 10, 20, 30, 40]]. Finally, the interviewer should ask some follow-up questions. One common question is: what other solutions are there? There's actually another relatively simple solution that would use a divide-and-conquer strategy. We could recursively merge each half of the lists and then combine the two lists. This would have the same asymptotic complexities but would require more "real" memory and time. Doing all these steps will definitely help you crystallize your thought process, grasp the problem better, and show that you are a strong communicator and help you land that job offer! Best of luck! Marc ''' # Started at 11:09 import pytest import heapq @pytest.mark.parametrize( 'lists_of_sorted_lists_and_right_answer', [([[10, 15, 30], [12, 15, 20], [17, 20, 32]], [10, 12, 15, 15, 17, 20, 20, 30, 32])] ) @pytest.mark.parametrize('sorting_function', [("brute_force_sort_lists"), ("heap_sort_lists")]) def test_merge_sort_list(lists_of_sorted_lists_and_right_answer, sorting_function): sorted_list = [] list_of_sorted_lists = lists_of_sorted_lists_and_right_answer[0] right_answer = lists_of_sorted_lists_and_right_answer[1] local_dictionary = locals() exec("sorted_list =" + sorting_function + "(list_of_sorted_lists)", globals(), local_dictionary) sorted_list = local_dictionary['sorted_list'] assert right_answer == sorted_list def flatten_list(list_of_sorted_lists): sorted_list = [] for sublist in list_of_sorted_lists: for item in sublist: sorted_list.append(item) return sorted_list def brute_force_sort_lists(list_of_sorted_lists): sorted_list = [] for sublist in list_of_sorted_lists: for item in sublist: sorted_list.append(item) sorted_list.sort() return sorted_list def heap_sort_lists(list_of_sorted_lists): ''' Takes a lists of sorted lists and returns a single element with all elements sorted ''' heap = [] final_sorted_list = [] heap = [ (sublist[0], list_index, 0) for list_index, sublist in enumerate(list_of_sorted_lists) if sublist] print(heap) heapq.heapify(heap) # Here we have a heap with the first elements of each sublist while heap: # Now we have to pop the smaller element of the heap item, list_index, item_index = heapq.heappop(heap) final_sorted_list.append(item) # Then for each element we take we look for other inside that element initial sublist # Till they're over if item_index + 1 < len(list_of_sorted_lists[list_index]): next_tuple = (list_of_sorted_lists[list_index][item_index+1], list_index, item_index+1) heapq.heappush(heap, next_tuple) return final_sorted_list
bcc3e360323d6e27bdf2046c7d719db9cc8cf403
rakesh2827/Rakesh_python_lab
/week3_c.py
235
4.28125
4
def factorial(num): fact = 1 for i in range(1, num + 1): fact = fact * i return fact number=int(input(" enter any Number to find factorial :")) factof= factorial(number) print("factorial is:" ,factof)
7611dae3167e7e36288d4aee2e4d56342b1f2d2d
why1679158278/python-stu
/python资料/day8.15/day12/exercise03.py
845
3.984375
4
""" day10/exercise01 day10/exercise03 直接打印商品对象: xx的编号是xx,单价是xx 直接打印敌人对象: xx的攻击力是xx,血量是xx 拷贝两个对象,修改拷贝前数据,打印拷贝后数据. 体会拷贝的价值. """ class Commodity: def __init__(self, cid=0, name="", price=0): self.cid = cid self.name = name self.price = price def __str__(self): return "%s的编号是%d,单价是%d" % (self.name, self.cid, self.price) def __repr__(self): return "Commodity(%d, '%s', %d)" % (self.cid, self.name, self.price) class Enemy: def __init__(self, name="", atk=0, hp=0): self.name = name self.atk = atk self.hp = hp bxjg = Commodity(1001, "变形金刚", 300) print(bxjg) bxjg2 = eval(bxjg.__repr__()) print(bxjg2)
464574dd981dc1b91f191c6f4aa87e47d32e3d15
ImtiazMalek/PythonTasks
/GuessGame.py
349
3.9375
4
counter=0 limit = int(input('How many time you wanna guess? :')) correct_word = 'panda' check =False #taking the guesses while counter<limit: guess=input('Guess a word: ') if guess == correct_word: check=True break counter+=1 #checking the boolean if check: print('You win') else: print('You lose')
cd9a279c36fb98d4691eae227e88b7dcd4c4662c
UvinduW/Smart-Dots
/smart_dots.py
19,164
4.0625
4
# smart_dots.py # Created: 27/07/2018 # Author: Uvindu Wijesinghe # # Description: # This code is a Python implementation of the "Smart Dots" example/tutorial done by Code Bullet. He used the # Processing language to build his version. You can view his detailed tutorial and project at: # YouTube: https://www.youtube.com/watch?v=BOZfhUcNiqk&index=19&list=WL&t=0s # GitHub: https://github.com/Code-Bullet/Smart-Dots-Genetic-Algorithm-Tutorial # # A genetic algorithm that attempts to get a swarm of dots from the start point to the end goal in the least number # of steps. # In each iteration of the algorithm, a new generation of dots are bread from the previous generation and mutations # are introduced in the process to enhance genetic variety. Each parent dot will have a fitness value which is a # measure of its performance and the offspring are more likely to get their "genes" from a parent with a higher # fitness than a lower fitness. The offspring dot is generated by cloning a selected parent dot, and then introducing # mutations with a specified probability (currently set to 1%) # # The "genes" are actually acceleration vectors. Each dot has a "brain" which holds 400 acceleration vectors which # specify the direction should accelerate in at each step. It's these vectors that get cloned, mutated and eventually # optimised by the algorithm so that they end up holding the necessary vectors to direct the dot from start to finish. # The algorithm rewards dots with a fitness score such that the highest rewards are achieved by dots that get to the # goal (with a higher reward for fewer steps). For the dots that didn't get there, the dots that got closest get a # higher score, but they won't be higher than dots that managed to reach the goal. # # The Population class holds all the dots in the swarm. Each dot is an instantiation of the Dot class, which holds the # attributes for each dot. Each dot has a brain, which is an instantiation of the Brain class. The brain holds all the # direction vectors for that specific dot and a keeps track of the number of steps the dot has taken (and therefore # which direction it needs to retrieve next from its list of direction vectors). The brain holds 400 direction vectors. # # Usage: # Simply run the script and watch the swarm improve in each iteration # You can alter the configurables given below to alter the behaviour of the script and algorithm # PyGame handles the on-screen graphics import pygame # Numpy handles the array manipulation import numpy as np # Gauss used to generate random vectors and uniform used to select parents from random import gauss, seed, uniform # Sleep used to set the frame rate and time used to do timing analysis for debugging from time import sleep, time # Configurables swarm_size = 50 # Number of dots in the swarm - as this increases, time taken to start new iteration increases mutation_rate = 0.01 # Sets the likelihood of a gene/vector getting randomly mutated when generating offspring dot_max_velocity = 15 # Velocity limit for each dot - if too high it can overshoot the goal or get embedded in barrier frame_rate = 100 # Frequency of screen redraw - also increases algorithm call rate (dots appear to move faster) # Initialise screen screen = 0 # Define screen resolution height = 800 width = 1600 # Define rectangle sizes rect_1 = (0, 200, width/2.5, 50) rect_2 = (width/2, 500, width, 50) # Define goal goal = np.array([20, width/2], dtype=np.int64) # Define some colours black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) darkBlue = (0, 0, 128) grey = (192, 192, 192) # Stat Trackers dead_count = 0 goal_count = 0 class Brain: def __init__(self, size): # This function runs when class gets initialised # Series of vectors which get the dot to the goal self.directions = np.zeros((size, 2)) # Record of how many steps have been taken so far self.step = 0 # Randomize the initialised array with random vectors self.randomize() def randomize(self): # Generate a random unit vector for each vector in directions for i in range(self.directions.__len__()): # Generate a random vector seed(time()) vec = np.array([gauss(0, 1), gauss(0, 1)]) # Get magnitude of vector using pythagoras mag = (vec**2).sum()**0.5 # Divide vector by magnitude to get unit vector self.directions[i] = vec/mag def clone(self): # Return a copy of the current brain object with identical direction vectors # The direction vectors are analogous to genes # Create an instance of this class clone_brain = Brain(self.directions.__len__()) # Copy over the direction vectors to the cloned brain np.copyto(clone_brain.directions, self.directions) return clone_brain def mutate(self): # Mutates the brain by randomizing some of the vectors for i in range(self.directions.__len__()): # Iterate through all the vectors in directions # Generate a random number between 0 and 1 (all numbers equally likely) rand = uniform(0, 1) # If the number generated is lower than mutation rate, then the vector should be mutated if rand < mutation_rate: # Set this direction to be a random direction # Generate a random vector seed(time()) vec = np.array([gauss(0, 1), gauss(0, 1)]) # Get magnitude of vector using pythagoras mag = (vec ** 2).sum() ** 0.5 # Divide vector by magnitude to get unit vector self.directions[i] = vec / mag class Dot: def __init__(self): # Will hold all the directions (analogous to genes) for this dot self.brain = Brain(400) # A vector holding the current position, initialised to where all dots should start from self.pos = np.array([height - 125, width * 0.95]) # A vector to hold the velocity of the dot self.vel = np.array([0, 0], dtype=np.float64) # A vector to hold the acceleration of the dot self.acc = np.array([0, 0], dtype=np.float64) # Is the dot still active, or dead? self.dead = 0 # Fitness measures how well the dot performed (closer to the target or fewer steps yield higher fitness) self.fitness = 0 # Has the dot reach the goal? self.reached_goal = 0 # Set to 1 if this dot is the best dot in the swarm self.is_best = 0 def show(self, display_screen): # Draw this dot on the screen if self.is_best: # If this dot is the best, draw it in green pygame.draw.circle(display_screen, green, (self.pos.astype(int)[1], self.pos.astype(int)[0]), 10, 0) else: # If this is not the best, then draw it in red pygame.draw.circle(display_screen, red, (self.pos.astype(int)[1], self.pos.astype(int)[0]), 10, 0) def move(self): global dead_count if self.brain.directions.__len__() > self.brain.step: # If there are directions left set the acceleration as the next vector in the directions array self.acc = self.brain.directions[self.brain.step] # Increment the step counter to retrieve the next direction vector in the next iteration self.brain.step += 1 else: # If the end of directions array has been reached, the dot is dead self.dead = 1 dead_count += 1 print("Out of moves") # Update velocity self.vel += self.acc # Limit the magnitude of velocity to 15 (tweakable - too high and dot can be embedded in barrier and not edge) velocity_mag = (self.vel**2).sum()**0.5 if velocity_mag > dot_max_velocity: self.vel = dot_max_velocity * self.vel / velocity_mag # Update position self.pos += self.vel def update(self): global dead_count global goal_count # Call the move function and check for collisions if (not self.dead) and (not self.reached_goal): # Move if the dot is still within the window and hasn't reached the goal self.move() if self.pos[0] < 2 or self.pos[1] < 2 or self.pos[0] > (height - 2) or self.pos[1] > (width - 2): # Dot is dead if it reached within 2 pixels of the edge of the window self.dead = 1 dead_count += 1 # print("Out of bounds") elif np.linalg.norm(goal - self.pos) < 20: # If the dot reached the goal self.reached_goal = 1 goal_count += 1 elif rect_1[1] < self.pos[0] < (rect_1[1] + rect_1[3]) and rect_1[0] < self.pos[1] < ( rect_1[0] + rect_1[2]): # If the dot hits the first rectangle self.dead = 1 dead_count += 1 elif rect_2[1] < self.pos[0] < (rect_2[1] + rect_2[3]) and rect_2[0] < self.pos[1] < ( rect_2[0] + rect_2[2]): # If the dot hits the second rectangle self.dead = 1 dead_count += 1 def calculate_fitness(self): # Calculate fitness, with a higher value being assigned for better performing dots # Preference given to dots that reached goal, over dots that came close but died if self.reached_goal: # If the dot reached the goal then the fitness is based on the amount of steps it took to get there self.fitness = 1.0/16.0 + 1000.0/(self.brain.step**2) else: # If the dot didn't reach the goal then the fitness is based on how close it is to the goal distance_to_goal = np.linalg.norm(goal - self.pos) self.fitness = 1/(distance_to_goal ** 2) def get_baby(self): # Clone the parent baby = Dot() # Babies have the same brain as their parent baby.brain = self.brain.clone() return baby class Population: def __init__(self, size): # Sum of all population fitnesses combined self.fitness_sum = 0 # Keep track of population generation self.gen = 1 # Index of the best performing dot self.best_dot = 0 # Min number of steps taken by a dot to reach the goal self.min_step = 400 # Array to hold all the dots in the population self.dots = np.zeros(size, dtype=object) # Assign the dot object to each element for i in range(size): self.dots[i] = Dot() def show(self, display_screen): # Show all the dots on the screen for i in range(1, self.dots.__len__()): self.dots[i].show(display_screen) # To Check: Why is the best dot shown separately self.dots[0].show(display_screen) def update(self): global dead_count # Update all dots with their new positions for i in range(self.dots.__len__()): if self.dots[i].brain.step > self.min_step: # If the dots have exceeded the minimum number of steps, then they should be killed self.dots[i].dead = 1 dead_count += 1 else: # Update the dots with their new positions self.dots[i].update() def calculate_fitness(self): # Calculate the fitness values for each of the dots for i in range(self.dots.__len__()): self.dots[i].calculate_fitness() def all_dots_dead(self): # Check if all the dots are dead or have reached the goal already (i.e. no dots active) for i in range(self.dots.__len__()): if (not self.dots[i].dead) and (not self.dots[i].reached_goal): return 0 return 1 def natural_selection(self): # Gets the next generation of dots # New array of dots for babies new_dots = np.zeros(self.dots.__len__(), dtype=object) # Find and set the best dot in current population self.set_best_dot() # Let the best dot live without getting mutated new_dots[0] = self.dots[self.best_dot].get_baby() new_dots[0].is_best = 1 # Calculate the sum of all the fitness values self.calculate_fitness_sum() baby_time = 0 # temp variable to measure processing times for i in range(1, new_dots.__len__()): # Set each element in the array to a Dot() object new_dots[i] = Dot() # Select parent based on fitness parent = self.select_parent() # Get baby from them wait_time = time() # temp variable to measure processing times new_dots[i] = parent.get_baby() baby_time += time() - wait_time # temp variable to measure processing times print("Baby: ", baby_time) # temp: print processing time to get babies # Set the current dots to be the new baby dots self.dots = new_dots # Increment generation counter self.gen += 1 def calculate_fitness_sum(self): self.fitness_sum = 0 for i in range(self.dots.__len__()): self.fitness_sum += self.dots[i].fitness def select_parent(self): # Chooses dot from the population to return randomly(considering fitness) # this function works by randomly choosing a value between 0 and the sum of all the fitnesses then go # through all the dots and add their fitness to a running sum and if that sum is greater than the random # value generated that dot is chosen since dots with a higher fitness function add more to the running # sum then they have a higher chance of being chosen # Get a random number that is within the range of fitness_sum rand = uniform(0, self.fitness_sum) running_sum = 0 # Go through the fitnesses, and when the running sum exceeds rand, return the dot at which this occurred for i in range(self.dots.__len__()): running_sum += self.dots[i].fitness if running_sum > rand: return self.dots[i] # Should never get to this point return 0 def mutate_babies(self): # Mutates the brains of all the babies for i in range(1, self.dots.__len__()): self.dots[i].brain.mutate() def set_best_dot(self): # Finds the dot with the highest fitness, and sets it as the best dot max_fitness = 0 max_index = 0 for i in range(self.dots.__len__()): if self.dots[i].fitness > max_fitness: max_fitness = self.dots[i].fitness max_index = i self.best_dot = max_index # If the best dot reached the goal, then reset min number of steps needed to reach goal if self.dots[self.best_dot].reached_goal: self.min_step = self.dots[self.best_dot].brain.step def draw_static_objects(): # Draw 2 rectangle pygame.draw.rect(screen, white, rect_1, 0) pygame.draw.rect(screen, white, rect_2, 0) # Draw goal dot in blue pygame.draw.circle(screen, blue, (goal[1], goal[0]), 10, 0) def main(): # This function controls the whole script. First, it initialises PyGame and the swarm of dots # It has a loop which redraws the screen on each iteration and calls the necessary functions to update the # positions of dots and perform the natural selection and breeding when generating the next generation global screen global dead_count global goal_count # initialize the PyGame module pygame.init() pygame.display.set_caption("Smart Dots") # create a surface on screen that has the size of 240 x 180 screen = pygame.display.set_mode((width, height)) # Initialise fonts pygame.font.init() gen_font = pygame.font.SysFont('Calibri', 50, True) credit_font = pygame.font.SysFont('Calibri', 20, True) # Set screen colour screen.fill(black) # Draw rectangles draw_static_objects() # Create the swarm of dots swarm = Population(swarm_size) # define a variable to control the main loop running = True # Track the number of moves moves = 0 # main loop while running: # Increment number of iterations of this loop moves += 1 # Reset window with a black colour screen.fill(black) # Draw the rectangles and goal draw_static_objects() # Draw label to show current generation gen_label = gen_font.render("GEN: " + str(swarm.gen), False, grey) screen.blit(gen_label, (width/2, height/2)) # Draw label to show credits credit_label = credit_font.render("Uvindu Wijesinghe (2018)", False, grey) screen.blit(credit_label, (width/2, height - 20)) if swarm.all_dots_dead(): # If all the dots are dead perform genetic algorithm # Update the screen to show the last position of dots pygame.display.update() # Print the number of moves taken by this generation print("Moves: ", moves) # Reset trackers moves = 0 dead_count = 0 goal_count = 0 # Perform genetic algorithms swarm.calculate_fitness() swarm.natural_selection() swarm.mutate_babies() else: # Update the dots' positions and status swarm.update() # Draw the dots on the screen swarm.show(screen) # Print stats on dots that reached the goal or got killed print("Reached Goal: ", goal_count, " Dead: ", dead_count) # Redraw the screen pygame.display.update() # Sleep for 10 ms (yielding ~ 100 FPS) sleep(1/frame_rate) # event handling, gets all event from the event queue for event in pygame.event.get(): # only do something if the event is of type QUIT if event.type == pygame.QUIT: # change the value to False, to exit the main loop running = False # run the main function only if this module is executed as the main script # (if you import this as a module then nothing is executed) if __name__ == "__main__": # call the main function main()
ffa2064a19e8bc0c5344176cdcb4415e064cc5b9
dayalnigam/-Python-Development-Intern
/q.6.py
203
4.0625
4
#q.6: Write a Python program to convert an array to an array of machine values and return the bytes representation. from array import * x = array('b', [1, 2, 3, 4, 5, 6]) s = x.tobytes() print(s)
7b00e3881325330c435b44fede2d39d3d25f2980
southwall93/pycharm_project1
/05If/06while.py
462
3.765625
4
#숫자를 계속 더해서 더한 숫자가 100보다 커지면 빠져나가서 출력 i=1 sum=0 while True: sum+=i i+=1 if sum>100: print("i: ",i-1) print("sum: ", sum) break #1~10 출력 홀수만 출력 #1부터 시작하면서 2씩 증가 i=1 while True: print(i) i+=2 if i>10: break i=1 while True: if i%2==0: i += 1 continue if i>10: break print(i) i+=1
e8b1a40ce25339f694dab3fc00dad0dc48988345
mohdjahid/Python
/Data types/String.py
166
3.890625
4
str="Hello,World!"; print(str); #Hello,World! print(str[0]); #H print(str[2:5]); #llo print(str[2:]); #llo,World! print(str*2); #Hello,World!Hello,World!
f13f45c0e9ac00a422fea0082ec765ccb137e58f
adriancarriger/experiments
/udacity/self-driving-intro/3-working-with-matrices/3/36.py
1,433
4.6875
5
# TODO: Write a function called inverse_matrix() that # receives a matrix and outputs the inverse ### # You are provided with start code that checks # if the matrix is square and if not, throws an error ### # You will also need to check the size of the matrix. # The formula for a 1x1 matrix and 2x2 matrix are different, # so your solution will need to take this into account. ### # If the user inputs a non-invertible 2x2 matrix or a matrix # of size 3 x 3 or greater, the function should raise an # error. A non-invertible # 2x2 matrix has ad-bc = 0 as discussed in the lesson ### # Python has various options for raising errors ### raise RuntimeError('this is the error message') ### raise NotImplementedError('this functionality is not implemented') ### raise ValueError('The denominator of a fraction cannot be zero') def inverse_matrix(matrix): inverse = [] if len(matrix) != len(matrix[0]): raise ValueError('The matrix must be square') if len(matrix) > 2: raise ValueError('The matrix cannot be greater than 2') if len(matrix) == 1: inverse.append([1 / matrix[0][0]]) # TODO: Check if matrix is 1x1 or 2x2. # Depending on the matrix size, the formula for calculating # the inverse is different. # If the matrix is 2x2, check that the matrix is invertible # TODO: Calculate the inverse of the square 1x1 or 2x2 matrix. return inverse
e979009432f7830312be1ba93b8cc0b229167957
reyeskevin9767/modern-python-bootcamp-2018
/12-lists/06-accessing-values-exercise/app.py
561
4.09375
4
# * Accessing List Data Exercise people = ['Hanna', 'Louisa', 'Claudia', 'Angela', 'Geoffrey', 'aparna'] # Change 'Hanna' to 'Hanna' people[0] = 'Hannah' # Change 'Geoffrey' to 'Jeffrey' people[4] = 'Jeffrey' # Change 'aparna' to 'Aparna' (capitalize it) people[-1] = 'Aparna' print(people) # ['Hannah', 'Louisa', 'Claudia', 'Angela', 'Jeffrey', 'Aparna'] numbers = [1, 2, 3, 4] for number in numbers: print(number) # 1 # 2 # 3 # 4 numbers_two = [1, 2, 3, 4] i = 0 while i < len(numbers_two): print(numbers_two[i]) i += 1 # 1 # 2 # 3 # 4
1d0adab6dfcd38391b6b05800fcd4d6ee7350601
npkhang99/Competitive-Programming
/Codeforces/101473A.py
175
3.71875
4
a, b, c = [int(i) for i in input().split()] if a == b == c: print("*") elif a == b and b != c: print("C") elif a == c and c != b: print("B") else: print("A")
0af09bb616b0adadb3e7baf150626414216a8fa7
rexelit58/python
/2.Advanced/10.Nested_Classes_Nested_Methods.py
494
3.875
4
class Person: def __init__(self,name,dd,mm,yyyy): self.name=name self.dob = self.DOB(dd,mm,yyyy) def display(self): print("Name:",self.name) self.dob.display() class DOB: def __init__(self,dd,mm,yyyy): self.dd = dd self.mm=mm self.yyyy=yyyy def display(self): print("Date of Birth:{}/{}/{}".format(self.dd,self.mm,self.yyyy)) p = Person("Sunny",25,5,2001) p.display() p.dob.display()
17071c25dc46e353dc4005a096688e211c765c14
MareikeJaniak/PFB_ProblemSets
/ProblemSets/Python5/sets_practice.py
309
3.796875
4
#!/usr/bin/env python3 mySet = {'3','14','15','9','26','5','35','9'} mySet2 = {'60','22','14','0','9'} print('intersection: ',mySet.intersection(mySet2)) print('difference: ',mySet.difference(mySet2)) print('union: ',mySet.union(mySet2)) print('symmetrical difference: ',mySet.symmetric_difference(mySet2))
b12d08cd128542602f885f541b89f64c1482abe1
jonte450/Hackerrank
/Python/Electronic_shop.py
899
3.828125
4
#!/bin/python from __future__ import print_function import os import sys # # Complete the getMoneySpent function below. # def getMoneySpent(keyboards, drives, b): answer = -1; for key in keyboards: for driv in drives: tot_sum = key + driv; if tot_sum <= b: answer = max(answer,tot_sum); return answer; if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') bnm = raw_input().split() b = int(bnm[0]) n = int(bnm[1]) m = int(bnm[2]) keyboards = map(int, raw_input().rstrip().split()) drives = map(int, raw_input().rstrip().split()) # # The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items # moneySpent = getMoneySpent(keyboards, drives, b) fptr.write(str(moneySpent) + '\n') fptr.close()
d546b1b4faa7cabe233755a66b781709067db259
sasha-n17/python_homeworks
/homework_3/task_2.py
639
3.765625
4
def personal_info(name, surname, year_of_birth, town, email, phone_number): info = [name, surname, year_of_birth, town, email, phone_number] return ' '.join(info) print(personal_info(surname=input('Введите фамилию: '), name=input('Введите имя: '), town=input('Введите город: '), phone_number=input('Введите номер телефона: '), year_of_birth=input('Введите год рождения: '), email=input('Введите адрес электронной почты: ')))
389f9ec59a9ae91c3fdad6556e28a050dfd70d94
HITESH-235/PYTHON-2
/2.17.Indexing_lists.py
383
3.875
4
# 0th 1st 2nd 3rd 4th 5th THIS I HOW INDEXING WORKS WHEN "[x:y]"(colon) is used(line 10) # +0th +1st +2nd +3rd +4th POSITIVE INDEXING(line 8) x = ["apple", 1 ,"banana", 2 ,"mango"] # -1th -2st -3nd -4rd -5th NEGATIVE INDEXING(line 12) print(x[4]) #POSITIVE INDEXING print(x[0:3]) print(x[-3]) #NEGATIVE INDEXING
1dad52df74b27ce57abf6cb539efcd9c74d5e65c
TCReaper/Computing
/Computing Revision/Computing Quizzes/The Folder/TD01 - Jit/JIT/T1.py
2,257
4.09375
4
# 2017 - Term 1 - SH2 Computing Practical Lecture Test # Code for Task 1 from random import random #ASKING FOR PLAYER NAME ============================================ name_p = str(input("Please enter your name:")) name_p = name_p.strip() while True: try: name_p = int(name_p) print("Illegal name; Please only use letters and/or spaces") name_p = str(input("Please enter your name:")) except ValueError: #print("\n") break def quiz(): #QUIZZING===================================================================== no_qns = 0 score = 0 while no_qns != 10: no_qns += 1 while True: t1 = int((random())*100) t2 = int((random())*100) if t2 < t1: break else: pass ans_c = t1 - t2 while True: try: ans = int(input("Q" + str(no_qns) + ") What is " + str(t1) + " - " + str(t2)+ " equals to:")) break except ValueError: print("Please enter a positive integer as your answer\n") if ans == ans_c: print("Correct!", end = "") score += 1 else: print("Incorrect!", end = "") print(str(t1) + " - " + str(t2) + " = " + str(ans_c) + "\n\n") #RESULTS & SCORES======================================================================== print(name_p + ", your final score is: " + str(score) + " / 10") grade = {1:"U",2:"U", 3:"U", 4:"U", 5:"D", 6:"C+", 7:"B+", 8:"A", 9:"A+", 10:"A+"} print("Your grade is " + grade[score]+ "\n") #RETRY & QUIT===================================================================== print("Please select an option:") while True: try: user_opt = int(input("1: Play another round\n2: Quit\n")) if user_opt == 1 or user_opt == 2: break else: print("Please enter either a \"1\" or \"2\".") except ValueError: print("Invalid input, please select either \"1\" or \"2\".") if user_opt == 2: exit() elif user_opt == 1: print("Sure! Let's start from the top!") quiz() quiz()
30fc31ac54d5e838e57cbbe3be4681d9af010e7f
willnien10005914/VPA
/tf.py
14,630
4.0625
4
import math import statistics import pandas as pd import numpy as np """ 台北第一期 """ def Deviation(X): N = 0 sum = 0 avg = 0 result = 0 for i in X: N += 1 sum += i avg = sum / N for i in X: result += (i - avg) * (i - avg) result = result / (N - 1) return math.sqrt(result) def Fibonacci_recursive(n): if (n < 2): return n else: return Fibonacci_recursive(n - 1) + Fibonacci_recursive(n - 2) """ 台北第二期 """ def Derivative(f, x, h=0.01): return (f(x + h / 2) - f(x - h / 2)) / h def Square(x): return x * x def Derivative_g(x, n, h=0.01): if (n == 0): ret = g(x) else: ret = (Derivative_g(x + h / 2, n - 1) - Derivative_g(x - h / 2, n - 1 )) / h return ret def g(x): """ g(x) = f1 + f2 f1 = 2^x f2 = 2 * x^7 """ f1 = 1 f2 = 1 for i in range(int(x)): f1 *= 2 for i in range(7): f2 *= x f2 *= 2 return f1 + f2 def Taylor_Reminder(a, x, n): factorial = 1 x_pow = 1 for j in range(n + 1): factorial *= (j + 1) x_pow *= (x - a) # c between x and a c = 0.01 return (Derivative_g(c, n + 1) * (x_pow)) / factorial def Taylor_Expansion(a, x, n): ret = g(a) for i in range(n): factorial = 1 x_pow = 1 for j in range(i + 1): factorial *= (j + 1) x_pow *= (x - a) ret += ((Derivative_g(a, i + 1) * x_pow) / factorial) return ret + Taylor_Reminder(a, x, n) """ 台北第三期 """ def MinMaxScaler(data): ret = [] min = Min(data) max = Max(data) for i in data: ret.append((i - min) / (max - min)) return ret def Min(data): ret = data[0] for i in range(1, len(data)): if ret > data[i]: ret = data[i] return ret def Max(data): ret = data[0] for i in range(1, len(data)): if ret < data[i]: ret = data[i] return ret def PassFail(grades): if grades is None: return False start = 0 end = len(grades) status = [] while (start < end): if grades[start] >= 60: status.append('Pass') else: status.append('Fail') start += 1 return status def MagicSquare(data): sum_r = 0 sum_c = 0 sum_d = 0 if row_sum_check(data) is True and column_sum_check(data) is True and diagonal_sum_check(data) is True: for row in range(len(data)): sum_r += data[0][row] sum_c += data[row][0] sum_d += data[row][row] if sum_r == sum_c == sum_d: return True else: return False else: return False def row_sum_check(data): r_len = len(data) c_len = len(data[0]) ret = [0,]*r_len i = 0 for r in range(r_len): for c in range(c_len): ret[i] += data[r][c] i += 1 for i in range(len(ret) - 1): if ret[i] != ret[i+1]: return False return True def column_sum_check(data): r_len = len(data) c_len = len(data[0]) ret = [0,]*c_len i = 0 for c in range(c_len): for r in range(r_len): ret[i] += data[r][c] i += 1 for i in range(len(ret) - 1): if ret[i] != ret[i+1]: return False return True def diagonal_sum_check(data): d = [0,]*2 length = len(data) - 1 i = 0 for row in range(len(data)): d[0] += data[row][i] d[1] += data[row][length - i] i += 1 for i in range(len(d) - 1): if d[i] != d[i+1]: return False return True """ 新竹第三期 """ def Fibonacci(n): t1 = 0 t2 = 1 for i in range(n): next = t1 + t2 t1 = t2 t2 = next return t1 def reverse(data): i = 0 c = 0 for i in range(len(data) // 2): c = data[i] data[i] = data[len(data) - i - 1] data[len(data) - i - 1] = c return data def func1(x, i, j): a = x[i] x[i] = x[j] x[j] = a def func2(data): for i in range(len(data) - 1): for j in range(len(data) - 1 - i): if data[j] > data[j+1]: func1(data, j, j + 1) return data def pair(data, target): for i in range(len(data)): for j in range(i + 1, len(data)): if data[i] + data[j] == target: return [i, j] return None """ 台北第四期 """ def swap(i, j, data): tmp = data[i] data[i] = data[j] data[j] = tmp def reverse_1(data): for i in range(len(data) // 2): swap(i, len(data) - 1 - i, data) return data def Function_3(x): if x > 0: return x else: return x / 100 def Function_4(data): return [Max(data), Min(data)] def Function_5(data): return MinMaxScaler(data) def MSE(y, y_hat): sum = 0 for i in range(len(y)): sum += ((y[i] - y_hat[i]) * (y[i] - y_hat[i])) return sum/(len(y) - 1) def roman_numerals(num): values = [100, 90, 50, 40, 10, 9, 5, 4, 1] symbols = ['C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] list = [] for i in range(len(values)): for j in range(int(num / values[i])): list.append(symbols[i]) num = num % values[i] return list def RLE(list): rle = [] previous = list[0] count = 1 for i in range(1, len(list)): if previous == list[i]: count += 1 else: rle.append(count) rle.append(previous) count = 1 previous = list[i] rle.append(count) rle.append(previous) return rle def ngram(list, n): ret = [] if len(list) <= n: return list for i in range(len(list) - (n - 1)): tmp = [] for j in range(0, n): tmp.append(list[i + j]) ret.insert(i, tmp) del tmp return ret def similarity(s1, s2, n): ns1 = ngram(s1, n) ns2 = ngram(s2, n) count = 0 for i in range(len(ns1)): for j in range(len(ns2)): if ns1[i] == ns2[j]: count += 1 return (2 * count) / (len(ns1) + len(ns2)) def Statistics(d): df = pd.DataFrame(d) #print(df['x'].value_counts(sort=False)) #print(df.describe()) #print("var = %.2f"%df.var()) Q1 = np.percentile(df['x'], 25, interpolation='midpoint') Q3 = np.percentile(df['x'], 75) IQR = Q3 - Q1 lower_inner_fence = Q1 - (1.5 * IQR) upper_inner_fence = Q3 + (1.5 * IQR) print("numpy pr 25 (Q1) : %.2f" % Q1) print("numpy pr IQR : %.2f" % IQR) print("numpy pr 75 (Q3) : %.2f" % Q3) print("lower_inner_fence : %.2f" % lower_inner_fence) print("upper_inner_fence: %.2f\n" % upper_inner_fence) outlier_count = 0 for i in df['x']: if i > upper_inner_fence or i < lower_inner_fence: outlier_count += 1 print("found outlier : %d" % i) print("outlier count : %d\n" % outlier_count) print("statistics mean : %.2f" % statistics.mean(df['x'])) print("statistics stdev : %.2f"%statistics.stdev(df['x'])) print("statistics median : %.2f" % statistics.median(df['x'])) print("statistics mode : %.2f" % statistics.mode(df['x'])) print("statistics var : %.2f" % statistics.variance(df['x'])) if statistics.mean(df['x']) < statistics.median(df['x']) and statistics.median(df['x']) < statistics.mode(df['x']) : print("=> left skewed distribution") if statistics.mean(df['x']) > statistics.median(df['x']) and statistics.median(df['x']) > statistics.mode(df['x']) : print("=> right skewed distribution") def Derangement(n): if (n == 1): return 0 if (n == 0): return 1 if (n == 2): return 1 return (n - 1) * (Derangement(n - 1) + Derangement(n - 2)) def findStep(n): if (n == 1 or n == 0): return 1 elif (n == 2): return 2 else: return findStep(n - 2) + findStep(n - 1) """ with step 3 option return findStep(n - 3) + findStep(n - 2) + findStep(n - 1) """ def ZscoreToX(mean, std, z): x = (z * std) + mean return x def getPBA(PA, PB, PAB): intersection = PAB * PB return intersection / PA def BayesRule(target, PA, PBA): sum = 0 for i in range(len(PA)): sum += (PA[i] * PBA[i]) return (PA[target] * PBA[target]) / sum def P(n): return 1 / ((n + 1) * (n + 2)) def BayesRule_1(PA, PB): p_target_event = 0 p_known_event = 0 for i in PA: p_target_event += P(i) for i in PB: p_known_event += P(i) return p_target_event / p_known_event def main(): print("================程式題================================\n") print("%s" % "台北第一期 :") print("1. Compute the Formula for standard deviation :") test_array = [20, 3, 3, -3, -3] #print("\tVerify deviation by stdev : %f" % statistics.stdev(test_array)) print("\tDeviation is '%f' in test_array%s\n" % (Deviation(test_array), test_array)) print("2. Consider Fibonacci numbers :") test_index = 30 print("\tFibonacci_recursive(%d) = %d\n" % (test_index, Fibonacci_recursive(test_index))) print("\n%s" % "台北第二期 :") print("1. Create a custom function, Derivative() :") test_f = Square test_x = 3 print("\tDerivative : %d\n" % Derivative(test_f, test_x)) print("2. Try to create Taylor_Expansion() :") a = 0 x = 3 n = 7 ans_g = g(x) ans_g_taylor = Taylor_Expansion(a, x, n) err = ((ans_g - ans_g_taylor) / ans_g) * 100 print("\tg(%d) = %.2f, Taylor_Expansion(%d) = %.2f, err = %.2f%%\n" % (x, ans_g, x, ans_g_taylor, err)) print("\n%s" % "台北第三期 :") print("1. Create a function and named it MinMaxScaler :") test_arr = [4, 9, 3, 10, 0, 2] print("\tMinMaxScaler : %s\n" % MinMaxScaler(test_arr)) print("2. Debug PassFail function :") test_grades = [10, 60, 59, 100] print("\tPassFail %s : %s\n" % (test_grades, PassFail(test_grades))) print("3. Create a function and named it MagicSquare :") test_arr = [[2, 7, 6], [9, 5, 1], [4, 3, 8]] print("\tMagicSquare %s : %s\n" % (test_arr, MagicSquare(test_arr))) print("\n%s" % "新竹第三期 :") print("1. Please finish the Fibonacci function :") print("\tFibonacci(%d) = '%d'\n" % (test_index, Fibonacci(test_index))) print("2. Please finish the reverse function :") test_arr = [5, 7, 9, 1, 3, 4] print("\treverse(%s) =" % test_arr, end='') print("\t%s\n" % reverse(test_arr)) print("3. Please write down the result of the following lines :") test_arr = [6, 5, 1, 8, 13, 22, 9, 1] print("\t%s\n" % func2(test_arr)) print("4. Write a function which satisfies following rules :") test_arr = [3, 6, 2, 5, 9, 1] print("\t%s\n" % pair(test_arr, 10)) print("\n%s" % "台北第四期 :") print("1. Given two integers i, j and a list :") test_arr = ['A', 'I', 'A', 'o', 'T', 'e', 'm', 'o', 'c', 'l', 'e', 'W'] print("\treverse_1(%s) =" % test_arr) print("\t\t\t %s\n" % reverse_1(test_arr)) test_data = 5 print("\tFunction_3(%d) = '%d'" % (test_data, Function_3(test_data))) test_data = -5 print("\tFunction_3(%d) = '%.2f'" % (test_data, Function_3(test_data))) test_arr = [3, 16, 11, 5, 28] print("\tFunction_4(%s) = '%s'" % (test_arr, Function_4(test_arr))) test_arr = [1, 2, 3] print("\tFunction_5(%s) = '%s'" % (test_arr, Function_5(test_arr))) test_arr = [2, 4, 6, 8, 10] print("\tFunction_5(%s) = '%s'\n" % (test_arr, Function_5(test_arr))) y = [1, 2, 3, 4, 5, 6, 6] y_hat = [1, 2, 3, 4, 5, 6, 7] print("\tMSE() = '%.2f'\n" % (MSE(y, y_hat))) print("2-1. Roman numerals are represented y seven different symbols :") test_data = 388 print("\troman_numerals(%d) =%s\n" % (test_data, roman_numerals(test_data))) print("2-2. Run-length encoding (RLE) :") test_arr = ['L', 'X', 'X', 'X', 'V', 'I', 'I'] print("\tRLE(%s) =%s\n" % (test_arr, RLE(test_arr))) print("2-3. Please write a function that returns the n-gram :") test_arr = ['A', 'I', 'A', 'C', 'A', 'D', 'E', 'M', 'Y'] n = 4 print("\tn-gram(%s) =%s\n" % (test_arr, ngram(test_arr, n))) print("2-4. Please write a function that returns the similarity :") s1 = ['H', 'O', 'N', 'E', 'Y'] s2 = ['L', 'E', 'M', 'O', 'N'] n = 2 print("\tsimilarity(%s, %s, %d) = %.2f\n" % (s1, s2, n, similarity(s1, s2, n))) print("\n================機率與統計題================================\n") print("上課講義 Example 7 : ") n = 4 print("Derangement(%d) = %d" % (n, Derangement(n))) print("\n上課講義 Example 8 : ") n = 10 print("findStep(%d) = %d" % (n, findStep(n))) print("\n台北第一期第18題 :") d = { 'x': pd.Series([ 0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 7, 8, ]) } Statistics(d) print("\n台北第一期第11題 : ") PA = 0.25 PB = 0.4 PAB = 0.1 print("getPBA(PA=%.2f, PB=%.2f, PAB=%.2f) = %.2f" % (PA, PB, PAB, getPBA(PA, PB, PAB))) print("\n台北第一期第16題 : ") mean = 100 std = 15 z = 1.2 print("ZscoreToX(mean=%.2f, std=%.2f, z=%.2f) = %.2f" % (mean, std, z, ZscoreToX(mean, std, z))) print("\n台北第三期第14題 : ") #target for 21-30 on the index 1 target = 1 PA = [0.06, 0.03, 0.02, 0.04] PBA = [0.08, 0.15, 0.49, 0.28] print("BayesRule(target=%d, PA=%s, PBA=%s) = %.4f" % (target, PA, PBA, BayesRule(target, PA, PBA))) print("\n台北第三期第16題 : ") PA = [2, 3, 4] PB = [0, 1, 2, 3, 4] print("BayesRule_1(PA=%s, PB=%s) = %.4f" % (PA, PB, BayesRule_1(PA, PB))) print("\n台北第四期第7題 :") d = { 'x': pd.Series([ 25, 60, 60, 80, 95, 100 ]) } Statistics(d) print("\n台北第四期第9題 :") d = { 'x': pd.Series([ 83, 99, 99, 103, 103, 103, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 110, 110, 110, 110, 110, 110, 110, 110, 110, 113, 113, 113, 113, 113 ]) } Statistics(d) if __name__ == '__main__': main() __author__ = "Will Nien" __email__ = "will.nien@quantatw.com" __version__ = "1.0.2"
bf030cc3d4e550e26681ba21f7dd945fb4582fc2
SyedTajamulHussain/Python
/PythonTutorial/IFELSEdemo.py
686
4.09375
4
x = int(input("Please enter the value of X")) if x < 0: print("X is a negarive number") elif x > 0: print("X is a positive nubmber") elif x == 0: print("x is equal to zero") else: print("undefined") # write a program to find the highest number a = 100 b = 20 c = 30 if a > b and a > c: print("a is the highest number") elif b > c: print("b is the highest number") else: print("C is the highest number") total = int(input("Enter the total amount")) if total < 100: total = total + 20 elif 100 < total < 500: total = total + 50 else: total = total + 100 print(total) print("Total =" + str(total)) print(f'{"total value ="}{total}')
d004fdcd07acd68e21ccfb58ad69fbd3c1cc642e
Goopard/Study-2
/Currency.py
8,794
4.59375
5
#!/usr/bin/env python3 import abc import functools class Course: """This is a descriptor class for the subclasses of class Currency. It is used to store and operate a course of some currency.""" def __init__(self, value): """Constructor of class Course. :param value: Value of the course in some conventional units. :type value: float or int. """ self.value = value def __get__(self, instance, owner): """This method is used to access the value of the course. It works in two ways: 1) When instance is not None this method will return the value of the course: >>>e = Euro(10) # Creating an instance of some subclass of the class Currency. >>>e.course 1.22 2) When instance is None, this method will return a function that takes one argument: some other currency, and returns the course of the owner currency to that other currency: >>>Euro.course(Dollar) 1.22 Note that since the call Some_currency.course (where Some_currency is the subclass of the class Currency) returns a function, you can't use it to find out the course of Some_currency. To find out the course use: some_instance.course, where some_instance is an instance of Some_currency Some_currency(1).course, where you can put any integer or float value instead of 1. Also note that you can still use such call to set the value of the course for the currency Some_currency: >>>Some_currency.course = 10 :param instance: Instance of the owner class. :type instance: owner. :param owner: Class owning this instance of the descriptor Course. :type owner: Subclass of the class Currency. """ if instance is not None: return self.value else: def course_to_other(other_currency): return self.value / other_currency(1).course return course_to_other def __set__(self, instance, value): """This method is used to set the value of the course. :param instance: Instance of some subclass of class Currency :type instance: Subclass of the class Currency. :param value: New value of the course. :type value: float or int. :return: """ self.value = value @functools.total_ordering class Currency(metaclass=abc.ABCMeta): """This is an abstract class which subclasses are used to embody amounts of money of some currencies. Since this class is abstract, you are not able to create any instances of class Currency.""" def __init__(self, value, symbol): """Constructor of class currency. :param value: Amount of money. :type value: float or int. :param symbol: Special symbol of the currency, i.eg. $ for dollar. :type symbol: str. """ self.value = value self.symbol = symbol self.currency = type(self).__name__ def __str__(self): """Str representation of some amount of money in some currency.""" return str(self.value) + ' ' + self.symbol def __add__(self, other): """This method allows us to sum amounts of money in different (or the same) currencies. :param other: Some other instance of some subclass of the class Currency. :type other: Subclass of the class Currency. """ self_currency = type(self) if isinstance(other, Currency): return self_currency(self.value + other.to(self_currency).value) else: raise TypeError('unable to sum an instance of {} and an instance of {}'.format(self_currency, type(other))) def __sub__(self, other): """This method allows us to subtract amounts of money in different (or the same) currencies. :param other: Some other instance of some subclass of the class Currency. :type other: Subclass of the class Currency. """ self_currency = type(self) if isinstance(other, Currency): return self_currency(self.value - other.to(self_currency).value) else: raise TypeError('unable to subtract an instance of {} from an instance of class {}' .format(type(other), self_currency)) def __mul__(self, other): """This method allows us to multiply some amount of money in some currency on an int or a float number. :param other: Multiplier. :type other: float or int. """ self_currency = type(self) if isinstance(other, (float, int)): return self_currency(self.value * other) else: raise TypeError('unable to multiply an instance of class {} on an instance of class {}' .format(self_currency.__name__, type(other).__name__)) def __truediv__(self, other): """This method allows us to divide some amount of money in some currency on an int or a float number. :param other: Divisor. :type other: float or int. """ self_currency = type(self) if isinstance(other, (float, int)): return self_currency(self.value / other) else: raise TypeError('unable to divide an instance of class {} on an instance of class {}' .format(self_currency.__name__, type(other).__name__)) def __eq__(self, other): """This method allows us to find out if two amounts of money in different (or the same) currencies are equal. :param other: Some other instance of some subclass of the class Currency. :type other: Subclass of the class Currency. """ if isinstance(other, Currency): return self.value * self.course == other.value * other.course else: raise TypeError('unable to compare an instance of class {} to an instance of class {}' .format(type(self).__name__, type(other).__name__)) def __lt__(self, other): """This method allows us to find out if one amount of money in some currency is less than the other one. :param other: Some other instance of some subclass of the class Currency. :type other: Subclass of the class Currency. """ if isinstance(other, Currency): return self.value * self.course < other.value * other.course else: raise TypeError('unable to compare an instance of class {} to an instance of class {}' .format(type(self).__name__, type(other).__name__)) def to(self, other_currency): """This method transforms the instance of some subclass of the class Currency to the other one. :param other_currency: The currency we wish to transform this instance to. :type other_currency: Subclass of the class Currency. :return: other_currency. """ return other_currency(self.value * type(self).course(other_currency)) @abc.abstractmethod def _dummy(self): """This is a method that makes this class an abstract one. It is totally useless, but you have to instantiate it for all the subclasses of the class Currency.""" pass class Dollar(Currency): """This class embodies the Dollar currency.""" course = Course(1) def __init__(self, value): """Constructor of the class Dollar. :param value: Amount of money. :type value: float or int. """ super().__init__(value, '$') def _dummy(self): """The instantiation of the useless method _dummy.""" pass class Euro(Currency): """This class embodies the Euro currency.""" course = Course(1.22) def __init__(self, value): """Constructor of the class Euro. :param value: Amount of money. :type value: float or int. """ super().__init__(value, '€​') def _dummy(self): """The instantiation of the useless method _dummy.""" pass class Ruble(Currency): """This class embodies the Ruble currency.""" course = Course(1/67) def __init__(self, value): """Constructor of the class Ruble. :param value: Amount of money. :type value: float or int. """ super().__init__(value, '₽') def _dummy(self): """The instantiation of the useless method _dummy.""" pass if __name__ == '__main__': e = Euro(5) print(e.course) e.course = 1.5 c = Euro(10) print(c.course) d = Dollar(100) r = Ruble(1000) print(c.to(Dollar)) print(c + d) print(d + c) print(Euro.course(Ruble)) print(e > Euro(6)) print(e > d) print(e == e.to(Ruble))
c88cb1dfc03d33eae0a8ed42039316ef75ddcf1d
codewarriors12/jobeasy-python-course
/lesson_1/homework_1_2_passed.py
566
4.21875
4
# Find the second power of a variable. Save the expression to result_1 variable #Find the second power of a variable. a = 10 result_1 = a ** 2 # Convert integer variable b to a float. Save the expression to result_2 variable b = 10 result_2 = float(b) # Convert a float variable c to integer. Save the expression to result_3 variable c = 5.04 result_3 = int(c) # Sum up variables d and e and then multiply the total by f. Convert result to an integer and save the # expression to result_4 variable d = 5.04 e = 2 f = 1.2 sum = (d + e) result_4 = int(sum*f)
9099dede0f7d1b83ee33ed4a217c78fa725f56b5
eeshaun/python_exercises
/centenary.py
522
4.03125
4
from datetime import datetime now = datetime.now() print now year = now.year print year name = raw_input("name: ") age = raw_input("age: ") def check_name(name): x = 1 while x >= 0: if name.isalpha(): x -= 1 return name else: name = int(raw_input("You need to enter your name: ")) name = check_name(name) print name def check_age(age): while True: if age.isdigit(): return age else: age = raw_input("You need to enter your age: ") age = check_age(age) print age
d39347f5c827e08547015c1b40f8a6bfe11211ad
yashwanth-chamarthi/Logics
/PalindromeCheck.py
245
4.15625
4
def palindrome_check(string): x = '' for a in string.lower(): if a.isalpha(): x += a if x==x[::-1]: return True else: return False string = input() print(palindrome_check(string))
e5a5af1b7889d2b3e0b7238042fd62aba7ab0878
FrontendFigoperiFistemi/code-jams
/975485/975485.py
3,398
3.578125
4
import logging logging.basicConfig(filename='975485.log', level=logging.DEBUG) log = logging.getLogger(__name__) hallway = range(1, 101) class bot(object): def __init__(self, name, hallway): self.__name__ = name self.name = name if name == "orange": self.short_name = "O" elif name == "blue": self.short_name = "B" else: log.error("bot name can be orange or blue") raise self.hallway = hallway self.position = 1 def press_button(self, buttons): next_button, index = self._get_first_button(buttons) if not next_button: log.info("{0}: finished".format(self.name)) return False # print "{0} moving to {1}, position: {2}".format(self.name, next_button, self.position) if next_button < self.position: log.debug("{0}: moving backward".format(self.name)) self.position -= 1 return False elif next_button > self.position: log.debug("{0}: moving forward".format(self.name)) self.position += 1 return False elif next_button == self.position: if index == 1: log.debug("{0}: pressing button".format(self.name)) return True # button pressed else: log.debug("{0}: waiting".format(self.name)) # waiting for the other robot move return False raise def _get_first_button(self, buttons): index = 1 for button in buttons: if button[0] == self.short_name: return button[1], index index += 1 return None, index def parse_input(input_string): parts = input_string.split() number_of_buttons = parts[0] coordinates = [] for index in range(1, len(parts), 2): bot_name = parts[index] coordinate = int(parts[index + 1]) coordinates.append((bot_name, coordinate)) return coordinates def main(): case_number = 1 orange = bot with open("A-large-practice.in") as input_file: with open("output.txt", "w") as output_file: number_of_tt = int(input_file.readline()) print number_of_tt for case in input_file: log.debug("processing input {0}".format(case)) print "processing input", case coordinates = parse_input(case) button_to_push = coordinates orange = bot("orange", hallway) blue = bot("blue", hallway) seconds = 0 while len(button_to_push): print "_________________________________" print button_to_push print "bots: {0} {1}, {2} {3}".format(orange.name, orange.position, blue.name, blue.position) orange_pressed = orange.press_button(button_to_push) blue_pressed = blue.press_button(button_to_push) if orange_pressed or blue_pressed: # a button has been pressed button_to_push = button_to_push[1:] seconds += 1 output_file.write("Case #{0}: {1}\n".format(case_number, seconds)) case_number += 1 if __name__ == "__main__": main()
015006694facae6bcc17f007e47c929ddf242cec
itachiRedhair/ds-algo-prep
/trees/check-balanced-bt.py
2,576
3.96875
4
import sys # Better algorithm here, for poor one scroll down more # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # This code runs in O(N) time and O(H) space, where H is the height of the tree. class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: def getHeight(root_node): # Base case: # This is because at the end when child is None, # height is -1, not zero as that's not the child node, # it's just child node's left node which is None if not root_node: return -1 leftHeight = getHeight(root_node.left) if leftHeight == -sys.maxsize: return -sys.maxsize rightHeight = getHeight(root_node.right) if rightHeight == -sys.maxsize: return -sys.maxsize height_diff = leftHeight - rightHeight if abs(height_diff) > 1: return -sys.maxsize else: return max(leftHeight, rightHeight) + 1 return getHeight(root) != -sys.maxsize # Although this works. it's not very efficient. On each node. we recurse through its entire subtree. This means # that getHeight is called repeatedly on the same nodes. The algorithm isO(N log N) since each node is # "touched" once per node above it. # LogN is for getHeights() and N is for isBalanced() call for every node # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: def getHeight(root_node): # Base case: # This is because at the end when child is None, # height is -1, not zero as that's not the child node, # it's just child node's left node which is None if not root_node: return -1 return max(getHeight(root_node.left), getHeight(root_node.right) )+ 1 if root is None: return True height_diff = getHeight(root.left) - getHeight(root.right) if abs(height_diff) > 1: return False else: return self.isBalanced(root.left) and self.isBalanced(root.right)
0e709f1b933447d013b954ca3e28cda2b40da513
Darya1501/Python-course
/lesson-14/Password-generator.py
2,848
3.765625
4
import random def ask_question(question, sets): global enabled_chars print('Если в пароле нужны', question, 'введите Да: ') answer = input().lower() if answer.strip() == 'да': enabled_chars += sets def generate_password(length, chars): password = ' ' if length > 0: for i in range(length): random_index = random.randint(0, len(chars)-1) password += chars[random_index] return password print('\nПривет. Я - генератор паролей. \nЯ задам несколько уточняющих вопросов,на основе которых сгенерирую пароль. \nДавай начнем!', end='\n\n') while True : print('Сколько паролей вы хотите сгенерировать? Введите число: ') count = input() if count.isdigit() and int(count) > 0: count = int(count) else: print('Неверный ввод, будет сгенерирован 1 пароль') count = 1 print('Введите длину паролей:') length = input() if length.isdigit() and int(length) > 0: length = int(length) else: print('Неверное значение длины, будут сгенерировны пароли длиной 7 символов') length = 7 enabled_chars = '0' digits = '1234567890' latin_lowercase_letters = 'abcdefghijklmnopqrstuvwxyz' latin_uppercase_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' russian_lowercase_letters = 'абвгдеёжзиклмнопрстуфхцчшщъыьэюя' russian_uppercase_letters = 'АБВГДЕЁЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' punctuation = '!#$%&*+-=?@^_' ask_question('цифры,', digits) ask_question('строчные латинские буквы,', latin_lowercase_letters) ask_question('заглавные латинские буквы,', latin_uppercase_letters) ask_question('строчные русские буквы,', russian_lowercase_letters) ask_question('заглавные русские буквы,', russian_uppercase_letters) ask_question('знаки пунктуации,', punctuation) for i in range(count): password = generate_password(length, enabled_chars) print('Сгенерированный пароль:', password) again = input('Еще раз? Да / нет: ') .lower() if again == 'нет': break elif again == 'да': continue else: print('Неизвестное значение, игра прекращена') break print('До новых встреч!')
29216478e08bb673816f0998d73f83c63be81a26
avni510/data_structures_and_algo
/src/sorting/sorting_algorithms.py
4,632
4.28125
4
## Bubble Sort - bubbles up the largest item to the end # of the array # Runtime: O(N^2) # Space Complexity: O(1) def bubble_sort(array): for size in range(len(array) - 1, 0, -1): for i in range(size): if array[i] > array[i + 1]: temp = array[i] array[i] = array[i + 1] array[i + 1] = temp return array ## Selection Sort - find the max element, swap it with the # last element in the array # Runtime: O(n^2) # Space Complexity: O(1) def selection_sort(array): # decrement the size of the array for size in range(len(array) - 1, 0, -1): # find max element max_index = 0 for i in range(1, size + 1): if array[i] > array[max_index]: max_index = i # once max is found replace the last item with # the max value temp = array[size] array[size] = array[max_index] array[max_index] = temp return array ## Insertion Sort - removes an element per iteration and finds the place the element belongs # in the array. For each element A[i] > A[i + 1], swap until # A[i] <= A[i + 1] # Runtime: O(N^2) def insertion_sort(array): for index in range(1, len(array)): current_value = array[index] position = index while position > 0 and array[position - 1] > current_value: array[position] = array[position - 1] position -= 1 array[position] = current_value return array ## Bucket Sort - break down the array into buckets. Sort each bucket. Make # window of the bucket smaller # Runtime: O(N^2) # Space Complexity: def bucket_sort(array): bucket_size = len(array) // 2 while bucket_size > 0: for start_position in range(bucket_size): sort_bucket(array, start_position, bucket_size) bucket_size = bucket_size // 2 return array def sort_bucket(array, start, gap): for i in range(start + gap, len(array), gap): current_value = array[i] position = i while position >= gap and array[position - gap] > current_value: array[position] = array[position - gap] position -= gap array[position] = current_value ## Merge Sort # Runtime: O(N log(N)) def merge_sort(array): if len(array) < 2: return array else: mid = len(array) // 2 lefthalf = array[:mid] righthalf = array[mid:] lefthalf = merge_sort(lefthalf) righthalf = merge_sort(righthalf) i = 0 j = 0 # put the two halfs in sorted order with each other merged_array = [] while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: merged_array.append(lefthalf[i]) i += 1 else: merged_array.append(righthalf[j]) j += 1 while i < len(lefthalf): merged_array.append(lefthalf[i]) i += 1 while j < len(righthalf): merged_array.append(righthalf[j]) j += 1 return merged_array ## Quick Sort # Runtime: O(N log(N)) on Average, O(N^2) Worst Case # Space Complexity: O(N log(N)) # Given an array, pick the first value as the pivot # continue moving left and right if left value is less than pivot # and right value is great than pivot. If not swap the values # stop when left > right. Swap the right value with the pivot # return the right value as the split value -> sort the left # half, then the right half. # Essentially trying to find the right position for the pivot point def quick_sort(array): quick_sort_helper(array, 0, len(array) - 1) def quick_sort_helper(array, first, last): if first < last: split_point = parition(array, first, last) quick_sort_helper(array, first, split_point - 1) quick_sort_helper(array, split_point + 1, last) def parition(array, first, last): pivot = array[first] left_marker = first + 1 right_marker = last done = False while not done: while left_marker <= right_marker and array[left_marker] <= pivot: left_marker += 1 while left_marker <= right_marker and array[right_marker] >= pivot: right_marker -= 1 if left_marker > right_marker: done = True else: temp = array[left_marker] array[left_marker] = array[right_marker] array[right_marker] = temp temp = array[first] array[first] = array[right_marker] array[right_marker] = temp return right_marker
2bc80e66a5f6137243421a68686234a44ab2e882
MarkJParry/MyGMITwork
/Week03/absolute.py
257
4.125
4
#Filename: absolute.py #Author: Mark Parry #Created: 03/02/2021 #Purpose: Program to take in a number and give its absolute value inNum = float(input("Please enter a negative number: ")) print("the absolute value of {} is: {}".format(inNum,abs(inNum)))
93befa506193332d1a8f14a64ae1e630f4d880d0
dmaring/holbertonschool-higher_level_programming
/0x11-python-network_1/8-json_api.py
727
3.78125
4
#!/usr/bin/python3 """ A Python script that takes in a letter and sends a POST request to http://0.0.0.0:5000/search_userA script sends an email """ import requests import sys def searchAPI(): """ A function that sends POST and prints the response """ if len(sys.argv) < 2: _data = {'q': ""} else: _data = {'q': sys.argv[1]} _url = 'http://0.0.0.0:5000/search_user' res = requests.request('POST', _url, data=_data) try: _json = res.json() if not _json: print("No result") else: print("[{}] {}".format(_json.get('id'), _json.get('name'))) except: print("Not a valid JSON") if __name__ == '__main__': searchAPI()
2bd8e8f3bb7c1f72e2f790fe61faa8ef1267fe9a
vishnoiprem/pvdata
/lc-all-solutions-master/028.implement-strstr/test.py
329
3.546875
4
class Solution(object): def strStr(self, haystack, needle): if len(haystack)<1 and len(needle): return 1 n=len(needle) for i in range(len(haystack)): #print(haystack[i:i+n],i) if haystack[i:i+n]==needle: return i return -1 if __name__ == "__main__": print (Solution().strStr("hello", "ll"))
a7e1fca5e40361977737653c3f94b67b23fbd26d
Minh-Trung-SE/Python_Core
/Lesson_8/8.03.py
267
4.0625
4
# Counting elements in list until it's tuple. def count(data_source): result = 0 for element in data_source: if isinstance(element, tuple): return result else: result += 1 data = [1,2,5,6,(9,9)] print(f"{count(data)}")
c7a8640520f04478ea3aef8cfc4f824401a0a8e0
Gi1ia/TechNoteBook
/Algorithm/855_Exam_Room.py
3,335
3.5
4
import heapq import bisect class ExamRoom(object): def __init__(self, N): self.N = N self.students = [] self.heap = [] self.avail_first = {} # used later in leave() self.avail_last = {} # used later in leave() self.put_seg(0, self.N - 1) # Initialize with empty room def seat(self): while True: _, first, last, is_avail = heapq.heappop(self.heap) if is_avail: # delete del self.avail_last[last] del self.avail_first[first] break if first == 0: res = 0 if first != last: self.put_seg(first + 1, last) elif last == self.N - 1: res = last if first != last: self.put_seg(first, last - 1) else: res = (last - first) // 2 + first if res > first: self.put_seg(first, res - 1) if res < last: # break the segment and put both into heap self.put_seg(res + 1, last) return res def leave(self, p): left = p - 1 # looking for left and right segment right = p + 1 first, last = p, p # Default value, incase p == 0 or p == N - 1 if left >= 0 and left in self.avail_last: seg_left = self.avail_last.pop(left) first = seg_left[1] seg_left[3] = False if (right <= self.N - 1) and right in self.avail_first: seg_right = self.avail_first.pop(right) last = seg_right[2] seg_right[3] = False self.put_seg(first, last) def put_seg(self, first, last): if first == 0 or last == self.N - 1: l = last - first else: l = (last - first) // 2 segment = [-l, first, last, True] self.avail_last[last] = segment # pass by ref? self.avail_first[first] = segment heapq.heappush(self.heap, segment) def seat_ON(self): """ Seat function O(N) time """ if not self.students: # no one in the room student = 0 else: # Try to seat from position 0 # dist = students[0] - 0 = students[0] dist, student = self.students[0], 0 for i, position in enumerate(self.students): if i > 0: prev_position = self.students[i - 1] current_dist = (self.students[i] - prev_position) // 2 if current_dist > dist: dist, student = current_dist, prev_position + current_dist last = self.N - 1 - self.students[-1] if last > dist: student = self.N - 1 bisect.insort(self.students, student) return student def leave_ON(self, p): """ Leave function for `self.seat_ON()` """ self.students.remove(p) # Your ExamRoom object will be instantiated and called as such: # obj = ExamRoom(N) # param_1 = obj.seat() # obj.leave(p) # ref: [heap solution](https://leetcode.com/problems/exam-room/discuss/139941/Python-O(log-n)-time-for-both-seat()-and-leave()-with-heapq-and-dicts-Detailed-explanation)
233ee00d9e19344e982499a6d241b2286505b6cb
hrrs/wikiscraper
/plot_network.py
814
3.53125
4
from turtle import * from types import * myTree = ["A",["B",["C",["D","E"],"F"],"G","H"]]; s = 50; startpos = (0,120) def cntstrs(list): return len([item for item in list if type(item) is type('')]) def drawtree(tree, pos, head=0): c = cntstrs(tree) while len(tree): goto(pos) item = tree.pop(0) if head: write(item,1) drawtree(tree.pop(0),pos) else: if type(item) is type(''): newpos = (pos[0] + s*c/4 - s*cntstrs(tree), pos[1] - s) down() goto((newpos[0], newpos[1] + 15)) up() goto(newpos) write(item,1) elif type(item) is type([]): drawtree(item,newpos) up() drawtree(myTree, startpos,1) ht() mainloop()
ec20e8e84c830679dece10d80b273dfab2f07609
letai2001/python
/python/Baitap8.xulichuoi.py
674
3.75
4
"""Xây dựng hàm nhận đầu vào là chuỗi s và hai số nguyên k, n sau đó xóa chuỗi con độ dài n bắt đầu từ vị trí k ra khỏi chuỗi s . Viết chương trình minh họa""" def xoaKiTu(string,k,n): list = [] for i in range (k): list.append(string[i]) newstring = ''.join(list) return newstring print("nhap k = ",end = " ") k = int(input()) print("nhap n = ",end = " ") n = int(input()) print("nhap string co do dai bang n , string = ",end = " ") string = input() while(len(string)!=n): print("Nhap lai chuoi") string = input() print("ki tu sau khi da xoa: ") print(xoaKiTu(string,k,n))
09377a7b25dde34dc0fb7c03d2e5f83bf26dadee
Clever/kayvee-python
/kayvee/kayvee.py
1,054
3.6875
4
import json def format(data): """ Converts a dict to a string of space-delimited key=val pairs """ return json.dumps(data, separators=(',', ':')) def formatLog(source="", level="", title="", data={}): """ Similar to format, but takes additional reserved params to promote logging best-practices :param level - severity of message - how bad is it? :param source - application context - where did it come from? :param title - brief description - what kind of event happened? :param data - additional information - what details help to investigate? """ # consistently output empty string for unset params, because null values differ by language source = "" if source is None else source level = "" if level is None else level title = "" if title is None else title if not type(data) is dict: data = {} data['source'] = source data['level'] = level data['title'] = title return format(data) # Log Levels UNKNOWN = "unknown" CRITICAL = "critical" ERROR = "error" WARNING = "warning" INFO = "info" TRACE = "trace"
cca5ba722e79b2a238d8143a9d74093b468f5172
610yilingliu/leetcode
/Python3/693.binary-number-with-alternating-bits.py
539
3.5625
4
# # @lc app=leetcode id=693 lang=python3 # # [693] Binary Number with Alternating Bits # # @lc code=start class Solution: def hasAlternatingBits(self, n: int): if n == 0 or n == 1: return True pre = n & 1 n = n >> 1 while n > 0: cur = n & 1 if cur == pre: return False pre = cur n = n >> 1 return True # if __name__ == '__main__': # a = Solution() # b = a.hasAlternatingBits(5) # print(b) # @lc code=end
1b7a53144aede78bf8c269edfc5553c65db351d5
JunyaZ/LeetCode-
/Algorithm/Contains Duplicate.py
722
4.0625
4
""" Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true """ from collections import defaultdict class Solution: def containsDuplicate(self, nums: List[int]) -> bool: D=defaultdict(int) for i in nums: D[i]+=1 Counter=0 for i in D: if D[i]>1: Counter+=1 if Counter>0: return True else: return False
ce1b6eed4f85c14e76f6db5119852459b0feabbf
savourylie/interview_questions
/bst/heap.py
2,212
3.859375
4
class MinHeap(object): def __init__(self, value_list=[]): self.heap = [] if len(value_list) > 0: for x in value_list: self.add(x) def add(self, value): self.heap.append(value) self.heapify_up() def pull(self): min_element = self.heap.pop(0) last_element = self.heap.pop() self.heap.insert(0, last_element) self.heapify_down() def get_left_child_index(self, current_index): return current_index * 2 + 1 def get_right_child_index(self, current_index): return current_index * 2 + 2 def has_left_child(self, current_index): return True if self.get_left_child_index(current_index) < len(self.heap) else False def has_right_child(self, current_index): return True if self.get_right_child_index(current_index) < len(self.heap) else False def get_parent_index(self, current_index): return int((current_index - 1) / 2) def has_parent(self, current_index): if current_index == 0: return False return True if self.get_parent_index(current_index) >= 0 else False def swap(self, index1, index2): self.heap[index1], self.heap[index2] = self.heap[index2], self.heap[index1] def heapify_up(self): current_index = len(self.heap) - 1 while self.has_parent(current_index): parent_index = self.get_parent_index(current_index) if self.heap[parent_index] < self.heap[current_index]: return current_index self.swap(parent_index, current_index) current_index = parent_index return current_index def heapify_down(self): current_index = 0 while self.has_left_child(current_index): smaller_child_index = self.get_left_child_index(current_index) if self.has_right_child(current_index) and self.heap[self.get_right_child_index(current_index)] < self.heap[smaller_child_index]: smaller_child_index = self.get_right_child_index(current_index) if self.heap[smaller_child_index] > self.heap[current_index]: return current_index self.swap(current_index, smaller_child_index) current_index = smaller_child_index return current_index if __name__ == '__main__': minheap = MinHeap([5, 3, 18, 1, 6]) print(minheap.heap) minheap.pull() print(minheap.heap) minheap.add(2) print(minheap.heap)
c02bedb9024eb21d645655c15ae63896c600cc6c
BenjiDa/sga
/sgapy/ZeroTwoPi.py
717
4
4
import numpy as np def zerotwopi(a): ''' zerotwopi constrains azimuth to lie between 0 and 2*pi radians b = zerotwopi(a) returns azimuth b (from 0 to 2*pi) for input azimuth a (which may not be between 0 to 2*pi) NOTE: Azimuths a and b are input/output in radians MATLAB script written by Nestor Cardozo for the book Structural Geology Algorithms by Allmendinger, Cardozo, & Fisher, 2011. If you use this script, please cite this as "Cardozo in Allmendinger et al. (2011)" Converted to python by bmelosh Sept 27th 2022 ''' b=a twopi = 2.0*np.pi if b < 0.0: b = b + twopi elif b >= twopi: b = b - twopi return b