blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
80ae141c16fcf2189dc0f08db30e6c8f67b0d958
arianacabral/Introduction-to-Python
/Atividade 6/Q4.py
255
3.8125
4
# Escreva um programa que leia o valor de 4 produtos e informe o total da compra soma = 0 for x in range(1,5): valor = float(input("Informe o valor do produto {}:".format(x))) soma = soma + valor print("O valor da soma é {:.2f}".format(soma))
9a4e416deb54684638d4f911f93aad70dec58724
arianacabral/Introduction-to-Python
/Atividade 1/Q2.py
273
4
4
# Escreva um programa que leia o valor de dois produtos. Imprima a soma dos valores na tela Produto_1 = float(input("Informe o valor do primeiro produto:")) Produto_2 = float(input("Informe o valor do segundo produto:")) print("A soma dos valores é:",Produto_1+Produto_2)
1ece557d863785a37540b26cf2aa648e824dce9a
arianacabral/Introduction-to-Python
/Atividade 3/Q1.py
390
4
4
# Faça uma função que receba a base e altura de um retângulo e retorne a área do mesmo. def area_retangulo(altura,base): area = altura*base return area rect = [float(input("Altura do retângulo:")),float(input("Base do retângulo:"))] area_rect = area_retangulo(rect[0],rect[1]) print("A área do retângulo de a...
078e86484585b8ecac95ca781ab8d83744c841b3
arianacabral/Introduction-to-Python
/Atividade 2/Q5.py
305
3.625
4
Notas = [float(input("Nota 1:")),float(input("Nota 2:")),float(input("Nota 3:")),float(input("Nota 4:"))] media_notas = sum(Notas)/4 if media_notas >= 7: print("A média das notas é",media_notas) print("Aprovado!") else: print("A média das notas é",media_notas) print("Reprovado!")
5fa16174370a41598f0371bc3e2c0960adc12c9b
arianacabral/Introduction-to-Python
/Atividade 2/Q2.py
290
3.65625
4
d = [int(input("Ano de Nascimento:")),int(input("Ano Atual:"))] idade = d[1]-d[0] if idade >= 60: print("Você tem",idade,"anos e já pode dar entrada na APOSENTADORIA!") else: print("Você tem", idade, "anos e NÃO possui a idade mínima para dar entrada na APOSENTADORIA!")
97bc56785b9f1c55e068c285e3862f3c4faedd1b
PetrSpacek/angrylikegame-python-pyqt5
/model/shooting_mode.py
1,683
3.796875
4
from abc import abstractmethod from config import BASE_MISSILE_DAMAGE class ShootingMode: def __init__(self, damage: float): self.damage = damage def get_damage(self): return self.damage @abstractmethod def update_base_damage(self, damage): pass @abstractmethod def...
b854614deb4dfa4b749c14eb899caafbaef40db3
rohanverma2711/python_lab
/python9.py
122
3.78125
4
a = (1,3,2,3,4,5,6,6,6) b = [] for i in a: if a.count(i) > 1 and i not in a: print(i) b.append(i)
6ea3b259591bb4b04ac42259b9ab1567f6533f17
anyapoliakova/PythonLabs
/3.py
482
3.984375
4
let1_to_let2 ={ 'a':'0', 'e':'1', 'i':'2', 'o':'2', 'u':'3' } def encrypt(phrase): res = '' for letter in phrase[::-1]: if letter in let1_to_let2: res += let1_to_let2[letter] else: res += letter return res +'aca' print('encrypt("banana") ->', encryp...
87681e1b1471f167a65fb0ca2792911d5a2020d9
clojia/tic-tac-toe
/game.py
4,938
3.96875
4
import copy class Game(object): """ Game basic elements: generating board, recordig checker movements and successors, deciding winner, generating features and history as raw data. """ def __init__(self): self.board = self.generateBoard() self.history = [copy.deepcop...
2ba3a475cdc63076b68e280da8322b48032bef77
harrifeng/Python-Study
/Interviews/Min_Stack.py
888
3.796875
4
""" #####From NC Class 7 Data Structures, slides 8 [Solution](http://www.geeksforgeeks.org/design-and-implement-special-stack-data-structure/) """ class MinStack(): def __init__(self, size): self.data_stack = [] self.min_stack = [] self.size = size def is_full(self): return len...
6c20c085ffe901d04fd126289c71680e3923e7a4
harrifeng/Python-Study
/Leetcode/Swap_Nodes_in_Pairs.py
1,417
3.984375
4
""" Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. """ # Definition for singly-linked list. # c...
cc33cdcb0aff9efb393e7b318c1105e10f685088
harrifeng/Python-Study
/Leetcode/Minimum_Window_Substring.py
1,709
3.921875
4
""" Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". Note: If there is no such window in S that covers all characters in T, return the emtpy string "". If there are multipl...
4e488befdaa7a40934e982c2f4c68b8722c757c9
harrifeng/Python-Study
/Leetcode/Binary_Tree_Zigzag_Level_Order_Traversal.py
1,584
4.09375
4
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], ...
b63efc355b0dcd7783af4a371d66beb2f08aa3c7
harrifeng/Python-Study
/Leetcode/3Sum.py
1,402
3.59375
4
""" Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. For example, giv...
67fbdedf93de35dd4f98b0a1dca7bdb87263004f
harrifeng/Python-Study
/Leetcode/Convert_Sorted_Array_to_Binary_Search_Tree.py
810
3.875
4
""" Given an array where elements are sorted in ascending order, convert it to a height balanced BST. """ # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param num, a list of intege...
fdfef0ee83ca41127963a66d49ed1993f8fa312f
harrifeng/Python-Study
/Leetcode/Reverse_Words_in_a_String.py
1,125
4
4
""" Given an input string, reverse the string word by word. For example, Given s = 'the sky is blue', return 'blue is sky the'. Clarification: What constitutes a word? A sequence of non-space characters constitutes a word. Could the input string contain leading or trailing spaces? Yes. However, your reversed string s...
5ea5d5916fa7922ff6c3d00f84bb0614942fa3b9
harrifeng/Python-Study
/Interviews/Longest_Common_Subsequence.py
3,016
3.71875
4
""" Need to distinguish from Longest Common Substring Examples: LCS for input Sequences "ABCDGH" and "AEDFHR" is "ADH" of length 3. LCS for input Sequences "AGGTAB" and "GXTXAYB" is "GTAB" of length 4. [Solution](http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/) DP way is O(m*n) Nor...
272c7f4dee0fb8177ec2b07cf075b9bece34b239
harrifeng/Python-Study
/Leetcode/Count_and_Say.py
847
4.03125
4
""" The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represent...
070f2e1bd1234a1bf4a81109d6169f861cb55db6
harrifeng/Python-Study
/Interviews/Shortest_Path.py
2,259
3.734375
4
""" #####With Twitter & Cyan 2D array of characters ``` 1 1 1 1 1 S 1 X 1 1 1 1 1 1 1 X 1 1 E 1 1 1 1 1 X ``` S is the starting point E is the ending point X means you cannot traverse to that point 1. Find if there is a path from S to E 2. Find the length of shortest path from S to E given the above matrix 3. Find t...
bb19afb7378a67c10683b86b693a23f0e508885e
harrifeng/Python-Study
/Interviews/Flattening_a_Linked_List.py
1,343
4.3125
4
""" Given a linked list where every node represents a linked list and contains two pointers of its type: (i) Pointer to next node in the main list (we call it ‘right’ pointer in below code) (ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer in below code). All linked lists are sorted. See ...
87ec61b10fa731eb272a5707925420027d6dd48a
harrifeng/Python-Study
/WhiteBook/node.py
5,082
3.9375
4
#!/usr/bin/env python # This is the structure of Node # Note: there's no need to delare it before the __init__ class Node: def __init__(self, data): self.data = data self.next = None def create_linked_list(current, data_list): if isinstance(current, int): current = Node(current) fo...
37a9e4475c1d77854b51666509745f8569618238
harrifeng/Python-Study
/Leetcode/Binary_Tree_Level_Order_Traversal_II.py
1,251
4.125
4
""" Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] ""...
5ed15577156679e7b1662c4355ec55076136fb38
harrifeng/Python-Study
/Leetcode/Permutation_Sequence.py
866
3.84375
4
""" The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. """ cl...
cb88de59be33b52cdb5e525b517407f43930bccb
harrifeng/Python-Study
/Leetcode/Word_Break_II.py
2,254
3.875
4
""" Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. For example, given s = "catsanddog", dict = ["cat", "cats", "and", "sand", "dog"]. A solution is ["cats and dog", "cat sand dog"]. """ class So...
86424141595892ec8bec181b0f6113bfe3040e4f
harrifeng/Python-Study
/Leetcode/Remove_Duplicates_from_Sorted_List_II.py
1,011
3.734375
4
""" Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 2->3. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # ...
6edaf33994024ed20d5b506f5c2fe513c603f6c0
harrifeng/Python-Study
/Leetcode/Palindrome_Partitioning_II.py
1,897
3.625
4
""" Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab", Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. """ import sys class Solution: # @para...
86e4328f9fa2b29b6307b7c4a168c77eaf99ffcc
harrifeng/Python-Study
/Leetcode/First_Missing_Positive.py
965
3.765625
4
""" Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. """ class Solution: # @param A, a list of integers # @return an integer def firstMissingPositive(self...
dc273d1e478864d2e39898c8cb58b9e93c7e2213
harrifeng/Python-Study
/Leetcode/Single_Number_II.py
1,719
3.6875
4
""" Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ class Solution: # @param A, a list of integer # @return an integer def singleNumber(s...
fdd6014cc6416b74b34c483b46213ed1238a7d4d
SouravGowda/Python
/student_managment.py
1,065
4.09375
4
def calculate_highest_in_maths(student_list): highest = 0 highest_name = '' for student in student_list: if(student.get("Maths")> highest): highest = student.get("Maths") highest_name = student.get("name") print(f"highest marks in maths is {highest} by {highest_name}") ...
00b16517a818999ddfd68bbedab9a37939362a9e
computingForSocialScience/cfss-homework-lkofler
/Assignment5/barChart.py
2,909
3.546875
4
import unicodecsv as csv import matplotlib.pyplot as plt def getBarChartData(): f_artists = open('artists.csv') #opens artists.csv file f_albums = open('albums.csv') #opens albums.csv file artists_rows = csv.reader(f_artists) #looks at rows from artists.csv and makes a new variable representing those row...
53e88191bbbf288eb75edec4e2eed090baf0a1e4
Daustoe/Euler
/problem_13.py
377
3.734375
4
""" Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. (numbers in problem_13_input.txt file) """ __author__ = 'cjpowell' def main(): number_file = open('problem_13_input.txt', 'r') numbers = [] for line in number_file: numbers.append(int(line)) print str(...
152e409ab1fc09f2dc916058814848b29b82a957
Daustoe/Euler
/problem_2.py
750
4
4
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """...
61113bf96e3af6f3780d4e134dddae6e4d41590c
sallav/Tree
/Tree/Tree.py
1,570
3.734375
4
import Tree_node as Tnode import Tree_func as Func class Tree: def __init__(self, root=Tnode.Tree_node()): self.root = root self.height = 0 def getRoot(self): return self.root def getHeight(self): self.setHeight() return self.height def setHeight(self): ...
1bd929ccef8adbaaf67c3d12e0cdca0d19d7d63d
corus87/logstream
/app/helpers.py
1,615
3.59375
4
def seek1(fileobj, nline, buffersize=1024): """ takes fileobject and an integer, nline to return a pointer to the file where nlineth line exist from last """ fileobj.seek(0, 2) # seeking to end total_bytes = bytes = fileobj.tell() size = nline + 1 # will include the first line wholly block = -1...
d346ef2fe9adc5f7e82219b94daac7cb4519b33d
deepcloudlabs/dcl162-2020-sep-09
/module02-functional.programming.in.python/exercise02.py
293
3.875
4
names = ["jack", "james", "ben", "Sun", "kate", "jin"] print(names) order_by_string_length = lambda name: len(name) names.sort(key=order_by_string_length, reverse=True) print(names) order_by_lower_case = lambda name: name.lower() names.sort(key=order_by_lower_case, reverse=True) print(names)
103fe923a2b46bbe62099225dfbf8412c2518b6e
deepcloudlabs/dcl162-2020-sep-09
/module06-thread.programming.in.python/study-multiprocessing.py
265
3.5625
4
from multiprocessing import Pool def times2(x): return x * 2 def parallel_map(xs, chunk=50000): with Pool(8) as P: x = P.map(times2, xs, chunk) return x if __name__ == '__main__': N = 1000000 data = range(N) parallel_map(data)
0ad9e91656efc1d608bf3170411d6de971a54b05
sa5ra2000/project-ir
/project/Test.py
2,275
3.578125
4
import random path_dic={'D1':"D1.txt",'D2':"D2.txt",'D3':"D3.txt"} #putting all words of the collection docs in one dictionary def GetChars (path) : chars_dic ={} for key in path : f = open(path[key], "r") x = f.read() x = x.replace(" ", "") for i in x : chars_dic[i...
a06706282546ecc80d0fc8eebfee131bcba9eef9
lexjox777/Python-Static-method
/main.py
455
3.578125
4
class Student: def __init__(self,scores = []): self.scores = scores def avg(self): return round(sum(self.scores)/ len(self.scores)) # static method is a decorator and does not have access to instance method @staticmethod def notice(): return "Exam next week!" kingsley= Student(scores=[3,5,7,8,7])...
88949a96473ba8ffc4d3f798506cc9336ffff2a9
geekychandraul/cs50-psets
/mario.py
441
4.3125
4
#To make mario pyramid of hash between length 0-23 while True: #Check for integer try: length = int(input('Enter a number between 0-23:')) except: print("Please enter a integer") #Check for length if length < 0 or length > 23: print('Please enter a number between 0 - 23') ...
692e34d63931cc99ee7cfb72d3978805fbf3d149
Ocho262/Python_Challenges_2
/tax_calculator.py
635
3.9375
4
subtotal = input("What is the order amount? ") print(subtotal) subtotal = float(subtotal) f_subtotal = '{:20,.2f}'.format(subtotal) f_subtotal = str(f_subtotal) print("subtotal: " + f_subtotal) state = raw_input("What is the state? ") if (state == "MD"): print("subtotal: " + f_subtotal) taxrate = float(0.06) ...
c1af2e8b1a9d7afb418226cb973913ce62c4e70d
Ocho262/Python_Challenges_2
/simple_math_2.py
499
3.90625
4
first_number = raw_input("What is the first number?") second_number = raw_input("What is the second number?") int_1 = int(first_number) int_2 = int(second_number) addition = int_1 + int_2 subtraction = int_1 - int_2 multiplication = int_1 * int_2 division = int_1 / int_2 simplemath = [] simplemath.append(addition) s...
a131643be8b6ab422b1ebe444da53b1c596fa10a
515hikaru-sandbox/setup-python-poetry-in-actions
/main.py
72
3.546875
4
def fizz(n): if n % 3 == 0: return 'fizz' return str(n)
368889df15a633976129de7a7b3f8887c305ddd2
mconsoni/codility
/FrogImp.py
277
3.53125
4
#!/usr/bin/env python2.7 def solution(X, Y, D): dist = Y - X jumps = dist // D if jumps * D >= dist: return jumps else: return jumps + 1 sol = solution(10, 85, 30) print(str(sol)) sol = solution(10, 100, 10) print(str(sol)) sol = solution(10, 25, 10) print(str(sol))
7905e73e5a020ab68b9455e1f3dc51c31377c2fe
Dioscur/Python
/prometheus/test_7_1.py
1,015
3.984375
4
import math class Sphere(object): def __init__ (self, r=1.0, x=0.0, y=0.0, z=0.0): self.radius = r self.center = (x,y,z) def get_volume(self): return 4.0*math.pi*(self.radius**3)/3 def get_square(self): return 4.0*math.pi*self.radius**2 def get_radius(self): r...
68d5ffd5e042b6ecf8f515de0d7d8660eb4e8eba
Dioscur/Python
/prometheus/test_7_4.py
1,185
3.6875
4
import sys import datetime import calendar def create_calendar_page(month = None,year = None): import datetime import calendar today = datetime.datetime.today() if month == None: month = today.month if year == None: year = today.year day = datetime.datetime (year, month, 1) weekday ...
c69e55bd302ddfc8a15573e86c478f1035b501f2
alexmendezsomoza/Real_Estate_Project
/src/manage_data.py
3,866
3.5625
4
import pandas as pd data = pd.read_csv("data/casas_limpio.csv") data.drop("Unnamed: 0", axis=1, inplace=True) #------------------------------------------------- #Yes/No #------------------------------------------------- def si_no(): ''' This function let you choose between yes or no ''' sn = ["No", "...
99962fe162ac4881b5f32385eeb5fb03e9c25891
TomekDominiak/podstawypythona
/Izogram.py
340
3.609375
4
def izogram(word): list_of_words = list(word) set_of_words = set(list_of_words) if len(list_of_words) == len(set_of_words): print(f'twoje slowo ({word}) jest izogramem') else: print(f'twoje slowo ({word}) nie jest izogramem') if __name__ == "__main__": izogram(input("prosze wpis...
adff1e6e0e1f8cc5e11b0f47795279a8570aff43
duk1edev/tceh
/tceh_homework3/tceh_hm3_examples/examples.py
2,559
3.6875
4
def this_functions_print_stars(): print('I will print stars!') print('**********') this_functions_print_stars() # Step 1 def my_function(input_var1, input_var2): print(input_var1, input_var2) return input_var1 + input_var2 first_call = my_function(1, 1) print(first_call) second_call = my_function...
9e71419dd9ec4dd9bf2a794627c480f75913ee31
duk1edev/tceh
/tceh_course4/functions.py
843
4.03125
4
def my_function(): print('I am function') print(my_function) print('Functions are objects', isinstance(my_function, object)) test = my_function test() # You can do any actions with functions my_list = [] my_list.append(my_function) print(my_list) # You can pass functions as parameters def call_passed_functi...
bcb36131b8622d6fde00369d25557bb59fbea919
duk1edev/tceh
/tceh5_homework/classworks_examples/class_worl2.py
4,175
4.03125
4
# ЗАДАЧА С КУРСА ДЕНЬ 5 # пользователь вводит список чисел через пробел. если ввел: # 1 число, строим квадрат # 2 числа, строим прямоугольник # 3 числа, треугольник # 4 числа, многоугольник # # вычисляем периметр и площадь. выводим в консоль. # можно сделать проверки на "возмонжость" построить данную фигуру с такими ст...
4e258e7d541f0455a6cfe2a5ef00e10389b112ce
duk1edev/tceh
/tceh_homework3/tceh_hm3_examples/example1_why.py
468
3.890625
4
data = [1, 2, 6.43, - 4, 0.4] minimum = data[0] for item in data: if item < minimum: minimum = item print('Minimum is ', minimum) # But other_data = [-10, -23, -9, 0.12, 0.4, -1.4] new_minimum = other_data[0] def min_in_list(input_list): new_minimum = other_data[0] for item in input_list: ...
923c5dd66f2983dcafe12088d4aa550298b5ed7e
nahidulislam-cse15/cracking_the_coding_interview_tecognize
/practice/linkedlist.py
3,700
4.1875
4
# linkedlist implementation # 1.create node ->create linked list # 2.add data class Node: def __init__(self, value): self.value = value self.next = None # print(self.value) class NodeList: def __init__(self): self.head = None def insert(self, new_node): if self.hea...
c4bb2d05288b577ff4b44e08dae8f165aec6d34b
herrsommer7894/SoftwareConstruction
/ass1/demo00.py
396
3.875
4
#!/usr/local/bin/python3.5 -u import sys, re o_count = 0 print ("I wonder how many words have vowels are in the sentence:") print ("hint: try for 10 words with vowels! Ctrl+D to sys.exit") for line in sys.stdin: if re.match(r'[AEIOUaeiou]', line): o_count += 1 print("There were %d words with...
b800986618b9da92c2ca63c2d2ceff7abf182734
christofoo/hard-way
/ex6.py
1,424
4.59375
5
# this is a string with an integer conversion that is defined outside the string as 10 x = "There are %d types of people." % 10 # this is a string that is named binary binary = "binary" # this is a string named do_not do_not = "don't" # this is a string with two string conversions in it that mean binary and do_not, res...
97d394dc79629dde7cda65537427166543da7697
christofoo/hard-way
/ex3.py
1,082
4.15625
4
# this line prints the message print "I will now count my chickens:" # this line prints a message and does an equation print "Hens", 25.0 + 30.0 / 6.0 # this line prints roosters and does an equation print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 # this line prints a message print "Now I will count the eggs:" # this line d...
9aff3cefc7b8d5c82d00adf21c411b0a78bb3ecc
AlexandruSte/100Challenge
/Paduraru Dana/26_queue.py
891
4.46875
4
# IMPLEMENTING A QUEUE IN PYTHON # https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt from collections import deque # A double-ended queue, or deque, has the feature of adding and removing elements from either end. class Queue: def __init__(self): self.queue = deque([]) def __add...
ad54a4182c9da6eabc51c1f8b0c2654a24fb215c
AlexandruSte/100Challenge
/Paduraru Dana/32_cycle_in_graph.py
1,476
3.921875
4
""" Detect cycle in an undirected graph """ from collections import defaultdict class Graph: def __init__(self): self.nodes = defaultdict(list) def add_edge(self, node_1, node_2): self.nodes[node_1].append(node_2) self.nodes[node_2].append(node_1) def has_cycle(self, node, visi...
1ac06e2b5148d70e50d6f9f913b3bd344e5980e0
AlexandruSte/100Challenge
/Stefan Alexandru/Day1/problem2.py
283
3.6875
4
# https://www.codewars.com/kata/numericals-of-a-string/train/python def numericals(s): dict = {} res = '' for letter in s: if letter in dict: dict[letter] += 1 else: dict[letter] = 1 res += str(dict[letter]) return res
c7df1339f5003c86d8be2bc1128cbcd874fd41c0
AlexandruSte/100Challenge
/Paduraru Dana/5_different_number.py
529
3.859375
4
# https://www.codewars.com/kata/iq-test/train/python def iq_test(numbers): numbers = [int(number) for number in numbers.split(' ')] even_numbers = list(filter(lambda element: element%2 == 0, numbers)) parity = 1 if len(even_numbers) > 1 else 0 # zero if even for index, number in enumerate(numbers, 1): ...
7bdc1bb81a224fbb9d552505b0bb8f6cedb0b145
AlexandruSte/100Challenge
/Paduraru Dana/21_regex_exercises_1.py
4,453
4.5625
5
# Learning regex in Python - Exercises Part 1 (20 exercises) import re # 1. Write a Python program to check that a string contains only a certain set of characters (in this case a-z, # A-Z and 0-9). def is_allowed_characters_set(string): char_re = re.compile(r'[^a-zA-Z0-9.]') string = char_re.search(string)...
28ad5cb72a54d428b1b27410d9c6f77754c48186
AlexandruSte/100Challenge
/Stefan Alexandru/Day 17/problem.py
223
3.546875
4
# https://www.codewars.com/kata/build-a-pile-of-cubes/train/python def find_nb(m): for value in range(1, m): m -= value ** 3 if m == 0: return value elif m < 0: return -1
b21a448b013c4bae35160d90b05e08565b1ed743
AlexandruSte/100Challenge
/Stefan Alexandru/Day5/problem.py
433
3.78125
4
# https://www.codewars.com/kata/find-last-fibonacci-digit-hardcore-version/train/python def last_fib_digit(n): if n > 60: n = int(n % 60) if n in [1, 2]: return 1 if n % 5 == 0: if n % 3 != 0: return 5 else: return 0 first, second, index = 1, 1, 2 ...
d2cda660dc40694537a9ca16094144825db9c546
AlexandruSte/100Challenge
/Paduraru Dana/9_tower.py
737
3.84375
4
# https://ww w.codewars.com/kata/576757b1df89ecf5bd00073b/train/python def build_tower(n): floor = '*' * (2 * n - 1) floors = [floor] spaces = 0 # number of spaces for one side while n > 1: spaces += 1 length = len(floor) floor = ' ' * spaces + floor[spaces: length - spaces] +...
d24c0ef65e77d730f2397458bc97f02672efb597
AlexandruSte/100Challenge
/Paduraru Dana/20_insertion_sort.py
403
4.09375
4
# INSERTION SORT def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] k = i - 1 # Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position while k >= 0 and key < arr[k]: arr[k + 1] = arr[k] k -= 1...
fdc6ea6ef7aa8d5bc9ccac58a37826cc061e4c72
AlexandruSte/100Challenge
/Stefan Alexandru/Day 10/problem.py
499
3.828125
4
# https://www.codewars.com/kata/split-and-then-add-both-sides-of-an-array-together/train/python def split_and_add(numbers, n): while len(numbers) > 1 and n > 0: listt = [] if len(numbers) % 2: listt.append(numbers[int(len(numbers) / 2)]) del numbers[int(len(numbers) / 2)] ...
06fc77408aeeea9fe08e1759ac444ba85c242b2a
k200x/algo_practice
/medium/moveElementToEnd.py
428
3.859375
4
def moveElementToEnd(array: list, to_move: int): collect_list = list() for i in array: if i != to_move: collect_list.append(i) collect_list.sort() moved_list = collect_list + [to_move] * (len(array) - len(collect_list)) return moved_list if __name__ == "__main__": arr = [2,...
faf7d5e4a13b9d79483a9cfc5d0101c4b4f00647
k200x/algo_practice
/medium/find_successor.py
1,026
3.671875
4
class BinaryTree: def __init__(self, value, left=None, right=None, parent=None): self.value = value self.left = left self.right = right self.parent = parent def findSuccessor(tree, node): inOrderTraversalOrder = getInOrderTraversalOrder(tree) pass def getInOrderTraversa...
ddf8f68722bd9823b9c5286874421a642811721e
Nayoumi/Crisp-and-fuzzy-relations
/crisp relation.py
3,043
3.84375
4
import numpy as np from colorama import Fore ### This function takes the user input with same number of elements in set 1 and set2#### def UserInput(): listX =[] listY=[] print("Enter number of elements X: ") nX=int(input()) print("Enter number of elements Y: ") nY = int(input()) print(Fore.RED + "Enter ...
18ad6746db7b1974908762098ea1960efc4bf9a4
managorny/python_basic
/homework/les02/task_4.py
524
4.03125
4
""" 4. Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ a = input("Введите слова через пробел:\n") a = a.split(' ') k = 0 for i in a: k = k + 1 print(f'{...
7e65017ed9807c9248a751ee5a4442c43aadc9fe
managorny/python_basic
/homework/les03/task_6.py
1,197
3.953125
4
""" 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в...
5a87189e0f46a875cd319cffec8dddd38c90e168
managorny/python_basic
/homework/les03/task_3.py
425
4.3125
4
""" 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. """ def my_func(a, b, c): if b < a < c or b < c < a: d = a + c elif a < b < c or a < c < b: d = b + c else: d = a + b return d print(my_func(20, 1...
2341d48ab30e17adbde07236b6623ee985f1d891
managorny/python_basic
/homework/les05/task_2.py
570
3.78125
4
""" 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке. """ with open('task_2.txt', 'r', encoding='UTF-8') as file: a = [] for itm in file: a.append(itm) print(f'Кол-во строк: {len(a)}') for i in a: ...
e3e85e57b963ddafc6b8a7a99a88b4e93214b224
managorny/python_basic
/homework/les05/task_5.py
774
3.734375
4
""" 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. """ from random import randint size = 10 with open('task_5.txt', 'w') as file: for i in range(size): x = randint(1, 100) ...
bd7598d6ab640aefa619edc3f3edfdc00886fc17
rogerlinh/MindXSchool.github.io
/Teachingteam/Gen12X/VuongTranLuc_8/q5.py
135
4.0625
4
# print a list of number from 1 - 20 that divided by 3 for i in range(20): if (i+1) % 3 == 0: print(i+1, end=' ') print()
b377c5086019d06d305a39251c0e69799cde6294
rogerlinh/MindXSchool.github.io
/Teachingteam/Gen12X/DuongTuanMinh_2/08_list_pop.py
561
3.71875
4
import random sequence = [random.randint(-10, 10) for i in range(4)] print("Hi there, this is our sequence:") print(*sequence, sep=", ") if len(sequence) > 0: loop = True while loop: answer = input("Where do you want to delete (head/tail): ") if answer == "head": pos = 0 ...
9d7c499395c17c35e32ecd6ab3f70a2a532d2033
phillipdwright/vscode-python-sample-configuration
/trees/node.py
316
3.53125
4
class Node: def __init__(self, value, parent=None): self.value = value self.children = set() if parent: parent.add_child(self) def add_child(self, child): self.children.add(child) def __repr__(self): return '<Node: {value}>'.format(value=self.value)
88f89624461a53383586dcd36cf80184a6ce6799
aaapham128/Data
/dict.py
550
4.1875
4
# Create a dictionary with KNOWN values answers = {} #curly brackets means dictionary # Create an array of survey questions survey = [] #square brackets means lists # Create an array of keys for each survey question # Hint: All keys must be unique # Use a for loop to go through the questions in your surve...
3880401e7358eb85a57d2f51b83bff00a3c9f4b2
silverflow/python_study
/property.py
297
3.75
4
class User: user_name: str e_mail: str def __init__(self, user_name, e_mail): self.user_name = user_name self.e_mail = e_mail def dd(self): return {"user_name": self.user_name, "e_mail": self.e_mail} asdd = User("asdfasf", "asdfas") print(asdd.dd())
0e6c68ed94c655a5b10959d348c17cb3ffd49d96
Yoctoboy/MixWithTSP
/distance_computer.py
1,848
3.703125
4
class DistanceComputer(object): def __init__(self, start_node, end_node): """ Constructor for the DistanceComputer Arguments: start_node {dict} -- start_node of the distance to compute end_node {dict} -- end node of th distance to computer """ ...
96b8fe9a60139959a7b2eef22d8e1dfcdcb4eab5
chesterlee0722/hackerrank
/challenges/grading/Grading Students.py
778
4
4
#!/bin/python3 #https://www.hackerrank.com/challenges/grading/problem import os import sys # # Complete the gradingStudents function below. # def calculateGrade(grade): print(grade, grade % 5) if(grade < 38): return grade elif((grade % 5 >= 3) and (grade % 5 != 0)): return 5 *(int(int(grad...
ee82d85715cb6f5013460f379f145436b6e6c273
RowlandOti/AlgorithmAndDataStructure
/algo/src/main/python/sort/sort.py
1,485
4.1875
4
class Sorting(object): def bubbleSort(self, arr, n): for i in range(n-1): for j in range(n-1-i): if(arr[j] > arr[j+1]): self.swap(arr, j, j+1) def selectionSort(self, arr, n): for i in range(n): # Assume min is the first element ...
e215b41f4d675b433ab2bd7d4bb156edb634f354
hosjiu1702/Programming_Problems
/leetcode/problems/p605/main.py
800
3.78125
4
from math import floor class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: l = len(flowerbed) zeros = 0 c = 0 if flowerbed[0] == 0: j = 0 zeros = 0 while j < l: if flowerbed[j] != 1: ...
34de71ef5ab1c698a305009bcc9b0b789feab0d0
MinwooRhee/unit_five
/assignment_five.py
1,585
4.375
4
# Minwoo Rhee # 10/16/18 # assignment_five # a game of guessing a random number from 1 to 100 import random def instruction(): """ give instructions of the program :return: None """ print("Welcome to the game of guessing!") print("Computer will pick a random number between 1 - 100 and you are...
de7f3d5ab6bb2f29f7951974483170f9f0144848
alanespinozaz/S1-TAREA_1
/14.py
780
3.953125
4
# """ Determinar si un número entero proporcionado por el usuario es primo. # Un número primo es un entero que no tiene más divisores que él mismo y la unidad. """ class Ejemplo14: def __init__(self): pass def evaluarprimo(self): divisor, num, res= 0,0,0 primo = True ...
a8fd33b9e4f50a365c5fb7d3d119042dd398a621
huangm96/Algorithms
/stock_prices/stock_prices.py
1,107
3.875
4
#!/usr/bin/python import argparse def find_max_profit(prices): max_num = 0 max_num_index = 0 if len(prices) < 2: return 0 # find the max num from index 1 for i in range(1, len(prices)): if prices[i] > max_num: max_num = prices[i] max_num_index = i # if the index of the max = 1, return ...
0c42ea1b3ec7b67dd7756e4529484c52c3d87d8a
pravinherester/LearnPython
/functions/calculator/Calculator-3.py
906
4.25
4
def add(n1,n2): return n1+n2 def subtract(n1,n2): return n1-n2 def multiply(n1,n2): return n1*n2 def divide(n1,n2): return n1/n2 operations={ "+":add, "-":subtract, "*":multiply, "/":divide, } first_number= int (input("Enter the first number\n")) second_number= int (input("Enter the second number\...
395aa14b1094093a87040f041074ff610296dcfe
pravinherester/LearnPython
/DataTypeandManipulation/DataTypeQuiz.py
810
3.671875
4
#Which statement is incorrect? # 932 is Integer # "False" is Boolean # 857.25 is Float # "523" is String # Solution "False" is Boolean - > Booleans are either True or False, they don't have quotation marks around them, otherwise it would turn them into a String. So it should be bool = False #What is the data type of ...
5b6baea35aac1f67bc007ad8e8558d9cc19531b8
pravinherester/LearnPython
/functions/calculator/Calculator-5.py
881
4.0625
4
def add(n1,n2): return n1+n2 def subtract(n1,n2): return n1-n2 def multiply(n1,n2): return n1*n2 def divide(n1,n2): return n1/n2 from art import logo print (logo) operations={ "+":add, "-":subtract, "*":multiply, "/":divide, } num1= int (input("Enter the first number:\t")) for key in operations: p...
bb2e69f53052d4314660d8518d6d30b7446794d1
pravinherester/LearnPython
/DataTypeandManipulation/Quiz.py
345
4.125
4
a = int("5") / int(2.7) #what is the data type of a print (type(a)) print(6 + 4 / 2 - (1 * 2)) #what will get printed # Which of these lines of code will give you an error? name = input("What is your name") print(f"Your name is {name}") print("Your name is "+name) age=12 print(f"You are {age} years old") print("You a...
e47be68ca3c35001cba73fde7b3c7f663b4e22c1
pravinherester/LearnPython
/blackjac/final.py
3,839
3.953125
4
import random from replit import clear from art import logo to_play=True to_loop=True def deal_card(): cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] return random.choice(cards) def calculate_score(cards): sum_of_cards=sum(cards) if (sum_of_cards==21 ): return 0 else: return sum_of_cards de...
49cafe4ad936e44e7aeb09c59ae77ac95e4cc31c
pravinherester/LearnPython
/scope/scopequiz.py
423
3.6875
4
# What will be printed in the console when the following code is run? # DO NOT run the code, just pretend to be a computer. # def a_function(a_parameter): # a_variable = 15 # return a_parameter # a_function(10) # print(a_variable) # i = 50 # def foo(): # i = 100 # return i # foo() # print(i) ...
bb8afe16206214aaa195d8c713d6bcf46e694105
pravinherester/LearnPython
/list/listclass.py
1,038
3.5625
4
# #import random # counties=['Somerset','kent','Essex','Sussex','Leicestershire','Derbyshire','Durham','Hampshire','Middlesex','Northamptonshire','Surrey','Warwickshire'] # test="p ,r ,a ,v ,i ,n".split(' ~') # print(test) # print(counties) # print(counties[-5]) # print(len(counties)) fruits = ["Strawberries", "Ne...
096b9568ffe759a091d4c8cd7c999e17505b5b16
pravinherester/LearnPython
/ConditonalBlock/rollercoaster/roller-coasterv2.py
627
4.25
4
# if condition: # if condition: # do some code # else: # do some code # else: # do some code print("Welcome to tthe roller coaster") int_height=int(input("what is your height\n")) # converting Strig to int int_age=int(input("What is your age\n")) #Note the collon used after if conditon if (in...
154cddf392c227b2b1a4a3dd0045dc19451985d0
pravinherester/LearnPython
/list/tressure.py
513
3.6875
4
emoji1=['😀','😀','😃'] emoji2=['😁','😆','😅'] emoji3=['😂','🤣','😇'] emoji=[emoji1,emoji2,emoji3] row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map=[row1,row2,row3] print(f"{row1}\n{row2}\n{row3}") number= input("choose the number") int_first_number=int(number[0]) int_second_number=int(nu...
69bdb78123e8cdb4ea3934d90630db564338554b
PrabhatRoshan/Daily_Practice_Python
/Daily_practice_codes/set/max_min.py
217
4.34375
4
# Write a Python program to find maximum and the minimum value in a set my_set = set([7,3,15,2,8,31,21,6]) print("Maximum value of the set is: ",max(my_set)) print("minimum value of the set is: ",min(my_set))
b60f9232a3f4fb3ddd419ad90b782794cc049f3b
Rudydemon/RockPaperScissors_Tkinter
/rps.py
1,548
4.09375
4
# Rock Paper Scissors # Peri Smith - Python Project 1 import tkinter import random root = tkinter.Tk() root.title("Rock Paper Scissors") mainframe = tkinter.Frame(root) mainframe.grid(column=2, row=3) root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) # row 1, column 1 l11 = tkinter.Lab...
e60a1200de05fd86e21485738a77dc99fdd601dd
AlisterTT/Learnpy
/ex15.py
508
3.859375
4
# -*- coding: utf-8 -*- from sys import argv #引入模组 script, filename = argv #定义读取文件的名称 txt = open(filename) #用open命令获得filename文件 print "Here's your file %r:" % filename #显示文件名 print txt.read() #对之前open获得的文件进行read操作 print "Type the filename again:" file_again = raw_input(">") #再次获取文件名 txt_again = open(file_aga...
6e43455cf02eacf1406ec9703d2adabb722e23e3
dojoufjf/DOJO
/P2010/Palavras/src/test_palavras.py
1,678
3.671875
4
# To change this template, choose Tools | Templates # and open the template in the editor. import unittest import math dicionario = {'a':1,'b':2, 'c':3, 'd':4} def parImpar(string): acumulador = 0 for letra in string[:]: acumulador += dicionario[letra] if ((acumulador % 2) == 0): return ...
4265131f5e2fe749c16f700c9b6bf03939600bed
yek13/Basic-Python-Example
/fonksiyonBolumSonu.py
2,243
3.828125
4
""" MÜKEMMEL SAYI def mukemmel(a): toplam=0 for i in range(1,a): if a%i==0: toplam+=i return toplam==a while True: sayi=input("sayi giriniz") if (sayi=="q"): print("görüşürüz") break else: sayi=int(sayi) if mukemmel(sayi): ...
bd7e6b6211b987954736a26e31bf5fe250f37475
omarnabulsi16/Pong-Game
/Paddles.py
7,244
3.65625
4
import pygame from pygame.sprite import Sprite class MidPaddle1(Sprite): # constructor def __init__(self, settings, screen): super(MidPaddle1, self).__init__() self.screen = screen self.width = settings.vertical_paddle_width self.height = settings.vertical_paddle_heig...