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
a7ff174b1476ef15f181bce08584237210d98705
bssrdf/pyleet
/W/WiggleSubsequence.py
2,738
4.03125
4
''' -Medium- Given an integer array nums, return the length of the longest wiggle sequence. A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) are alternately positive and negative. In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero. A subsequence is obtained by deleting some elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order. Example 1: Input: nums = [1,7,4,9,2,5] Output: 6 Explanation: The entire sequence is a wiggle sequence. Example 2: Input: nums = [1,17,5,10,13,15,10,5,16,8] Output: 7 Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. Example 3: Input: nums = [1,2,3,4,5,6,7,8,9] Output: 2 Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000 Follow up: Could you solve this in O(n) time? ''' class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 up, down = 1, 1 for i in range(1, len(nums)): if nums[i] > nums[i-1]: up = down + 1 elif nums[i] < nums[i-1]: down = up + 1 return max(down, up) def wiggleMaxLengthDP(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 dp = [[0 for _ in range(2)] for _ in range(len(nums))] # 0: up, 1: down dp[0][0], dp[0][1] = 1, 1 for i in range(1, len(nums)): if nums[i] > nums[i-1]: dp[i][0] = dp[i-1][1] + 1 dp[i][1] = dp[i-1][1] elif nums[i] < nums[i-1]: dp[i][1] = dp[i-1][0] + 1 dp[i][0] = dp[i-1][0] else: dp[i][0] = dp[i-1][0] dp[i][1] = dp[i-1][1] print(nums) print([dp[i][0] for i in range(len(nums))]) print([dp[i][1] for i in range(len(nums))]) return max(dp[-1][:]) if __name__ == "__main__": #print(Solution().wiggleMaxLength([1,17,5,10,13,15,10,5,16,8])) #print(Solution().wiggleMaxLengthDP([1,17,5,10,13,15,10,5,16,8])) print(Solution().wiggleMaxLengthDP([3, 10, 11, 10, 12, 11]))
d000abaaf2dc1cc2d558d0fad7d898c2b32bbd49
smecham/SI506
/Section_Resources/Section 008/section8_solution.py
1,451
3.875
4
# This is the solution to the steps involving multiple tweets (the file tweets.txt, steps 3+ on the handout) import json f = open('tweets.txt') tweets = [] for line in f: tweet = json.loads(line) tweets.append(tweet) # Now tweets contains a list of tweet objects # Part 1: most liked tweets # Break ties alphabetically: tweets = sorted(tweets, key=lambda t: t['text']) sorted_by_fav = sorted(tweets, key=lambda t: t['favorite_count'], reverse=True) print('FavCount Tweet') for t in sorted_by_fav[:5]: print(t['favorite_count'], '\t', t['text']) print() # Just prints an extra blank line for clarity of output # Part 2: writing a CSV f = open("tweet_favcounts.csv",'w') header_str = "FavCount,Tweet\n" f.write(header_str) # Code just like above, but building strings and writing to file... for t in sorted_by_fav[:5]: f.write("{},{}\n".format(t["favorite_count"],t['text'])) # Use string formatting to put those values into the string you are writing to the file each time f.close() # And close the file # Part 3: most popular hashtags hashtag_count = {} for t in tweets: hashtags = t['entities']['hashtags'] for hashtag in hashtags: ht_text = hashtag['text'] if ht_text not in hashtag_count: hashtag_count[ht_text] = 0 hashtag_count[ht_text] += 1 most_popular_hashtags = sorted(hashtag_count.items(), key=lambda item: item[1], reverse=True) print('Hashtag\tCount') for h in most_popular_hashtags[:5]: print(h[0], '\t', h[1])
686cd03909f0ee5a79ebd80ce99324dd0a91d4a1
eduardoimagno/materias-programacao
/materias de programaçao/Algoritmo e estrutura de dados ipg/PROGRAMAÇÃO/Aula03+-+Condições+e+instruções+de+seleção-20191225/examples/ex1ifelse.py
182
4.09375
4
# Example: A simple if-else statement. idade = int(input("idade? ")) print(idade) if idade >= 18: res = "OK" print("MAIOR") else: res = "KO" print(res) print("FIM")
04d2195f4c2eb563f573dcb5d7d00b3ceffed825
masaniwasdp/Pyfunge
/source/pyfunge/parser.py
1,940
3.8125
4
""" パーサモジュール。 Date: 2017/7/31 Authors: masaniwa """ from pyfunge import operation from pyfunge.codestream import Direction def parse(character, quoting): """ 文字を命令にパースする。 Params: character = パース対象の文字。 quoting = 文字を文字とする場合はTrue。文字を命令とする場合はFalse。 Returns: パースした命令。パースできなかった場合はNone。 """ if character == "\"": return operation.Quoter() if quoting: return operation.Value(ord(character)) if character.isdigit(): return operation.Value(int(character)) if character not in OPERATIONS: return None return OPERATIONS[character] OPERATIONS = { "<": operation.Director(Direction.left), ">": operation.Director(Direction.right), "^": operation.Director(Direction.up), "v": operation.Director(Direction.down), "_": operation.Selector(Direction.right, Direction.left), "|": operation.Selector(Direction.down, Direction.up), "?": operation.Random(), " ": operation.Space(), "#": operation.Skipper(), "@": operation.Stopper(), "&": operation.NumberInput(), "~": operation.CharInput(), ".": operation.NumberPrinter(), ",": operation.CharPrinter(), "+": operation.Calculater(lambda x, y: x + y), "-": operation.Calculater(lambda x, y: x - y), "*": operation.Calculater(lambda x, y: x * y), "/": operation.Calculater(lambda x, y: x // y), "%": operation.Calculater(lambda x, y: x % y), "`": operation.Calculater(lambda x, y: 1 if x > y else 0), "!": operation.Inverter(), ":": operation.Duplicator(), "\\": operation.Reverser(), "$": operation.Popper(), "g": operation.Reader(), "p": operation.Writer()}
d1d0ce3d6ca8e27aff52930ca067d0462000a880
trvsed/100-exercicios
/ex034.py
426
3.734375
4
s=float(input('Digite o valor do seu salário: ')) r1=(s+s*10/100) r2=(s+s*15/100) if s >= 1250: print('O valor do seu salário era de R${} e recebeu um reajuste de 10%, portanto o valor reajustado é referente a importância de: R${}.'.format(s, r1)) else: print('O valor do seu salário era de R${} e recebeu um reajuste de 15%, portanto o valor reajustado é referente a importância de: R${}.'.format(s, r2))
7a8b468dfc38bb25b2734ee126f54ad06b00d706
Matematik411/AdventOfCode2020
/day22.py
2,169
3.65625
4
def play(one, two, dejavu): while one and two: #konec igre, ce ponovitev postavitve if (tuple(one), tuple(two)) in dejavu: return (1, one, two) else: dejavu.add((tuple(one), tuple(two))) a = one[0] del one[0] b = two[0] del two[0] #moramo v pod-igro if len(one) >= a and len(two) >= b: lower_game = play(one[:a], two[:b], set())[0] if lower_game == 1: one.append(a) one.append(b) else: two.append(b) two.append(a) else: #igra se navadno if a > b: one.append(a) one.append(b) else: two.append(b) two.append(a) if one: return (1, one, two) else: return (2, one, two) #podatki fst = [] snd = [] input() for i in range(2): for _ in range(25): a = int(input()) if i == 0: fst.append(a) else: snd.append(a) if i == 0: input() input() #for part two parttwo_fst = fst.copy() parttwo_snd = snd.copy() #part one while (fst) and (snd): a = fst[0] del fst[0] b = snd[0] del snd[0] if a > b: fst.append(a) fst.append(b) else: snd.append(b) snd.append(a) if snd: print("Winner of the first round is the second player!") result = 0 l = len(snd) for x in range(l): result += (l-x) * snd[x] else: print("Winner of the first round is the first player!") result = 0 l = len(fst) for x in range(l): result += (l-x) * fst[x] print(result) #part two winner, end_fst, end_snd = play(parttwo_fst, parttwo_snd, set()) if winner == 1: print("Winner of the second round is the first player!") result = 0 l = len(end_fst) for x in range(l): result += (l-x) * end_fst[x] else: print("Winner of the second round is the second player!") result = 0 l = len(end_snd) for x in range(l): result += (l-x) * end_snd[x] print(result)
ae24dc5149d4e4e049d55ac3d74531ba3b9fea26
aayush1607/Hackerrank-Solutions
/algorithms/implementation/climbing-the-leaderboard.py
1,253
4.03125
4
#!/bin/python3 import math import os import random import re import sys def binarySearch(arr,val, start, end): if start == end: if arr[start] > val: return start else: return start+1 if start > end: return start mid = (start+end)//2 if arr[mid] < val: return binarySearch(arr, val, mid+1, end) elif arr[mid] > val: return binarySearch(arr, val, start, mid-1) else: return mid+1 # Complete the climbingLeaderboard function below. def climbingLeaderboard(s, a): s=set(s) s=list(s) s.sort() print(s) r=[] for j in range(len(a)): r.append(len(s)-binarySearch(s,a[j],0,len(s)-1)+1) return (r) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') scores_count = int(input()) scores = list(map(int, input().rstrip().split())) alice_count = int(input()) alice = list(map(int, input().rstrip().split())) result = climbingLeaderboard(scores, alice) fptr.write('\n'.join(map(str, result))) fptr.write('\n') fptr.close()
d7e8adf50ee301c1386f95668b6ba7f2bc1bd74f
leonardosilvab/python_learning
/Cap 05/5.3.py
59
3.59375
4
x = 10 while(x>0): print (x) x-=1 print ("Fogo!")
7d1bae4bed5abbdbe008d2ebf4c3da33de8cc6f6
WeiweiVivianWang/Leetcode
/TwoPointer/TwoPointerTwoArray/88_Merge_Sorted_Array.py
2,000
3.6875
4
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ res = [] i,j = 0, 0 while i < m and j < n: if nums1[i] < nums2[j]: res.append(nums1[i]) i+=1 else: res.append(nums2[j]) j+=1 while i < m: res.append(nums1[i]) i+=1 while j < n: res.append(nums2[j]) j+=1 for index in range(m+n): nums1[index]=res[index] #此题是改一个数组,Do not return anything, modify nums1 in-place instead. #Time O(m+n) #Space O(m+n) for storing res. class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # Set p1 and p2 to point to the end of their respective arrays. p1 = m - 1 p2 = n - 1 # And move p backwards through the array, each time writing # the smallest value pointed at by p1 or p2. for p in range(n + m - 1, -1, -1): if p2 < 0: break if p1 >= 0 and nums1[p1] > nums2[p2]: nums1[p] = nums1[p1] p1 -= 1 else: nums1[p] = nums2[p2] p2 -= 1 #Time O(m+n) #Space O(1) #三个pointer start from the end #!!!从大开始比较, 从后往前append!!!! #set p1 to point at index m - 1 of nums1, p2 to point at index n - 1 of nums2, #and p to point at index m + n - 1 of nums1. #This way, it is guaranteed that once we start overwriting the first m values in nums1, #we will have already written each into its new position. In this way, we can eliminate the additional space.
54c05c40e579c3787708b10119b2cd36dc381071
Nehanavgurukul/Dictionary
/resorce4_square_value.py
337
3.734375
4
# d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} # def is_key_present(x): # if x in d: # print('Key is present in the dictionary') # else: # print('Key is not present in the dictionary') # is_key_present(5) # is_key_present(9) n=int(input("Input a number ")) d = dict() for x in range(1,n+1): d[x]=x*x print(d)
b8312d3389cd798043bba7547d60823000ecb413
kartikwar/programming_practice
/graphs/islands_of_1s.py
2,290
4.03125
4
""" Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands Input : mat[][] = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1} Output : 5 Question link :- geeksforgeeks.org/find-number-of-islands/ """ # from sklearn import neighbors def get_neighbours(A, pos, visitor_stack, visited): i, j = pos neighbours = [] if j -1 in range(len(A)): neighbours.append((i, j-1)) if j + 1 in range(len(A)): neighbours.append((i, j+1)) if i -1 in range(len(A)): neighbours.append((i-1, j)) if i + 1 in range(len(A)): neighbours.append((i+1, j)) valid_neighbours = [] found = False for row_i, col_i in neighbours: if visited[row_i][col_i] == False: if (row_i, col_i) not in visitor_stack: valid_neighbours.append((row_i, col_i)) if A[row_i][col_i] == 1: found = True if not found: valid_neighbours = [] return valid_neighbours def count_islands(A): count = 0 #can be optimized by using a 2d array of visited, visited positions can be set to 1 #and non visited can remain 0, but for now just using append logic visited = [[False for i in range(len(A))] for j in range(len(A))] visitor_stack = [] for row in range(len(A)): for col in range(len(A)): if visited[row][col]: continue else: ele = A[row][col] if ele == 1: count += 1 visitor_stack.append((row, col)) #apply dfs algo while(len(visitor_stack)): # for pos in positions: pos = visitor_stack.pop(0) visitor_stack += get_neighbours(A, pos, visitor_stack, visited) visited[pos[0]][pos[1]] = True # visited[row][col] = True return count if __name__ == "__main__": A = [ [1,1,0,0,0], [0,1,0,0,1], [1,0,0,1,1], [0,0,0,0,0], [1,0,1,0,1] ] print(count_islands(A))
4a3cb3f002cd808a199d29d4ed77679b71dbaf02
jmnich/UFP_Regulator_Simulations
/FUZZY/FUZMain.py
1,183
3.609375
4
# -*- coding: utf-8 -*- """ FUZZY REGULATOR 1. Create an instance of the balanced arm 2. Set initial conditions 3. Prepare a fuzzy regulator 4. Begin iterating: a) 5. Visualize results note: all values are scaled in standard metric units note: input params: angle, angular_velocity note: output params: left thrust, right thrust """ import math import ArmModel import FuzzyRegulator import matplotlib.pyplot as plt structure_mass = 1.0 arm_length = 0.25 arm_radius = 0.01 interval = 0.01 record = [] fit_factor = 0.0 arm_inertial_moment = (1.0 / 12.0) * structure_mass * \ (math.pow(arm_radius, 2) * 3 + math.pow(arm_length * 2, 2)) arm = ArmModel.ArmModel(arm_inertial_moment, arm_length) arm.setInitialConditions(45.0, 0.0) regulator = FuzzyRegulator.FuzzyRegulator(0.0, 10.0) for i in range(0, 1000): regulator.calcNewThrusts(arm.angle, arm.angular_speed, 0.0) arm.updateState(interval, regulator.getLeftThrust(), regulator.getRightThrust()) record.append(arm.angle) fit_factor += abs(regulator.getLastErr() * interval) plt.plot(record) plt.show() print(fit_factor)
7e659ac03165ed498a94b219ba65392ed3ea7fbc
annarider/UdacityCS101
/Lesson2/OptionalQ2.py
376
3.5
4
def stamps(n): five = n /5 two = 0 one = 0 if (n % 5) > 0: two = (n % 5) / 2 if ((n % 5) % 2) > 0: one = 1 return (five, two, one) print 3 / 2 print stamps(2) # 0, 1, 0 print stamps(3) # 0, 1, 1 print stamps(29) # 5, 2, 0 print stamps(8) # 1, 1, 1 print stamps(0) # 0, 0, 0 print stamps(5) # 1, 0, 0 print stamps(7) # 1, 1, 0
3f2771ad4e0bf24166229543b8c1ee1c6c005a66
HussainAther/computerscience
/theory/montecarlo.py
3,120
4.53125
5
import numpy as np from math import exp """ Monte Carlo method randomly tests data points to approxiamte or guess a solution, thus getting a good idea of what is going on by sampling only a few points rather than many. This approach is often coupled with trrgeting the selection of data points towards the most promising or important results. This leads directly into the Markov chain in which we can base a new selection on the last one. A famous example of this is the Metropolis-Hastings algorithm for making the next guess for an effectively random walk with probabilistic selection that echoes thermodynamic energy. Generating random numbers is key. For a simple Monte Carlo integration (determining the area bounded by some condition), we'll use a circle to estimate pi. """ uniform = np.random.uniform numSamples = 100000 numInside = 0 for i in range(numSamples): x, y = uniform(-1.0, 1.0, 2) if (x * x) + (y * y) < 1.0: numInside += 1 pi = 4.0 * numInside / float(numSamples) print(pi) """ Next we'll minimize a 2-d function f(x,y,) = (1-x)^2 + 100(y-x^2)^2 using the Rosenrock test. It's sometimes used in optimization with a crescent-shaped valley and a minimum (1,1) in a flat region. """ def testFunc(point): x, y = point a = 1.0 - x b = y - (x * x) return (a * a) + (100 * b * b) bestPoint = uniform(-5, 5, 2) bestValue = testFunc(bestPoint) numSteps = 100000 for i in range(numSteps): point = uniform(-5, 5, 2) value = testFunc(point) if value < bestValue: bestPoint = point bestValue = value x, y = point print("%5d x:%.3f y:%.3f value:%.3f" % (i, x, y, value)) """ We can improve this loop using the normal() function that selects the next point on a Gaussian spread. """ normal = np.random.normal numSteps = 100000 for i in range(numSteps): point = normal(bestPoint, 0.5, 2) value = testFunc(point) if value < bestValue: bestPoint = point bestValue = value x, y = point print("%5d x:%.3f y:%.3f value:%.3f" % (i, x, y, value)) """ The Metropolis-Hastings Monte Carlo algorithm uses a probability distribution and estimates what is effectively a probability ratio by comparing the value at previous points to new testpoints. It sometimes accepts worse points such that the algorithm may jump out of what may be only a local optimum to search for a better global optimum. """ def monteCarlo(numSteps, testFunc, spread=0.1, nDims=2): bestPoint = uniform(-1.0, 1.0, nDims) prevPoint = bestPoint bestValue = testFunc(bestPoint) prevValue = bestValue for i in range(numSteps): testPoint = normal(prevPoint, spreads, nDims) value = testFunc(testPoint) prob = exp(prevValue-value) if prob > uniform(): prevPoint = testPoint prevValue = value if value < bestValue: bestPoint = testPoint bestValue = value coordinates = ", ".join(["%.3f" % v for v in testPoint]) print("%5d [%s] value:%e" % (i, coordinates, value)) return bestValue, bestPoint
65870e21c3e648fcbbd4dc9940d62b55bb9d6cef
darwady2/pythonStudies
/functions/quickSortFunction.py
391
3.859375
4
def quickSort(array): less = [] equal = [] greater = [] if len(array) > 1: p = array[0] for i in array: if p > i: less.append(i) elif p == i: equal.append(i) else: greater.append(i) return quickSort(less) + equal + quickSort(greater) else: return array
804fc329b85f92d2e26b5aaf653c30c10aee9885
daniel-reich/ubiquitous-fiesta
/KEz3TAQfh9WxSZMLH_4.py
202
3.75
4
def count_all(txt): count = {"LETTERS": 0, "DIGITS": 0} for ch in txt: if ch.isalpha(): count['LETTERS'] += 1 elif ch.isdigit(): count['DIGITS'] += 1 return count
280bc68b109e462731782054d2a86a0b6f185457
JuniorMSG/python_study
/study_project/text_mining/01_re_module/sample_re_012_exam.py
417
3.765625
4
# 연습문제 # 다양한 패턴의 홈페이지(웹사이트) 주소 URL을 매치시키는 정규식 패턴을 작성하시오? import re text = '우리의 홈페이지 회사소개 페이지 주소는 http://yourcompany.com/search?a=111&b=222 입니다.' pattern = re.compile( r'http[s]*://[a-zA-Z0-9-_]*[.]*[\w-]+[.]+[\w.-/~?&=%]+' ) rst_matchLst = re.findall( pattern, text ) print( ''.join(rst_matchLst) )
ede41742194167cd2760a4b8a536ac7ec589bc33
hanyberg/Python
/övn2_4.py
127
4.09375
4
x=int(input("What is your starting number")) y=int(input("What is your ending number")) for i in range (x,y+1): print(i)
5ebbef93b4e1ee2bac4eae34e33744b263d996a4
alphafan/Data_Structure_And_Algorithms
/array/common_three_sorted_array.py
802
4.15625
4
""" Find common elements in three sorted array https://www.geeksforgeeks.org/find-common-elements-three-sorted-arrays/ """ def commonElements(nums1, nums2, nums3): l1, l2, l3 = len(nums1), len(nums2), len(nums3) i, j, k = 0, 0, 0 results = [] while i < l1 and j < l2 and k < l3: if nums1[i] == nums2[j] and nums2[j] == nums3[k]: results.append(nums1[i]) i += 1 j += 1 k += 1 elif nums1[i] < nums2[j]: i += 1 elif nums2[j] < nums3[k]: j += 1 else: k += 1 return results if __name__ == '__main__': input1 = [1, 5, 10, 20, 40, 80] input2 = [6, 7, 20, 80, 100] input3 = [3, 4, 15, 20, 30, 70, 80, 120] print(commonElements(input1, input2, input3))
d5eed0332f625d6794854d4a3092d1b2dd076fe9
Airopolis/github_week2
/fib.py
255
3.625
4
# fibonacci.py def fib(): fibs = [1, 2] for i in range(1,100): fib = fibs[0]+fibs[1] fibs[0] = fibs[0] +1 fibs[1] = fibs[1] +1 return fibs def main(): print('OUTPUT', fib()) if __name__ == "__main__": main()
b214fb10c59ff0eb8ecdb34fb532bd69a5f990be
vanshikagandhi/Python_WE_Dec_18
/Functions_7.py
166
3.65625
4
def calc(x,y): return x+y, x-y, x*y, x/y #output = calc(12,45) #print(output) a,b,c,d = calc(12,45) print(a,b,c,d) a,b,*c = calc(12,6) print(a,b,c)
083dfab1068304cb3e91591de8561878ecd8a3fe
vkvasu25/leetcode
/arrays/single_number.py
3,003
3.90625
4
""" https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/549/ Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 """ """ BAD one (too slow): class Solution(object): def singleNumber(self, nums): for i in nums: if nums.count(i) == 1: return i """ # class Solution(object): # def singleNumber(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # nums.sort() # print(nums) # uniq = None # for i in range(len(nums)): # print('-------') # print(uniq) # print(nums[i]) # print(nums[i+1:]) # if nums[i] not in nums[i+1:] and uniq != nums[i]: # print('got it') # return nums[i] # else: # uniq = nums[i] # return uniq # class Solution(object): # def singleNumber(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # uniq = [] # for i in range(len(nums)): # if nums[i] not in nums[i+1:] and nums[i] not in uniq: # print('got it') # return nums[i] # else: # uniq.append(nums[i]) # return uniq class Solution(object): # this one works good but uses addional memory def singleNumber(self, nums): testik = {} for i in nums: if i in testik: testik[i] = 1 else: testik[i] = 0 for key in testik.keys(): if testik[key] == 0: return key # this one works like a charm but nor for huge input # def singleNumber(self, nums): # if len(nums) == 1: # return nums[0] # while True: # if nums[0] not in nums[1:]: # return nums[0] # else: # nums = [z for z in nums if z!=nums[0]] # def singleNumber(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # uniq = {} # for i in nums: # if i in uniq: # print('yes') # uniq[i] = 0 # print(uniq[i]) # else: # print('nope') # uniq[i] = 1 # print(uniq[i]) # print(uniq) # # for i in uniq.keys(): # if (uniq[i] == 1): # return i solution = Solution() # print(solution.singleNumber([2,2,1,1,8])) # print(solution.singleNumber([4,1,2,1,2])) # print(solution.singleNumber([2,2,1])) # print(solution.singleNumber([1,0,1])) # print(solution.singleNumber([1]))
51ac4b11639c9db1232569fa6bcefac6651659d3
ntexplorer/PythonPractice
/tkinterPrac/dialog.py
517
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/20 12:12 # @Author : Tian ZHANG # @Site : # @File : dialog.py # @Software: PyCharm # @Version: from tkinter import * from tkinter.dialog import * def dialog(): d = Dialog(None, title='This is a dialog', text='Dialog test', bitmap=DIALOG_ICON, default=0, strings=('test1', 'test2', 'test3')) print(d.num) t = Button(None, text='Test4', command=dialog) t.pack() b = Button(None, text='test5', command=t.quit) b.pack() t.mainloop()
c2853c66d01171b20dc2733a14dbed425f9ff14d
ttg432/dsj
/nlp/cos/StringTest.py
712
4.0625
4
import operator s = ' hello, world!' # 用于去掉字符串的头部和尾部的特殊字符串 print(s.strip("!")) # 截取左边的指定字符串,并生成新的字符串,如果没有则返回整个字符串 print(s.lstrip(' hello, ')) print(s.lstrip(" hello, ")) # 分隔字符串并转成数组 结果:[' hello, world', ''] print(s.rsplit('!')) # 连接字符串 # 查找字符 查找某个字符首次出现的位置 print(s.index("o")) # 比较字符串 False s1 = "hello" print(operator.eq(s1, s)) # 翻转字符串 s3 = s[::-1] print(s3) # 分隔字符串 sStr1 = 'ab,cde,fgh,ijk' sStr1=sStr1[sStr1.find(",") + 1:] #cde,fgh,ijk print(sStr1) #['cde', 'fgh', 'ijk'] print(sStr1.split(","))
9f3c2e1ac956c029ae992e4cc447f2e34db92aca
Lohit9/MasterYourAlgorithms
/General Questions/inversion_count.py
873
3.671875
4
# Standard implementation of the worls's most famous divide and conquer algorithm! # Inversion count implementation def merge(n1, n2, split): crossConflict = 0 i,j = 0,0 while i<len(n1) and j<len(n2): if n1[i] <= n2[j]: i += 1 else: # n1[i] > n2[j] crossConflict += split - i j += 1 return crossConflict def merge_sort(nums): if len(nums) <= 1: return 0 split = len(nums)/2 leftConflict = merge_sort(nums[:split]) rightConflict = merge_sort(nums[split:]) crossConflict = merge(nums[:split], nums[split:], split) # print leftConflict, rightConflict, crossConflict return leftConflict + rightConflict + crossConflict print merge_sort([7,1,6,2,5]) print merge_sort([2,34,1,3]) print merge_sort([3,1,4,6,5,2,8,7]) print merge_sort([1, 20, 6, 4, 5]) print merge_sort([2,3,4,1])
ee7ec7f91ee7da7b6faa1c4fb1c17e76e052e78a
ICCV/coding
/tree/q96.py
407
3.515625
4
class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ status = [0] * (n+1) status[0] = 1 status[1] = 1 for i in range(2,n+1): for j in range(1,i+1): status[i] += status[j-1]*status[i-j] return status[n] if __name__ == '__main__': s = Solution() n = 3 s.numTrees(n)
f8b8d85ed9ccfc0f144f71cd7a6ef7789c00d5a7
KATO-Hiro/AtCoder
/AtCoder_Virtual_Contest/macle_20220506/c/main.py
431
3.546875
4
# -*- coding: utf-8 -*- def main(): from itertools import product import sys input = sys.stdin.readline s = input().rstrip() n = len(s) patterns = product(["", "+"], repeat=n-1) ans = 0 for pattern in patterns: value = s[0] for i, p in enumerate(pattern, 1): value += p + s[i] ans += eval(value) print(ans) if __name__ == "__main__": main()
6353824bad95f96e7a08f168691ac39ec9260eaa
IshanPradhan/Data-Structures-and-Algorithms
/Graph/Graph.py
509
3.703125
4
from collections import defaultdict graph = defaultdict(list) def add_edge(graph,u,v): graph[u].append(v) def generate_edges(graph): edges = [] for node in graph: for neghibours in graph[node]: edges.append((node,neghibours)) return edges add_edge(graph,'a','b') add_edge(graph,'a','c') add_edge(graph,'b','c') add_edge(graph,'b','d') add_edge(graph,'b','e') add_edge(graph,'c','e') add_edge(graph,'c','b') add_edge(graph,'d','f') add_edge(graph,'e','f') print(graph)
59952f5ec98930fdb893d13de6a1531f320f9b34
daniel-reich/ubiquitous-fiesta
/Erhk4BdRwd6J4MXH9_8.py
95
3.59375
4
def is_leap(year): return True if year%400==0 or (year%4==0 and year%100 !=0) else False
6026edf8cb6504183c01f8c0ce644343281c0bb3
FranciscaOpoku/intro_to_python
/con.py
98
3.828125
4
import math degree =int (input("lsenter the degree")) radian = degree*math.pi/180 print (radian)
8a3746f8f711f3895e4ce0754c613b3de8bae10b
08vishal/Binary-Search-1
/Search_in_a_Rotated_Sorted_Array.py
1,032
3.875
4
#time:O(logn) #space:O(1) #LeetCode: Accepted #Problem Faced:applying binary search in the region where the array is rotated class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ l=0 r=len(nums)-1 while l <= r: mid=l+(r-l)//2 #if the element at mid is target then return mid if nums[mid]==target: return mid #check in which half is the target element elif nums[mid] >= nums[l]: #checking weather the target is rotated half or not if target >= nums[l] and nums[mid] > target: r = mid - 1 else: l = mid + 1 else: if target <= nums[r] and target > nums[mid]: l=mid+1 else: r=mid-1 #not found the target so returning -1 return -1
76eba90f32ae13501beddbaec1be521e003e1353
awright361B/WrightMATH361B
/NumberTheory/N1_Collatz_Alecia.py
404
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 12 13:53:11 2019 @author: aleci """ def printcollatz(a): #create a while loop while a != 1: print(a, end = ' ') # n is odd if a & 1: a = 3 * a + 1 # n is even else: a = a // 2 print(a) print("The terms of the sequence are") printcollatz(600)
61f2bf0f9a79a584b56515bc9000f3e72f772d2a
HvyD/AppleSiri-Privacy-Data_Engineer_prep
/LEET/Ransom_Note.py
921
4.125
4
""" Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Example 1: Input: ransomNote = "a", magazine = "b" Output: false Example 2: Input: ransomNote = "aa", magazine = "ab" Output: false Example 3: Input: ransomNote = "aa", magazine = "aab" Output: true """ class Solution: def canConstruct(self, ransomNote, magazine): mag=list(magazine) for i in ransomNote: if i in mag: mag.remove(i) else: return False return True obj = Solution() assert(obj.canConstruct("a", "b") == False) assert(obj.canConstruct("aa", "ab") == False) assert(obj.canConstruct("aa","aab") == True)
c6ec17725fead624a1ee1ad18a5f5a0b357aad29
AndreiR01/Recursion-Practise
/recusion stack calls.py
850
4
4
#We are building our own recursion stack def sum_to_one(n): result = 1 call_stack = [] #the below loop represents the recursive calls which lead to the base case while n != 1: execution_context = {"n_value": n} call_stack.append(execution_context) n -= 1 print(call_stack) print("BASE CASE REACHED") # the below loop simulates the recursive function when we return values as the function calls are "popped" off the call stack while len(call_stack) != 0: return_value = call_stack.pop() #each element we pop off the stack is a dictionary which represents a single recursive function call. print("Return value of {0} adding to result {1}".format(return_value['n_value'], result)) result += return_value['n_value'] return result, call_stack sum_to_one(4)
0102ff7e748ae24aae5ee8429c0fdc368dec5631
enessgurkan21/myRepo
/Hesap Makinesi v.1.1.py
1,759
4.1875
4
print(""" ---Hoşgeldiniz--- ==================================== 1-Toplama 2-Çıkarma 3-Çarpma 4-Bölme 5-Üs Alma 6-Kök Alma ==================================== """) while True: sayı=input("Lütfen Yapmak İstediğiniz İşlemi Giriniz : (Çıkış İçin 'q' Tuşuna Basınız) :") if sayı=="q": print("Sistemden Çıkılıyor...") break elif sayı=="1": sayı1=int(input("Lütfen Birinci Sayıyı Giriniz :")) sayı2=int(input("Lütfen İkinci Sayıyı Giriniz :")) sayı3=int(input("Lütfen Üçüncü Sayıyı Giriniz :")) print(sayı1,"+",sayı2,"+",sayı3,"=",sayı1+sayı2+sayı3) elif sayı=="2": sayı1=int(input("Lütfen Birinci Sayıyı Giriniz :")) sayı2=int(input("Lütfen İkinci Sayıyı Giriniz :")) print(sayı1,"-",sayı2,"=",sayı1-sayı2) elif sayı=="3": sayı1=int(input("Lütfen Birinci Sayıyı Giriniz :")) sayı2=int(input("Lütfen İkinci Sayıyı Giriniz :")) sayı3=int(input("Lütfen Üçüncü Sayıyı Giriniz :")) print(sayı1,"x",sayı2,"x",sayı3,"=",sayı1*sayı2*sayı3) elif sayı=="4": sayı1=int(input("Lütfen Birinci Sayıyı Giriniz :")) sayı2=int(input("Lütfen İkinci Sayıyı Giriniz :")) print(sayı1,"/",sayı2,"=",sayı1/sayı2) elif sayı=="5": sayı1=int(input("Lütfen Birinci Sayıyı Giriniz :")) sayı2=int(input("Lütfen İkinci Sayıyı Giriniz :")) print(sayı1,"^",sayı2,"=",sayı1**sayı2) elif sayı=="6": sayı1=int(input("Lütfen Sayıyı Giriniz :")) print(sayı1,"√2","=",sayı1**0.5) else: print("Hatalı İşlem Yaptınız Tekrar Deneyiniz.")
8059a7d8dd189c661ba77eacb159f0c32a618915
kwx4github/facebook-hackercup-problem-sets
/2015/round_1/2.Autocomplete/solutions/sources/x.3675.Tayfun
1,129
3.890625
4
#!/usr/bin/python # -*- coding: utf-8 -*- def print_case(case, cost): print "Case #%d: %s" % (case, str(cost) if cost is not None else 'impossible') if __name__ == '__main__': input_file = open('autocomplete.txt', 'r') number_of_cases = int(input_file.readline()) for case in xrange(1, number_of_cases + 1): number_of_words = int(input_file.readline()) message = list() letters_needed = 0 for i in xrange(number_of_words): word = input_file.readline().strip() message.append(word) # Prefix set begins with all words. prefix_set = set(message) for word in message: prefix = '' for letter in word: prefix = prefix + letter # Another word should not be equal to a prefix if prefix != word and prefix in prefix_set: continue # We found our prefix. letters_needed += len(prefix) prefix_set.add(prefix) break print_case(case, letters_needed)
ae25005394f3426188d2cd6a5d2fd0adf4227262
prachi1234bansal/python_tkinter_projects
/RockPS.py
2,567
3.703125
4
from tkinter import * from random import choice root=Tk() root.geometry("400x400") root.title("Rock Paper Scissor") l=Label(text="ROCK PAPER SCISSOR LETS GO TO PLAY",font="italic",bg="black",fg="dark blue",width=55,height=5) def r1(): #userChoice["text"]="User Choice is: Rock"; comp_list=["Rock","Paper","Scissor"]; comp_list_choice=choice(comp_list); comChoice["text"] = f"Computer Choice is {comp_list_choice}" r1["stat"] = "disabled"; r2["stat"] = "disabled"; r3["stat"] = "disabled"; if comp_list_choice=="Rock": msg["text"]="It is draw"; if comp_list_choice=="Paper": msg["text"]="Computer wins"; if comp_list_choice=="Scissor": msg["text"]="User wins"; def r2(): #userChoice["text"]="User choice is :Paper"; comp_list=["Rock","Paper","Scissor"]; comp_list_choice=choice(comp_list); comChoice["text"]=f"Computer Choice is {comp_list_choice}" r1["stat"] = "disabled"; r2["stat"] = "disabled"; r3["stat"] = "disabled"; if comp_list_choice=="Rock": msg["text"]="User wins"; if comp_list_choice=="Paper": msg["text"]="It is draw"; if comp_list_choice=="Scissor": msg["text"]="Computer wins"; def r3(): #userChoice["text"]="User Choice is :Scissor"; comp_list=["Rock","Paper","Scissor"]; comp_list_choice=choice(comp_list); comChoice["text"] = f"Computer Choice is {comp_list_choice}" r1["stat"]="disabled"; r2["stat"]="disabled"; r3["stat"]="disabled"; if comp_list_choice=="Rock": msg["text"]="Computer wins"; if comp_list_choice=="Paper": msg["text"]="User wins"; if comp_list_choice=="Scissor": msg["text"]="It is draw"; def active(): r1["stat"]="normal"; r2["stat"]="normal" r3["stat"]="normal" msg["text"]="" comChoice["text"]="" userChoice["text"]=""; r1=Button(text="Rock",fg="black",bg="white",font="bold",width=40,height=3,relief="groove",command=r1) r2=Button(text="Paper",fg="black",bg="white",font="bold",width=40,height=3,relief="groove",command=r2) r3=Button(text="Scissor",fg="black",bg="white",font="bold",width=40,height=3,relief="ridge",command=r3) active=Button(text="PLAY AGAIN!!",fg="white",bg="black",font="bold",width=40,height=3,relief="ridge",command=active) l.pack(); r1.pack(); r2.pack(); r3.pack(); comChoice=Label(root,text="") comChoice.pack(); msg=Label(root,text="",font=("Helvetica",17,"bold")) msg.pack(); active.pack(); root.mainloop();
54a450cf6b81126b8945e6ffd4c0f799dfcc844b
Gevorg102/Lesson_git_1
/Lesson_14, List.py
2,063
3.75
4
''' my_list = 'Hay Word, grgr' my_list = my_list.split() my_list1 = my_list.split(',') print(my_list) print(my_list1) ''' ''' fruits = ['banan', 'qiwi', 'mango'] fruits[1] = 'apple' print(fruits) ''' ''' my_list = list(range(100)) #kta 0-ic minchew 99 tver@ neraryal print(my_list) ''' ''' fruits = ['banan', 'qiwi', 'mango'] fruits.append('orange') print(fruits) ''' '''fruits = ['banan', 'qiwi', 'mango'] fruits.insert(1, 'orange') #kta worpes nshvac tvi indexi sharqum avelacnelu print(fruits)''' ''' fruits = ['banan', 'qiwi', 'mango'] fruits.remove('qiwi') #jnjum e print(fruits) ''' ''' fruits = ['banan', 'qiwi', 'mango'] test = fruits.pop(1) #hanum e nshvac indexow elementy u darcnum string print(fruits) print(test) ''' ''' fruits = ['banan', 'qiwi', 'mango'] del fruits[2] #nshvac@ indexow@ jnjum e, ete indexy nshvac chi bolor elementnern e jnjum print(fruits) ''' ''' fruits = ['banan', 'qiwi', 'mango'] numbers = [48, 48, -8847.48, 4897] fruits.extend(numbers) #nshvac parametrerow elementner@ print(fruits) ''' ''' numbers = [48, 21, -8847.48, 4897] numbers.sort() # poqric mec numbers.reverse() # fracnum e print(numbers) ''' ''' list1 = [1, 'Text', (48, 221)] list2 = [1, 'Text', (48, 221)] print(list1 == list2) # True print(list1 is list2) # False, qani wor id ner@ chi hamapatasxanelu qani wor integer chen ''' ''' res = [i for i in range(10)] print(res) c = [] for i in range(10): #kta nuyn hraman@ c.append(i) print(c) ''' # res = [i for i in 'Aram' if i=='A'] # print(res) ## A ''' my_list = [] for i in range(100): if i % 2 ==0: my_list.append(i**2) print(my_list) #zuyg tveri qarakusin ''' ''' res = [i**2 for i in range(100) if i %2==0] print(res) ''' ''' res = [i if i%2 ==0 else -1 for i in range(100)] print(res) ''' ''' my_list = [] for i in range(100): if i % 2 ==0: my_list.append(i) my_list.append('-1') print(my_list) ''' ''' my_list = [4, 2, 22, 5, 5, 6, 7, 5] for i in my_list: c = my_list.count(i) print('number: ', i, c, 'times') '''
a36d703c7f81e2cfba26b4687740bfb669c26e32
sigitkusuma/password_generator
/passwordGenerator.py
331
3.734375
4
import random lower = str(input('Masukan huruf kecil : ')) upper = str(input('Masukan huruf besar : ')) number = str(input('Masukan Angka : ')) symbol = str(input('Masukan Symbol : ')) all = lower + upper + number + symbol length = 16 password = "".join(random.sample(all, length)) password_width = len(password) print(password)
e9366c617a02514a1059a264e035ad0fead00c06
Pectin-eng/Lesson-6-Python
/lesson_6_task_5.py
941
4.03125
4
print('Задача 5.') # Пользователь вводит значение атрибута: class Stationery: title = input('Введите название вашего инструмента: ручка, карандаш или маркер ') def draw(self): print('Запуск отрисовки') class Pen(Stationery): def draw(self): print('Запуск письма') class Pencil(Stationery): def draw(self): print('Запуск штриховки') class Handle(Stationery): def draw(self): print('Запуск маркировки') # Ветвление определяет, метод какого из подклассов запускать: stationery = Stationery() pen = Pen() pencil = Pencil() handle = Handle() if stationery.title == 'ручка': pen.draw() elif stationery.title == 'карандаш': pencil.draw() else: handle.draw()
b9fa864820004e6dc760f4b39044131af744c331
curest0x1021/Python-Django-Web
/Apatira_Authman/Assignments/CoinToss/CoinToss.py
359
3.671875
4
def CoinToss(): import random newArr = [] tails = 0 heads = 0 for count in range(1000): random_num = random.random() newArr.append(round(random_num)) for count in range(len(newArr)): if(newArr[count] > 0): heads += 1 elif(newArr[count] == 0): tails += 1 print 'Number of Head Tosses: ', heads print 'Number of Tails Tosses: ', tails
1b81926b38658b15ed01c37add166fb569d9ce27
Amithabh/Python4Informatics
/Course_2_Python_to_Access Web Data/chapter12/Ex_12.3.py
632
4.15625
4
# Exercise 3: Use urllib to replicate the previous exercise of (1) retrieving the # document from a URL, (2) displaying up to 3000 characters, and (3) counting the # overall number of characters in the document. Don’t worry about the headers for # this exercise, simply show the first 3000 characters of the document contents. import urllib.request, urllib.parse, urllib.error name = input("Enter url:") fhand = urllib.request.urlopen(name) text = "" for line in fhand: text = text + line.decode() if len(text) > 3000: break print (text) text = text.strip() print ("Number of characters: ", len(text))
efb3418b235b52fb09f0e3bd1050c3d26168cd4d
asatiratnesh/Python_Assignment
/FileHandlingAssig/removeEmptyFiles.py
412
3.65625
4
# math import os import zipfile dirName = raw_input("Enter Dir Name: ") if os.path.exists(dirName): if os.path.isdir(dirName): os.chdir(dirName) for root, dirList, fileList in os.walk(os.getcwd()): for x in fileList: if not os.path.getsize(root+"\\"+x): os.remove(root+"\\"+x) print "Empty files removed..." else: print "Not Exists"
ea14a87a924c0a3249a884a9881a68a48e641b88
icarus1513/pythonAlgorithm
/Level2/소수 찾기.py
471
3.609375
4
import itertools def is_prime_number(x): if(x<=1): return False for i in range(2, x): if x % i == 0: return False return True def solution(numbers): val_set = set() for i in range(len(numbers),0,-1): for val in list(map("".join, itertools.permutations(numbers,i))): if is_prime_number(int(val)) is True: val_set.add(int(val)) print(val_set) answer = len(val_set) return answer
0af48cc85cff355c2502a8b5376608cfc267253c
xcorter/iquest
/main/schedule/api.py
6,607
3.984375
4
__author__ = 'Stepan' import calendar import datetime def increment_month(year, month): """ Функция для инкремента месяца, если месяц - декабрь, то инкремент года + месяц = 1 """ if month == 12: year += 1 month = 1 else: month += 1 return [year, month] def is_holiday(month, day): """ Праздничный ли день """ holidays = [ [1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8], [2, 23], [3, 8], [5, 1], [5, 2], [5, 3], [5, 9], [6, 12], [11, 4] ] for date in holidays: if date[0] == month and date[1] == day: return True return False def is_weekend(year, month, day): """ Является ли день выходным """ weekends = [5, 6] date = datetime.datetime(year, month, day) if date.weekday() in weekends: return True return False def fill_calendar(schedule, year, month, current_day, amount_days): ''' Заполняем расписание днями ''' days_in_month = calendar.monthrange(year, month)[1] for day in range(current_day, days_in_month + 1): amount_days -= 1 schedule.append([ year, month, day, is_weekend(year, month, day) ]) if amount_days == 0: return [schedule, amount_days] return [schedule, amount_days] # Устанавливаем праздники с переносом, если праздник выпал на выходной def set_holidays(schedule): next_holiday = False january = 1 for i in range(len(schedule)): date = schedule[i] if is_weekend(date[0], date[1], date[2]) and \ is_holiday(date[1], date[2]) and \ date[1] != january: next_holiday = True elif is_holiday(date[1], date[2]): schedule[i][3] = True elif next_holiday and not is_weekend(date[0], date[1], date[2]): schedule[i][3] = True next_holiday = False return schedule def get_shifted_date(): ''' Получаем дату отчета со двигом в два дня, т.к. если сегодня понедельник, а в субботу был праздник, то понедельник должен быть выходной ''' today = datetime.date.today() day = today.day month = today.month year = today.year if day > 3: return [year, month, day - 2] else: if month > 1: days_in_month = calendar.monthrange(year, month - 1)[1] return [year, month - 1, days_in_month + day - 2] else: month = 12 year -= 1 days_in_month = calendar.monthrange(year, month)[1] return [year, month, days_in_month] def create_schedule_obj(times): obj = [] arr_times = times.split() for time in arr_times: time_cost = time.split('=') if len(time_cost) != 2: continue obj.append({ 'time': time_cost[0].strip(), 'cost': time_cost[1].strip() }) return obj def create_schedule_form_template(template, quests): ''' Создает расписание для квестов с различными ценами ''' schedule_arr = {} for quest in quests: try: schedule = quest.schedule except: continue if template == "weekday": schedule_arr[quest.id] = create_schedule_obj(schedule.weekday) elif template == "before_weekend": schedule_arr[quest.id] = \ create_schedule_obj(schedule.weekday_before_weekend) elif template == "weekend": schedule_arr[quest.id] = \ create_schedule_obj(schedule.weekend) else: schedule_arr[quest.id] = \ create_schedule_obj(schedule.weekend_before_weekday) return schedule_arr def add_times(quest_calendar, quests): ''' Добавляем время с учетом следующего дня ''' for i in range(len(quest_calendar) - 1): day = quest_calendar[i] next_day = quest_calendar[i + 1] if not day[3] and not next_day[3]: day_type = "weekday" elif not day[3] and next_day[3]: day_type = "before_weekend" elif day[3] and next_day[3]: day_type = "weekend" else: # elif day[3] and not next_day[3]: day_type = "weekend_before_weekday" quest_calendar[i].append( create_schedule_form_template(day_type, quests) ) return quest_calendar def change_bool_to_int(schedule): for i in range(len(schedule)): schedule[i][3] = int(schedule[i][3]) return schedule def get_schedule(quests): ''' Генерация расписания Берем 34 дня, но возвращаем 30, чтобы на грницах расписания были правильные времена бронирования и цены ''' shifted = 2 amount_days = 34 [year, month, day] = get_shifted_date() quest_calendar = [] [quest_calendar, amount_days] = \ fill_calendar( quest_calendar, year, month, day, amount_days ) while amount_days > 0: [year, month] = \ increment_month(year, month) [quest_calendar, amount_days] = \ fill_calendar( quest_calendar, year, month, 1, amount_days ) quest_calendar = set_holidays(quest_calendar) schedule = add_times(quest_calendar, quests) schedule = change_bool_to_int(schedule) return schedule[shifted:32] def check_time_in_schedule(date, time, cost, quest_id, quests): schedule = get_schedule(quests) order_date = datetime.datetime.strptime(date, "%Y-%m-%d") for schedule_date in schedule: if schedule_date[0] == order_date.year and \ schedule_date[1] == order_date.month and \ schedule_date[2] == order_date.day: for key in schedule_date[4][quest_id]: if key["time"] == time and \ key["cost"] == str(cost): return True return False
5a648a8993e2d4d0ba3554f1e2bf8ba9170c8997
Jon-Ting/UH-DA-with-PY-summer-2019
/part01-e08_solve_quadratic/src/solve_quadratic.py
328
3.734375
4
#!/usr/bin/env python3 import math def solve_quadratic(a, b, c): sol1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) sol2 = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) return (sol1,sol2) def main(): print(solve_quadratic(1,-3,2)) print(solve_quadratic(1,2,1)) if __name__ == "__main__": main()
7fc2e4821ac858b7ee9c20ca880978f30a775bc8
IanFinlayson/exploring-cs
/programs/4.5.py
203
4.21875
4
# read in the starting cost cost = float(input("How much was the bill? ")) # figure out the cost with a 15% tip added total = cost * 1.15 # print the result print("The amount with 15% tip is", total)
8b8ce8200ae987aaf8995d84e41ec2bd60107abe
anandvv/CodingDojo
/projects/05-Python/LearningPython/LearningPython/CheckerBoard.py
317
3.546875
4
list1 = ['*', ' ', '*', ' ', '*', ' ', '*', ' '] list2 = [' ', '*', ' ', '*', ' ', '*', ' ', '*'] string1 = "" string2 = "" for i in range(0, 4): for item in list1: string1 += item for item in list2: string2 += item print string1 print string2 string1 = "" string2 = ""
c5df6ad6940c95ca1967b42543e6e21c49f4ca3d
andrewrgoss/udemy-ultimate-python
/Chapter 09/otheriters.py
335
3.59375
4
#numbers = range(1,11) #it = iter(numbers) #print(next(it)) import os files = os.popen('dir *.py') # popen runs os command for current directory and returns specified data in an object that is iterable fileit = iter(files) print(next(fileit), end='') print(next(fileit), end='') print(next(fileit), end='') print(next(fileit), end='')
15dc8ccd2cc57c1cb67a844fadd246622ff24739
Brunohdp/Meus-Projetos-Python
/ex001 - Desconto ou acrescimo em produtos usando if.py
440
3.734375
4
valor = float(input('Digite o valor do produto: R$')) res = str(input('Você quer pagar a vista ou parcelado? ')) j = valor + (valor*20/100) d = valor - (valor*35/100) if res == 'parcelado': print(f'O valor parcelado tem um acrescimo de 20% no valor total, portanto, você pagará: R${j:.2f} pelo produto!') else: print(f'O pagamento a vista tem um desconto de 35% do valor total, portanto, você pagará: RS{d:.2f} pelo produto!')
055b349b4166481559ba0d0d4c599711cb1d14c3
turbo00j/python_programming
/positive or negetive.py
125
3.71875
4
def pn(): a=int(input("Enter a number:")) if(a>0): print("positive") else: print("Negetive") pn()
132c283933930b596ea904d3169cba2318aaf490
regenalgrant/learning_journal_basic
/learning_journal_basic/dfs_bfs.py
1,257
3.90625
4
"""DFS and BFS.""" graph = { 'A': ['B', 'C'], 'B': ['D', 'A'], 'C': ['A'], 'D': ['B'] } class Graph: def __init__(self): self.edges = {} self.weights = {} def neighbors(self, node): return self.edges[node] def get_all(self, from_node, to_node): return self.weights[(from_node + to_node)] def dfs(graph, start, goal): visited = set() stack = [start] while stack: node = stack.pop() if node not in visited: visited.add(node) if node == goal: return for neighbor in graph[node]: if neighbor not in visited: stack.append(neighbor) def bfs(graph, start, goal): # maintain q paths queue = [] # irst path into the queue queue.append([start]) while queue: # irst path from the queue path = queue.pop(0) # last node from the path node = path[-1] # path found if node == goal: return path # adjacent nodes, construct path and push it to queue for adjacent in graph.get(node, []): new_path = list(path) new_path.append(adjacent) queue.append(new_path)
28e90b75dfb54d12b0c1fbe5b1cf4c406f61822c
dfhai/weekend1
/day1/LoginTest2.py
712
3.65625
4
#1.打开浏览器 from selenium import webdriver driver = webdriver.Chrome() driver.get("http://localhost/") #2.点击登陆链接 driver.find_element_by_link_text("登录").click() #从浏览器的所有窗口中,排除第一个窗口,剩下第二个窗口 #把selenium切花到第二个窗口 cwh = driver.current_window_handle whs = driver.window_handles #item 表示集合中的一个元素 for item in whs: if item == cwh: driver.close() else: driver.switch_to.window("item") #输入用户名和密码 driver.find_element_by_id("username").send_keys("df001") driver.find_element_by_id("password").send_keys("123456") driver.find_element_by_class_name("login_btn").click()
7a54350dda0cbc2f1ca52c3df20f938180aed8dd
stoppable408/algorithms-and-data-structures
/cencry-encryption/test-cases.py
389
3.5
4
import unittest import cencry_encryption class TestSum(unittest.TestCase): def test_encryption1(self): test_input = "2\nbaax\naaa" cencry_encryption.get_input(test_input) self.assertEqual(sum([1, 2, 3]), 6, "Should be 6") def test_sum_tuple(self): self.assertEqual(sum((1, 2, 3)), 6, "Should be 6") if __name__ == '__main__': unittest.main()
a7e1448c274d07323dc1cb0e1f90b0daa75e15cd
mrbug2020/PyLearn_100PythonExercises
/resolve-exercises/Ex07.py
1,059
3.8125
4
#! python3 """ Bài 07: Câu hỏi: Python có nhiều hàm được tích hợp sẵn, nếu không biết cách sử dụng nó, bạn có thể đọc tài liệu trực tuyến hoặc tìm vài cuốn sách. Nhưng Python cũng có sẵn tài liệu về hàm cho mọi hàm tích hợp trong Python. Yêu cầu của bài tập này là viết một chương trình để in tài liệu về một số hàm Python được tích hợp sẵn như abs(), int(), input() và thêm tài liệu cho hàm bạn tự định nghĩa. """ def functionDocEx(param): """ this is documention for function. fucName: 'functionDocEx' param: {param} @return docOfThisFunc """ return functionDocEx.__doc__ def square(num): """ Function return square of number """ return num ** 2 def main(): print(functionDocEx.__doc__) print(abs.__doc__) print(input.__doc__) print(int.__doc__) print(square.__doc__) def test(): print("unit test success.") if __name__ == "__main__": test() main()
bc3c6cf88d1d00c7c15721a220b9a81324edea52
Li-Pro/Short-Codes
/topic2.py
3,075
3.78125
4
""" Topic: Analysis of MAX hash collision. This is not the analysis of expected collision complexity, but the maximum collision occurs in a hash table. In the analyses: N = bucket size, M = object count. """ import math import random def countCollid(N, M): # Count the max (not average nor expected sum) collisions. cnt = [0] * N mxn = 0 for i in range(M): x = random.randrange(N) cnt[x] += 1 mxn = max(mxn, cnt[x]) return mxn def test1(size=1000): """ Fixed N, with M growing. """ return [countCollid(size, i) for i in range(1, size)] def test2(size=1000): """ With N growing, and N = M. """ return [countCollid(i, i) for i in range(1, size)] def runSubTest(testfunc, size, estf=lambda x: x+3, estlabel='O(N)'): T = testfunc(size) avgt, estt = 1, 1 for i in range(1, size): x = T[i-1] avgt *= (x ** (1/size)) estt *= ((x / estf(i)) ** (1/size)) print('Result: average({tfunc}) = {avg:.3f}, average({tfunc}/{estname}) = {est:.3f}' .format(tfunc=testfunc.__name__, avg=avgt, est=estt, estname=estlabel)) def runTest(): def factorSameOrderOfMagnitude(func): def wrapFunc(factor=1.0): assert(0.1 <= factor <= 10.0) # One order of magnitude (base 10) return func(factor) return wrapFunc @factorSameOrderOfMagnitude def fNlogN(factor=1.0): return (lambda i: math.log2(i+3) * factor) @factorSameOrderOfMagnitude def fN(factor=1.0): return (lambda i: (i+1) * factor) size = 1000 runSubTest(test1, size, fNlogN(0.426), 'O(logM)') # seems to be logM ? runSubTest(test2, size, fNlogN(0.577), 'O(logM)') # seems to be logM too? #-------------------------- Testing Part ---------------------------- import importlib import sys if __name__ == "__main__": ### MODULE RUN ### def main(): """ This only runs simple tests. Use plotGraph (by Li-Pro) to graph the function. plotGraph: https://github.com/Li-Pro/plotGraph.git """ runTest() main() else: ### MODULE IMPORTED ### def runHook(pathspec='Locals.plotGraph'): """ Run the external plotGraph program. Usage: runHook(path_to_plotGraph_folder) """ plotGraph = __import__(pathspec, fromlist=['plotGraph']).plotGraph plotGraph.startPlot({**globals(), **locals()}) def reload(glob=None): """ Reload this module (at runtime). Usage: reload() if called from the __main__ module. reload(globals()) otherwise. """ if glob == None: glob = vars(sys.modules['__main__']) currMod = sys.modules[__name__] importlib.reload(currMod) glob.update({name: getattr(currMod, name) for name in __all__}) def testAvg(func, count=100): def testFunc(i): sumt = 0 for t in range(count): sumt += func(i) return sumt / count return testFunc ## plotGraph plotting arguments ## pltTest1 = dict(func=testAvg(lambda i: countCollid(1000, i)), domain=(1, 1000), precision=10) pltTest2 = dict(func=testAvg(lambda i: countCollid(i, i)), domain=(1, 1000), precision=10) __all__ = ['reload', 'runHook', 'pltTest1', 'pltTest2'] #--------------------------------------------------------------------
cb829efeb6af90460af64d767ff3ba29bd3acccb
lekuid/Practice
/mergelists.py
248
4.15625
4
#return a new sorted merged list from K sorted lists, each with size N def merge(lists): merged = [] for x in lists: for y in x: merged.append(y) return sorted(merged) print(merge([[1, 2 , 8], [0], [5, 6, 1, 3]]))
69989e0a19d997cfbc030a478587bc9536df0f23
rnithin1/school
/20-fall/ee c106a/hw/code/hw1.py
2,998
3.53125
4
import numpy as np ########## PROBLEM 4 ########## def g02(t, v2, R2): ''' Problem 4 (a) Returns the 4x4 rigid body pose g_02 at time t given that the satellite is orbitting at radius R2 and linear velocity v2. Args: t: time at which the configuration is computed. v2: linear speed of the satellite, in meters per second. R2: radius of the orbit, in meters. Returns: 4x4 rigid pose of frame {2} as seen from frame {0} as a numpy array. Functions you might find useful: numpy.sin numpy.cos numpy.array numpy.sqrt numpy.matmul numpy.eye Note: Feel free to use one or more of the other functions you have implemented in this file. ''' g = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) return g def g01(t, v1, R1): ''' Problem 4 (b) Returns the 4x4 rigid body pose g_01 at time t given that the satellite is orbitting at radius R1 and linear velocity v1. Args: t: time at which the configuration is computed. v1: linear speed of the satellite, in meters per second. R1: radius of the orbit, in meters. Returns: 4x4 rigid pose of frame {1} as seen from frame {0} as a numpy array. Functions you might find useful: numpy.sin numpy.cos numpy.array numpy.sqrt numpy.matmul numpy.eye Note: Feel free to use one or more of the other functions you have implemented in this file. ''' g = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) return g def g21(t, v1, R1, v2, R2): ''' Problem 4 (c) Returns the 4x4 rigid body pose g_21 at time t given that the first satellite is orbitting at radius R1 and linear velocity v1 and the second satellite is orbitting at radius R2 and linear velocity v2. Args: t: time at which the configuration is computed. v1: linear speed of satellite 1, in meters per second. R1: radius of the orbit of satellite 1, in meters. v2: linear speed of satellite 2, in meters per second. R2: radius of the orbit of satellite 2, in meters. Returns: 4x4 rigid pose of frame {2} as seen from frame {0} as a numpy array. Functions you might find useful: numpy.matmul numpy.linalg.inv Note: Feel free to use one or more of the other functions you have implemented in this file. ''' g = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) return g ########## END PROBLEM 2 ##########
7aa25022314189577f161dc289c2c3bf57b95119
pejorativefox/codetabai-oct-2014
/04_pew_pew_make_the_ship_shoot.py
4,869
4.09375
4
# I wont go over the things covered in the last section. If something here is # not covered by a comment look back a step. import pygame from pygame.locals import * pygame.init() screen = pygame.display.set_mode((800, 600)) image = pygame.image.load('assets/sprite_sheet.png') game_running = True ship_x = screen.get_width() / 2 ship_y = screen.get_height()-40 sprite_width, sprite_height = (36, 36) ship_sprite_area = (0*sprite_width, 2*sprite_height, sprite_width, sprite_height) # Just like before we are gonna calculate a sub rectangle for the bullet sprite. # it is on the 3rd row and the 3rd column. (remember ranges start at 0!!!) bullet_sprite_area = (0,204,13,22) # Here is our first exposure to the python class class Bullet(object): """ Our bullet has a state that need to be kept and in addition we will place the update code here as well. A bullet knows what its suppose to do and this design will help us keep code duplication to a minimum. """ def __init__(self, start_x, start_y): """The __init__ method is a special method of python classes that is analogous to constructors in other languages. Here we can accept data from the creation call and build an initial state for the bullet""" # Here we set the initial position of the bullet self.x = start_x self.y = start_y # Using the method get_ticks we can store the time in milliseconds # that the bullet is created. We will need this later in update() to # calculate the movement of the bullet on the screen. self.last_time = pygame.time.get_ticks() def update(self): """Our update method is going to get called with every loop of our game. Here we are gonna update the location of the bullet using the time functions provided by pygame""" # We need a temp local variable with the current time in milliseconds current_time = pygame.time.get_ticks() # We can calculate the delta by subtracting the last time from our # current time and that gives us the total milliseconds since the # last update delta_time = current_time - self.last_time # The bullets move up on the screen so we will subtract the delta * 1px # from the y axis of the bullet. This is VERY crude and only for an # example. This does not take into account actual time as a faster # computer will do this faster. The math to make this framerate # independent is not complicated but requires more variables. self.y -= 1 * delta_time # When we are done moving the bullet we will reset out last_time member # to the current time so the value is fresh and we can get a proper # value for the amount of time that has passed since last call. self.last_time = current_time # We will store our active bullets in a simple array. bullets = [] while game_running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: game_running = False if event.key == K_LEFT: ship_x -= 5 if event.key == K_RIGHT: ship_x += 5 # A small addition to our key handling code. when the spacebar is # pressed we can add a new bullet to the play area. here I use the # current location of our ship. if event.key == K_SPACE: bullets.append(Bullet(ship_x+2, ship_y)) print 'shoot' screen.fill((0, 0, 0)) # We need a place to store bullets that need to be removed from our array # our bullet class has a member alive which will be set if the y position # goes off the screen or later when they can hit enemies. The reason we # have to track these separate is, you can not modify a sequence while # you are looping through it with the for keyword. dead_bullets = [] # Lets iterate all the bullets, update them and check if they need to be # deleted, then draw them. for bullet in bullets: bullet.update() # Here we check if the y position of the bullet is off the screen if bullet.y <= 0: # if so append it to dead_bullets dead_bullets.append(bullet) # Here we draw each bullet at its new position screen.blit(image, (bullet.x, bullet.y, 0, 0), bullet_sprite_area) # now that we have a list of bullets that are no longer visible to the # player and cant effect the game. we can iterate over it and delete them # from our collection of active bullets for dead in dead_bullets: print 'removing', dead bullets.remove(dead) screen.blit(image, (ship_x, ship_y, 0, 0), ship_sprite_area) pygame.display.flip() print 'Fin.'
ac3e0fe9c37e1a489cae2b2026d633de8d71edf1
jkatzur/AIND-VUI-Capstone
/sample_models.py
8,454
3.640625
4
from keras import backend as K from keras.models import Model from keras.layers import (BatchNormalization, Conv1D, Dense, Input, TimeDistributed, Activation, Bidirectional, SimpleRNN, GRU, LSTM) def simple_rnn_model(input_dim, output_dim=29): """ Build a recurrent network for speech """ # Main acoustic input input_data = Input(name='the_input', shape=(None, input_dim)) # Add recurrent layer simp_rnn = GRU(output_dim, return_sequences=True, implementation=2, name='rnn')(input_data) # Add softmax activation layer y_pred = Activation('softmax', name='softmax')(simp_rnn) # Specify the model model = Model(inputs=input_data, outputs=y_pred) model.output_length = lambda x: x print(model.summary()) return model def rnn_model(input_dim, units, activation, output_dim=29): """ Build a recurrent network for speech """ # Main acoustic input input_data = Input(name='the_input', shape=(None, input_dim)) # Add recurrent layer rnn = GRU(units, activation=activation, return_sequences=True, implementation=2, name='rnn')(input_data) """ TODO: Add batch normalization - see https://arxiv.org/abs/1502.03167 Most notably, 'Batch Normalization achieves the same accuracy with 14 times fewer training steps, and beats the original model by a significant margin.' This is achieved by normalizing distribution of layers between inputs. """ bn_rnn = BatchNormalization(name='bn_rnn')(rnn) # TODO: Add a TimeDistributed(Dense(output_dim)) layer time_dense = TimeDistributed(Dense(output_dim))(bn_rnn) # Add softmax activation layer y_pred = Activation('softmax', name='softmax')(time_dense) # Specify the model model = Model(inputs=input_data, outputs=y_pred) model.output_length = lambda x: x print(model.summary()) return model def cnn_rnn_model(input_dim, filters, kernel_size, conv_stride, conv_border_mode, units, output_dim=29): """ Build a recurrent + convolutional network for speech """ # Main acoustic input input_data = Input(name='the_input', shape=(None, input_dim)) # Add convolutional layer # this adds a convolutional layer up front to transform the input data prior to the RNN conv_1d = Conv1D(filters, kernel_size, strides=conv_stride, padding=conv_border_mode, activation='relu', name='conv1d')(input_data) # Add batch normalization bn_cnn = BatchNormalization(name='bn_conv_1d')(conv_1d) # Add recurrent layer rnn = GRU(units, activation='relu', return_sequences=True, implementation=2, name='rnn')(bn_cnn) bn_rnn = BatchNormalization(name='bn_rnn')(rnn) # TODO: Add a TimeDistributed(Dense(output_dim)) layer time_dense = TimeDistributed(Dense(output_dim))(bn_rnn) # Add softmax activation layer y_pred = Activation('softmax', name='softmax')(time_dense) # Specify the model model = Model(inputs=input_data, outputs=y_pred) model.output_length = lambda x: cnn_output_length( x, kernel_size, conv_border_mode, conv_stride) print(model.summary()) return model def cnn_output_length(input_length, filter_size, border_mode, stride, dilation=1): """ Compute the length of the output sequence after 1D convolution along time. Note that this function is in line with the function used in Convolution1D class from Keras. Params: input_length (int): Length of the input sequence. filter_size (int): Width of the convolution kernel. border_mode (str): Only support `same` or `valid`. stride (int): Stride size used in 1D convolution. dilation (int) """ if input_length is None: return None assert border_mode in {'same', 'valid'} dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1) if border_mode == 'same': output_length = input_length elif border_mode == 'valid': output_length = input_length - dilated_filter_size + 1 return (output_length + stride - 1) // stride def deep_rnn_model(input_dim, units, recur_layers, output_dim=29): """ Build a deep recurrent network for speech """ # Main acoustic input input_data = Input(name='the_input', shape=(None, input_dim)) recur_layer_data = input_data # TODO: Add recurrent layers, each with batch normalization for recur_layer in range(0,recur_layers): recur_layer_name = 'recur_layer_' + str(recur_layer) deep_rnn = GRU(units, activation='relu', return_sequences=True, implementation=2, name=recur_layer_name)(recur_layer_data) bnn_layer_name = 'bnn_layer_' + str(recur_layer) recur_layer_data = BatchNormalization(name=bnn_layer_name)(deep_rnn) # TODO: Add a TimeDistributed(Dense(output_dim)) layer time_dense = TimeDistributed(Dense(output_dim))(recur_layer_data) # Add softmax activation layer y_pred = Activation('softmax', name='softmax')(time_dense) # Specify the model model = Model(inputs=input_data, outputs=y_pred) model.output_length = lambda x: x print(model.summary()) return model def bidirectional_rnn_model(input_dim, units, output_dim=29): """ Build a bidirectional recurrent network for speech """ # Main acoustic input input_data = Input(name='the_input', shape=(None, input_dim)) # TODO: Add bidirectional recurrent layer bidir_rnn = Bidirectional(GRU(units, activation='relu', return_sequences=True, implementation=2, name='bidir_rnn'), merge_mode='concat')(input_data) # TODO: Add a TimeDistributed(Dense(output_dim)) layer time_dense = TimeDistributed(Dense(output_dim))(bidir_rnn) # Add softmax activation layer y_pred = Activation('softmax', name='softmax')(time_dense) # Specify the model model = Model(inputs=input_data, outputs=y_pred) model.output_length = lambda x: x print(model.summary()) return model def final_model(input_dim, units, recur_layers, output_dim=29): """ Build a deep network for speech """ # Main acoustic input input_data = Input(name='the_input', shape=(None, input_dim)) # TODO: Specify the layers in your network recur_layer_data = input_data # First, I chose to enable deep rnns because the deep rnn approach performed better than the standard rnn for recur_layer in range(0,recur_layers): recur_layer_name = 'recur_layer_' + str(recur_layer) """ I chose to make my deep rnns using BiDirectional rnns becase the basic BiDirectional RNN performed exceedingly well compared to the simple_rnn model, even without any batch normalization - which was crucial in getting the rnn_model to perform well. I also tweaked my deep rnn from above to add dropout_W and dropout_U to the rnns. Dropout_W drops some input data at the start of the model. My intuition is to avoid overfitting between layers so I included this at .1 = 10% of input data dropped each run. I also include dropout_U. Dropout_U drops values out between recurrent connections. This helps us avoid overfitting within a given epoch for each RNN. Given RNNs penchant for overfitting I wanted to experiment with both options. The idea to include dropouts came from the documentation and the referred paper here: https://arxiv.org/pdf/1512.05287.pdf """ deep_bi_rnn = Bidirectional(GRU(units, activation='relu', return_sequences=True, implementation=2, name=recur_layer_name), merge_mode='concat')(recur_layer_data) bnn_layer_name = 'bnn_layer_' + str(recur_layer) # Batch normalization is included because we saw how effective this would be recur_layer_data = BatchNormalization(name=bnn_layer_name)(deep_bi_rnn) time_dense = TimeDistributed(Dense(output_dim))(recur_layer_data) # TODO: Add softmax activation layer y_pred = Activation('softmax', name='softmax')(time_dense) # Specify the model model = Model(inputs=input_data, outputs=y_pred) # TODO: Specify model.output_length model.output_length = lambda x: x print(model.summary()) return model
65a4e84bcefc9063be6f7659141a1eb637d02ede
Kavipriya98/Guvi
/s_is_palindrome_or_not.py
110
3.984375
4
def palindrome(N): M=N[::-1] if(M==N): print("yes") else: print("no") N=input("") palindrome(N)
ef5f42ab822a2194d109be20c42a4567cde406cc
beingayush/random-test-case-generator
/src/main.py
6,821
3.75
4
import random import os from numpy import random as npr # ------------- utils ------------------ def generate_non_uniform_random_array(N, min_val, max_val): for _ in range(N): yield random.randint(min_val, max_val) def generate_uniform_random_array(N, min_val, max_val): res = [] if max_val - min_val + 1 >= N: # n is smaller compared to range so generate distinct # divide into buckets and choose randomly from each extra = (max_val - min_val + 1) % N bucket_size = (max_val - min_val + 1) // N st = 0 for i in range(N - 1): offset = 1 if i < extra else 0 lo, hi = min_val + st, min_val + st + offset + bucket_size - 1 yield random.randint(lo, hi) st += bucket_size + offset yield random.randint(min_val + st, max_val) else: # n is much larger hence include everything with uniform distribution for i in range(N): yield min_val + i % (max_val - min_val + 1) def generate_pairs_non_uniform(N, p0min, p0max, p1min, p1max): # order is random and everything is random gen1 = iter(generate_non_uniform_random_array(N, p0min, p0max)) gen2 = iter(generate_non_uniform_random_array(N, p1min, p1max)) for _ in range(N): yield (next(gen1), next(gen2)) def generate_pairs_uniform(N, p0min, p0max, p1min, p1max, order): # order is inc, dec, noninc, nondec if not order in ['inc', 'dec', 'noninc', 'nondec']: raise Exception("order invalid") gen = iter(generate_uniform_random_array(N, p0min, p0max)) for _ in range(N): first = next(gen) if order is 'inc': yield (first, random.randint(first + 1, min(p1max, max(first + 1, p1max)))) elif order == 'dec': yield (first, random.randint(max(p1min, min(p1min, first - 1)), first - 1)) elif order is 'noninc': yield (first, random.randint(max(p1min, min(p1min, first)), first)) elif order is 'nondec': yield (first, random.randint(first, min(p1max, max(first + 1, p1max)))) def write_to_file(file_path, content): try: file = open(file_path, 'w') file.write(content) file.close() except Exception as e: print(e) # todo maybe better error handling print('error in writing to file') # ----------- main functions ------------------------- def generate_random_array(file_path, config={}): def gen_arr_str(N, min_v, max_v, distinct, include_n): res = generate_uniform_random_array(N, min_v, max_v) if distinct \ else generate_non_uniform_random_array(N, min_v, max_v) res = map(lambda x: x.__str__(), res) res = [" ".join(res)] if include_n: res.append(N.__str__()) res.reverse() return "\n".join(res) try: tc = config['n_test_cases'] N_min = config['arr_size_min'] N_max = config['arr_size_max'] N_same = config['arr_sizes_all_same'] N_uniform = config['arr_sizes_uniform_distribution'] min_val = config['min_value'] max_val = config['max_value'] distinct_val = config['distinct_value_flag'] include_n = config['include_n_flag'] include_tc = config['include_n_test_cases_flag'] Ns = (generate_non_uniform_random_array(tc, N_min, N_max) if not N_uniform \ else generate_uniform_random_array(tc, N_min, N_max)) if not N_same \ else generate_non_uniform_random_array(tc, N_min, N_min) res = [gen_arr_str(N, min_val, max_val, distinct_val, include_n) for N in Ns] # todo shuffle res if include_tc: res.append(tc.__str__()) res.reverse() content = "\n".join(res) write_to_file(file_path, content) return True except Exception as e: print(e) return False def generate_random_string(file_path, config={}): pass def generate_random_char_matrix(file_path, config={}): pass def generate_random_array_pairs(file_path, config={}): # for inc dec the ranges must be valid # need to figure out for distinct or maybe not needed pass def generate_random_matrix(file_path, config={}): # todo make different rows and columns def square_gen(n): pass def row_less_col_gen(): pass def simple_gen(): pass def make_mat_str(rows, cols, arr): pass try: tc = config['n_test_cases'] rows_min = config['num_rows_min'] rows_max = config['num_rows_max'] cols_min = config['num_cols_min'] cols_max = config['num_cols_max'] all_same_size = config['all_same_size'] min_val = config['min_value'] max_val = config['max_value'] distinct = config['distinct_flag'] include_nm = config['include_n_m_flag'] except Exception as e: print(e) return False def generate_random_numbers(file_path, config={}): try: n_test_cases = config['n_test_cases'] min_val = config['min_value'] max_val = config['max_value'] include_n = config['include_n_test_cases_flag'] uniform = config['uniform_distribution'] nums = generate_uniform_random_array(n_test_cases, min_val, max_val) if uniform \ else generate_non_uniform_random_array(n_test_cases, min_val, max_val) nums = list(nums) # todo shuffle if include_n: nums.append(n_test_cases) nums.reverse() content = "\n".join(map(lambda x: x.__str__(), nums)) write_to_file(file_path, content) return True except Exception as e: print(e) return False # ---------- for manual test case generation ---------- def write_list(file_path, list, include_tc=True, include_n=True): pass def write_list_of_list(file_path, list_of_list, include_tc=True, include_n=True): pass def main(): parent_dir = os.path.join(os.getcwd(), "..", "generated_input") generate_random_numbers(os.path.join(parent_dir, 'a.in'), config={ 'n_test_cases': 10, 'min_value': 1, 'max_value': 1, 'include_n_test_cases_flag': True, 'uniform_distribution': True }) generate_random_array(os.path.join(parent_dir, 'b.in'), config={ 'n_test_cases': 10, 'arr_size_min': 1, 'arr_size_max': 1, # dont care if next true 'arr_sizes_all_same': False, 'arr_sizes_uniform_distribution': False, # dont care if prev true 'min_value': 2, 'max_value': 10, 'distinct_value_flag': True, 'include_n_flag': True, 'include_n_test_cases_flag': True, }) # pass if __name__ == '__main__': main()
7538e1b902da842cb41370ffa204d85ae32acfec
Hrishikeshbele/Competitive-Programming_Python
/middleoflinkedlist.py
1,420
4.03125
4
''' Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ first=head #here we first find the len of linked list then mid of linked list #and we move the pointer to mid of linked list and return that pointer #see this pointer will always point to our desired elm since first it is pointed to first elm and then moving j=0 while head: j+=1 head=head.next head=first for i in range(j//2): head=head.next return head #another solution using pointer techique,we are moving slow pointer by one node and fast by 2 node and we see that #by the point fast pointer reaches end of linked list our slow pointer reaches mid elm of linked list class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ slow=fast=head while fast and fast.next: slow=slow.next fast=fast.next.next return slow
27a2186c95a5e76982179e74f414579ef2fe1caf
wenchonglai/leetcode-practice
/202108/20210831-305-number-of-islands-ii.py
1,353
3.75
4
# LintCode 434 · Number of Islands II """ Definition for a point. class Point: def __init__(self, a=0, b=0): self.x = a self.y = b """ class Solution: """ @param n: An integer @param m: An integer @param operators: an array of point @return: an integer array """ def numIslands2(self, m, n, operators): # write your code here res = [] grid = {} ct = 0 def findroot(x, y): nonlocal grid while (x, y) != grid[(x, y)]: (x, y) = grid[(x, y)] return (x, y) for op in operators: x, y = op.x, op.y for (dx, dy) in ((-1, 0), (0, -1), (1, 0), (0, 1)): x_, y_ = x + dx, y + dy if 0 <= x_ < m and 0 <= y_ < n and (x_, y_) in grid: tup = findroot(x_, y_) if (x, y) not in grid: grid[(x, y)] = tup else: t2 = findroot(x, y) if grid[tup] != t2: grid[(x_, y_)] = t2 grid[tup] = t2 ct -= 1 if (x, y) not in grid: grid[(x, y)] = (x, y) ct += 1 res.append(ct) return res
08b9db2693cd5a1bdc8d5d4a5572cb0d7a909336
BluArsenic/Computer-Science
/adventure.py
528
3.953125
4
def start(): choice = input("\n\n\n\n\n\nGreetings! \n\nYou are heading to the dining hall one day" "when there's a bear walking with a dinosaur on campus!! Do you" "\n\n1) Run, 2) Hide, or 3) Resist? \n\n>>") #/n = enter \s = space \t = tab if choice == "1": inside() elif choice == "2": inside() elif choice == "3": walkWithDinoBear() else: print("You nincompoop!") exit() def inside(): print("Lame!") def walkWithDinoBear(): print("We love a brave sister") start() # exit() >> ends the game
ac45c69ff2a821a42702c6ca9a0c3ac6798f89a2
xiaohuwu/Python-camp
/learningPython/src/day03/test01.py
248
3.578125
4
""" 水仙花数 """ import math for x in range(100,1000): bai = int(x / 100) sheng = x % 100 shi = int(sheng / 10) ge = x % 10 if (math.pow(bai, 3) + math.pow(shi, 3) + math.pow(ge, 3)) == x: print("x = {}".format(x))
260b1f1811c736fff1beb5cc449972032252f171
KaloObr/Python-Fundamentals
/p3_list_basics/lab_1_courses.py
120
3.765625
4
n = int(input()) temp_list = [] for i in range(n): string = input() temp_list.append(string) print(temp_list)
23b54f28bf3c9ec089283d628f005ebe9f255b6e
Jill1627/lc-notes
/wordDistanceII.py
632
3.84375
4
""" LC 244 Shortest Word Distance II """ class WordDistance(object): def __init__(self, words): """ :type words: List[str] """ self.hm = dict() for i, word in enumerate(words): self.hm[word] = self.hm.get(word, []) + [i] def shortest(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ return min(abs(i1 - i2) for i1 in self.hm[word1] for i2 in self.hm[word2]) # Your WordDistance object will be instantiated and called as such: # obj = WordDistance(words) # param_1 = obj.shortest(word1,word2)
c7356a3497d4b4d55790c5f4d0154ca3a98149ac
qkrwldnjs89/dojang_python
/UNIT_11_시퀀스 자료형 활용하기/126p_시퀀스 객체 연결하기.py
344
3.515625
4
# 시퀀스 객체 연결하기 a = [0, 10, 8, 9] b = [213, 5, 1, 2] print(a + b) ''' #range(0, 10) + range(10, 20) 는 에러 발생 range 는 + 연산자로 객체 연결 불가 -> range 를 튜플, 리스트로 만들어 연결하면 해결 ''' # 문자열에 숫자를 연결하려면 print("Hello, " + str(10) + " people.")
837a8ef97bc9d6830fc399c2033ab92ce231ed8b
franklingu/leetcode-solutions
/questions/number-of-lines-to-write-string/Solution.py
1,840
4.15625
4
""" We are to write the letters of a given string S, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths, an array where widths[0] is the width of 'a', widths[1] is the width of 'b', ..., and widths[25] is the width of 'z'. Now answer two questions: how many lines have at least one character from S, and what is the width used by the last such line? Return your answer as an integer list of length 2. Example : Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] S = "abcdefghijklmnopqrstuvwxyz" Output: [3, 60] Explanation: All letters have the same length of 10. To write all 26 letters, we need two full lines and one line with 60 units. Example : Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] S = "bbbcccdddaaa" Output: [2, 4] Explanation: All letters except 'a' have the same length of 10, and "bbbcccdddaa" will cover 9 * 10 + 2 * 4 = 98 units. For the last 'a', it is written on the second line because there is only 2 units left in the first line. So the answer is 2 lines, plus 4 units in the second line. Note: The length of S will be in the range [1, 1000]. S will only contain lowercase letters. widths is an array of length 26. widths[i] will be in the range of [2, 10]. """ class Solution(object): def numberOfLines(self, widths, S): """ :type widths: List[int] :type S: str :rtype: List[int] """ ls, p = 0, 0 for c in S: w = widths[ord(c) - ord('a')] if p + w > 100: ls += 1 p = w else: p += w return [ls + 1, p]
ee74f284c06121bd9ca595f77d20021caee27bf3
gofr1/python-learning
/challenge/21.py
799
3.71875
4
#21 # Let's work with zip from the previous task from zipfile import ZipFile, ZipInfo with ZipFile('bin.zip', 'r') as zout: zout.namelist() #* ['readme.txt', 'package.pack'] with ZipFile('bin.zip', 'r') as zout: print(zout.read('readme.txt', pwd=bytes('invader'[::-1].encode())).decode('utf-8')) #* Yes! This is really level 21 in here. #* And yes, After you solve it, you'll be in level 22! #* #* Now for the level: #* #* * We used to play this game when we were kids #* * When I had no idea what to do, I looked backwards. with ZipFile('bin.zip', 'r') as zout: print(zout.read('package.pack', pwd=bytes('invader'[::-1].encode())).decode('ISO-8859-1')) # UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9c in position 1: invalid start byte # Let's change to some different
2862a4603391033fb24df88e1b8c7d6d441304e4
MullerBjorn/Week2Resportbasicprog
/Week 2 vs py/Oef4.py
505
3.78125
4
#week 2 oef 4 leeftijd_hond = int(input("Geef de leeftijd van de hond op: ")) if leeftijd_hond < 0: print("Ongeldige leeftijd") elif leeftijd_hond == 0: print("De hond is tussen de 0 en 12 maanden oud in mensenmaanden") elif leeftijd_hond == 1: print("Deze leeftijd komt overeen met 14 mensenjaren") elif leeftijd_hond == 2: print("Deze leeftijd komt overeen met 22 mensenjaren") else: print(f"Deze leeftijd komt overeen met {22 + (leeftijd_hond - 2) *5} mensenjaren")
7f5afa444112d910f1e4ef32ca60a9c8951eadd4
u101022119/NTHU10220PHYS290000
/student/101022202/HW4/mypoker.py
6,189
3.78125
4
import random as rand suit_dict = {0:"S",1:"H",2:"D",3:"C"} num_dict = {i:str(i) for i in range(1,14)} class Card(): def __init__(self,suit,num): if suit in range(4): if num in range(1,14): self.suit = suit self.num = num self.get_order() else: print "ERROR" def get_order(self): self.order = self.suit*13 + self.num return self.order def get_name(self): self.suit = int(self.order/13) self.num = int(self.order%13) return self def __str__(self): s = suit_dict[self.suit] n = num_dict[self.num] return s+'_'+n def __cmp__(self,C2): o1, o2 = self.get_order(), C2.get_order() if o1 < o2: return 1 elif o1 > o2: return -1 else: return 0 class Deck(): def __init__(self): self.cards = [] for i in range(4): for j in range(1,13): self.cards.append(Card(i,j)) def __str__(self): str_list = '' for i in self.cards: s = suit_dict[i.suit] n = num_dict[i.num] str_list += s + "_" + n + ' ' return str_list def pop_card(self,n): c = self.cards.pop(n) return c def add_card(self,c): if c in self.cards: print "ERROR" else: self.cards.append(c) return self def shuffle(self,n,m): if 0 <= n < len(self.cards) and 0 <= m < len(self.cards): c_temp = self.cards.pop(n) self.cards.insert(m,c_temp) return self def sort(self): d = self.cards for i in range(1,len(d)): valueToInsert = d[i] holePos = i while holePos > 0 and valueToInsert > d[holePos-1]: d[holePos] = d[holePos-1] holePos = holePos - 1 d[holePos] = valueToInsert self.cards = d return self def deal_hands(self,n_h,n_c): h_dict = dict() for i in range(n_h): h_temp = Hand() for j in range(n_c): r = rand.randint(0,len(self.cards)-1) c_temp = self.pop_card(r) h_temp.add_card(c_temp) h_dict[i] = h_temp.sort() for i in h_dict.values(): print i return h_dict class Hand(Deck): def __init__(self,n = 0): self.cards = [] for i in range(n): test = False while test is False: test = True suit = rand.randint(0,3) num = rand.randint(1,13) c_temp = Card(suit,num) for i in self.cards: if c_temp == i: test = False self.cards.append(Card(suit,num)) self.sort() def num_dict(self): l = [c.num for c in self.cards] l.sort() d = dict() for i in l : if d.get(i) is None: d[i] = 0 d[i] += 1 return d def suit_dict(self): l = [c.suit for c in self.cards] l.sort() d = dict() for i in l : if d.get(i) is None: d[i] = 0 d[i] += 1 return d def has_pair(self): d = self.num_dict() for i in d.values(): if i is 2: return True return False def has_two_pair(self): d = self.num_dict() p = 0 for i in d.values(): if i is 2: p += 1 if p >= 2: return True else: return False def has_three_of_a_kind(self): d = self.num_dict() for i in d.values(): if i is 3: return True return False def has_straight(self): d = self.num_dict() for i in d.keys(): test = True for j in range(5): if i+j not in d.keys(): test = False if test is True: return True return False def has_flush(self): d = self.suit_dict() for i in d.values(): if i >= 5: return True return False def has_full_house(self): pair = self.has_pair() three = self.has_three_of_a_kind() ans = pair and three return ans def has_four_of_a_kind(self): d = self.num_dict() for i in d.values(): if i is 4: return True return False def has_straight_flush(self): self.sort() for s in range(4): l = [] for c in self.cards: if c.suit is s: l.append(c.num) for i in l: test = True for j in range(5): if i+j not in l: test = False if test is True: return True return False def classify(self): if self.has_straight_flush(): return "has_straight_flush",1 elif self.has_four_of_a_kind(): return "has_four_of_a_kind",2 elif self.has_full_house(): return "has_full_house",3 elif self.has_flush(): return "has_flush",4 elif self.has_straight(): return "has_straight",5 elif self.has_three_of_a_kind(): return "has_three_of_a_kind",6 elif self.has_two_pair(): return "has_two_pair",7 elif self.has_pair(): return "has_pair",8 else: return "has_nothing",9 h = Hand(7) print h print h.suit_dict() print h.num_dict() print h.classify() num_test = 10000 count = {t:0 for t in range(1,10)} for i in range(1,num_test): h = Hand(5) msg, test = h.classify() count[test] += 1 result = {t:count[t]*100.0/num_test for t in range(1,10)} for t,i in result.iteritems(): print t,":",i,"%"
4c9536b9031ef3982b1bff304dfe399efe14f701
eternalSeeker/pcc
/pcc/AST/comparisons/compare_equal.py
1,247
3.640625
4
from pcc.AST.binary_operator import BinaryOperator class CompareEqual(BinaryOperator): def __init__(self, depth, operand_1, operand_2): super(CompareEqual, self).__init__(depth, operand_1, operand_2) self.operator = '==' def evaluate(self, source, destination, assembler): """Evaluate the operator, leaving the result in the destination reg. Args: source (ProcessorRegister): the source operand destination (ProcessorRegister): the destination operand assembler (Assembler): the assembler to use Returns: bytearray: the byte code """ value = bytearray() cmp_values = assembler.cmp(source, destination) clear_result = assembler.copy_value_to_reg(0, destination) set_result = assembler.copy_value_to_reg(1, destination) jump_amount = len(set_result) jump_over_set_result = assembler.jne(jump_amount) # compare the 2 value, clean the destination and if the 2 values # were equal, set the result, else jump over these instructions value += cmp_values value += clear_result value += jump_over_set_result value += set_result return value
cc1ec623e4703f660234e72c79d23f1d255d4fa5
dustycodes/Algorithms-UofU
/PS4/autosink1.py
3,170
3.59375
4
#/usr/env python visit_number = 1 linearized_cities = [] current_cost = 0 class City: def __init__(self, name, toll): self.name = name self.toll = toll self.routes_to = [] self.routes_in = [] self.visited = False self.post_number = -1 self.pre_number = -1 class Trip: def __init__(self, from_index, to_index): self.from_index = from_index self.to_index = to_index def previsit(city): global visit_number city.pre_number = visit_number visit_number += 1 def postvisit(city): global visit_number, linearized_cities city.post_number = visit_number linearized_cities.insert(0, city) visit_number += 1 def explore(cities, v): v.visited = True previsit(v) for ind in v.routes_to: if cities[ind].visited is False: explore(cities, cities[ind]) postvisit(v) def dfs(cities): for city_index in cities: cities[city_index].visited = False for city_index in cities: if cities[city_index].visited is False: explore(cities, cities[city_index]) def main(): global linearized_cities, current_cost cities = {} city_names = {} number_of_cities = int(input()) n = 0 while n < number_of_cities: line = input() s = line.split() name = s[0] toll = int(s[1]) cities[n] = City(name, toll) city_names[name] = n n += 1 adj_matrix = [[None] * number_of_cities for x in range(number_of_cities)] number_of_highways = int(input()) h = 0 while h < number_of_highways: line = input() s = line.split() from_city = s[0] to_city = s[1] from_index = city_names[from_city] to_index = city_names[to_city] cities[from_index].routes_to.append(to_index) cities[to_index].routes_in.append(from_index) adj_matrix[from_index][to_index] = cities[to_index].toll h += 1 trips = [] number_of_trips = int(input()) t = 0 while t < number_of_trips: line = input() s = line.split() from_city = s[0] to_city = s[1] from_index = city_names[from_city] to_index = city_names[to_city] trips.append(Trip(from_index, to_index)) t += 1 dfs(cities) for trip in trips: f = cities[trip.from_index] t = cities[trip.to_index] from_index = linearized_cities.index(f) to_index = linearized_cities.index(t) cost = 0 found = False if from_index == to_index: print("0") continue else: leng = len(linearized_cities) while from_index < leng and len(f.routes_to) != 0: cost += linearized_cities[from_index].toll if from_index == to_index and current_cost == 0 or current_cost > cost: current_cost = cost found = True f = cities[from_index] from_index += 1 if found is True: print(current_cost) if __name__ == "__main__": main()
c7dfa93d09d0e21627e97dae98504f127743a058
Kresna777/Just-My-Program
/Python2/QR Code/qr_code.py
211
3.546875
4
import qrcode text = input("input text or link then enter : ") name = input("name QRcode picture then enter : ") img = ".png" img = name + img save = qrcode.make(text) save.save(img) print(f"QR {img} saved")
fc101cdfbe238cd67da66111b96dca6c5391bb2e
hcketjow/Trips-with-python3
/Transformacje_dan/wyrazenia_slownikowe.py
510
4.03125
4
names = ["Wojciech", "Arek", "Maja","Aleksander","Zuzanna"] numers = [1,2,3,4,5,6] celcius = {'t1': -20, 't2': -15, 't3': 0, 't4': 12, 't5':24} print('\n') namesLength = { name : len(name) for name in names if name.startswith("A") } multipleNumber = { number : number*number for number in numers } Temperature = { key: celcius * 1.8 + 32 for key,celcius in celcius.items() if celcius > -5 if celcius < 20 } print(namesLength) print(multipleNumber) print(Temperature)
8a95bbc3e4794fd5b8b758314520b81b8ca77a99
VanessaSilva99/estrutura2
/estruturas/arvore.py
865
3.75
4
class Arvore: def __init__(self, node): self.raiz = node def mostra_profundidade(self): visitados = set() visitados.add(self.raiz) falta_visitar = [self.raiz] result = "" while falta_visitar: vertice = falta_visitar.pop() result += str(vertice) + " >> " for filho in vertice.prox: if filho not in visitados: visitados.add(filho) falta_visitar.append(filho) print( result.rstrip(' >> ')) def mostra_largura(self): # implementar return None class Node: def __init__(self, val): self.conteudo = val self.prox = [] def adiciona(self, node): self.prox.insert(0,node) def __str__(self): return str(self.conteudo)
9e3fbd695a56d2d620dda8dd2a24e05281d8efdb
littlefattiger/My_LC_solution
/python/by_tag/Topological Sort/2115. Find All Possible Recipes from Given Supplies.py
1,540
3.90625
4
# You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. # You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. # Return a list of all the recipes that you can create. You may return the answer in any order. # Note that two recipes may contain each other in their ingredients. class Solution: def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]: supply_set = set(supplies) r_g = defaultdict() for i, v in enumerate(recipes): r_g[v] = ingredients[i] def helper(item, visited): if item in supply_set: return True if item not in r_g: return False if item in visited: return False visited.add(item) for v in r_g[item]: if not helper(v, visited): return False supply_set.add(item) visited.remove(item) return True ans = [] for v in recipes: if helper(v, set()): ans.append(v) return ans
433d310a2b3d69fa6f0bc14f443b260301cbf770
SCarozza/simulate_and_track
/simulate_diffusion/simulate_diffusion.py
2,610
3.765625
4
__author__ = 'Sara' import sys import simulate_diffusion_trace import IO """ Simulates a particle undergoing free diffusion and creates a movie: the name of the movie is given by command line. 1. Generates the coordinates of the movement, simulating a free diffusion: the parameters of the diffusion are given as input: diffusion coefficient D, number of time steps N, width of each time step t, size frame. 2. For every step in the trace, a frame is generated (as np array), containing a Gaussian peak with the defined coordinates. The peak and frame features are given as input (ampiltude A, width w and offset b of the peak, background noise level n). The trajectory is plotted to an image file. 3. Creates a movie (mp4) collecting all the frames. """ def main(): #inputs to give: trace_file_name print "Give the properties of the desired trace:" D = input("diffusion coefficient:") #diffusion coefficient N = input("number of points:") #time points size = input("size of each frame:") #size frame in pix print "Now give the properties of the Gaussian peak:" A = input("amplitude:") #amplitude sx = sy = input("standar deviation:") #width in x and y. in most of the case the peak is symmetric so wx = wy n = input("noise:") #noise b = input("offset:") #offset filename = sys.argv[1] # takes from command line the name of the file to write trace = simulate_diffusion_trace.trace(N,size,D,1) # creates a trace of free diffusing coordinates IO.write_frames_ascii(filename,trace,size,sx,sy,A,n,b) # generates a file (.ascii) containing the frames (arrays) corresponding to each time step. # Inputs: name of the ascii file, the trace, the size of the frame, the Gaussian peak properties. filename_plot = filename + 'trajectory.png' # creates a path for the file containing the trajectory plot IO.plot_trajectory(trace, filename_plot) # plots the trajectory and writes it to a a file (.png) IO.frames_to_movie(filename, size, N, 10, 0) # writes a movie (.mp4) containing all the frames. Inputs: name of the ascii file from which to read the frames, # size of each frame, total number of frames N, fps (frames per second), a boolean that indicates whether # to add the fit to the images or not. if __name__=='__main__': main()
f79c3fdfde3726a30619788dea5ee691c1f276ca
meshalawy/kharita
/plot_map.py
620
3.53125
4
""" Author: Sofiane Date: Jan 21, 2020 Sample code on how to plot the output map of Kharita Star (online). NOTE: THIS DOESN'T WORK WITH KHARITA OFFLINE. """ from matplotlib import collections as mc, pyplot as plt edges = [] with open('data/data_uic_edges.txt') as f: lines = f.readlines() i = 0 while i < len(lines) - 3: edges.append([lines[i].strip().split(','), lines[i+1].strip().split(',')]) i += 3 lc = mc.LineCollection(edges) fig, ax = plt.subplots() ax.add_collection(lc) ax.autoscale() ax.margins(0.1) plt.savefig('figs/uic_map_new.png', format='PNG') plt.show()
7afa34df1cb49e20035e7917e2c6b7e8b0e5660f
hhigorb/exercicios_python_brasil
/1_EstruturaSequencial/4.py
431
3.84375
4
"""4. Faça um Programa que peça as 4 notas bimestrais e mostre a média.""" try: n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) n3 = float(input('Digite a terceira nota: ')) n4 = float(input('Digite a quarta nota: ')) media = (n1 + n2 + n3 + n4) / 4 print(media) except (ValueError, NameError): print('Por favor, digite um valor inteiro ou real')
40a40eac1920af1f7ef448c01adeb244f300b711
PollobAtGit/python-101
/oj/hacker-rank/python.badge/set-mutation.py
1,047
3.625
4
def init(): return set([1, 3, 4]), set([3, 4, 66]) def play(): print(init()) s, q = init() s.intersection_update(q) # keeps intersection of sets print(s) s, q = init() s.update(q) # converts just to set print(s) s, q = init() s.symmetric_difference_update(q) # converts just to set print(s) s, q = init() s.difference_update(q) # converts just to set print(s) if __name__ == "__main__": input() org_list = set(map(int, input().split())) op_cnt = int(input()) while op_cnt: op = input().split()[0] nw_list = set(map(int, input().split())) if op == 'intersection_update': org_list.intersection_update(nw_list) elif op == 'update': org_list.update(nw_list) elif op == 'symmetric_difference_update': org_list.symmetric_difference_update(nw_list) else: org_list.difference_update(nw_list) op_cnt = op_cnt - 1 print(sum(org_list))
366eed73fe05678b8b447bb7d8464d451028db36
IvanCarlos21/Formation-Python
/TP_Jour3/Adresse.py
1,646
3.921875
4
# Ma classe class Adresse: def __init__(self,rue, numero,code_postal,ville): assert len(rue) > 3 and len(rue) < 25, "la rue doit contenir entre 3 et 25 caractères" self.rue = rue self.numero = numero self.code_postal = code_postal self.ville = ville #redefinition de la méthode d'affichage def __str__(self): return "{} \n{}\n{}\n{}".format(self.rue,self.numero,self.code_postal,self.ville) #Mère class Personne: #constructeur def __init__(self,nom,prenom,age): self.nom = nom self.prenom = prenom self.age = age #redefinition de la méthode d'affichage def __str__(self): return "{} \n{}\n{}".format(self.nom,self.prenom,self.age) # definition des autres autres methodes def se_nourrir(self): print("Je mange ...") #Classe Fille class Etudiant(Personne): def __init__(self,nom,prenom,age,moyenne): Personne.__init__(self,nom,prenom,age) self.moyenne = moyenne def se_nourrir(self): print("Je mange au fast food...") #Classe Fille class Professeur(Personne): def __init__(self,nom,prenom,age,matiere_enseigne): Personne.__init__(self,nom,prenom,age) self.matiere = matiere_enseigne def se_nourrir(self): print("Je mange au restaurant...") # Heritage multiple class Doctorant(Etudiant, Professeur): pass #Class Voiture : getter / setter # Programme principal a1 = Adresse("rue de paris","5","75000","Paris") print(a1) p1 = Personne("zec","union",40) et1 = Etudiant("toto","tata",25,26) prof1 = Professeur("eddy","CHRISTIAN",35,"C#") # connaître le type d'un objet print(type(p1)) print(type(et1)) print(type(prof1)) # Appel des méthodes p1.se_nourrir() et1.se_nourrir() prof1.se_nourrir()
c273b13fabda1841925c8332721e24eb82325f9b
v-v-d/algo_and_structures_python
/Lesson_2/1.py
3,312
3.75
4
""" 1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), то программа должна сообщать ему об ошибке и снова запрашивать знак операции. Также сообщать пользователю о невозможности деления на ноль, если он ввел 0 в качестве делителя. """ # Рекурсия def get_calc(): operator = input('Введите оператор или 0, чтобы выйти: ') if operator == '0': exit(0) try: if operator in ('/', ':', '*', '+', '-'): num1 = float(input('Введите первое число: ')) num2 = float(input('Введите второе число: ')) if operator in ('/', ':'): print(f'Результат деления: {num1 / num2}') if num2 != 0 else print('Ошибка! Делить на 0 нельзя') if operator == '*': print(f'Результат умножения: {num1 * num2}') if operator == '+': print(f'Результат сложения: {num1 + num2}') if operator == '-': print(f'Результат вычитания: {num1 - num2}') else: print('Вы ввели некорректный оператор') except ValueError: print('Необходимо ввести число. Разделитель - точка') return get_calc() get_calc() # Цикл while True: operator = input('Введите оператор или 0, чтобы выйти: ') if operator == '0': break try: if operator in ('/', ':', '*', '+', '-'): num_1 = float(input('Введите первое число: ')) num_2 = float(input('Введите второе число: ')) if operator in ('/', ':'): print(f'Результат деления: {num_1 / num_2}') if num_2 != 0 else print('Ошибка! Делить на 0 нельзя') if operator == '*': print(f'Результат умножения: {num_1 * num_2}') if operator == '+': print(f'Результат сложения: {num_1 + num_2}') if operator == '-': print(f'Результат вычитания: {num_1 - num_2}') else: print('Вы ввели некорректный оператор') except ValueError: print('Необходимо ввести число. Разделитель - точка')
3808d3961156dfcc8b963689ac6acebde9736223
jjpikoov/jjblog
/database.py
4,279
3.875
4
import os import sqlite3 class Database(): def __init__(): raise NotImplementedError() def connect_db(): raise NotImplementedError() def init_db(): raise NotImplementedError() def get_connection(): raise NotImplementedError() class SqliteDatabase(Database): def __init__(self, db_file): """ Database's file in constructor """ self.db_file = db_file def connect_db(self): """ Function establishes the connection to db. """ self.db = sqlite3.connect(self.db_file) def close_db(self): """ Function closes connection with db. """ if self.db is not None: self.db.close() def init_db(self): """ Function creates db file with given schema if doesn't exist. """ if not os.path.isfile(self.db_file): self.connect_db() with open('schema.sql', 'r') as f: schema = f.read() self.db.cursor().executescript(schema) self.db.commit() self.db.close() def add_post(self, title, date, text): """ Function for adding new posts. """ self.db.cursor().execute( "INSERT INTO posts (title, date, text)\ VALUES(?, ?, ?)", [title, date, text]) self.db.commit() def get_posts(self): """ Function for getting posts persisted in db. """ posts = [] for row in self.db.cursor().execute( "SELECT id, title, date, text FROM posts ORDER BY id DESC"): posts.append(dict( post_id=str(row[0]), title=row[1], date=row[2], text=row[3])) return posts def get_post_by_id(self, post_id): """ Function returns post with given id. """ for post in self.db.cursor().execute( "SELECT id, title, date, text FROM posts WHERE id = ?", post_id): return dict( post_id=str(post[0]), title=post[1], date=post[2], text=post[3]) def delete_post(self, post_id): """ Function removes post with given id. """ self.db.cursor().execute( "DELETE FROM posts WHERE id = ?", str(post_id)) self.db.commit() def edit_post(self, post_id, title, date, text): """ Function updates post (by id). """ self.db.cursor().execute( "UPDATE posts SET title = ?, date = ?, text = ?\ WHERE id = ?", [title, date, text, post_id]) self.db.commit() def add_widget(self, name, body): """ Function for adding new widgets. """ self.db.cursor().execute( "INSERT INTO widgets (name, body)\ VALUES(?, ?)", [name, body]) self.db.commit() def get_widgets(self): """ Function for getting widgets persisted in db. """ widgets = [] for row in self.db.cursor().execute( "SELECT id, name, body FROM widgets"): widgets.append(dict( widget_id=str(row[0]), name=row[1], body=row[2])) return widgets def get_widget_by_id(self, widget_id): """ Function returns widget with given id. """ for widget in self.db.cursor().execute( "SELECT id, name, body FROM widgets WHERE id = ?", widget_id): return dict( widget_id=str(widget[0]), name=widget[1], body=widget[2]) def delete_widget(self, widget_id): """ Function removes widget with given id. """ self.db.cursor().execute( "DELETE FROM widgets WHERE id = ?", str(widget_id)) self.db.commit() def edit_widget(self, widget_id, name, body): """ Function updates widget (by id). """ self.db.cursor().execute( "UPDATE widgets SET name = ?, body = ?\ WHERE id = ?", [name, body, widget_id]) self.db.commit()
f243902a1381a244fbd93438fb7ebd89d30b3fb0
Divyamop/HACKTOBERFEST2021_PATTERN
/Patterns/Kemosabe2911.py
93
3.5625
4
n=5 for i in range(n): s="" for j in range(n-i): s=s+"* " print(s)
e41b2084618d0b1a6ba6f913eb97209eba345ee1
hxk11111/Danny-Huang
/leetcode_py2/Medium 220. Contains Duplicate III.py
1,494
3.75
4
# -*- coding: utf-8 -*- # !/usr/bin/env python """ This module is provided by Authors: hxk11111 Date: 2019/1/30 File: Medium 220. Contains Duplicate III.py """ ''' Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3, t = 0 Output: true Example 2: Input: nums = [1,0,1,1], k = 1, t = 2 Output: true Example 3: Input: nums = [1,5,9,1,5,9], k = 2, t = 3 Output: false ''' class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if t < 0: return False bucket = {} width = t + 1 for i in range(len(nums)): if nums[i] / width in bucket: return True if nums[i] / width + 1 in bucket and abs(bucket[nums[i] / width + 1] - nums[i]) <= t: return True if nums[i] / width - 1 in bucket and abs(bucket[nums[i] / width - 1] - nums[i]) <= t: return True bucket[nums[i] / width] = nums[i] if i >= k: del bucket[nums[i - k] / width] return False if __name__ == '__main__': s = Solution() print s.containsNearbyAlmostDuplicate(nums=[-1, -1], k=1, t=-1)
52392189c201cf4931906ee0e7abb59cc626740d
hickeroar/project-euler
/030/solution033.py
1,192
3.578125
4
""" The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If the product of these four fractions is given in its lowest common terms, find the value of the denominator. """ from fractions import Fraction final = 1 for d in [a for a in xrange(11, 99) if a % 10 != 0]: denominator = list(str(d)) for n in [b for b in xrange(11, d) if b % 10 != 0]: numerator = list(str(n)) orig = float(n)/float(d) inter = set(numerator).intersection(set(denominator)) for i in inter: onum = list(numerator) oden = list(denominator) onum.remove(i) oden.remove(i) new = float(''.join(onum))/float(''.join(oden)) if new == orig: final *= orig print Fraction(str(final))
dba85ee0ccdda569858c8017942eea66e026c1c8
cfredberg/Level0-Module1
/_03_if_else/_3_secret_message_box/message.py
400
3.625
4
from tkinter import messagebox, simpledialog, Tk if __name__ == '__main__': window = Tk() window.withdraw() message = simpledialog.askstring(None, "Enter a secret message") guess = simpledialog.askstring(None, "Guess the password") password = "GuessMeIfYouCan" if guess == password: messagebox.showinfo(None, message) else: messagebox.showinfo(None, "WRONG!")
8a6b57cb90f3579c31b0f781312b9d1e90fa6408
Universe-c0de/Python
/random.py
615
4.03125
4
# Задание №2. В списке A=(a1, а2, ..., аn) все элементы, равные нулю, поставить сразу после # максимального элемента данного списка. Заполняем список с помощью randint(). import random number = int(input("Введите количество элементов в списке: ")) A = [] for i in range(number): a = random.randint(0, 6) A.append(a) maxi = max(A) mini = min(A) if mini == 0: A.append(maxi) print(A) print(maxi) print(mini)
3bffa9ecf6475b2b3529f888a7ca8e84a55b235a
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4363/codes/1670_1396.py
127
3.6875
4
a = float(input("valor consumido:")) if (a<=300): b = a+a*(10/100) else: b = 0 if (a>300): b = a+a*(6/100) print(round(b,2))
d16b5bb34572fd835d75cba6122b1eb4b2eec78d
saideep3/Python-tools
/Chat.py
547
3.890625
4
#!/usr/bin/python class Chat: GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "what's up",) GREETING_RESPONSES = ["'sup bro", "hey", "*nods*", "hey you get my snap?"] def check_for_greeting(self, sentence): """If any of the words in the user's input was a greeting, return a greeting response""" for word in sentence.words: if word.lower() in self.GREETING_KEYWORDS: return random.choice(self.GREETING_RESPONSES) chat = Chat() print(chat.check_for_greeting(sentence="ff fgt"))
3af8085735ca614277b73911a92d6b8ecdcc169a
xiaochenchen-PITT/Leetcode
/Python/Ugly Number.py
226
3.703125
4
class Solution(object): def isUgly(self, num): if n <= 0 : return False while n != 1: if n % 2 == 0: n /= 2 elif n % 3 == 0: n /= 3 elif n % 5 == 0: n /= 5 else: return False return True
2f652e86572636857e418e311d40287c7ab83656
James-Lee1/Unit_6-02
/unit_6-02-1.py
566
4.34375
4
# Created by: James Lee # Created on: Dec 2017 # Created for: ICS3U # This program displays an enumerated type from enum import Enum # an enumerated type of days of the week Days = Enum('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') day_selected = raw_input('Enter your favorite day of the week: ') counter = 0 position = None for day in Days: if str(day) == day_selected: print(day_selected) position = counter + 1 counter = counter + 1 print("Day " + str(position) + " is your favourite day of the week")
1836f01f55cd75eff1a3a6f37ac65ee14d1e981b
jilikuang/practice
/leetcode/maximal_rectangle/maximal_rectangle.py
1,070
3.546875
4
import random def maximial_rectangle(matrix): if not matrix or not matrix[0]: return 0 m = len(matrix) n = len(matrix[0]) lefts = [0 for j in range(n)] rights = [n for j in range(n)] heights = [0 for j in range(n)] max_area = 0 for i in range(m): left, right = 0, n for j in range(n): if matrix[i][j] == 1: lefts[j] = max(lefts[j], left) heights[j] += 1 else: lefts[j] = 0 left = j + 1 heights[j] = 0 r = n - j if matrix[i][r-1] == 1: rights[r-1] = min(rights[r-1], right) else: rights[r-1] = n right = r - 1 for j in range(n): max_area = max(max_area, (rights[j] - lefts[j]) * heights[j]) return max_area if __name__ == '__main__': m = 5 n = 5 matrix = [[random.randint(0,1) for j in range(n)] for i in range(m)] for r in matrix: print r print maximial_rectangle(matrix)
3a3d58eaa522ac579bfa4e6e738aa2cad3321445
naresh0101/Warm_up_python
/creditCard.py
425
3.765625
4
user = input("enter you no.")#4215-2352-1220-2002 num = "0123456789-" def three(): for i in user: if i in num: ch = "" ch = i*3 if ch in user: return("invalied") else: return("valied") def credit(): if user[0] == "4": if len(user)==19: if user[4] == "-" and user[9] == "-" and user[14] == "-": return(three()) elif len(user)==16: return(three()) else: return("invalied") print(cradit())
77ad5a528aae099a436bc39dac62616ee6a40b8c
KennethNielsen/ubd
/ubd/pyqt/label.py
507
3.953125
4
"""Implements a label widget""" from PyQt5.QtWidgets import QLabel class Label: """A common implementation of a widget with a label""" def __init__(self, parent, label, position): """Initialize labeled widget Args: parent (QWidget): The QWidget the label should be draw into label (str): The label text position (tuple): A tuple of x, y coordinates """ self._label = QLabel(label, parent) self._label.move(*position)
e7ab3acdd2561bd8486fa34f516c04ced26d29d0
daniel-reich/ubiquitous-fiesta
/XKEDTh2NMtTLSyCc2_19.py
354
3.65625
4
def valid_credit_card(number): addup=0 lst = [int(j) for j in list(str(number))] lst.reverse() for i in range(len(lst)): if i % 2 !=0: if lst[i]*2<10: addup+=lst[i]*2 else: addup+=sum([int(a) for a in list(str(lst[i]*2))]) else: addup+=lst[i] if addup%10==0: return True else: return False
5c050148df830733faa1e904de1eb4c0b607079d
gawdn/advent-of-code-2019
/4/4-2.py
1,262
3.734375
4
from datetime import datetime def count_possible_password(min_num=108457, max_num=562041): """ Counts password matching the criteria: The value is within the range given in your puzzle input. Two adjacent digits are the same (like 22 in 122345). Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679). """ possible_count = 0 start = datetime.now() for i in range(min_num, max_num): possible_password = f"{i:0{len(str(max_num))}}" is_valid = True runs = [] for i in range(len(possible_password)): try: if int(possible_password[i]) > int(possible_password[i + 1]): is_valid = False break except IndexError: pass if not runs or runs[-1][0] != possible_password[i]: runs.append([possible_password[i], 1]) else: runs[-1][1] += 1 has_repeat = any([True for x in runs if x[1] == 2]) if has_repeat and is_valid: print(possible_password, runs) possible_count += 1 print(f"\n\nTook {datetime.now() - start}") return possible_count