blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6a05b06340aaa9f43e39ea930ec174c5cba6cbf2
RyutaHoshino/SchoolProject
/q8.py
184
3.53125
4
#coding:utf-8 import random num=30 count=0 for i in range(num): a=random.uniform(0,1) b=random.uniform(0,1) if a*a+b*b<1: count+=1 print ("pi="+str(4.0*count/num))
d5c5ef30eac59ec1c86b0bafad460dd8407e709b
ErenBtrk/Python-Fundamentals
/Python File Management/2-ReadFile.py
1,069
3.90625
4
# try: # file = open("newfile.txt") #default mode is "r" # print(file) # except FileNotFoundError: # print("File not found error.") # finally: # print("File is closed.") # file.close() ####################################################### file = open("newfile.txt","r",encoding = "utf-8") #utf-8 turkish characters # for loop # for i in file: # print(i,"") #second parameter says dont add a space at last #**********read function # content = file.read() # print("Content 1") # print(content) # file = open("newfile.txt","r",encoding = "utf-8") #if you add it content2 is not blank # content2 = file.read() # print("Content 2") # print(content2) # content = file.read(5) # read 5 byte # content = file.read(3) # content = file.read(3) # print(content) #**********readline() function # print(file.readline(),end="") # print(file.readline(),end="") # print(file.readline(),end="") # print(file.readline(),end="") #**********readlines() function list = file.readlines() print(list) print(list[0]) print(list[1]) file.close()
9a67d8901e07a8126a45a6eca617736e6a81b616
SidPatra/ProgrammingPractice
/Coding/Ex5.py
714
3.890625
4
# Base 10 to Base 2 # algorithm # j # SUM bi * 2**i # i=0 # 1. Determine bj by finding the greatest power of 2 less than or equal to decimal # 2. find the next bi set into 1 by finding (bj+bi) <= decimal # 3. Repeat 2 until you sum is equal to decimal print('base 10 number:') b10 = int(input()) # base10 number f = b10 d = 1 # 2**eth power e = 0 # the power to the 2 list = [0,0,0,0,0,0,0,0,0] # for the results of each loop g = 0 # adds up all numbers while(f != 0): while d <= b10-g: e += 1 d = 2**e else: e = e-1 d = 2**e g += d f = b10 - g list[e] = 1 d = 1 e = 0 z = list[::-1] print('to converted into base 2') print(z)
e00e27f8d239b84d0c6192b52177daacfaa267ec
mube1/Cryptool
/decrypt_with_offset.py
1,361
3.734375
4
# the data used can be programmed to be from the user Cipher_text="utnrocifrigaYaeoanomgnsregrmnulpi" keye=5 # the length of the key offset=6 # the offset Len=len(Cipher_text)+ offset # total length assumed with offset in mind offset=offset%(2*keye-1) # offset at most can be twice the key minus 1 Plain=[None]*(Len) G=2*(keye-1) # this is the distance between the two sharp edges of the fence E= keye-(offset%(keye-1))-1 inc=0 for i in range(keye): #Two cases are assumed:when the character is at the bottom or top of the fence and when it is not j=i if j>0 and j<keye-1: while j <Len: if i==j and i <offset: Plain[j]="*" else: Plain[j]=(Cipher_text[inc]) inc=inc+1 j=j+G-2*i if j<Len: if i>E and i==j-(G-2*i) and offset>keye: Plain[j]="*" else: Plain[j]=(Cipher_text[inc]) inc=inc+1 j=j+2*i else: while j < Len: if i==j and i < offset: Plain[j]="*" else: Plain[j]=(Cipher_text[inc]) inc=inc+1 j=j+G print(''.join(Plain).replace('*',''))
438befc2bbe97ae45fb45a2a3a353338640006b2
sweavo/code-advent-2020
/day10_1.py
1,683
4
4
""" the problem It looks like the question of whether such a path exists is a red herring. It's enough to sort the list of "joltages" and then count the intervals as we walk up the values. I can use the interval as an index to a dict and just increment the value there. python contains collections.Counter that encapsulates this semantic. """ import collections import day10input EXAMPLE1=[ 16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4 ] EXAMPLE2=[ 28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11, 1, 32, 25, 35, 8, 17, 7, 9, 4, 2, 34, 10, 3 ] def intervals(sequence): """ generate the differences between consecutive elements of the sequence >>> list(intervals([0,1,3,5,8])) [1, 2, 2, 3] """ return map(lambda tup: tup[1]-tup[0], zip(sequence[:-1],sequence[1:])) def count_intervals(sequence): """ Tally the differences between consecutive items in sequence. (which must be ordered) >>> dict(count_intervals([0,1,4,5,7,10])) {1: 2, 3: 2, 2: 1} """ return collections.Counter(intervals(sequence)) def test_joltage_adaptors(adaptor_set): """ The puzzle algorithm includes a 3-jolt interval for the last step >>> result=test_joltage_adaptors(EXAMPLE1) >>> result[1] 7 >>> result[3] 5 >>> result=test_joltage_adaptors(EXAMPLE2) >>> result[1] 22 >>> result[3] 10 """ tally = count_intervals(sorted([0] + adaptor_set)) # Add the 3-jolt interval for the device itself tally.update([3]) return tally def day10_1(): """ >>> day10_1() 1984 """ results = test_joltage_adaptors(day10input.ADAPTOR_RATINGS) return results[1] * results[3]
524ea5331a81c8a3dec7b5a5b4f8497b4fc5edae
patkhai/LeetCode-Python
/LeetCode/DecodeString.py
1,280
4.15625
4
''' Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. Example 1: Input: s = "3[a]2[bc]" Output: "aaabcbc" Example 2: Input: s = "3[a2[c]]" Output: "accaccacc" Example 3: Input: s = "2[abc]3[cd]ef" Output: "abcabccdcdcdef" Example 4: Input: s = "abc3[cd]xyz" Output: "abccdcdcdxyz" ''' def decodeString(s): stack = [] currCount = 0 res = "" for char in s: if char == "[": stack.append((res,currCount)) res = "" currCount = 0 elif char == "]": prevString = stack.pop() res = prevString[0] + res * prevString[1] elif char.isdigit(): currCount = currCount * 10 + int(char) else: res += char return res s = "abc3[cd]xyz" print(decodeString(s))
d37cd4d10fee602ffcb0433c98d1d19b3e3c45d2
Akshatt/show-me-the-data-structures
/problem2.py
1,361
3.546875
4
import os def find_files(suffix, path): if suffix == '' or not os.path.exists(path): return "Error:for {} files in {}\nFile/Directory does not exist".format(suffix,path) path_entries = os.listdir(path) #base case if len(path_entries) == 0: return [] #file_paths = [path+'/'+file for file in path_entries if file.endswith('.'+ suffix)] #sub_dir = [directory for directory in path_entries if '.' not in directory] sub_dir = [] file_paths = [] for entry in path_entries: if entry.endswith('.' + suffix): file_paths.append(path+'/'+entry) elif '.' not in entry: sub_dir.append(entry) for dir in sub_dir: file_paths.extend(find_files(suffix,path+'/'+dir)) return file_paths #testcase1 - has both .c files and sub directories containing .c files print("testcase 1") print(find_files('c', './testdir1')) #testcase2 - has no .c files and only sub directories with other files so should return empty list print("\ntestcase 2") print(find_files('c', './testdir2')) #testcase3 - path doesnt exist: should return with error msg print("\ntestcase 3") print(find_files('c', './testdir1/imaginary_directory')) #testcase4 - suffix not provided: should return with error msg print("\ntestcase 4") print(find_files('', './testdir2'))
708a9a83230f741936115df2688ecb1eb9ed925c
sengarmaithili/python_project
/load_csv.py
4,013
3.5
4
import csv def load_students_csv(): elist = [] file = open('students.csv','r') reader = csv.reader(file) header = ('FormNumber', 'Name', 'A_rank','B_rank', 'C_rank','Degree','Percentage','Preference', 'Course_name', 'CenterID', 'Payment', 'Reported_center', 'PRN') def convert_student_field(field, value): if field == 'FormNumber' or field == 'A_rank' or field == 'B_rank' or field == 'C_rank' or field == 'Preference' or field == 'Reported_center': return int(value) elif field == 'Percentage' or field == 'Payment': return float(value) else: return value for r in reader: row = {} for key,value in zip(header,r): row[key] = convert_student_field(key,value) row['Preferred'] = [] elist.append(row) return elist def load_preferences_csv(): elist = [] file = open('preferences.csv','r') reader = csv.reader(file) header = ('FormNumber', 'Preference', 'Course_name', 'CenterID') def convert_preferences_field(field, value): if field == 'FormNumber' or field == 'Preference': return int(value) else: return value for r in reader: row = {} for key,value in zip(header,r): row[key] = convert_preferences_field(key,value) student = next(s for s in students if s['FormNumber'] == row['FormNumber']) student['Preferred'].append(row) elist.append(row) return elist def load_eligibilities_csv(): elist = [] file = open('eligibilities.csv','r') reader = csv.reader(file) header = ('Course_name', 'Degree','min_Percentage' ) def convert_eligibilities_field(field, value): if field == 'min_Percentage': return float(value) else: return value for r in reader: row = {} for key,value in zip(header,r): row[key] = convert_eligibilities_field(key,value) course = next(c for c in courses if c['Course_name'] == row['Course_name']) course['Eligibility'].append(row) elist.append(row) return elist def load_courses_csv(): elist = [] file = open('courses.csv','r') reader = csv.reader(file) header = ('CourseID', 'Course_name', 'Fees', 'Section') def convert_courses_field(field, value): if field == 'CourseID' or field == 'Fees': return int(value) else: return value for r in reader: row = {} for key,value in zip(header,r): row[key] = convert_courses_field(key,value) row['Eligibility'] = [] elist.append(row) return elist def load_centers_csv(): elist = [] file = open('centers.csv','r') reader = csv.reader(file) header = ('CenterID','Center_name','Address','Coordinator','Password') for r in reader: row = {} for key,value in zip(header,r): row[key] = value row['CourseCapacity'] = {} elist.append(row) return elist def load_capacities_csv(): elist = [] file = open('capacities.csv','r') reader = csv.reader(file) header = ('CenterID', 'Course_name', 'Capacity', 'Filled_Capacity') def convert_capacities_field(field, value): if field == 'Capacity' or field == 'Filled_Capacity': return int(value) else: return value for r in reader: row = {} for key,value in zip(header,r): row[key] = convert_capacities_field(key,value) center = next(c for c in centers if c['CenterID'] == row['CenterID']) center_capacity = center['CourseCapacity'] center_capacity[row['Course_name']] = len(elist) elist.append(row) return elist students = load_students_csv() preferences = load_preferences_csv() courses = load_courses_csv() eligibilities = load_eligibilities_csv() centers = load_centers_csv() capacities = load_capacities_csv()
a4987ff5c4ca812748fcdea0805f20f1e71d9262
colephalen/SP_2019_210A_classroom
/students/BrianB/lesson04/dic_lab.py
1,648
4.5625
5
#!/usr/bin/env python3 d = { 'name': 'Chris', 'city': 'Seattle', 'cake': 'Chocolate' } def dict_1(): """ reads a dictionary Returns: dictionary, deletes one key, adds a new key: value, displays the new key: value, displays dictionary keys and values and test if 'cake' is a key and test if 'Mango' is a value """ d1 = d # display dictionary print('Original Dictionary: ', d1) # delete key, cake del d1['cake'] # display dictionary without cake print('\nDictionary with key "cake" deleted: ', d1, '\n') # add dictionary with a fruit d1.update({'fruit': 'Mango'}) # display dictionary with new key and value print('Key, value with fruit, mango added:') for key, value in d1.items(): print(key, ': ', value) # display the dictionary keys print('\n', d1.keys()) # display the dictionary values print('\n', d1.values()) # test if 'cake' is no longer a key #for key, value in d1.items(): if 'cake' in d1.keys(): print(True) else: print(False) # test if 'mango' is a value if 'Mango'in d1.values(): print(True) else: print(False) return d1 def dict_2(): """ reads a dictionary Returns: the count of 't' in dictionary values """ d2 = d print("The count of 't's in each value are: ") while True: for key, value in d2.items(): print(key, ':', value.lower().count('t')) break return d2 if __name__ == "__main__": # display dictionary keys: dict_1() # dictionary 2 function call dict_2()
500c4932fb601d1397d7d89c20dbf9bcc24398a9
MihaiCatescu/python_exercises
/exercise9.py
510
4.1875
4
''' Take two lists and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. ''' import random list_a = random.sample(range(100), 10) list_b = random.sample(range(100), 15) list_c = [] for i in list_a: if i in list_b and i not in list_c: list_c.append(i) if not list_c: print("The two lists have no common numbers.") else: print(list_c)
a6e28f9420a501add2bfcdb49cf10b1e44f3216d
mmbsow/Coursera_Intro2DataScience_UW
/assignment3/unique_trims.py
508
3.609375
4
import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() def mapper(record): # key: friend A # value: friend B sequence_id = record[0] nucleotide = record[1][:-10] if nucleotide: mr.emit_intermediate(nucleotide, 1) def reducer(key, list_of_nucs): # key: nucleotide # value: count (1) mr.emit(key) if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
0b8260b4808c46537a208d9f1f1747c404bdd03d
subZiro/adventofcode_2020
/code/day_9.py
2,796
4.21875
4
# -*- coding: utf-8 -*- # --- Day 9: Encoding Error --- # from itertools import combinations """ For example, suppose your preamble consists of the numbers 1 through 25 in a random order. To be valid, the next number must be the sum of two of those numbers: 26 would be a valid next number, as it could be 1 plus 25 (or many other pairs, like 2 and 24). 49 would be a valid next number, as it is the sum of 24 and 25. 100 would not be valid; no two of the previous 25 numbers sum to 100. 50 would also not be valid; although 25 appears in the previous 25 numbers, the two numbers in the pair must be different. Suppose the 26th number is 45, and the first number (no longer an option, as it is more than 25 numbers ago) was 20. Now, for the next number to be valid, there needs to be some pair of numbers among 1-19, 21-25, or 45 that add up to it: 26 would still be a valid next number, as 1 and 25 are still within the previous 25 numbers. 65 would not be valid, as no two of the available numbers sum to it. 64 and 66 would both be valid, as they are the result of 19+45 and 21+45 respectively. """ def get_data(): """получение списка чисел из файла""" with open('../data/day_9.txt', "r") as f: lines = f.readlines() result = [int(line.strip())for line in lines] return result def part_one(data: list, pre: int): """ получение первого числа не соответствующего eXchange-Masking Addition System алгоритму шифрования """ for i in range(pre, len(data)): comb = combinations(data[i-pre:i], 2) sum_in_comb = [sum(x)==data[i] for x in comb] if not any(sum_in_comb): return data[i] return None """ The final step in breaking the XMAS encryption relies on the invalid number you just found: you must find a contiguous set of at least two numbers in your list which sum to the invalid number from step 1. """ def get_min_max_sum(data: list): """ Возвращает сумму минимального и максимального элемента списка data """ return min(data) + max(data) def part_two(data: list, num: int): """ Возвращает результат второго задания """ arr = [] for x in data: arr.append(x) if sum(arr) > num: while not sum(arr) <= num: del arr[0] if sum(arr) == num: return get_min_max_sum(arr) return None data = get_data() # --- Part One --- # result = part_one(data, 25) print(f'part one result: {result}') # --- Part Two --- # result_two = part_two(data, result) print(f'part two result: {result_two}')
c0216360ebf4789deb3376c69da0e05a98acb813
Shristi19/DataStructuresInPython
/tree traversal.py
941
3.71875
4
class node: def __init__(self,key): self.right=None self.left=None self.val=key def preorder(root): if root: print(root.val) preorder(root.left) preorder(root.right) def postorder(root): if root: postorder(root.left) postorder(root.right) print(root.val) def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) root=node(25) root.left=node(15) root.left.left = node(10) root.left.left.left=node(4) root.left.left.right=node(12) root.left.right = node(22) root.left.right.left=node(18) root.left.right.right=node(24) root.right=node(50) root.right.left=node(35) root.right.left.left=node(31) root.right.left.right=node(44) root.right.right=node(70) root.right.right.left=node(66) root.right.right.right=node(90) preorder(root) print("\n") inorder(root) print("\n") postorder(root) print("\n")
9a77ed842cee4f07713ca1ba35b68b46b76a1d13
Darcy382/code-breakers
/2.Fundamentals/linked_list_cycle.py
1,192
3.734375
4
class ListNode: def __init__(self, x): self.val = x self.next = None # First Attempt O(n) time and O(1) space def hasCycle(self, head: ListNode) -> bool: if head: slow = head.next if slow: fast = head.next.next else: return False else: return False while fast: if fast is slow: return True else: slow = slow.next fast = fast.next if fast: fast = fast.next else: return False # Second attempt: time = O(N) space = O(1) def hasCycle1(self, head: ListNode) -> bool: try: slow = head.next fast = head.next.next while slow is not fast: slow = slow.next fast = fast.next.next return True except: return False # Third attempt: time = O(N) space = O(1) def hasCycle3(self, head: ListNode) -> bool: try: slow = head.next fast = head.next.next while slow is not fast: slow = slow.next fast = fast.next.next return True except AttributeError: return False
70988a0caf9a1a1ef063df4939741a3ea26986f0
ellinx/LC-python
/IntersectionOfTwoArraysII.py
1,042
4.1875
4
""" Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: 1. Each element in the result should appear as many times as it shows in both arrays. 2. The result can be in any order. Follow up: 1. What if the given array is already sorted? How would you optimize your algorithm? 2. What if nums1's size is small compared to nums2's size? Which algorithm is better? 3. What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? """ class Solution: def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ counter = collections.Counter(nums1) ret = [] for num in nums2: if counter.get(num, 0)>0: ret.append(num) counter[num] -= 1 return ret
3dbad7e2ab1b82f21d88b3a1a515ed5c5095dfcd
ravindrajoisa/Python
/Basics/Inherit and Polymorphism.py
1,201
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[20]: class Student(): def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname self.term = 1 def name(self): return self.firstname + " " + self.lastname class WorkingStudent(Student): # Student is from the super class >> inherit def __init__(self, firstname, lastname, company): super().__init__(firstname, lastname) # using super() to inherit self.company = company # def name(self): # return "WorkingStudent:" + self.firstname + " " + self.lastname #this will overwrite the method in the super class def name(self): return super().name() + " (" + self.company + ")" # want to add something in addition to what is present in super method. student = [ WorkingStudent("Ravi", "Joisa", "EMC"), Student("Chai", "V"), Student("Ani", "Kid"), WorkingStudent("Latha", "Krishna", "Home") ] #polymorphism for stud in student: print(stud.name()) # In[ ]: # In[ ]:
480c0f84d8766e342b0cac105589dc7ef857a4e7
syedayazsa/HackOff-MLH
/brain.py
2,582
3.5
4
#Importing keras libraries and packages from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense import numpy as np import pickle #Initializing the CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu')) # Step 2 - Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Convolution2D(32, 3, 3, activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection classifier.add(Dense(output_dim = 128, activation = 'relu')) classifier.add(Dense(output_dim = 1, activation = 'sigmoid')) # Compiling the CNN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Part 2 - Fitting the CNN to the images from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('BT/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory('BT/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, samples_per_epoch = 400, nb_epoch = 15, validation_data = test_set, nb_val_samples = 80) #Pickling pickle.dump(classifier, open('brain.pkl','wb')) ##The prediction import numpy as np from keras.preprocessing import image test_image = image.load_img('h3.png', target_size = (64, 64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) mod = pickle.load(open('brain.pkl', 'rb')) result = mod.predict(test_image) training_set.class_indices if result[0][0] == 1: prediction = 'not Haem.' else: prediction = 'Haem.' print(prediction)
fb6ac69ceb4ebd677638c7570619269a016de3b8
urluba/summer2018
/20180808/calculatrice.py
1,068
3.765625
4
''' 1 - Lire un fichier dont le format est: int;int;operation (+|-|*|/) exemple: 1;1;+ 2 - utiliser les informations fournies dans le fichier pour effectuer les operations arithmetiques définies 3 - Ecrire les résultats justes dans un fichier sous le format: L'addition de <premier nombre> avec <second nombre> est: <resultat> 4 - Ecrire les erreurs dans un autre fichier sous le format: la ligne "a;1;e" contient 2 erreurs: a n'est pas un chiffre e n'est pas une operation Il faut lire tout le fichier Ecrire un fichier qui permet d'effectuer tous les tests Utiliser des noms parlant ''' import os import csv from fonction_calculs import operation, saisie_int, saisie_ope def compute_from_file(input_filename): ''' Read provided file name and execute operations in it ''' with open(os.path.abspath(input_filename), newline='') as fd: for calcul in fd.read().splitlines(): left, right, operand = calcul.split(';') print(left, right, operand) if __name__ == '__main__': compute_from_file('test_input.csv')
eca4e4b2dd9953fc06121e9c2330c7d02a5bfa64
jadewu/Practices
/Python/Copy_List_with_Random_Pointer.py
787
3.546875
4
""" # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ # 用字典存储每个原节点和对应的新节点,d中的key是原节点,value是新节点,d[node] = new_node,这样可以很方便地找到next和random # 核心:d[node].random = d[node.random] class Solution: def copyRandomList(self, head: 'Node') -> 'Node': d = {} cur = head while cur: d[cur] = Node(cur.val) cur = cur.next cur = head d[None] = None while cur: d[cur].next = d[cur.next] d[cur].random = d[cur.random] cur = cur.next return d[head]
4fbfb712553dfa75b6ae1d3f2d09314bf17a701c
yuuuhui/Basic-python-answers
/梁勇版_5.54py.py
396
3.65625
4
import turtle from math import * turtle.showturtle() turtle.penup() turtle.goto(-175,0) turtle.pendown() turtle.goto(175,0) turtle.dot() turtle.penup() turtle.goto(0,-180) turtle.pendown() turtle.goto(0,180) turtle.dot() turtle.penup() turtle.goto(-15,0.25 * 15 ** 2) turtle.pendown() for i in range(-15,20): turtle.goto(i, 0.25 * i ** 2) turtle.done()
42b18e684da6da0da7b056b2fe12e6d8474aa642
mfaria724/CI2691-lab-algoritmos-1
/Laboratorio 03/Lab03Ejercicio3.py
985
3.765625
4
# # Lab03Ejercicio3.py # # DESCRIPCION: Programa que dado un entero positivo n, determina si n # es perfecto. # # Autor: # Manuel Faria # Variables: # n: int // ENTRADA: Número que se desea verificar si es primo. # i: int // Iterador que servirá para salir del do. # k: int // Valor donde se almacenará la suma de los divisores. # esPerfecto: bool // SALIDA: Variable donde se almacena si n es perfecto o no. # Valores Iniciales: n = int(input("Ingrese el número que desea verificar: ")) i,k=1,0 cota=n-i # Precondicion assert( n>0 ) # Calculos: # Invariante y cota: assert( n>=i ) assert( cota>=0 ) while n>i: if n%i == 0: k=k+i i=i+1 #Verifica el invariante y modifica la cota. assert( n>=i ) cota=n-i if n==k: esPerfecto=True else: esPerfecto=False # Postcondicion: assert( (n!=k or esPerfecto==True) and (n==k or esPerfecto==False) ) # Salida: if esPerfecto==False: print("El número",n,"NO es perfecto.") else: print("El número",n,"es perfecto.")
3fb841d16f7d56af86d245f390ee049ea754fda2
sunxianfeng/LeetCode-and-python
/leetcode with python/sort colors.py
572
3.6875
4
# -*- coding:utf-8 -*- def sortColors(A): len_A = len(A) if len(A) == 1: return left = 0 right = len_A - 1 i = 0 while i <= right: if A[i] == 0: if left == i: i += 1 else: A[left], A[i] = A[i], A[left] left += 1 elif A[i] == 1: i += 1 else: if right == i: i += 1 else: A[right], A[i] = A[i], A[right] right -= 1 a = [1,2,0,0,0,2,1,0,1,2,0,0,2,2] sortColors(a) print a
64b3429e5b8f55550c3715614c5c1df99990d475
tompika/num_beadando
/problems/MatrixVektor/main.py
867
3.921875
4
#!/usr/bin/env python3 from functools import reduce def matrix_vector_multiplication(A, v): nrows = len(A) w = [None] * nrows for row in range(nrows): w[row] = reduce(lambda x, y: x + y, map(lambda x, y: x*y, A[row], v)) return w def main(): first_line = list(map(float, input().strip().split(' '))) m = int(first_line[0]) n = int(first_line[1]) matrix = [] for i in range(m): a = [] line_num = list(map(float, input().strip().split(' '))) for j in line_num: a.append(j) matrix.append(a) #print(matrix) vector = list() for i in range(n): vector.append(float(input())) #print("Vector:", vector) result = matrix_vector_multiplication(matrix, vector) for item in result: print("%.12f" % item) if __name__ == '__main__': main()
e801f62f4b15b20a3ac2921f9bc0c1c2b04db954
miloscomplex/100_Days_of_Python
/day-18-start/spirograph.py
488
3.6875
4
from turtle import Screen import turtle as t import random tim = t.Turtle() t.colormode(255) tim.shape("turtle") tim.pensize(3) tim.speed("fastest") def random_color(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) return (r,g,b) directions = [0, 90, 180, 270] heading = 0 for n in range(0, 365, 5): tim.color(random_color()) tim.circle(200) tim.setheading(n) # heading += 5 screen = Screen() screen.exitonclick()
0ea75584e69d9f7b96110738982b9a4eeab490a1
Randomgamer22/uploadingFile
/uploadFiles.py
809
3.5
4
import os import dropbox class TransferData: def __init__(self, token): self.token = token def upload_file(self, file_from, file_to): dbx = dropbox.Dropbox(self.token) for root, folders, files in os.walk(file_from): print("done") for f in files: local_path = os.path.join(root, f) relative_path = os.path.relpath(local_path, file_from) dropbox_path = os.path.join(file_to, relative_path) with open(local_path, 'rb') as f: dbx.files_upload(f.read(), dropbox_path) def main(): token = 'sl.Av0h0sokMdiQeiXP-BiMhTOKRSLy3jFtWM_8FSwFsSu486G3dT7XcsCLUnRdMKYmbVwQ1h_ImyNNeBE9kWs4gRQ81gzF81ySdGPW8VVeoGZGaCb0X0QlaRGpUbiaciZHpaFa1OmC72Y' transfer_data = TransferData(token) file_from = input("Enter which folder you want to upload from: ") file_to = input("What should the folder be named: ") transfer_data.upload_file(file_from, file_to) print("Upload successful!") main()
1f0d272771edb9ea8f6e5ae363d5d68d246ede3f
hajin-kim/2020-HighSchool-Python-Tutoring
/day2/day2-09 elif.py
146
3.9375
4
num1 = int( input() ) num2 = int( input() ) if num1 > num2: print(num1) elif num1 < num2: print(num2) else: print(num1)
e99c65c86d7261f4847bb41395750f1aa682d1c4
muhadeel/hadoop_patterns
/filtering.py
665
3.703125
4
import re from mrjob.job import MRJob class MRJobFilter1(MRJob): def mapper(self, _, line): # assume CSV input, format Author;Title;Year # retrieve records from 2021 attributes = line.split(';') if attributes[2] == '2021': yield line, None def reducer(self, key, values): yield key, None class MRJobFilter2(MRJob): def mapper(self, _, line): # sherlock.txt input # retrieve lines that contain the word London # uses regular expression package if re.search('London', line): yield line, None def reducer(self, key, values): yield key, None
8e3ac4363427cc16f768e402a67ccaaabdee2a96
archeskeith/socket_programming
/client.py
1,638
3.578125
4
import socket #declares global variables #variables match with the server variable values to initiate compatibility HEADER = 64 PORT = 5050 FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" SERVER = "192.168.1.5" ADDR = (SERVER,PORT) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect to the server client.connect(ADDR) #uses send function to send to server def send(msg): #encodes the message according to the format (to ensure that the server can be able to read it) message = msg.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER-len(send_length)) client.send(send_length) client.send(message) #receives the pig latin word from the server print(client.recv(2048).decode(FORMAT)) #uses while loop to loop input statements #added initial input for initial statement send(input("Input your statement here: \t")) while(1): variable = input("[!] Do you still want to send messages? [1 if yes. Else, you'll be disconnected]: \t") if(variable == "1"): send(input("Input your statement here: \t")) else: send(DISCONNECT_MESSAGE) print("[!] Client Disconnected.") break #REFERENCES: #A quick Guide for translating to Pig Latin with Examples: https://bunnystudio.com/blog/library/translation/a-quick-guide-for-translating-to-pig-latin-with-examples/#:~:text=Pig%20Latin%20is%20a%20pseudo-language%20or%20argot%20where,word%20%E2%80%98pig%E2%80%99%20would%20become%20igp%2Bay%20which%20becomes%20igpay. #Python Socket Programming Tutorial: https://www.youtube.com/watch?v=3QiPPX-KeSc
4b46da9e14f16a6b97e735cb7aac9da9ebceb9a4
gabriellaec/desoft-analise-exercicios
/backup/user_241/ch16_2020_06_22_17_36_57_149053.py
93
3.640625
4
x = input(float("Qual o valor da conta: ") print("Valor da conta com 10%: R$ X.YZ".format(x))
3a7478b78f498878743969ab29bc5366131bede0
daniel-reich/turbo-robot
/cHzvB5KCWCK3oCLGL_22.py
1,985
4.40625
4
""" ![Conway's Game of Life](https://s3.amazonaws.com/edabit-images/game-of- life.gif) The goal of this challenge is to implement the logic used in Conway's Game of Life. Wikipedia will give a better understanding of what it is and how it works (check the resources tab above). ### Rules * **For a space that's "populated":** * Each cell with 0 or 1 neighbours dies, as if by solitude. * Each cell with 2 or 3 neighbours survives. * Each cell with 4 or more neighbours dies, as if by overpopulation. * **For a space that's "empty" or "unpopulated":** * Each cell with 3 neighbours becomes populated. ### Parameters `board`: a 2-dimensional list of values 0 to 1. * 0 means that the cell is empty. * 1 means the cell is populated. ### Return Value A `string` containing the board's state after the game logic has been applied once. On character: I Off character: _ ### Notes * The string should be divided by newlines `\n` to signal the end of each row. * A cell's "neighbours" are the eight cells that are vertically, horizontally and diagonally adjacent to it. """ def game_of_life(board): # put wall of 0's around board b = [] top = [0]*(2+len(board[0])) b.append(top) for row in board: b.append([0] + row + [0]) b.append(top) ​ loa = [] for r in range(1, 1+len(board)): a = '' for c in range(1, 1+len(board[0])): a += get_new(b, r, c) loa.append(a) return '\n'.join(loa) ​ def get_new(b, r, c): cnt = 0 rr = r-1 for cc in [c-1, c, c+1]: if b[rr][cc] == 1: cnt +=1 rr = r+1 for cc in [c-1, c, c+1]: if b[rr][cc] == 1: cnt +=1 rr = r for cc in [c-1, c+1]: if b[rr][cc] == 1: cnt +=1 if b[r][c] == 1: if cnt in (0, 1, 4, 5, 6, 7, 8): return '_' else: return 'I' if cnt == 3: return 'I' return '_'
bfd8165d6f952c96fa9472a0be1bfacffa762a00
MaksimBibaev/task6
/6.py
636
3.71875
4
try: kol=int(input("Сколько значений вы хотите ввести?")) except ValueError: print("Ошибка") else: if kol>0: array=[] c=0 count=0 while c!=kol: a=int(input("Введите значение")) array.append(a) c+=1 delta=int(input("Введите дэльту")) minValue=min(array) for i in array: if i-minValue==delta: count+=1 print("Количество элементов с заданным условием:",count) else: print("Ошибка")
f712278fc4345231a27bf8d8f5a58d12bb508fc5
wncbb/prepare_meeting
/airbnb/url_decode/2.py
290
3.671875
4
def letterCasePermutation(S): res = [''] for ch in S: if ch.isalpha(): res = [i+j for i in res for j in [ch.upper(), ch.lower()]] else: res = [i+ch for i in res] return res s='aBc' rst=letterCasePermutation(s) for v in rst: print v
50de5e3cdb9f19eb82032e06e93573937c68a7d8
MJeremy2017/dancing-pie
/indeed/linklist.py
931
3.71875
4
class Node: def __init__(self, val, nxt=None): self.val = val self.nxt = nxt class LinkedList: def __init__(self, head): self.head = head def find(self, index): i = 0 node = self.head while node: if i == index: return node.val node = node.nxt i += 1 if index > i: return -1 def insert(self, index, value): prev, curr = None, self.head node = Node(value) i = 0 while curr: if index == i: if i == 0: node.nxt = curr return node else: prev.nxt = node node.nxt = curr return self.head prev = curr curr = curr.nxt i += 1 prev.next = node return self.head
0f05ebdeb700a3226ed2fe0dbb14b06606437a81
rajeshalda/Python-Tutorials
/Day 7 len str sliceing.py
1,322
3.9375
4
#mystr="Rajesh is Good Boy" #print(mystr) #in python index start with 0,1,2.. #in this i want only some charater that i want mystr="RAJESH IS GOOD BOY" print(mystr[0:3]) #RESULT RAJ #HERE YOU 0 INCLUDE AND 3 EXCLUDE ITS TAKE 012 TOTAL 3 STRING #R A J E S H #0 1 2 3 4 5 6 mystr="RAJESH IS GOOD BOY" print(len(mystr)) #length of my mystr #result 18 print(mystr[0:17]) mystr="RAJESH IS GOOD BOY" print(len(mystr)) #length of my mystr #print(mystr[18]) #error string index out of range #print(mystr[0:19]) #result correct #print(mystr[0:30]) #result correct python is intillegent print(mystr[0:98]) mystr="RAJESH IS GOOD BOY" print(len(mystr)) #length of my mystr #result 18 #slicing print(mystr[0:18:1]) #RAJESH IS GOOD BOY print(mystr[0:18:2]) #RJS SGO O print(mystr[0:18:3]) #RE OB print(mystr[0:18:4]) #RSSOO print(mystr[::]) #RAJESH IS GOOD BOY #print(mystr[0:0:0]) #error slice step cannot be zero print(mystr[0:0:1]) #nothing printed print(mystr[0:0:2]) #nothing printed print(mystr[0:1:1]) #R print(mystr[::18]) #R print(mystr[::100]) #R #negative index start with ....etc -3 -2 -1 #positive index start with 0 1 2 3...etc print(mystr[-1:]) #result Y print(mystr[-4:-2]) #result B print(mystr[15:16]) #result B print(mystr[-4:]) #result BOY #reverse the string easy way print(mystr[::-1]) #result YOB DOOG SI HSEJAR print(mystr[::-2]) #YBDO IHEA
fc70f19a1067c4ce3665c022940510068df607c3
Eragon-18/Project98
/swappingData.py
355
3.625
4
def swappingFileData() : f1in = input("Enter name of the first file") f2in = input("Enter name of the second file") f1op = open(f1in, "r") f2op = open(f2in, "r") f1r = f1op.read() f2r = f2op.read() f1ow = open(f1in, "w") f2ow = open(f2in, "w") f1ow.write(f2r) f2ow.write(f1r) swappingFileData()
1bed2ec2ebdc4eebfa40805960470e2ea44a5d52
ChastityAM/Python
/Python-data/identity_operators.py
396
3.96875
4
x = 10 y = 10 print(x == y) print(x is y) str1 = "Hello" str2 = "Hello" print(str1 == str2) print(str1 is str2) list1 = [1, 2, 3] #these have the same values, but are list2 = [1, 2, 3] # 2 different objects print(list1 is list2) #checks if they are the same object(identity) print(list1 == list2) #checks if values are same print(type("Hello") is str) #check class print("Hello" is not "World")
f4f98df85530b6c42adf4eac325b569330479f58
RafaelDSS/uri-online-judge
/iniciante/python/uri-1045.py
548
3.875
4
# -*- coding: utf-8 -*- valores = list(map(float, input().split())) valores.sort(reverse=True) a, b, c = valores no = True if a >= b+c: print('NAO FORMA TRIANGULO') no = False if a**2 == b**2 + c**2 and no: print('TRIANGULO RETANGULO') if a**2 > b**2 + c**2 and no: print('TRIANGULO OBTUSANGULO') if a**2 < b**2 + c**2 and no: print('TRIANGULO ACUTANGULO') if a == b == c and no: print('TRIANGULO EQUILATERO') if a == b and c != a or a == c and b != a or b == c and a != b: print('TRIANGULO ISOSCELES')
75a05b8430b02f3bd7e654b81031a5245a398482
JimmyKent/PythonLearning
/com/jimmy/basic/PlotLearning.py
1,533
3.96875
4
import numpy as np import matplotlib.pyplot as plt def draw_point(x_list, y_list): # 绘制散列点 plt.plot(x_list, y_list, '*') plt.show() def draw_line(a, b): """ 关键在于 1.坐标轴的取值范围 2.x的取值范围 y = ax + b :param a: :param b: """ plt.figure() # 实例化作图变量 plt.title('line') # 图像标题 plt.xlabel('x') # x轴文本 plt.ylabel('y') # y轴文本 plt.grid(True) # 是否绘制网格线 x = np.linspace(0, 50, 10) # 在0-5之间生成10个点的向量 print("x", x) plt.plot(x, a * x + b, 'g-') # 绘制y=2x图像,颜色green,形式为线条 plt.show() # 展示图像 def draw_line_range(a, b, x_y_range): """ 关键在于 1.坐标轴的取值范围 2.x的取值范围 y = ax + b :param a: :param b: :param x_y_range: x, y轴的范围. eg: [0, 5, 0, 10] # x轴范围0-5,y轴范围0-10 """ plt.figure() # 实例化作图变量 plt.title('line') # 图像标题 plt.xlabel('x') # x轴文本 plt.ylabel('y') # y轴文本 plt.axis(x_y_range) # x轴范围,y轴范围 plt.grid(True) # 是否绘制网格线 x = np.linspace(x_y_range[0], x_y_range[1], 10) # 在x之间生成10个点的向量 print("x", x) plt.plot(x, a * x + b, 'r-') # 绘制y=2x图像,颜色green,形式为线条 plt.show() # 展示图像 if __name__ == "__main__": draw_line(1, 1) draw_line_range(10, 10, [-10, 50, -10, 600])
41b006028f46c25be4989ee1c3997a388bf3a8ee
snehadasa/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
598
4.375
4
#!/usr/bin/python3 """Module to print square pattern""" def print_square(size): """prints square pattern for given size. size: size of the square to be printed. Return: square pattern. Raise: TypeError, ValueError. """ if not isinstance(size, int): raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") elif isinstance(size, float) and size < 0: raise TypeError("size must be an integer") for i in range(size): for j in range(size): print("#", end="") print("")
0187158a50fdaa6078cd13e27dd38f90d8655acb
Fayebest/leetcode-hit
/在排序数组中查找元素.py
1,467
3.5625
4
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ ans = self.half_search(nums,target,0) sta = 0 end = 0 if ans == -1: return [-1, -1] if ans > 0 and nums[ans-1] == target: sta = half_search(nums,target,1) else: sta = ans if ans < len(nums) - 1 and nums[ans+1] == target: end = half_search(nums,target,2) else: end = ans return [sta,end] def half_search(self, nums, target, flag): # flag =1 left flag=2 right sta = 0 end = len(nums)-1 while sta <= end: mid = (sta + end) / 2 if nums[mid] < target: sta = mid + 1 elif nums[mid] > target: end = mid - 1 else: if nums[mid] == target and flag == 1: if mid > 0 and nums[mid - 1] == target: end = mid-1 else: return mid elif nums[mid] == target and flag == 2: if mid < len(nums) -1 and nums[mid +1 ] == target: sta = mid + 1 else: return mid elif flag == 0: return mid return -1
e3ade15099b295e649aa1a23f132556213dac865
ceasaro/ceasaro_py
/adventofcode.com/2021/day_01/puzzle_2.py
676
3.703125
4
#!/usr/bin/python3 import argparse import sys def run(input_file): increases = 0 values = [] with open(input_file) as fp: for position, line in enumerate(fp.readlines()): value = int(line) if len(values) == 3: previous_sum = sum(values) values = values[1:] values.append(value) current_sum = sum(values) if current_sum > previous_sum: increases += 1 else: values.append(value) print(increases) def main(prog_args): run(prog_args[1]) if __name__ == '__main__': sys.exit(main(sys.argv))
44ca7a5b2cb778360ea3a00c3fd964e804928945
kwasnydam/python_exercises
/StrukturyDanychIAlgorytmy/scripts/variables.py
656
3.890625
4
var1 = [2, 4, 6] #var1 nie jest obiektem, jest referencja print(var1) # [2 4 6] var2 = var1 #var2 var2.append(8) print(var1) #[2 4 6 8] print(var2) #[2 4 6 8] #Typowanie dynamiczne var1 = 1 print(type(var1)) #int var1 += 0.1 print(type(var1)) #float #zasieg zmiennych zm1 = 10 zm2 = zm1**2 def zasiegZmiennych(): global zm1 zm1 = 11 zm2 = 25 print(zm1, zm2) #10 100 zasiegZmiennych() print(zm1, zm2) #11 100 #porównywanie zmiennych """ if a == b -> jeśli a i b mają tą samą wartość if a is b -> Jeśli a i b są tym samym obiektem if type(a) is type(b) -> jesli a i b są tego samego typu
b624bf7c995cce05c921b52f102c83d670292317
mandar-degvekar/DataEngineeringGCP
/StringReverse.py
287
4.25
4
def reverse(s): str = "" for i in s: # print(i) str = i+" "+ str #print(str) return str print("Hello World") fval = input("Enter your fname: ") lval = input("Enter your fname: ") print("----------------------------------------") print("reverse " + reverse(fval+lval))
a16b1fb45854540de19b161c0868d53e7574d686
RafaelTeixeiraMiguel/PythonUri
/br/com/rafael/teixeira/uri/beginner/uri_1010_simple_calculate.py
260
3.796875
4
x = 0 total = 0 for x in range(0,2): values = input() array = [] array = values.split() cd = int(array[0]) qtd = int(array[1]) price = float(array[2]) total += qtd * price print("VALOR A PAGAR: R$ {total:.2f}".format(total = total))
5070854d2d4c1b633d68922137ea0e638a818ef2
mrtonks/Machine_Learning_AZ
/Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/data_preprocessing_template.py
726
3.59375
4
# Data Preprocessing # Importing the libraries import numpy as np # Maths import matplotlib.pyplot as plt # Plot charts import pandas as pd # Import/manage datasets # Importing the dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 3].values # Splitting the dataset int the Training Set and the Test Set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2 , random_state = 0) # Feature Scaling """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train)"""
14d726b10795edfd2c88c482e212a7dd7861cebd
jackngogh/Python-For-Beginners
/codes/03_data_types/002/tuples.py
138
3.53125
4
list = (1, 2, 4) print(list) print(list[0]) list2 = (4, 5, 6) print(list2) print(list2[0]) print(list2[1]) print(list2[2]) list2[2] = 7
9d5373aec397f0ee7968d6ccd08a3471cf871c7a
kojo-gene/python-tutorials
/lecture17.py
207
3.671875
4
print(7 > 6 and 6 >= 6) #true and true => true print(3 != 3 or 4 == 4) #false or true => true print(not 5 > 2) #false print(not 5 < 3 and true or 6 <= 6 and not false) #true and true or true and true => true
74d04a7bf3e559b0660a391868cc476d72c3ec93
n17/python_audio_demo
/spectrogram.py
427
3.5625
4
""" Compute and display a spectrogram. Give WAV file as input """ import matplotlib.pyplot as plt import numpy as np import sys from audio_demo import spectrogram, display_spectrogram, read if __name__ == "__main__": if len(sys.argv) != 2: print "Usage: python spectrogram.py wavfile.wav" sys.exit(1) x,sr = read(sys.argv[1]) X = spectrogram(x,sr) display_spectrogram(X) plt.show()
8669d4ecaf3cb3b70bdd2b06e47c8652919482fc
Radg/projecteuler
/012/euler012.py
1,202
3.953125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle numbers: # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: 1,2,5,10 # 15: 1,3,5,15 # 21: 1,3,7,21 # 28: 1,2,4,7,14,28 # We can see that 28 is the first triangle number to have over five divisors. # What is the value of the first triangle number to have over five hundred divisors? from operator import mul triangle = number = 1 def canonicalRepresentation(n): '''Returns canonical representation of number as a dictionary, key is factor, value is degree''' if n == 1: return {1:0} factors, d, c = {}, 2, 0 while d * d <= n: if n % d == 0: c += 1 factors[d] = c n //= d else: d += 1 c = 0 if n > 1: factors[n] = 1 return factors def factorsQuantity(n): '''Returns factors quantity for number''' return reduce(mul, (i + 1 for i in canonicalRepresentation(n).values())) while factorsQuantity(triangle) <= 500: number += 1 triangle += number print triangle
33ec8c4fc333deaa74d93a92ebb0d87967c2ca98
salvador-dali/algorithms_general
/interview_bits/level_6/06_dp/10_2d_string_dp/06_interleaving-strings.py
2,478
3.640625
4
# https://www.interviewbit.com/problems/interleaving-strings/ def isInterleave(s1, s2, s3): if len(s1) + len(s2) != len(s3): return False match = [[False for _ in xrange(len(s2) + 1)] for _ in xrange(len(s1) + 1)] match[0][0] = True for i in xrange(1, len(s1) + 1): match[i][0] = match[i - 1][0] and s1[i - 1] == s3[i - 1] for j in xrange(1, len(s2) + 1): match[0][j] = match[0][j - 1] and s2[j - 1] == s3[j - 1] for i in xrange(1, len(s1) + 1): for j in xrange(1, len(s2) + 1): match[i][j] = (match[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (match[i][j - 1] and s2[j - 1] == s3[i + j - 1]) return match[-1][-1] # ------------- from collections import Counter def full_solution(s1, s2, s3): if len(s1) + len(s2) != len(s3): return False if Counter(s1) + Counter(s2) != Counter(s3): return False hash_map = {} def obvious(s1, s2, s3): if (s1, s2, s3) in hash_map: return hash_map[(s1, s2, s3)] n1, n2, n3 = 0, 0, 0 while n1 < len(s1) and n2 < len(s2) and n3 < len(s3): if s1[n1] != s3[n3] and s2[n2] != s3[n3]: return False if s1[n1] == s3[n3] and s2[n2] != s3[n3]: n1 += 1 n3 += 1 elif s2[n2] == s3[n3] and s1[n1] != s3[n3]: n2 += 1 n3 += 1 else: break s1, s2, s3 = s1[n1:], s2[n2:], s3[n3:] n1, n2, n3 = len(s1) - 1, len(s2) - 1, len(s3) - 1 while n1 >= 0 and n2 >= 0 and n3 >= 0: if s1[n1] != s3[n3] and s2[n2] != s3[n3]: return False if s1[n1] == s3[n3] and s2[n2] != s3[n3]: n1 -= 1 n3 -= 1 elif s2[n2] == s3[n3] and s1[n1] != s3[n3]: n2 -= 1 n3 -= 1 else: break s1, s2, s3 = s1[:n1 + 1], s2[:n2 + 1], s3[:n3 + 1] if s1 == '' and s2 == '' and s3 == '': return True if s1 == '' and s2 == s3: return True if s2 == '' and s1 == s3: return True if s1 == '' or s2 == '': return False res = obvious(s1[1:], s2, s3[1:]) or obvious(s1, s2[1:], s3[1:]) hash_map[(s1, s2, s3)] = res return res return obvious(s1, s2, s3) s1, s2, s3 = 'aabcc', 'dbbca', 'aadbbcbcac' print full_solution(s1, s2, s3)
97a7d55d121239380cf5aceb9848dc38c0988516
ArkaprabhaChakraborty/Datastructres-and-Algorithms
/Python/Rat_in_a_maze.py
2,317
3.703125
4
''' Rat in a maze backtracking problem. Given a maze of zeroes and ones where 0's mark valid path and 1's mark obstacles, find the shortest path from a given source to a given destination. ''' import sys sys.setrecursionlimit(10**6) def rat_travel(maze,n,source_x,source_y,dest_x,dest_y): solution = [[0 for i in range(n)] for i in range(n)] solve_maze(maze,solution,source_x,source_y,dest_x,dest_y,n) print_path(solution) def solve_maze(maze,solution,x,y,dest_x,dest_y,n): if(x==dest_x and y==dest_y and maze[x][y] == 0): solution[x][y] = 1 return True if(x>=0 and y>=0 and x<n and y<n and maze[x][y]==0): if solution[x][y] == 1: return False solution[x][y] = 1 if (solve_maze(maze,solution,x+1,y,dest_x,dest_y,n) == True): return True if (solve_maze(maze,solution,x,y+1,dest_x,dest_y,n) == True): return True if (solve_maze(maze,solution,x-1,y,dest_x,dest_y,n) == True): return True if (solve_maze(maze,solution,x,y-1,dest_x,dest_y,n) == True): return True solution[x][y] = 0 return False def solve_maze_with_iterartions(maze,solutions,x,y,dest_x,dest_y,move_x,move_y,n): if (x>=0 and y>=0 and x<n and y<n): if (x == dest_x and y == dest_y and maze[x][y] == 0): solutions[x][y] = 1; return True if (x>=0 and y>=0 and x<n and y<n and maze[x][y] == 0): if solutions[x][y] == 1: return False if (x>=0 and y>=0 and x<n and y<n and maze[x][y] == 0): solutions[x][y] = 1 for i in range(4): x = x + move_x[i] y = y + move_y[i] if(solve_maze_with_iterartions(maze,solutions,x,y,dest_x,dest_y,move_x,move_y,n) == True): return True def rat_in_maze_iterative(maze,x,y,dest_x,dest_y,n): solution = [[0 for i in range(n)] for i in range(n)] move_x = [1,0,0,-1] move_y = [0,1,-1,0] solve_maze_with_iterartions(maze,solution,x,y,dest_x,dest_y,move_x,move_y,n) print_path(solution) def print_path(arr): for i in arr: print(i) mazes = [[0, 1, 1, 1], [0, 0, 1, 0], [1, 0, 1, 1], [1, 0, 0, 0] ] rat_in_maze_iterative(mazes,0,0,3,3,4)
293a7f89517569f85aa2b6922fed77cde27574a6
saiphaniedara/HackerRank_Python_Practice
/Sets_SymmetricDifference.py
453
3.984375
4
''' Problem statement: https://www.hackerrank.com/challenges/symmetric-difference ''' # Enter your code here. Read input from STDIN. Print output to STDOUT from sys import stdin m = int(stdin.readline()) M = set(map(int,stdin.readline().split())) n = int(stdin.readline()) N = set(map(int,stdin.readline().split())) sym_diff = (M.union(N)).difference( M.intersection(N)) sym_diff = sorted(sym_diff) for i in sym_diff: print(i)
4a6db656ad82b3a0f2f58fab8b3af26a4b29aa1b
TrendBreaker/project-euler-python
/problem_31.py
714
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Problem 31 In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? ''' coins = [1, 2, 5, 10, 20, 50, 100, 200] def count_change(amount, n): if amount == 0: return 1 elif amount < 0 or n == 0: return 0 else: return count_change(amount, n - 1) + count_change( amount - coins[n - 1], n); print count_change(200, len(coins))
6089aeae5cd44cecbf8e7ac07002ef7e4f2a77e7
JackoDev/holberton-system_engineering-devops
/0x16-api_advanced/0-subs.py
637
3.59375
4
#!/usr/bin/python3 """ a function that queries the Reddit API and returns the number of subscribers (not active users, total subscribers) for a given subreddit. If an invalid subreddit is given, the function should return 0. """ from requests import get def number_of_subscribers(subreddit): """ doc for number of subscribers of reddit """ headers = {"user-agent": "untaljacko"} url = "https://www.reddit.com/r/{}/about.json".format(subreddit) try: reqs = get(url, headers=headers).json() counter = reqs["data"]["subscribers"] return (counter) except Exception: return 0
50eab386c8476099bb9726770fd93df5bd6aa4c5
analuisadev/100-Days-Of-Code
/day-18.py
535
3.65625
4
from time import sleep print ('\033[1m{:=^40}\033[m'.format(' PALINTHROME DETECTOR ')) phrase = str(input('\033[1mType a phrase:\033[m ')).strip().upper() sleep(1) p = phrase.split() together = ''.join(p) reverse = together[::-1] print ('\033[1mThe reverse of\033[m \033[1;32m{}\033[m \033[1mis\033[m \033[1;32m{}\033[m'.format(together, reverse)) sleep(1) if reverse == together: print ('\033[1mThat phrase is a\033[m \033[1;33mPALINTHROME\033[m') else: print ('\033[1mThat phrase is not\033[m \033[1;31mPALINTHROME\033[m')
f4c07cda9a2a0da66f826b5088bfeb4cd1a31251
oGabrielF/DocumentationPython
/Python/Advanced/ListComprehension/listComprehension.py
1,001
4.34375
4
# PYTHON AVANÇADO LIST COMPREHENSION # FORMA SIMPLES DE FAZER ISSO x = [1,2,3,4,5] y = [] # Obter os valores dos números da lista x ao quadrado for i in x: y.append(i**2) # Append adicionar um item a lista print(x) # Números da lista print(y) # Números da lista x ao quadrado passado pra lista y # FORMA UTILIZANDO O LIST COMPREHENSION # Para criação de uma List Comprehension: # -Valor a Adicionar # -Laço # -Condição # y = [Valor_Adicionar Laço Condição] x = [1,2,3,4,5] y = [i**2 for i in x] print(x) print(y) # Valor a Adiconar = (i**2) # Laço = (for i in x) # O "i" do valor adicionar deriva-se do "for i in x" que no caso seria a lista x # Utilizando condições x = [1,2,3,4,5] y = [i**2 for i in x] z = [i for i in x if i%2 == 1] print(z) # "i%2 == 1" Irá exibir somente os números impares # "i%2 == 0" Irá exibir somente os números pares # Valor a Adicionar = "i" # Laço = (for i in x) # Condição = (if i%2 == 1) # i%2 = Modulo da divisão de i por 2
dcddb9d52ccc8e06ea900432162a619669ac5134
Manikantha-M/python
/programs/patterns.py
845
3.765625
4
# n=int(input('Enter:')) # for i in range(1,n+1): # for j in range(i): # print('*',end=' ') # print() # n=int(input('Enter:')) # for i in range(n,0,-1): # for j in range(i): # print('*',end=' ') # print() # n=int(input('Enter:')) # k=1 # for i in range(1,n+1): # for j in range(i): # print(k,end=' ') # k+=1 # print() # a='python' # l=len(a) # for i in range(1,l+1): # for j in range(i): # print(a[j],end=' ') # print() # n=int(input('Enter:')) # k=1 # while k<=n: # for i in range(n-k,0,-1): # print(' ',end='') # for j in range(k): # print('*',end=' ') # k+=1 # print() n=int(input('Enter:')) k=0 while k<n: for i in range(k): print(' ',end='') for j in range(n-k): print('*',end=' ') k+=1 print()
185bddb2e47eef7574be68f34b2145f1af659a23
HWNET12/ENAUTO
/functions.py
299
3.828125
4
import datetime def greet(): #Get current time dt = datetime.datetime.now() if dt.hour <= 11: greeting = "morning!" elif dt.hour <= 17: greeting = "afternoon!" else: greeting = "night" print(f"Hello, good {greeting}.") greet()
b2bb9afd51c08d3bca711048b7d69f8e804afcd5
Eqliphex/python-crash-course
/chapter03 - Lists/exercise3.8_seeing_the_world.py
399
4.25
4
locations = ['Nepal', 'Japan', 'Antarktis', 'Switzerland', 'Russia'] # Raw output print(locations) # Temp sorted print(sorted(locations)) # Still in original form print(locations) # Reversing the list locations.reverse() print(locations) locations.reverse() print(locations) # Sorting the list permanently locations.sort() print(locations) locations.sort(reverse=True) print(locations)
c4135a15bc611302f9b0f954d9fdf6c8aafd6873
yue-w/LeetCode
/Algorithms/429. N-ary Tree Level Order Traversal.py
2,184
3.734375
4
from typing import List ## Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children from collections import deque class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: #return self.method1(root) ## bfs #return self.method2(root) ## dfs uising recursion return self.method3(root) ## dfs using stack def method1(self, root): """ BFS """ rst = [] dq = deque() ## Keep entering form right (append()) and leaving from left (popleft()) if root: dq.append(root) while dq: curr = [] cur_len = len(dq) for i in range(cur_len): node = dq.popleft() curr.append(node.val) ## add children to the next level for c in node.children: dq.append(c) rst.append(curr) return rst def method2(self, root): """ DFS with recursion """ if not root: return [] def dfs(root, rst, level): ## base case if not root: return if level == len(rst): rst.append([root.val]) else: rst[level].append(root.val) for c in root.children: dfs(c, rst, level + 1) rst = [] dfs(root, rst, 0) return rst def method3(self, root): """ DFS using stack """ if not root: return [] rst = [] stack = [] stack.append((root, 0)) while stack: node, level = stack.pop() if level == len(rst): rst.append([node.val]) else: rst[level].append(node.val) for c in node.children[::-1]: stack.append((c, level + 1)) return rst
3b81ebdf3d49546c9c0d6fb36c5bdca7bc659062
Aswani-kolloly/luminarPython
/collections/list_pgm2.py
321
3.703125
4
lst=list() r=int(input("enter range of list")) print("Enter elements") for i in range(0,r): lst.append(int(input())) print("\nList\n",lst) num=int(input("Enter number")) print("\n 'pairs") for i in range(0,r): for j in range(i+1,r): if (lst[i]+lst[j]==num): print("\n(",lst[i],",",lst[j],")")
3cdef6d1da4c9fe5d6c0ff43ebc9e4b836854068
Sam-Tennyson/Database-Application
/mainDB.py
1,522
3.703125
4
from pythondb import DBHelper def Application(): db = DBHelper() while True: print("--------------WELCOME--------------") print() print("Press 1 to Insert new user") print("Press 2 to display all user") print("Press 3 to delete user") print("Press 4 to update user") print("Press 5 to exit program") print() choice = int(input()) try: if choice == 1: # Insert User uid = int(input("Enter user Id - ")) uname = input("Enter user name - ") ph = input("Enter Phone - ") db.insert_user(uid, uname, ph) elif choice == 2: # display user db.fetch_all() elif choice == 3: # delete user uid = int(input("Enter the Userid you want to delete ?")) db.delete_user(uid) elif choice == 4: # update User uid = int(input("Enter user Id")) nUname = input("Enter NEW name") nph = input("Enter NEW Phone") db.update_user(uid, nUname, nph) elif choice == 5: break else: print("Invalid Input") except Exception as e: print(e) print("Invalid details | Try Again ...!!!") if __name__ == "__main__": Application()
286b355d7e02857ea0730b1a7e57b7fe62b8aa85
VivaLaDijkstra/AC-Automation
/queue.py
321
3.71875
4
#! /usr/bin/env python from collections import deque class queue(deque): def push(self, item): self.append(item) def pop(self): return self.popleft() def test(): q = queue() for i in range(10): q.push(i) while q: print q.pop() for i in range(10): q[i] = i * i if __name__ == '__main__': test()
08790d897e0a5543f7c8fdcd900efeffc6c2b6db
muon012/python-Masterclass
/38-updatingShelve.py
1,672
4.5
4
# TWO WAYS TO UPDATE SHELVES print("------------------------- 1 -------------------------") # First method: # We create a temporary variable that will hold the values of a key. In this case we create a temporary list to # hold the values of the key we want to append. # We then append that temporary list. # Finally we set the value in the the shelve equal to the temporary variable import shelve blt = ["bacon", "lettuce", "tomato", "bread"] beans_toast = ["beans", "bread"] scrambled_eggs = ["eggs", "butter", "salt"] soup = ["can of soup"] with shelve.open("38-recipes") as recipe: recipe["blt"] = blt recipe["beans_toast"] = beans_toast recipe["scrambled_eggs"] = scrambled_eggs recipe["soup"] = soup temp_list = recipe["blt"] temp_list.append("mayo") recipe["blt"] = temp_list for snacks in recipe: print(snacks, recipe[snacks]) print("------------------------- 2 -------------------------") # Second method: # Pass a second parameter to open called "writeback=True" # This method uses less code because you can simply use the "append()" method to it. # The disadvantage is that it uses more memory. with shelve.open("38-recipes", writeback=True) as recipe: recipe["soup"].append("salt") for snacks in recipe: print(snacks, recipe[snacks]) print("------------------------- 3 -------------------------") # There is a third method that you can use to update as well using the "sync()" function. # But this method is not recommnended. Choose the "writeback" method better. with shelve.open("38-recipes", writeback=True) as recipe: recipe["beans_toast"].append("sour cream") recipe.sync() for snacks in recipe: print(snacks, recipe[snacks])
a22020227f6ec17d0303e536f8f35bfe3e6c87b9
jedzej/tietopythontraining-basic
/students/pluciennik_edyta/lesson_02_flow_control/knight_moves.py
237
3.5625
4
a = int(input()) b = int(input()) c = int(input()) d = int(input()) knight_can_move = ( (abs(a - c) == 2 and abs(b - d) == 1) or (abs(a - c) == 1 and 2 == abs(b - d)) ) if knight_can_move: print('YES') else: print("NO")
47b8bc485073e7c3cc1c7b1a763ebe5db9e24eb6
MuSaCN/PythonLearning
/Learning_Basic/老男孩Python学习代码/day3-函数与变量/func_test1.py
397
3.734375
4
# Author:Zhang Yuan #定义一个函数 def function1(): """testing1,注释最好写上""" print("you are in the Testing") return True #定义一个过程(没有返回值) #python中过程也有返回值None def function2(): """Testing2""" print("you are in the Testing2") x=function1() y=function2() print("from func1 return is %s"%x) print("from func2 return is %s"%y)
d733f7934374419f25b2599d4ccecafc6196ca00
yogesh1234567890/insight_python_assignment
/completed/Data18.py
239
4.375
4
#18.​ Write a Python program to get the largest number from a list. input_string = input("Enter a list element separated by space: ") list = input_string.split() list.sort() print("The largest number in the list is: " + str(list[-1]))
d918507818bae64f03848382b47df0ce9f0b5999
tcrowell4/adventofcode
/2020/day10_part2_working.py
4,153
3.859375
4
#!/usr/bin/python # aoc_day1_part1.py """ --- Day 10: Adapter Array --- Patched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off! Its battery is dead. You'll need to plug it in. There's only one problem: the charging outlet near your seat produces the wrong number of jolts. Always prepared, you make a list of all of the joltage adapters in your bag. Each of your joltage adapters is rated for a specific output joltage (your puzzle input). Any given adapter can take an input 1, 2, or 3 jolts lower than its rating and still produce its rated output joltage. In addition, your device has a built-in joltage adapter rated for 3 jolts higher than the highest-rated adapter in your bag. (If your adapter list were 3, 9, and 6, your device's built-in adapter would be rated for 12 jolts.) Treat the charging outlet near your seat as having an effective joltage rating of 0. Since you have some time to kill, you might as well test all of your adapters. Wouldn't want to get to your resort and realize you can't even charge your device! If you use every adapter in your bag at once, what is the distribution of joltage differences between the charging outlet, the adapters, and your device? Answer 75*32 2400 """ import sys import re def process_adapters(adapters): j1 = 0 j3 = 0 # print(adapters) # preamble_length = len # for i, adapter in enumerate(adapters): # print(adapter) # print("len(adapters) {}".format(len(adapters))) idx = 0 next_idx = 0 global valid_combos while idx < len(adapters): current_adapter = adapters[idx] # print("Current_adapter {}".format(current_adapter)) next_idx = idx + 1 while next_idx < len(adapters): """ print( ">>>jolt idx {} nxt {} nextadap{} curr{} diff{}".format( idx, next_idx, adapters[next_idx], current_adapter, adapters[next_idx] - current_adapter, ) ) """ jolt_diff = adapters[next_idx] - current_adapter if jolt_diff <= 3: """ print( "jolt diff = {} ..... {} {} ".format( adapters[next_idx] - current_adapter, adapters[next_idx], current_adapter, ) ) """ if jolt_diff == 1: # next_list = adapters[:next_idx] + adapters[next_idx:] next_list = adapters[:] next_list.pop(next_idx) print("Next iteration: {}".format(next_list)) ret = process_adapters(next_list) if ret: # print("*****", ret) valid_combos.append(ret) # since valid jolt found go to next entry break else: # anything greater than 3 won't work # print("invalid joltage {}".format(jolt_diff)) return 0 next_idx += 1 idx = next_idx return adapters # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def main(): global valid_combos valid_combos = [] lines = [] lines.append(0) # set to initial value with open("day10_sample.txt") as fp: for line in fp: lines.append(int(line.strip())) slines = sorted(lines) end = int(slines[-1]) + 3 slines.append(end) ret = process_adapters(slines) print(ret) z = " " total = 1 for x in sorted(valid_combos): if x != z: print(x) total += 1 z = x else: print("dupe", x) print(total) sys.exit(1) return if __name__ == "__main__": main()
1767fa67e54e485a8a1e9cf0a4437fa7754d8023
axu682/SkyMap
/Constellations v4/Cardinal.py
2,080
3.6875
4
import math class Cardinal(object): def __init__(self, label, angle): # initialize coordinates self.initialX = math.cos(math.radians(angle)) self.initialY = 0 self.initialZ = math.sin(math.radians(angle)) self.x = self.initialX self.y = self.initialY self.z = self.initialZ self.label = label self.manualVisible = True self.positionVisible = True def __repr__(self): return self.label def updatePosition(self, data): if not self.manualVisible: return newPoint = applyCardinalRotations(self.initialX, self.initialY, self.initialZ, \ data.xzAngle, data.headTiltAngle) self.x = newPoint[0] self.y = newPoint[1] self.z = newPoint[2] if self.y<0: self.positionVisible = False else: self.positionVisible = True def draw(self, data, canvas): if not (self.manualVisible and self.positionVisible): return color = data.cardinalColor R = data.skyRadius originX = data.skyOriginX originY = data.skyOriginY x = self.x z = self.z r = data.cardinalRadius canvas.create_oval((originX+R*x-r,originY-R*z-r), (originX+R*x+r,originY-R*z+r), fill=color, width=0) canvas.create_text((originX+R*x,originY-R*z), anchor="center", text=self.label, fill=data.cardinalTextColor) ################################################################################ ## HELPER FUNCTIONS ################################################################################ def applyCardinalRotations(x, y, z, xzAngle, yzAngle): x,z = (x*math.cos(xzAngle) - z*math.sin(xzAngle)), \ (x*math.sin(xzAngle) + z*math.cos(xzAngle)) y,z = (y*math.cos(yzAngle) - z*math.sin(yzAngle)), \ (y*math.sin(yzAngle) + z*math.cos(yzAngle)) return (x,y,z)
f4278dabf3056e95385a70d8928bc4f837b23572
Silentsoul04/notes-8
/algorithm/链表/83. 删除排序链表中的重复元素.py
1,750
4
4
""" 存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。 返回同样按升序排列的结果链表。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from notebook.algorithm.链表.utils import ListNode from notebook.algorithm.链表.utils import init_ln from notebook.algorithm.链表.utils import print_ln class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: cur = head while cur and cur.next: next = cur.next while next and next.val == cur.val: next = next.next cur.next = next cur = next return head # head = init_ln([1, 2, 3, 4, 4, 9]) # head = init_ln([1, 2, 3, 3, 4, 4, 5]) head = init_ln([1, 2, 3, 3, 4, 4]) print_ln(Solution().deleteDuplicates(head)) """ 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/solution/shan-chu-pai-xu-lian-biao-zhong-de-zhong-49v5/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 """ class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return head cur = head while cur.next: # 下一个如果跟当前一样,去掉链条关系!cur无须移动 if cur.val == cur.next.val: cur.next = cur.next.next else: cur = cur.next return head
c8605720817f452bfdb9915a9288d2a9e9e29841
priyapower/python_gui_calculator
/practice/g_layout.py
1,177
3.703125
4
"""Grid layout example.""" import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QGridLayout # Imports the Grid Layout Manager class from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QWidget app = QApplication(sys.argv) window = QWidget() window.setWindowTitle("QGridLayout") layout = QGridLayout() # Here is the grid class manager layout.addWidget(QPushButton("Button (0, 0)"), 0, 0) # The String defines the title of the button; # The Integers define the position layout.addWidget(QPushButton("Button (0, 1)"), 0, 1) layout.addWidget(QPushButton("Button (0, 2)"), 0, 2) layout.addWidget(QPushButton("Button (1, 0)"), 1, 0) layout.addWidget(QPushButton("Button (1, 1)"), 1, 1) layout.addWidget(QPushButton("Button (1, 2)"), 1, 2) layout.addWidget(QPushButton("Button (2, 0)"), 2, 0) layout.addWidget(QPushButton("Button (2, 1) + 2 Columns Span"), 2, 1, 1, 2) # The integers here represent 2 column span - but why isn't it: 2, 1, 2, 2?. when I experimented and put that in, it brought the double span button a little further down the grid (off kilter with button (2,0)) window.setLayout(layout) window.show() sys.exit(app.exec_())
f53f566bd7936089260b15f73ef957f03a7b8d53
dafnemus/python-curso-udemy
/Unidad_6/for_1.py
1,292
3.71875
4
# pylint: disable=missing-docstring # Uso del FOR: # Imprimir las letras de una cadena. PALABRA = 'mañana' for letra in PALABRA: print(letra) print() # imprimir los elementos de una lista. lista_nombres = ['lola', 'pablo', 'matias'] for persona in lista_nombres: print(persona) print() # imprimir todad las letras de una lista for palabra in lista_nombres: for letra in palabra: print(letra) print() # imprimir todos los numeros de una lista. numeros = [1, 2, 3] for num in numeros: print(num) print() # imprimir el rango de un numero. for x in range(5): print(x) print() # imprimir el rango de un numero de 2 en 2. for x in range(0, 10, 2): print(x) print() # FOR y break. for x in range(0, 10, 2): print(x) if x == 4: break print() # FOR y continue imprimir as palbras sin A. lista = ['ala', 'lupa', 'libro', 'a', 'pico'] for palabra in lista: if 'a' in palabra: continue print(palabra) print() # Imprimir hasta la tabla del 9. VALOR_1 = 1 VALOR_2 = 2 for VALOR_1 in range(1, 10): for VALOR_2 in range(1, 10): print(f'{VALOR_1}*{VALOR_2} = ') print(VALOR_1 * VALOR_2) print() # Uso de append y pow(potencia) con FOR. lista = [] for i in range(10): lista.append(pow(i, 3)) print(lista)
fec6976e2e000a5ee788816800a4ab2a42e9e2e3
DuncanArani/Security
/run.py
8,796
3.578125
4
#!/usr/bin/env python3.6 import string import random import datetime from locker import Locker from user import User def passwor_generator(size=8, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def new_password(account, username, thepass): new_pass = Locker(account, username, thepass) return new_pass def save_password(password): password.save_password() def del_password(password): password.delete_password() def display_password(username): return Locker.find_by_username(username) def search_if_exists(username): return Locker.password_exists(username) def display_all(): return Locker.display_password() # ********** USER RELATED FUNCTIONS ********* def check_exists(username): return User.user_exists(username) def new_user(name, username, email, thepass): new_user = User(name, username, email, thepass) return new_user def save_new_user(user): user.save_user() def auth(username, password): return User.pass_check(username, password) def it_checks(a, b): if a == b: return True time = datetime.datetime.now() def main(): print("-"*40) print("Welcome to pSecure App ! Sign up to continue") print("-"*70) while True: print(""" Select an option : [1] . Login [2] . Sign up [3] . Exit App """) select = input() if select == "1": print("Enter a username :") username = input() print("\nEnter your password") password = input() if check_exists(username): if auth(username, password): while True: print("-"*70) print(f"pSecure | Logged in as {username} | %time.!") print("-"*70) print(""" Kindly select an option to proceed :\n [1] . Create a locker \n [2] . Search \n [3] . Display your locked passwords \n [4] . Delete a password \n [5] . Logout\n """) choice = input() if choice == "1": print("Store a new Password :") print("-"*70) print("Enter Account e.g Facebook \n") acc = input() print("-"*70) print("Enter username e.g aruncodunco\n") username = input() print("-"*40) print("""You are doing Fantastic !\nNow , would you like us to generate a password for you ?\n Y or N ? """) yono = input() if yono.lower() == "y": password = passwor_generator() elif yono.lower() == "n": print("Enter your password :") password = input() else: print("\nInput unrecognized !") break save_password(new_password( acc, username, password)) print("-"*70) print(f"""New Password locked !\n Account : {acc}\n Username: {username}\n Password: {password}""") print("-"*70) # search password elif choice == "2": search = input("\nEnter username :\n") if search_if_exists(search): searched = display_password(search) print("-"*70) print("ACCOUNT | USERNAME | PASSWORD") print("-"*70) print( f"{searched.acc_name} | {searched.username} | {searched.password}") print("-"*70) else: print("Password not found !") # display all passwords elif choice == "3": print("Here are your passwords :") print("-"*70) print("ACCOUNT | USERNAME | PASSWORD") if display_all(): for locked in display_all(): print("-"*70) print( f"{locked.acc_name} | {locked.username} | {locked.password}") else: print("-"*70) print( "Ooops ! It's lonely here . You haven't locked any password(s)") print("-"*70) # delete specific password elif choice == "4": print("Kindly provide username") which = input() found = display_password(which) if search_if_exists(which): print("Confirm . Y or N") confirm = input() if confirm.lower() == "y": del_password(found) print("-"*70) print("Successfully deleted !") print("-"*70) elif confirm.lower() == "n": print("-"*70) print("Permission Denied !") print("-"*70) else: print("Sorry I didn't get that !") else: print("-"*70) print( "\nRecord not found ! Add Passwords to your locker .\n") print("-"*70) # exit the application elif choice == "5": print("-"*70) print("Logged Out !") print("-"*70) break else: print( "I'm sorry I didn't get that . Kindly use the provided option . ") else: print("-"*70) print("Sorry ! Couldn't match your credentials !") else: print("-"*70) print("\nKindly Sign Up to use pSecure !") elif select == "2": # print("Enter First Name and Last Name :") print("-"*70) f_and_last = input("Enter your First Name and Last Name :") # print("Choose a username :") print("-"*70) u_name = input("Choose a username : ") # print("Enter email :") print("-"*70) email = input("Enter email :") print("-"*70) initial = input("Enter password :") # initial = input() # print("Repeat password :") print("-"*70) repeated = input("Repeat password :") if it_checks(initial, repeated): save_new_user(new_user(f_and_last, u_name, email, initial)) print("-"*70) print( f"Welcome aboard {u_name} ! Login to secure some password !") print("-"*70) else: print("-"*70) print("""Ooops ! password didn't check !""") print("-"*70) elif select == "3": print("-"*70) print("Thanks for using pSecure . Bye ! .....") print("-"*70) break else: print("-"*70) print("Am sorry I didn't get that !") if __name__ == '__main__': main()
16e5616346fa5b01c020afead8a97565c883a326
yzjbryant/YZJ_MIX_Code
/Python_Code_Beginner/05_高级数据类型/hm_21_遍历字典的列表.py
687
4.09375
4
students = [ {"name":"阿土"}, {"name":"小美"} ] #在学员列表中搜索指定的姓名 find_name = "李四" for stu_dict in students: print(stu_dict) if stu_dict["name"] == find_name: print("找到了 %s" % find_name) #如果已经找到,应该直接退出循环,而不再遍历后续的元素 break # else: # print("抱歉没有找到 %s " % find_name) else: # #如果希望在搜索列表时,所有的字典检查之后,都没有发现需要 # #搜索的目标,还希望得到一个统一的提示! print("抱歉没有找到 %s" % find_name) print("循环结束")
76a6d212e536eedf75d1df0ab7fc499e7d7b491d
feiyu4581/Leetcode
/leetcode 51-100/leetcode_58.py
508
3.609375
4
class Solution: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ res, first = 0, True for index in range(len(s) - 1, -1, -1): if s[index] != ' ': first = False if s[index] == ' ' and not first: break if not first: res += 1 return res x = Solution() print(x.lengthOfLastWord("Hello World") == 5) print(x.lengthOfLastWord("a ") == 1)
645b7c8314d0e3cf26ed1762fd3d03b93675eb4c
ogenodisho/Tkinterweave
/utils.py
876
3.65625
4
''' This module is just for random/helpful utility methods that many other modules may find useful. ''' # Returns a tuple of coords that represent # (in order) the width, height, xPos, yPos of a window. def get_window_geometry(window): l = [] curr_value = "" for letter in window.geometry(): if letter.isdigit(): curr_value += letter else: l.append(curr_value) curr_value = "" l.append(curr_value) return tuple(map(int, l)) # Returns a geometry string from a tuple of coords that represent # (in order) the width, height, xPos, yPos of a window. def get_window_geometry_string(window_geometry): return "%dx%d+%d+%d" % (window_geometry[0], window_geometry[1], window_geometry[2], window_geometry[3])
a9b2516a3a8ca078519f0668c047cf049872df61
Aasthaengg/IBMdataset
/Python_codes/p03729/s699671169.py
152
3.546875
4
def main(): num = list(map(str,input().split())) if num[0][-1]==num[1][0] and num[1][-1]==num[2][0]: print('YES') else: print('NO') main()
217246b94c23f4047492aad374940d8f15cae075
garyyli/Unit5
/listDemo.py
272
4.21875
4
#Gary Li #11/14/17 #listDemo.py - print out the first and last word in a list words = input('Enter a list of words: ').split(' ') #print out the list one item per line for w in words: print(w) print('The first word is', words[0]) print('The last word is', words[-1])
3ab41de7d71e19023eba97a7dc0f0a7d9a2865b3
dolsbrandon/python
/rand_num_game.py
1,375
4.15625
4
#Random Number Guess Game by Brandon Dols # import random functions from random import seed from random import choice from random import shuffle #main function def main (): # seed random number generator seed(1) # prepare a sequence sequence = [i + 1 for i in range(20)] play = True; while play: shuffle(sequence) # make choices from the sequence for _ in range(1): selection = choice(sequence) print('Guess a number from 1 to 20') guess = 0 while int(guess) != selection: guess = input('Guess: ') # test for proper input while guess.isnumeric() == False: print('Guess a number from 1 to 20') guess = input('Guess: ') # guess is too high if int(guess) > selection: print('Too High') # guess is too low elif int(guess) < selection: print('Too Low') # guess is correct else: print('You guessed correctly!\n') # play again menu while True: play_again = input('Would you like to play again? (y/n)') if play_again.upper() == 'N': return elif play_again.upper() == 'Y': break main()
cc8581490008208f3351b31b8126f032d9ec03d4
SaintClever/Python-and-Flask-Bootcamp-Create-Websites-using-Flask-
/_Python Crash Course/46. Functions in Python Part Two.py
1,496
3.859375
4
# max and min print(max(2,3)) print(max([1,4,7,12,100])) print(min([47,45,2,9,19])) print('') #space # enumerate mylist = ['a','b','c'] index = 0 # WITHOUT Enumerate for letter in mylist: print(letter) print('Is at index: {}'.format(index)) index = index + 1 # index += index # because this is set to 0 its always zero print('') print('') #space #WITH enumerate for item in enumerate(mylist): print(item) print('') #space for index,item in enumerate(mylist): print(item) print(f'Is at index {index}') print('') # .join mylist = ['a','b','c','d'] print(''.join(mylist)) print('--'.join(mylist)) print('-x-'.join(mylist)) # PROBLEM 1 # Write a function that returns a boolean # (True/False) indicating if the word 'secret' # is in a string. # My answer def user_string(user_input): if 'secret' in user_input: # print(True) return True else: # print(False) return False result = user_string('ecret') print(result) print('') # Jose's answer def secret_check(mystring): if 'secret' in mystring: return True else: return False print(secret_check('simple')) # check the return print(secret_check('this is a secret')) print('') # Refactored answer def secret_check_refactored(mystring): return 'secret' in mystring.lower() print(secret_check_refactored('simple')) # check return print(secret_check_refactored('this is a secret')) print(secret_check_refactored('SECRET')) print('')
d38efbe28fd3a5dc97a33567a76c5ce53ff932ae
Utkarsh731/HackerRank-Sorting
/closestNumber
835
3.53125
4
#!/bin/python3 import math import os import random import re import sys # Complete the closestNumbers function below. def closestNumbers(arr): arr.sort() min=arr[1]-arr[0] output=[] for i in range(0,len(arr)-1): if abs(arr[i]-arr[i+1])==min: min=abs(arr[i]-arr[i+1]) output.append(arr[i]) output.append(arr[i+1]) elif abs(arr[i]-arr[i+1])<min: output=[] min=abs(arr[i]-arr[i+1]) output.append(arr[i]) output.append(arr[i+1]) return output if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = list(map(int, input().rstrip().split())) result = closestNumbers(arr) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
3374b004b004b419aef2c38833810339d4b047c7
tails1434/Atcoder
/ABC/103/B.py
233
3.765625
4
def rotate(word , n): return word[n:len(word)] + word[:n] def main(): S = input() T = input() for i in range(len(S)): if rotate(S,i) == T: print('Yes') exit() print('No') main()
50364c8bf8283ef96d89b31cefc89b5c47cc763d
Mahip-Jain/Calculator
/Calculator.py
6,928
4.09375
4
import sys only_numbers = "Sorry, you are only allowed to enter numbers" maxquestions = 10 correct_ans = "You gave the correct answer" incorrect_ans = "You gave the incorrect answer" correct_ans_is = "\nThe Correct answer is" enter_age = "Enter your age:" enter_name = "Enter you name:" welcome = "\nWelcome to MATH PROBLEM GENERATOR," if_level_easy = "If you want to do level EASY than enter 1" if_level_medium = "If you want to do level MEDIUM than enter 2" if_level_hard = "If you want to do level HARD than enter 3" ans = "Answer:" which_level = "\nWhich level do you want:" only_num_123 = "Sorry, you are only aloud to enter the number 1,2 or 3" start_test = "\nI will start your test now" not_num = "Not a number! Try again." raw_inp_quotient = "Quotient:" raw_inp_remainder = "Remainder:" multiply = "x" divide = "/" add = "+" minus = "-" seperator2 = "*" * 100 correct_quotient = "\nThe Correct quotient is " correct_remainder = "\nThe Correct remainder is " final_score = "Your score is " seperator3 = "=" * 100 right_comment = ["Exellent", "Amazing", "Brilliant", "Wow", "Unbelievable", "Good job", "Awesome", "Wonderful", "Marvellous","Incredible", "Mind-blowing"] wrong_comment = ["Better luck next time", "Well tried", "You can do better than this", "A little practice is all you need"] def printcenter(abc): #this function prints things in the center using center command print abc.center(150) def banner(): #this function prints the title and description of the project design_for_game_name = "########################" game_name = "#MATH PROBLEM GENERATOR#" design_for_my_name = "***********************" my_name = "*Created by Mahip Jain*" seperator_for_game_name = "-" *100 description = "This is an educational game made for kids to improve their mathematical skills. There are 3 levels, Easy, Medium and Hard. There is a set of ten questions for\neach level. I hope you enjoy using this game.\n" printcenter(design_for_game_name) printcenter(game_name) printcenter(design_for_game_name) printcenter(seperator_for_game_name) printcenter(design_for_my_name) printcenter(my_name) printcenter(design_for_my_name) print description def get_age(): #this function takes the age of the user and validates for alphabets age = raw_input(enter_age) while age.isdigit() == False: print only_numbers age = raw_input(enter_age) return int(age) def get_name(): #this function takes the name of the user name = raw_input(enter_name) return name def info_for_level(name): #this function prints which numbers are which level and validates for numbers which are not 1,2 or 3 and for alphabets print welcome + " " + name + " " + "!!\n" print if_level_easy print if_level_medium print if_level_hard while 1: level = raw_input(which_level) if level.isdigit(): if int(level) != 1 and int(level) != 2 and int(level) != 3: print only_num_123 else: break else: print only_numbers print start_test return int(level) def run_problem_generator(age, level): #this function prints the question, takes the answer and corrects it if wrong. It also validates the answer for thing which are not numbers import random def get_userinput(message): #validation for answer while True: try: userInput = int(raw_input(message)) except KeyboardInterrupt: sys.exit() except (ValueError, NameError) as e: print(not_num) continue else: return userInput break a = 1 random1 = 0 random2 = "" random3 = 0 random4 = [] random5 = [] score = 0 lst2 = [add] minimum = 1 if age <= 7: maximum = 9 elif age == 8 or age == 9: maximum = 99 else: maximum = 999 def level1(): lst2.append(minus) def level2(): lst2.append(minus) lst2.append(multiply) def level3(): lst2.append(minus) lst2.append(multiply) lst2.append(divide) if level == 1: level1() elif level == 2: level2() else: level3() print seperator2 while a < maxquestions + 1: random1 = random.randint(minimum,maximum) random2 = random.choice(lst2) random3 = random.randint(minimum, maximum) random4 = random.choice(right_comment) random5 = random.choice(wrong_comment) print random1, random2, random3, "\n" answer = 0 if random2 == add or random2 == minus or random2 == multiply: answer = get_userinput(ans) #correction if random2 == add: if answer == random1 + random3: print correct_ans print random4 score += 1 else: print incorrect_ans print correct_ans_is, random1 + random3 print random5 elif random2 == minus: if answer == random1 - random3: print correct_ans print random4 score += 1 else: print incorrect_ans print correct_ans_is, random1 - random3 print random5 elif random2 == multiply: if answer == random1 * random3: print correct_ans print random4 score += 1 else: print incorrect_ans print correct_ans_is, random1 * random3 print random5 else: quotient = get_userinput(raw_inp_quotient) remainder = get_userinput(raw_inp_remainder) if quotient == random1 / random3 and remainder == random1 - quotient * random3: print correct_ans print random4 score += 1 else: print incorrect_ans print correct_quotient, random1 / random3, correct_remainder, random1 - quotient * random3 print random5 print "score =", score, divide, a, "\n" a += 1 print final_score, score, divide, maxquestions, "\n" def continue_or_not(name, age): #this function checks weather you want to continue the game or not while True: level = info_for_level(name) run_problem_generator(age, level) print "Do you want to continue?" if_want_to_quit = raw_input("Type yes or no:") if if_want_to_quit == "no" or if_want_to_quit == "No": break print seperator3 def main(): #this function calls all of the other functions banner() age = get_age() name = get_name() continue_or_not(name, age) main()
5767dcc4a73fd4449ce01992b1453754fa3a1805
Athie9104/python-exersises
/matplot_exer.py
872
3.984375
4
# Example 1 import matplotlib.pyplot as plt import numpy as np x= np.array(["A", "B", "C", "D"]) y= np.array([3, 8, 1, 10]) plt.bar(x, y) plt.show() # Exercise 1 import matplotlib.pyplot as plt cities=['East London', 'Cape Town', 'Kimberley', 'Durban'] rainfall= [140, 200, 120, 157] x_pos = [i for i, _ in enumerate(cities)] #labels on the x-axis #labeling and visuals plt.bar(x_pos, rainfall, color='cyan') plt.xlabel("cities") plt.ylabel("Rainfall in (mm)") plt.title("Rainfall for the 4 main cities in SA") plt.xticks(x_pos, cities) plt.show() # Exercise 2 import matplotlib.pyplot as plt import numpy as np Testmarks =([98,78, 68, 73, 72, 97, 88, 60, 94, 95, 80, 73, 82, 80, 99, 91, 74, 88, 70, 94, 86, 81, 100, 99, 84, 93, 94, 79]) plt.title('Test marks box plot') plt.boxplot((Testmarks)) plt.show()
1990b0540637244e17e13b704adf865abd5b0062
GianlucaPal/Python_bible
/cinema.py
741
4
4
films = { 'Finding Dory':[3,5], 'Bourne':[18,5], 'Tarzan':[15,5], 'Ghost Busters':[12,5] } while True: choice = input('What film would you like to watch?:').strip().title() if choice in films: age = int(input('How old are you?:').strip()) #check users age if age >=films[choice][1]: #check enough seats numSeats = films[choice][1] if numSeats > 0: print('Enjoy your film') films[choice][1] = films[choice][1]-1 else: print('sorry, we are sold out') else: print('You aree underaged, sorry') else: print('we do not have that film')
6eb8e01d2a9614b54a7ba03853221d1f218465e8
matheus073/projetos-python
/CorridaDeBits/1013.py
201
3.578125
4
x = input() x = x.split() a,b,c,maior=int(x[0]),int(x[1]),int(x[2]),0 if a>=b and a>=c: maior = a elif b>=a and b>=c: maior = b else: maior = c print("%i eh o maior"%maior)
48a40b873d83ea325768e3ec700a3e3b83f204c7
aritrasen12345/J.A.R.V.I.S
/jarvis.py
6,280
3.53125
4
# Jarvis Project # pip install pyqt5 # pip install speechrecognition # pip install pyttsx3 # pip install pyaudio # pip install wikipedia import speech_recognition as sr import datetime import wikipedia import pyttsx3 import webbrowser import random import os import requests # Text to Speech # Make a speaker who speaks your attachs engine = pyttsx3.init() voices = engine.getProperty('voices') # print(voices) engine.setProperty('voice', voices[0].id) # Selecting 1nd Voice def speak(audio): # Here Audio is var which contain text engine.say(audio) engine.runAndWait() # Wait def wish(): hour = int(datetime.datetime.now().hour) if hour >= 0 and hour < 12: speak("Good morning sir i am Virtual Assistant Jarvis") elif hour >= 12 and hour < 18: speak("Good afternoon sir i am Virtual Assistant Jarvis") else: speak("Good night sir i am Virtual Assistant Jarvis") # Now convert audio to text def takecom(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening......") audio = r.listen(source) try: print("Recognising.") text = r.recognize_google(audio, language='en-in') # Use Google Api print(text) except Exception: # Error handling speak("Error....") print("Network connection error") return "none" return text def temperature(city): api_add = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid=' # Here add appid print(api_add); json_data = requests.get(api_add).json() temp = json_data["main"]["temp"] cond = json_data["weather"][0]["description"] name = json_data["name"] speak(f"temperature of {name} is {temp} degree celcius and the condition is {cond}") print(f"temperature of {name} is {temp} degree celcius and the condition is {cond}") # For Main Function if __name__ == "__main__": wish() # Jarvis Wishes u at the start while True: query = takecom().lower() if "wikipedia" in query: speak("Searching details......Wait") query.replace("wikipedia", "") results = wikipedia.summery(query, sentences=2) print(results) speak(results) elif "temperature of" in query: speak("please wait") idx = query.index("f") + 2 city = query[idx:] temperature(city) elif 'open youtube' in query or "open video online" in query: webbrowser.open("https://www.youtube.com") speak("opening youtube") elif 'open google' in query: webbrowser.open("https://www.google.com") speak("opening google") elif 'open facebook' in query: webbrowser.open("https://www.facebook.com") speak("opening facebook") elif 'open gmail' in query: webbrowser.open("https://www.gmail.com") speak("opening gmail") elif 'open github' in query: webbrowser.open("https://www.github.com") speak('opening github') elif 'music from pc' in query or "music" in query: speak("ok i am playing music") music_dir = './music' musics = os.listdir(music_dir) os.startfile(os.path.join(music_dir, musics[0])) elif 'video from pc' in query or "video" in query: speak("ok i am playing videos") video_dir = "./video" videos = os.listdir(video_dir) os.startfile(os.path.join(video_dir, videos[0])) elif 'good bye' in query: speak("Good Bye") exit() elif "shutdown" in query: speak("shutting down") os.system('shutdown -s') # Shut Down Pc elif "whats up" in query or 'how are you' in query: stMsgs = ['Just doing my thing!', 'I am fine!', 'Nice!', 'I am nice and full of energy', 'i am okey ! How are you'] ans_q = random.choice(stMsgs) speak(ans_q) ans_take_from_user_how_are_you = takecom() if 'fine' in ans_take_from_user_how_are_you or 'happy' in ans_take_from_user_how_are_you or 'okey' in ans_take_from_user_how_are_you: speak('okey..') elif 'not' in ans_take_from_user_how_are_you or 'sad' in ans_take_from_user_how_are_you or 'upset' in ans_take_from_user_how_are_you: speak('oh sorry..') elif 'make you' in query or 'created you' in query or 'develop you' in query: ans_m = " For your information Aritra Sen Created me ! I give Lot of Thannks to Him " print(ans_m) speak(ans_m) elif "who are you" in query or "about you" in query or "your details" in query: about = "I am Jarvis an A I based computer program but i can help you lot like a your close friend ! i promise you ! Simple try me to give simple command ! like playing music or video from your directory i also play video and song from web or online ! i can also entain you i so think you Understand me ! ok Lets Start " print(about) speak(about) elif "hello" in query or "hello Jarvis" in query: hel = "Hello Aritra Sir ! How May i Help you.." print(hel) speak(hel) elif "your name" in query or "sweat name" in query: na_me = "Thanks for Asking my name my self ! Jarvis" print(na_me) speak(na_me) elif "you feeling" in query: print("feeling Very sweet after meeting with you") speak("feeling Very sweet after meeting with you") elif query == 'none': continue elif 'exit' in query or 'abort' in query or 'stop' in query or 'bye' in query or 'quit' in query: ex_exit = 'I feeling very sweet after meeting with you but you are going! i am very sad' speak(ex_exit) exit() else: temp = query.replace(' ', '+') g_url = "https://www.google.com/search?q=" res_g = 'sorry! i cant understand but i search from internet to give your answer ! okay' print(res_g) speak(res_g) webbrowser.open(g_url+temp)
a9f1eaba2ae7f9cabac1b50aeb3ddb1018879b97
biqosik/CodeWars---solution
/Scramblies.py
154
3.640625
4
from collections import Counter def scramble(s1, s2): letters = Counter(s1) word = Counter(s2) return all(word[i] <= letters[i] for i in word)
1358bac7b88a2b8b6e59daeeb257d55b691a872f
gbramley/PythonFileMover1Drill
/PythonFileMoverDrill2.py
602
3.59375
4
# Python version 2.7.13 # Author: Gavin Bramley # Python Drill File Mover # - Move the files from Folder A to Folder B. # - Print out each file path that got moved onto the shell. # - Upon viewing Folder A after the execution, the moved files should not be there. import shutil import os def shutil(): path="C:/Miniconda3/pythondatetime/FolderA/" moveto = "C:/Miniconda3/pythondatetime/FolderB/" files = os.listdir(path) files.sort() for f in files: if f.endswith(".txt"): src= path+f dst = moveto+f shutil.move(src,dst)
6484330eb4f4b5dd70ec9dcbc04de86ce3c47293
heejung-choi/python
/03_slicing.py
434
3.8125
4
# slicing sample_list = list(range(0,31)) print(sample_list) print(sample_list[1:3]) # [|1,2,3,4] # | 슬라이싱의 시작부분 (공간을 자른다.) print(sample_list[10:-1]) # 끝에만 제외해서 하고 싶다면 print(sample_list[0:len(sample_list) :3]) #print(sample_list[0:31:3]) 동일 print (sample_list[::3]) print(sample_list[::-1]) # 뒤에서 부터 역순으로 print(sample_list[1:1]) # 아무것도 안뜬다.
fb6232a85f6e2db186a7bbbd4929166d2efce939
eltrai/algsContests
/GoogleCodeJam/2018/Qual/B-TroubleSort/B.py
560
3.578125
4
#!/usr/bin/env python3 def readint(): return int(input()) def readints(): return map(int, input().split()) def readline(): return str(input()) T = readint() for case in range(T): l = readint() sequence = list(readints()) s1 = sorted(sequence[::2]) s2 = sorted(sequence[1::2]) result = "OK" for i in range(len(s2)): if s1[i] > s2[i]: result = i*2 break elif i+1 < len(s1) and s2[i] > s1[i+1]: result = i*2+1 break print("Case #%d: %s" % (case+1, result))
644a26089daca4a3ff361f2f237678452b4ea2d3
natalia1722/kpk2016
/gun.py
3,713
3.71875
4
from tkinter import * from random import choice, randint screen_width = 400 screen_height = 300 timer_delay = 100 class Ball: initial_number = 20 minimal_radius = 15 maximal_radius = 40 available_colors = ['green', 'blue', 'red'] def __init__(self): """ Cоздаёт шарик в случайном месте игрового холста canvas, при этом шарик не выходит за границы холста! """ R = randint(Ball.minimal_radius, Ball.maximal_radius) x = randint(0, screen_width-1-2*R) y = randint(0, screen_height-1-2*R) self._R = R self._x = x self._y = y fillcolor = choice(Ball.available_colors) self._avatar = canvas.create_oval(x, y, x+2*R, y+2*R, width=1, fill=fillcolor, outline=fillcolor) self._Vx = randint(-2, +2) self._Vy = randint(-2, +2) def fly(self): self._x += self._Vx self._y += self._Vy # отбивается от горизонтальных стенок if self._x < 0: self._x = 0 self._Vx = -self._Vx elif self._x + 2*self._R >= screen_width: self._x = screen_width - 2*self._R -1 self._Vx = -self._Vx # отбивается от вертикальных стенок if self._y < 0: self._y = 0 self._Vy = -self._Vy elif self._y + 2*self._R >= screen_height: self._y = screen_height - 2*self._R - 1 self._Vy = -self._Vy canvas.coords(self._avatar, self._x, self._y, self._x + 2*self._R, self._y + 2*self._R) class Gun: def __init__(self): self._x = 0 self._y = screen_height-1 self._lx = +30 self._ly = -30 self._avatar = canvas.create_line(self._x, self._y, self._x+self._lx, self._y+self._ly) def shoot(self): """ :return возвращает объект снаряда (класса Ball) """ shell = Ball() shell._x = self._x + self._lx shell._y = self._y + self._ly shell._Vx = self._lx/10 shell._Vy = self._ly/10 shell._R = 5 shell.fly() return shell def init_game(): """ Создаём необходимое для игры количество объектов-шариков, а также объект - пушку. """ global balls, gun, shells_on_fly balls = [Ball() for i in range(Ball.initial_number)] gun = Gun() shells_on_fly = [] def init_main_window(): global root, canvas, scores_text, scores_value root = Tk() root.title("Пушка") scores_value = IntVar() canvas = Canvas(root, width=screen_width, height=screen_height, bg="white") scores_text = Entry(root, textvariable=scores_value) canvas.grid(row=1, column=0, columnspan=3) scores_text.grid(row=0, column=2) canvas.bind('<Button-1>', click_event_handler) def timer_event(): # все периодические рассчёты, которые я хочу, делаю здесь for ball in balls: ball.fly() for shell in shells_on_fly: shell.fly() canvas.after(timer_delay, timer_event) def click_event_handler(event): global shells_on_fly shell = gun.shoot() shells_on_fly.append(shell) if __name__ == "__main__": init_main_window() init_game() timer_event() root.mainloop()
845576bf6602e7eadc1043aa70943988b678926e
Idreesqbal/PythonTutorial
/11AdvancedFileObjects.py
1,036
4.3125
4
with open('test.txt', 'r') as f: # it is always a good practice to open files like this f = open('test.txt', 'r') # this also a way to work with files but the problem is f.mode f.close() # if u forget to put this at the end of file operation, the file may go to error # to make sure our file handeling is in the safe hands, it is always recommended to do it with 'with' with open('text.txt', 'r') as f: f_contents = f.readlines() # reads the line of the file all f_contents = f.readline() # will read only the first line of the text f_contents = f.read() # this will read the entire text all at once # read() take arguments, e.g. read(100) will paste the first 100 character of the text f.seek(0) # it basically put the cursor back to position 0 everything we loop the text print(f_contents) import os os.chdir('Location of the file') for f in os.listdir(): file_name, file_ext = os.path.splitext(f) f_title, f_course, f_num = file_name.split('-') print('{}-{}-{}{}'.format((file_name, f_title)))
651765b84de3a64d185db80a9eb15a0d86e7e8a2
WangYoudian/Algorithms
/LeetCode/Day8/HashTable.py
1,792
4.0625
4
# 构造哈希表的单个节点 class Node: def __init__(self, key, value): # self.hnext在Python中直接是列表的index体现 # self.hnext = None self.data = (key, value) # 构造哈希Map类,以及创建、插入、删除、查找方法 class ChainedHashMap: def __init__(self, size): self.size = size self.table = [[] for i in range(size)] def hash_func(self, key): return key%self.size def printMap(self): # 不是按照操作的顺序,而是按照节点在哈希Map中的存储顺序 for i in range(self.size): for nodes in self.table[i]: print(nodes.data) def insert(self, key, value): new_node = Node(key, value) hash_key = self.hash_func(key) self.table[hash_key].append(new_node) def delete(self, key): hash_key = self.hash_func(key) for node in self.table[hash_key]: if node is None: print('Key:', key, ' is not in the table!') return if node.data[0]==key: self.table[hash_key].remove(node) print('Delete successfully!') def search(self, key): # return the value of key as a list # if key has multiple values, then return all hash_key = self.hash_func(key) for node in self.table[hash_key]: # 没有节点 # 有节点但是却没有该key # 查找到 if node is None: print('Key:', key, ' is not in the table!') return if node.data[0]==key: print('Key has been found!', f'The value for {key} is:', node.data[1]) return print('Key:', key, ' is not in the table!') if __name__ == '__main__': # driver code hashtable = ChainedHashMap(10) hashtable.insert(10, 'India') hashtable.insert(20, 'Nepal') hashtable.insert(25, 'America') hashtable.printMap() hashtable.delete(20) hashtable.search(10)
a3893337645cbb64ae22af994b7d4c1d893560c8
valerpenko/Misha
/lists/checklist.py
731
3.734375
4
# арифм или геом? l=[2,3,4,5,6] if len(l)<3: print("список недостаточной длины") exit() if l[1]-l[0]== l[2] - l[1]: # проверка арифм прогрессии d=l[1]-l[0] i=2 while i+1<len(l): if l[i+1] - l[i]!=d: print("плохой список") exit() i+=1 print("арифм прогрессия") elif l[1]/l[0] == l[2]/l[1]: # проверка геом прогрессии d=l[1]/l[0] i=2 while i+1<len(l): if l[i+1] / l[i]!=d: print("плохой список") exit() i+=1 print("геом прогрессия") else: print("плохой список")
1f177ee7de336a51efe40fb6f174bb307fd2a125
dfbacon/holbertonschool-higher_level_programming
/0x06-python-test_driven_development/2-matrix_divided.py
1,049
3.875
4
#!/usr/bin/python3 ''' This is the "matrix_divided" module. The matrix_divided module supplies one function, matrix_divided(matrix, div). ''' def matrix_divided(matrix, div): '''Return matrix with each value divided by @div matrix: matrix being evaluated div: divisor ''' type_err = "matrix must be a matrix (list of lists) of integers/floats" if matrix is []: raise TypeError(type_err) for i in matrix: if i is []: raise TypeError(type_err) if len(i) != len(matrix[0]): raise TypeError("Each row of the matrix must have the same size") for j in i: if isinstance(j, (int, float)) is False: raise TypeError(type_err) if isinstance(div, (int, float)) is False: raise TypeError("div must be a number") if div is 0: raise ZeroDivisionError("division by zero") new = [] temp = [] for i in matrix: for j in i: temp.append(round(j / div, 2)) new.append(temp) return(new)
b138c7d646585c1ffa2c272c948861c27ed5dd9a
ruanpablom/PAP
/python/a8.py
1,148
3.578125
4
#!/usr/bin/env python str = input('Digite o texto: ') str2 = str.upper() vogais = "AEIOU" consoantes = "BCDFGHJKLMNPQRSTVWXYZ" pontos = ".;?:.!" n_vogais = 0.0 n_consoantes = 0.0 n_espacos = 0.0 n_pontos = 0.0 n_outros = 0.0 n_pa = 0.0 n_npa= 0.0 for i in range(0,len(str2)): if str2[i] in vogais: n_vogais+=1; elif str2[i] in consoantes: n_consoantes+=1; elif str2[i] in pontos: n_pontos+=1; elif str2[i] == ' ': n_espacos+=1; else: n_outros+=1; str1 = str2.replace(" ","") for i in range(2,len(str1)): for j in range(0,len(str1)-i+1): s = str1[j:(j+i)] if(s == s[::-1]): n_pa+=1; else: n_npa+=1; fator = 100/len(str2) print("Palavra: %s" %str) print("Caracters: %i" %len(str2)) print("%d vogais: %.2f%%" %(n_vogais,n_vogais*fator)) print("%d consoantes: %.2f%%" %(n_consoantes,fator*n_consoantes)) print("%d pontos: %.2f%%" %(n_pontos, fator*n_pontos)) print("%d espacos: %.2f%%" %(n_espacos,fator*n_espacos)) print("%d outros: %.2f%%" %(n_outros,fator*n_outros)) print("%d palindromos" %n_pa) print("%d nao palindromos" %n_npa)
cb439d9b8f7d02218a130e3c9179ab81b6876edb
RichardFlynn/KattisProblems
/icpcawards.py
137
3.859375
4
input() unis=[] while len(unis)<12: uni,team=input().split() if uni not in unis: unis.append(uni) print(uni,team)
8aa84d0aa56f0af66365d206b349f1fc5703924a
samuellsaraiva/1-Semestre
/l04e06mediaParesImpares.py
2,279
4.25
4
'''' 5. Construa o programa que calcule a média aritmética dos números pares. O usuário fornecerá os valores de entrada que pode ser um número qualquer par ou ímpar. A condição de saída será o número -1. 6. Complemente o programa anterior, acrescente o cálculo da média aritmética dos números ímpares. Teste 1: numero: 1, 2 e -1. Resposta: Média pares: 2 Média ímpares: 1 Teste 2: numero: 1, 5 e 1-. Resposta: Não tem número par Média ímpares: 3 Teste 3: numero: 2, 4 e -1. Resposta: Média pares: 3 Não tem número ímpar Teste 4: numero: -1 Resposta: Não tem número par Não tem número ímpar ''' soma_par = 0 # Declaração das variáveis soma_impar = 0 ct_par = 0 ct_impar = 0 print ('Digite ( -1 ) para sair') while(True): # while(numero != -1): # Laço de repetição while com o uso do break numero = int(input("Digite um número: ")) if(numero == -1): break # Interrompe a repetição while if(numero%2==0): # Se o resto da divisão de numero por 2 for 0 soma_par = soma_par + numero ct_par = ct_par + 1 else: soma_impar = soma_impar + numero ct_impar = ct_impar + 1 # Fim da estrutura de repetição (while) if (ct_par != 0): #imprime se algum par for digitado media_par = soma_par/ct_par print("Média dos pares: %.2f" %(media_par)) else: print ("Não tem números pares") if(ct_impar != 0): # imprime se algum impar for digitado media_impar = soma_impar/ct_impar print("Média dos ímpares: %.2f" %(media_impar)) else: print ("Não tem números ímpares") ''' ALTERAÇÕES: a. Mostre também a quantidade de números pares. b. Mostre também a quantidade de números ímpares. c. Mostre também a quantidade de números digitados. d. Calcule e mostre a porcentagem dos números pares. '''
7b66bac41ab8a98964873c7fa42ec73354461576
goodmanj/ArduinoPythonSerialGUI
/serialslider.py
856
3.625
4
# Blink an Arduino's built-in LED for an amount of time determined by a GUI # slider. # Works in cooperation with serialslider.ino on the Arduino side. # Serial comms library import serial # GUI library import tkinter as tk # Create a serial object. Change 'COM7' to match your computer's serial # port, or use serial.tools.list_ports.comports() to get a list of options. ser = serial.Serial('COM7',9600,timeout=1) # Create a window and a slider ('scale'), and show it on screen. window = tk.Tk() scale = tk.Scale(orient='horizontal') scale.pack() # This function is called when the 'Blink' button is pressed. def handleblink(): ser.write(bytes([scale.get()])) # Create and display the Blink button blinkbutton = tk.Button(text='Blink',command=handleblink) blinkbutton.pack() # Start watching the window waiting for button presses. window.mainloop()