blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
97228fe62a98c27e5a9744844f85b323e9651134
iamedwardshen/leetcode-solutions
/python/binary_tree_postorder_traversal.py
1,021
4.1875
4
#!/usr/bin/env python __author__ = 'Rio' class TreeNode(): def __init__(self, x): self.val = x self.left = None self.right = None def binary_tree_postorder(root): '''Traverse a binary tree in post order, which means traverse the left first, then right then root.''' if not root...
ef24c4df7f45f2e8536ea9d04922f54b6aafe76b
felipedrosa/algorithmsLessons
/week2/qs1.py
647
3.703125
4
def partition(alist, first, last): global count count = count + last - first pivot = alist[first] i = first + 1 j = i while j <= last: if alist[j] < pivot: aux = alist[i] alist[i] = alist[j] alist[j] = aux i += 1 j += 1 aux = alist[first] alist[first] = alist[i-1] alist...
0a297877552fda8e7fa29a0471b16950716b2904
boldizsarBalogh/battleship
/battleship_FINAL.py
3,786
3.734375
4
import getpass import sys wincondition = True def playagain(): gameon = input('Do you want to play again(Y/N)?') while (gameon != 'Y') and (gameon != 'N'): gameon = input('Do you want to play again(Y/N)?') if gameon == 'Y' or gameon == 'N': break if gameon == 'Y': globa...
7a299947f687028a531f4e809cabc5da98b61151
boanuge/seminar-raspberry-pi-educations-material
/Apdx.python_basic/12tuple_test.py
419
4.21875
4
tuple1 = ("one","two","three") print tuple1[0] #tuple1[0]="four" #tuple1.append("four") list1 = list(tuple1) print list1 result = list1 == tuple1 print"list1 == tuple1 : ", result tuple2 = tuple(list1) print tuple2 tuple3 = (10,) print type(tuple3) tuple4 =10,20,30 print"tuple4 : ",tuple4 num1, num2, num3=tuple4 ...
63b40b21693200eefdc5469a9964c3f7e4aed007
figureitout-kid/word_count
/wordcount.py
1,083
3.953125
4
#open file, # iterate through text, # create a dictionary, # set key to word in file, # and value to number of times it appears. # print key, value # def make_letter_counts_dict(phrase): # """Return dict of letters and # of occurrences in phrase.""" # letter_counts = {} # for letter in phrase: # ...
e5bc5d257cb9a51edf4e76267c609ed20699e71a
Aasthaengg/IBMdataset
/Python_codes/p03399/s898598562.py
159
3.53125
4
#!/usr/bin/env python3 def main(): a, b, c, d = (int(input()) for i in range(4)) print(min(a, b) + min(c, d)) if __name__ == "__main__": main()
c6687fd7cbba356a2c7432879b33b8c7ac3cdd76
evehsd/PythonStudy
/PythonStudy/Study.py
1,203
3.578125
4
### 1 ### for data in (2, 45, 55, 200, -100, 99, 37, 10284): if data % 3 == 0: print data ### 2 ### test = "this is test string" test = test[::-1] print(test) ### 3 ### friends = ['john', 'pat', 'gary', 'michael'] num = [1,2,3,4] print"No. %d is %s" % (num[0],friends[0]) print"No. %d is %s...
eb3147da85439df8419234acb4a963ee06b59203
JoachimIsaac/Interview-Preparation
/LinkedLists/21MergeTwoSortedLists.py
4,984
4
4
""" 21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 """ # Definition for singly-linked list. # class ListNode: # def __init__(se...
2a41c1f00ef04bc2a70090d1bb5a5e4acbf0ecd0
adusachev/Algorithms-and-Data-structures
/Algorithms/Динамическое программирование/рюкзак без повторений.py
2,027
3.90625
4
def transporate_table(d: list): """транспонирует таблицу""" trans = [] for j in range(len(d[0])): trans.append([]) for i in range(len(d)): trans[j].append(d[i][j]) return trans def get_table(d: list, sep_num=1): """ выводит таблицу sep_num - кол-во пробелов в ну...
7d92b76e15d7e8bafe1456b9e5ab830bbfefb743
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/2620.py
1,712
3.609375
4
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. import fileinput def main(): cases = 0 curCase = 0 f = open('flipSol','w') for line in fileinput.input(): if cases == 0: cases = int(line) else: ...
294a0d3b020e377a9694ca70287b32bd602ef361
lunar-r/sword-to-offer-python
/剑指offer/矩阵中的路径.py
4,251
3.828125
4
# -*- coding: utf-8 -*- """ File Name: 矩阵中的路径 Description : Author : simon date: 19-3-19 """ # -*- coding:utf-8 -*- """ matrix 是一维数据 """ class Solution: def __init__(self): self.flag = False def hasPath(self, matrix, rows, cols, path): # write code here if ...
8633bf4a153b782b172d2118b8fdc70f13fb3fcd
venkateswararao-kotha/it-cert-automation-all-modules
/debugging/part1/final_lab/greetings.py
854
4.5
4
#!/usr/bin/env python3 ''' When we look at the code, we can see that there are two different data types used, string and int. The variable name takes string values and the variable number stores integer (int) values. So, the print statement within the script concatenates both string and integer values, which is causin...
2377bc9128134917060ce847fba3a7e6a292039c
hungrytech/Practice-code
/DFS and BFS/DFS practice1.py
533
3.578125
4
def dfs(graph, start_node) : visited, need_visit= list(), list() need_visit.append(start_node) while need_visit : node = need_visit.pop() if node not in visited : visited.append(node) need_visit.extend((graph[node])) return visited data=dict() data['A'] = ['B',...
bbf8fe9c418a9ce2bbaf91833aabf57c3327cfed
thebinsohail/Python-track
/day3/worldcup.py
268
4.21875
4
#empty tuple initialized worldcup=() #take loop range loop=int(input("Enter number of inputs to be taken: ")) #loop till the range to take inputs for i in range(loop): worldcup=input("Enter value for country no %d " %(i+1) ) #display the countries print(worldcup)
d6b6c63a8f10fab7fb8fa33f99bbc83e48dc2458
Aravinda93/Python_KinterApp_application
/Databases4.py
6,907
3.75
4
from tkinter import * from PIL import ImageTk, Image import sqlite3 root = Tk() root.title('DropDowns') root.iconbitmap('./Icon_File.ico') root.geometry('400x600') #creating a database or connecting #conn = sqlite3.connect('address_book.db') #Create a cursor #cur = conn.cursor() #creating a table #cur.e...
dbc6eb91d25e2d805564917ab7136a9f7dd768f5
mzb2599/python
/classobject/class2.py
250
3.875
4
class Dog: kind = 'Bull dog' def __init__(self, name): print('Instance created of type dog') self.name = name d = Dog('Trump') print(d.kind) d.kind = 'German Shepherd' print('Type :', d.kind) print('Name :', d.name)
542159ce31406a91c64bdef870ea04c4a6c20d79
Iam-El/Random-Problems-Solved
/Bootcamp/IsItAnagram.py
497
3.765625
4
str1 = "rat bat" str2 = "car" dict1 = {} dict2 = {} count = 0 isTrue = False for i in range(len(str1)): val1 = str1.count(str1[i]) dict1.update({str1[i]: val1}) for i in range(len(str2)): val2 = str2.count(str2[i]) dict2.update({str2[i]: val2}) print(dict1) print(dict2) for j in dict1: if j not ...
67470c3675851e17a281fd1f0b958993d0ef03fa
leonlinsx/ABP-code
/Rice Fundamentals of Computing specialisation/Principles of Computing/Part 2/Week 6 Zombies.py
7,670
3.65625
4
""" Student portion of Zombie Apocalypse mini-project Simulates Zombies chasing, Humans fleeing, and stationary obstacles http://www.codeskulptor.org/#user47_8KxVJO5VXk_17.py """ import random import poc_grid import poc_queue import poc_zombie_gui # global constants EMPTY = 0 FULL = 1 FOUR_WAY = 0 EIG...
cb30747a5101037e74de960dec0a0de572473750
jovegill/Python-clothing-database
/clothing_database.py
7,609
3.96875
4
from tkinter import * import sqlite3 #Setup GUI 'screen' root = Tk() root.title("Welcome to Sales Database for Max's Clothing Store!") root.geometry("450x600") #Create a database and cursor then connect to the database conn = sqlite3.connect('apparel_store.db') c = conn.cursor() #Create table for apparel sales; sql...
630f900e6d1bc9c6e104819e7452d92a3b821ea7
sramyar/algorithm-problems
/fibonacci.py
954
4.28125
4
''' The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). Example 1: Input: n = 2 Output: 1 Explana...
ac688b939d0ff0ce85d4c95f39541f4ee67efb53
ehizman/Python_Projects
/src/chapter_two/negative_positive_and_zero_values.py
557
4.03125
4
countOfZeros = 0 countOfNegativeValues = 0 countOfPositiveValues = 0 for i in range(5): number = int(input("Enter number %s " % (i+1))) if number == 0: countOfZeros = countOfZeros + 1 else: if number < 0: countOfNegativeValues = countOfNegativeValues + 1 else: ...
a4be71644e483ff98c6daead1872cba67449886b
ehizman/Python_Projects
/src/chapter_two/car_pool_savings_calculator.py
863
4.15625
4
if __name__ == "__main__": total_miles_driven_per_day: float = float(input("Enter the total number of miles driven per day: ")) cost_per_gallon_of_gasoline = float(input("Enter the cost per gallon of gasoline: ")) average_miles_per_gallon: float = float(input("Enter the average miles covered per gallon of g...
adcabcb9b6baaf7224f2165d20a29165dc6e2067
Dreskiii1/CSE-231
/Homework Examples/gcd_testing.py
346
4.125
4
#calculates for gcd testing from math import gcd def main(): number = int(input("input a number ")) second_number = int(input("input another number ")) gcd_number = gcd(number, second_number) #print("the gcd of ", number, " and ", second_number, " is ", gcd_number) print(gcd_number) if __name__...
7855b01bf34c706f4fc9ed1e87c2b0bb3bffd1cb
rainly/scripts-1
/cpp2nd/e6-15.py
1,095
3.71875
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- from datetime import date def ex_615(birthday): ''' 我们省去第一个要求的实现,因为第一个要求的实现包含在后面两个实现里。 给定一个生日(格式为DD/MM/YY),分别计算出词人已经活过的天数,包括闰年天数 然后计算这个人的下一个生日还有多少天 该代码充分利用了datetime模块里的date对象 ''' (d,m,y) = birthday.split('/') #分隔出天,月和年,这里假定用户的输入是合法的 myb = d...
606204288bec47d7d1647cf34e9f64dc454c789b
Ulysses-WJL/study
/asynchronization/asnycio_test.py
2,727
3.828125
4
import asyncio import threading """异步IO, asyncio的编程模型就是一个消息循环 3.5 后 @asyncio.coroutine -> asyncio yield from -> await """ # @asyncio.coroutine async def hello(): print(f"Welcome Ulysses ...{threading.current_thread()}") # 耗时1s的io操作 # r = yield from asyncio.sleep(1) r = await asyncio.sleep(1) p...
d68285b128d8bb0d44d27a5101d7ce443e567925
martinyang0416/my_git
/client_program/demo.py
11,119
3.953125
4
"""Amazing Banking Corporation functions""" from typing import List, Tuple, Dict, TextIO # Constants # client_to_accounts value indexing BALANCES = 0 INTEREST_RATES = 1 # transaction codes WITHDRAW_CODE = -1 DEPOSIT_CODE = 1 LOAN_INTEREST_RATE = 2.2 # percent ## ------------ HELPER FUNCTIONS GIVEN BELOW ---------...
2e8796d8b8227526f3e7bd227b33e9b21f7d0227
signorrayan/linux-commands-Implementation-in-python
/rm.py
1,540
4.09375
4
#the rm command implementation import os, shutil, sys currentDirectory = os.getcwd() def main(): script = sys.argv[0] switch_path = sys.argv[1:] if switch_path: if switch_path[0].startswith('-'): #if we have a switch -r, it means we want to delete a directory reqursively switch = swit...
be1761d91454daef0a56f5b35afa2e6402ba850c
thedonflo/Flo-Python
/ModernPython3BootCamp/List Comprehension Exercises/ListCompEx4.py
305
4.28125
4
#Given the string "amazing" create a variable called answer, which is a list containing all the letters from "amazing" but not the vowels(a,e,i,o,u). #The answer should look like:['m','z','n','g'] #Use a list comprehension answer = [char for char in "amazing" if char not in "a,e,i,o,u"] print(answer)
55c9ad58ba70cd7620adb4e60406a9029ed577a7
MisterJackpot/SegurancaTrabalho2
/index.py
1,292
3.515625
4
#!/usr/bin/python import sys from Crypto.Hash import SHA256 """Divide a lista em pedaços de tamanho n""" def generate_chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n] """Inicio da Execução do Programa """ if len(sys.argv) < 2: print("Utilização: python .\\index.py {File Name}") ...
a7c534fff3f4b1cb52208acf7bfb511b12ad9ab4
rafaelperazzo/programacao-web
/moodledata/vpl_data/77/usersdata/169/43547/submittedfiles/exercicio24.py
279
3.890625
4
# -*- coding: utf-8 -*- import math a=int(input('Digite o Primeiro Número Inteiro Positivo:')) b=int(input('Digite o Segundo Número Inteiro Positivo:')) if (a>b): menor=a else: menor=b for i in range (1,menor+1,1): if(a%i==0) and (b%i==0): MDC=i print (MDC)
54d62f2125aaa3d9b98e8d2a4238ad00cebecfb3
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/thnsik001/question3.py
1,106
3.78125
4
""" Skhulile Thenjwayo Assignment 9 question3 12/05/2014""" grid = [] #inserts numbers into grid for i in range(9): line = input() line = line.replace("","-") line = line[1:-1] grid.append(line.split("-")) #converts string to int for row in range (9): for col in range(9): grid[row][co...
b51146e0cc345894873a89c1ed70b493beecb97a
Aasthaengg/IBMdataset
/Python_codes/p03477/s171906804.py
195
3.515625
4
import sys input = sys.stdin.readline A, B, C, D = [int(x) for x in input().split()] if (A + B) > (C + D): print("Left") elif (A + B) < (C + D): print("Right") else: print("Balanced")
6ec9cf2b3adfe58b1e235d1a250348d913cf4a40
jonag-code/python
/matplot_examples.py
205
3.734375
4
import matplotlib.pyplot as plt X= [x**2 for x in range(10)] Y= [y**3 for y in range(10)] plt.plot(X,Y, 'ro') plt.plot(X,Y, linestyle = 'solid') #plt.plot(Y, 'b') plt.axis([0,100,0,1000]) plt.show()
f20554a1b0417c2e555de508897bf22a30c09052
shir19-meet/YL1-201718
/Lab5/lab 5.py
1,394
4.0625
4
from turtle import Turtle import turtle class Square(Turtle): def __init__(self,size, shape,): Turtle.__init__(self) self.shape("square") self.shapesize(size) ## def random_color(self): ## red = randon.randint(0,256) ## green = random.randint(0,256) ## blue ...
a01c2782bb8b35533d7904e495aa020849d434dd
dharani277/guvi
/codekata/absolute_beginner/print_the_table_of_9_till_N.py
282
4.1875
4
#print the table of 9 till N # get input from user N=int(input()) # define multiples function def multiples(): # for loop is used to start the value from 1 to N for i in range(1,N+1): c=9*i print(c,end="") if(i<N): print(end=" ") # call the multiples function multiples()
a49d77829202e8d7e6faa1c03b6d392865291545
YadhiraCondori/PythonClass
/PRACTICA2/EJERCICIO1.PY
741
3.734375
4
print("EJERCICIO 1 - COMPARAR RESPUESTAS DE UN EXAMEN") print("***********************************************") def listas(lista_1,lista_2): print(f"Las respuestas correctas son: {lista_1}" ) print(f"las respuestas del alumno son: {lista_2}" ) contador = 0 for i in range(4): if lista_...
c13d4bd27b246aca9a0c729e9e3e8cbeabc0e987
avatargu/AID1908
/2_2_LINUX/day01/time_print.py
691
3.53125
4
""" 一秒打印一次当前时间 """ ################################################## import time f = open("log.txt","a+") f.seek(0,0) # 文件偏移量从结尾移动到开头 n = 0 for line in f: n += 1 while True: time.sleep(1) n += 1 s = "%d. %s\n"%(n,time.ctime()) f.write(s) f.flush() # 缓冲刷新方法1 ################################...
3e80d1d61d1aaf5c50fd8d8b52c215bb8bd9de31
ljragel/Learning-to-program-with-Python
/words_counter_from_a_string.py
402
3.9375
4
""" Crea un programa que cuente el número de veces que aparece una palabra en una string """ # counter = dict() print("Contador de palabras en una frase") print("------------------------------------") user_string = input("Frase: ") for new_word in user_string.split(" "): new_word_times = 0 word = new_word...
e4b05afe25c641f1e595df396539bda7f9ef9dda
Kim-Taehyeong/PyBaekjoon
/Once/5086.py
255
3.53125
4
import sys while True: X,Y = map(int, sys.stdin.readline().split()) if X == 0 and Y == 0: break if Y % X == 0: print('factor') continue if X % Y == 0: print('multiple') continue print('neither')
136381b70549d7e233cab1c661acc6a3b492df08
Aasthaengg/IBMdataset
/Python_codes/p03672/s712831330.py
109
3.515625
4
s=input() for i in range(2,len(s)-1,2): s=s[:-2] if s[:len(s)//2]==s[len(s)//2:]:print(len(s));exit()
c1fa8236dbfc944a7411e85b4e59c1600d53539d
emilyzfliu/6_0001_psets
/ps1/ps1c.py
1,711
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 3 17:06:13 2020 @author: Foofoo """ semi_annual_raise = 0.07 r = 0.04 portion_down_payment = 0.25 total_cost = 1000000 annual_salary = int(input("Starting salary: ")) n_months = 36 def amt_saved(savings_rate): portion_saved = savings_rate/1...
aae9d80c602849170188e1d18f0bc3cc9c0ded59
amiralimoghadamzadeh/pythonn
/2-4.py
217
3.625
4
a = int(input("number of the students in the class")) S = 0 L = [] for i in range(a): score = int(input("enter the score")) L.append(score) S += score print(max(L)) print(min(L)) print(float(S/a))
8dddde755d64b5813bc09089a695d984c7d812f1
priyankabb153/260150_daily_commits
/text_analyzer.py
586
4.3125
4
filename = input("enter a file name: ") with open(filename) as f: text = f.read() print(text) # This part of the program shows a function that counts how many times a character occurs in a string. def count_char(text, char): count = 0 for c in text: if c == char: count += 1 ret...
3cc7e03ff77549ab634cfe808a4c529a7298a902
ramsayleung/leetcode
/200/binary_tree_paths.py
1,175
4.125
4
""" source: https://leetcode.com/problems/binary-tree-paths/ author: Ramsay Leung date: 2020-04-11 Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, ...
4ecaa01821e6be563f2d50c25e59c972f56fdb4d
jorika/Python-CodeAcademy
/171-Create your own.py
130
4.125
4
A = ['3', '4', '1', '2'] for a in A: if a == '1' or a == '2': print a, 'AWE' else: print a, 'HYU'
d0098b676afc75c216a6a7c06de06e82893dee34
terranigmark/the-python-workbook-exercises
/part2/e35_dog_years.py
1,236
4.3125
4
""" It is commonly said that one human year is equivalent to 7 dog years. However this simple conversion fails to recognize that dogs reach adulthood in approximately two years. As a result, some people believe that it is better to count each of the first two human years as 10.5 dog years, and then count each additiona...
5da2cff6c1c3f5b9bec9bb4dacdfcf4c0253db17
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/allergies/4f6e999f318d4562b79058efb7d3353d.py
783
3.984375
4
class Allergies(object): # Allergens and their scores ALLERGENS = ( ('eggs', 1), ('peanuts', 2), ('shellfish', 4), ('strawberries', 8), ('tomatoes', 16), ('chocolate', 32), ('pollen', 64), ('cats', 128), ) # A mapping of item name: score ...
faf3224506efc2a6bc62a141053572ca4a458522
vtombou/python_par_la_pratique_101_exercices_corriges
/exercices/debutant/exercice044.py
132
3.796875
4
liste = ["Pierre", "Paul", "Marie"] for i in range(len(liste)): print("{indice} {element}".format(indice=i, element=liste[i]))
cb73d3634fd673bbbb827545e77e9cdc36173cec
amacabr2/iut_py_traitement_donnees
/Cryptographie/EnfanceDeLArt/bible.py
2,703
3.96875
4
""" Auteur: Anthony MACABREY S4A1 """ from math import sqrt def lireFichier(file): """Lit le texte dans le fichier passé en paramètre""" fichier = open(file) texte = fichier.readlines() return texte[0] def recupLettreValable(text): """Retire les espaces et les caractères tel que '.', ',', ':' e...
8cf050db3d454d4261dc09efd9938fe5ef2e4bdb
dumidu1998/pytube-Extended
/12start.py
977
3.5625
4
from datetime import datetime, time, timedelta import sys import pytube def is_time_between(begin_time, end_time, check_time=None): # If check time is not given, default to current UTC time check_time = check_time or datetime.utcnow().time() if begin_time < end_time: return check_time >= begin_tim...
de2282ba2adbd315b2df95325a04d6da2dc29678
brianhendel/edX_Python_HarvardX_PH526x
/Network_Analysis.py
1,737
3.625
4
import networkx as nx import matplotlib.pyplot as plt from scipy.stats import bernoulli import numpy as np bernoulli.rvs(p=0.2) N = 20 p = 0.2 #create empty graph #add N nodes #loop over all pairs of nodes #add an edge with prob p def er_graph(N,p): """Generate an ER graph""" G = nx.Graph() G.add_nod...
18b6b4226a8bbf739aa8ef1bfea7ed2e33280642
Khalif47/Oop_design_prac_8
/task_4_menu.py
2,413
3.875
4
from textEditor import TextEditor text_editor = TextEditor() def menu(): while True: try: print('---------menu--------\n\n\n') print('1. insert num\n') print('2. read filename\n') print('3. write filename\n') print('4. print num1 num2\n') ...
8163d3721385d266099b7473a4a0d39f5bf146df
GuanYangCLU/AlgoTestForPython
/LintCode/ladder/chapter_2/0062_Search_in_Rotated_Sorted_Array.py
1,943
3.6875
4
class Solution: """ @param A: an integer rotated sorted array @param target: an integer to be searched @return: an integer """ def search(self, A, target): # write your code here # firs BS find break point # second BS find target if not A: return -1 ...
478ddd2766efaff6c1641820e37d1b8de49f2639
mrcaesarliu/Machine_Learning
/Linear_Model/Test.py
373
3.53125
4
# -*- coding: utf-8 -*- import numpy as np from sklearn.datasets import make_regression import matplotlib from Linear_Regression import OLS def data_make(): X, y = make_regression(n_samples=100, n_features=2, n_targets=1) return X, y X, y = data_make() y = (y - np.mean(y)) / (np.std(y)) ...
e9dc05626acdb700467171c02546dbc7d6a8589b
ucefizi/KattisPython
/smallestmultiple.py
352
3.609375
4
# Problem statement: https://open.kattis.com/problems/smallestmultiple def gcd(a, b): if b == 0: return a return gcd(b, a%b) def lcm(a, b): return a*b // gcd(a, b) st = input() while st: tab = [int(i) for i in st.split()] x = tab[0] for i in range(1, len(tab)): x = lcm(x, tab[i]) print(x) try: st = inp...
0c9ceb07444164f35aea85763a69b1979225ffd2
dhulchuk/leetcode
/add_two_numbers/main.py
2,588
3.890625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __eq__(self, other): return str(self) == str(other) @staticmethod def from_reversed_list(l): first = ListNode(l[-1]) r = first for x in l[:-1][:...
e643c66ff8d703f028c3e45224907eddc7cb0c2b
Clint-cc/Leecode
/力扣/简单练习/009-回文数.py
523
3.6875
4
# !D:/Code/python # -*- coding:utf-8 -*- # @Author : Clint def reverse_num(num): initial_num = num if num > 0: a = len(str(num)) # a=3 n = len(str(num)) - 1 # n=2 sum = 0 while n >= 0: s = num // 10 ** n s = s * 10 ** (a - 1 - n) num = num ...
1e6f417432bfa6c11353c270ff1d38545e52d8fa
kcildo/exercicios_python
/exercicios_aula_03_funcoes_subprogramas/05.py
1,721
4.25
4
# Faça um programa com uma função chamada somaImposto. # A função possui dois parâmetros formais: taxaImposto, que é a # quantia de imposto sobre vendas expressa em porcentagem e custo, # que é o custo de um item antes do imposto. A função “altera” o valor # de custo para incluir o imposto sobre vendas. # -------------...
c4692cee075228cea40098c664b149f5db68480a
TomGallagher98/Programming2_Assignment_MusicListeningDatabase
/iTunes.py
6,826
3.75
4
##Run The Program Through The Interface File from Main_Code import add_song import sqlite3 from datetime import datetime #In the assignment I have included 2 files so that the update itunes function can be viewed #'Music.txt' is the old file, 'MusicNew.txt' is the updated #first import the Old file,...
db66d9e0b06ee7a65c1fb67c3212129d906ea728
dongfengchi/bicycle_project
/step1/calculate_sequence.py
1,272
3.5625
4
import pdb time_list = [] def add_zero(num): if num < 10: return '0' + str(num) else: return str(num) #list_day = ['08', '16', '24', '32'] list_day = [add_zero(x) for x in range(1, 32)] list_month = ['08', '09', '10', '11'] # the minimum of the total count # if you want all cars result, the v...
9140708877837eb4494bc90163900a2419d5435f
DylanonWicchiramala/covid_data_analysis
/source/data.py
610
3.546875
4
import pandas as pd index = ['iso_code','continent','location','date'] #split file by country and save as a new file. use isocode(uppercase) of country toget file only that country. world_csv = pd.read_csv('./source/owid_covid_data.csv', parse_dates=[3]) owid_covid_data_csv = world_csv world_df = pd.DataFrame(world...
f00c02bd4eb6bb12ea73cc767c96ae03ede883ce
Broomva/Numerical-Methods
/Python/Codigo Fuente/Sin Vista/Punto Fijo.py
547
3.53125
4
from sympy import * x, y, z = symbols("x,y,z") func = raw_input("Ingrese la Funcion: \n") pa = raw_input("Ingrese el punto: \n") tol = 0.0001 func = sympify(func) fdiff = diff(func, x) ev = 1 resu = 0 ite = 0 if fdiff.subs(x, 0.4) < 1: while ev > 0.1: ite += 1 fevala = func.subs(x, pa) eu = abs(pa ...
5864d56c5f163bbb4865e21d650793950d73a451
vanessably/seinfeldNLP
/language_model/generate_text_ngram_markov_train.py
4,496
3.796875
4
''' A simple ngram markov train to generate text. ''' from __future__ import print_function import os import numpy import pickle from nltk.util import ngrams from nltk.tokenize import word_tokenize def generate_context_word_dict_from_text(text, n): ''' Take a corpus of text and generate a ngram dictionary, usi...
4606e680351eacd332fef1c28ced48b78c5956a0
fernanluis/learning-pyton
/conditionals.py
978
4.21875
4
x = 40 if x < 30: print("x is less than 30") # con tabulacion x = 10 if x < 30: print("x is less than 30") # con tabulacion x = 10 if x < 20: print("x is less than 20") else: print("x is greater than 20") color = "blue" if color == "red": print("the color is red") else: print("any color") colo...
1a2a1c8863ad52c4adb668516d786d10dcacd579
avengerryan/daily_practice_codes
/eight_sept/programiz_builtin_funcs/python_pow.py
429
4.59375
5
# python pow() : returns the power of a number # the pow() function returns the power of a number """ # example 1: python pow() # positive x, positive y (x ** y) print(pow(2, 2)) # negative x, positive y print(pow(-2, 2)) # positive x, negative y print(pow(2, -2)) # negative x, negative y print(pow(-2, -2)) ""...
26652dedd069dbf433fc4013742d99b0d8c5021d
vsanchezrod/Python_Flask_Bootcamp
/1.PYTHON/expresiones_regulares.py
3,723
4.125
4
# Se importa módulo para las expresiones regulares import re # EXPRESIONES REGULARES (search, findall, split, sub) ''' EXP REGULAR: son secuencias de caracteres que forman una búsqueda por patrón Se utilizan para ver si una cadena de texto cumple con un patrón ''' texto = "Hola, mi nombre es Virginia" print...
66e6f95b7fc36328b884ea81e9b57808a9f12bb5
egilsk/fys3150x
/project5/temperature.py
1,143
3.5
4
import sys import numpy as np import matplotlib.pyplot as plt # Read the name of the input data file from the command line if len(sys.argv) <= 1: print "Error:", sys.argv[0], "reads the name of the input file" exit(1) else: datafile = sys.argv[1] # Open input data file and read in the results with open(da...
faf23ee8ed9b79539ebcf15cac80de5b015cc7b2
zeyee/57-
/code_3(2).py
221
4.09375
4
#!/usr/bin/env python #coding=utf-8 a = raw_input("What is the input string? ") if len(a) is 0: print '请你输入内容.' a = raw_input("what is the input string? ") print "%s has %d characters." % (a, len(a))
6a37427f42d70bf332454ec52bc1a03e3a403575
joetechem/python_tricks
/efforts/fill_the_basket.py
352
3.609375
4
# Challenge: Fill your basket with 20 tomatoes # Replace the ?? with the correct number # BONUS: # WHAT statement can you add to check how many tomatoes we have? # WHERE can you correctly put this statement? basketFull = False tomatoes = 0 while not basketFull: tomatoes += 1 # Line of code to edit below: if tom...
6cb9052bf3cd2900aa6f839cef5e034b7ffdc738
MartianInStardust/PathFindingVisualizer
/test.py
7,579
3.5625
4
import pygame as pg from pygame.locals import * import time from Node import Node from Grid import Grid from NodeList import NodeList def solve(grid,showSteps=True): paused = False operations = 0 av = (0,3,4,5) clock = pg.time.Clock() openList = NodeList() closedList = NodeList() board = gr...
4a5d541fbd1a49af33bbad6c5a9beed0f5237ceb
ursu1964/Libro2-python
/Cap4/Programa 4_18.py
1,425
3.8125
4
# -*- coding: utf-8 -*- """ @author: guardati Problema 4.21 Prueba las funciones que suman los elementos de las diagonales principal y secundaria del módulo matrices. """ import matrices filas = int(input('\nIngrese total de filas: ')) columnas = int(input('Ingrese total de columnas: ')) print('\nIngrese ...
0e460051e4da57fc57d718d2fe5a74246fc1ae48
BauyrzhanAzimkhanov/WebDevelopment
/lab7/First part/codingbat/Warmup-2/last2.py
249
3.734375
4
def last2(string): if(len(string) < 2): return 0 last2 = string[len(string)-2:] count = 0 for i in range(len(string)-2): sub = string[i:i+2] if(sub == last2): count = count + 1 return count
23b152416a1264bda1ab7ac25e28094098adaac2
olliesguy/Machine-Learning
/Neural Networks/3layerRN-NNalt.py
3,748
3.8125
4
from numpy import exp, array, random, dot class NeuronLayer(): def __init__(self, number_of_neurons, numbers_of_inputs_per_neuron): self.synpatic_weights = 2 * random.random((numbers_of_inputs_per_neuron, number_of_neurons)) class NeuralNetwork(): def __init__(self, l1, l2): self.l1 = l1 ...
32fc1ad2276a82e2d4a9c5f1fd2269a56ddd61bc
ItsMeVArun5/Hakerrank
/problem_solving/viralAdvertising.py
730
3.953125
4
#!/bin/python3 import math import os import random import re import sys # Complete the viralAdvertising function below. def viralAdvertising(days): """ Inputs: days - Total number of days Output: return the cumulative number of likes at the end of the last day. """ cumulat...
374a88bf86a9e994bb7088959d49ede8818ebe26
arnabs542/achked
/python3/graphs/practice/snake_ladder.py
1,366
3.84375
4
#!/usr/bin/env python3 def snake_ladder(board_sz, moves_list): # makes moves 0 based. Incoming moves is 1 based moves = [0] * len(moves_list) for i in range(len(moves_list)): moves[i] = moves_list[i] if moves[i] != -1: moves[i] -= 1 return _snake_ladder(board_sz, moves...
ae29c4b5ddcb2b384f4dd04aa1c5a0cec75990f2
ninjaco1/JR-Design-HyperRail
/Parser/gcodeDraw.py
3,420
3.5625
4
import turtle import math import tkinter # canvas root = tkinter.Tk() root.geometry('500x500-5+40') #added by me cv = turtle.ScrolledCanvas(root, width=1920, height=1000) cv.pack() # screen size screen = turtle.TurtleScreen(cv) screen.screensize(20000,20000) # Initialize pen and variables pen = t...
438960a531ecefcee9a976851a2541e25769f7d2
zackstout/prime-number-gaps
/index.py
1,332
4
4
import matplotlib.pyplot as plt from matplotlib import style import numpy as np style.use('ggplot') # Riiight we need 1 for the unique case between 2 and 3. freqObject = {1: 0} freqs = [] freqsOfFreqs = [] primes = [] differences = []; def isPrime(n): # Range goes from bottom to one less than top: for i i...
8bab96ac11fe3d946a3aa58637c6609dbfb8ac16
Aasthaengg/IBMdataset
/Python_codes/p03556/s548317205.py
70
3.609375
4
n = int(input()) x = 0 while (x+1) * (x+1)<= n: x += 1 print(x*x)
9caba39d4ee9df48e75b4dfceb85774fbdd80e43
bakunobu/exercise
/1400_basic_tasks/chap_7/7_84.py
290
3.671875
4
from main_funcs import get_input def count_pos(n:int, p:int=5) -> bool: pos_count = 0 for _ in range(n): a = get_input('Введите число: ', False) if a >= 0: pos_count += 1 if pos_count > p: break print(pos_count <= p)
a660dcb770778a5fad286852003cd0bc5e833acd
jkunciene/DB_PYcharm
/database/database.py
8,632
3.84375
4
import sqlite3 import pprint from books_publishers import book from books_publishers import publisher def execute_query(db_name, query, entry): connection = sqlite3.connect(db_name) connection_cursor = connection.cursor() connection_cursor.execute(query, entry) connection.commit() connection.close...
88f7e989370483f8cf9d0d353450ab377677f14f
sirsarr/-365DoC
/Day9/ex15v2.py
355
3.65625
4
#Exercise 15 Version 2 -- Reading files PTHW #Passage du nom du fichier par l'utilisateur. #Prompting print("Salut, veuillez entrer le nom du fichier que vous voulez ouvrir.") #Getting the file's name filename = input("> ") #Opening the file content = open(filename) #Affichage du contenu du fichier print(content.re...
58e9e223d8257ebff4dfc40dbcfe2482a18f82f4
Fredocg012/Programas_codigo
/Python/EDA2_scripts/Practica 1/16_EDAII_2018II_CODE2.py
679
3.78125
4
import time def bubbleSort2(A): bandera=True pasada=0 while pasada<len(A)-1 and bandera: bandera=False #Se cambia a falso, si no se hace ningun cambio dara por hecho que esta ordenado for j in range(len(A)-1): #Numero de comparaciones if(A[j]>A[j+1]): bandera=True #Si hace por lo menos un cambio o permut...
de76f840e37a725be8e8269d4e7becf315da8735
Super-Louis/key2offer
/chapter6/tree_depth.py
1,921
3.90625
4
# -*- coding: utf-8 -*- # Author : Super~Super # FileName: tree_depth.py # Python : python3.6 # Time : 19-1-30 11:26 # 面试题55:二叉树的深度 """ 题目一:二叉树的深度 输入一颗二叉树的根节点,求该树的深度。 从根节点到叶节点依次经过的节点(含根、叶节点) 形成树的一条路径,最长路径的长度为树的深度 """ def tree_depth(tree): if not tree: return 0 left = tree_depth(tree.left) righ...
8c1bb742acd310d4c8b604f53442f656080fa0bb
NinoYaal/LeetCode
/venv/src/solution剑指offer62.py
699
3.828125
4
# -*- coding: utf-8 -*-# # ------------------------------------------------------------------------------- # Name: 圆圈中最后剩下的数字 # Author: Nino # Date: 2020/11/2 # Note: # ------------------------------------------------------------------------------- class Solution: def lastRemaining(self, n, m...
0f555420d0c98c952950603c838e88df82a0550d
desenvolvefacil/SSC0800-2019-02-Introducao-a-Ciencia-de-Computao-I
/SSC0800 (2019-02) - Introdução à Ciência de Computação I/EX 057 - Lista 8 - Arquivos - Estatística Texto.py
1,181
3.65625
4
class Pessoa(object): __nome:str __sexo:str __idade:int def __init__(self,nome,sexo,idade): self.__nome = nome self.__sexo = sexo self.__idade = int(idade) def getNome(self): return self.__nome def getSexo(self): return self.__sexo def getIdade(sel...
f1d159a4f3c5d77c00cc9021d4887cada2634f28
BenGoodwin25/L3-Work
/secu/break/caesar_break.py
1,099
3.609375
4
#! /usr/bin/python3.5 import sys,os #Fonction def creatingAlphaDict(): dico=dict() dico={'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0} return dico def gettingMostUsedLetter(dico): i=0 fo...
270cd6071ff1d040857c1b799946f07b059160ca
Hessah95/python
/functions_task.py
1,753
4.4375
4
# Age Calcolator ;) from datetime import date def check_birthdate (year, month, day) : if today > In_Date : # the given birthdate is in the past return True elif today < In_Date : # the given birthdate is in the future return False def calculate_age (year, month, day) : Years = today.year - In_Dat...
b36e693c3a0a6ac43d909a40a173621309dfa2ae
zhaoyingx/Data-Structure-and-Algorithm
/sort/quickSort.py
757
3.84375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- def getMiddleIndex(l, start_index, end_index): flag = l[end_index] i = start_index - 1 for j in range(start_index, end_index): if l[j] > flag: pass else: i += 1 temp = l[i] l[i] = l[j] l...
7a233b190cea4d96893564e7d295a0162bc64a37
Hyrschall/Woz-U-Python-Class
/lesson_four/main/Dictionary_Testing.py
797
3.984375
4
user = {'name': 'Andrew', 'email': 'andrew@email.com', 'username': 'andrewUser'} for key in user: # type: str print(key, user[key]) # Activities with Dictionaries people = { 'person1': { 'name': 'Sally Sue', 'city': 'Phoenix' }, 'person2': { 'name': 'Billy Bob', 'city'...
e3dbfd525d6b1c64ea9a58e9fa9b7dbc384764c7
GrethellR/-t06_rodriguez.santamria
/santamaria/multiple06.py
575
3.65625
4
#Programa26: Simular compra de artículos import os #Detectores cant_articulos=0 #INPUT vis OS cant_articulos=int(os.sys.argv[1]) #PROCESSING #Si los artículos comprados <3 (Pagar en efectivo) if (cant_articulos < 3): print("Pagar en efectivo") #Si los artículos comprados es >15 (Pagar en tarjeta) if (cant_articul...
b254f3faa2222ff74d8dae0cc818a2890b00188b
NishantKC/fdb
/ghsjsg.py
208
3.5625
4
file= open("fjjx.txt","r") for i in file: print(i) sentence="hrllo fdzjzdn sdj f rg hr z" print(sentence.split()) print(len(sentence.split())) def greet(name): print("Hello "+ name) greet("Nishant")
afb93a3c0c3b1e4c2f862071bb1f783669fc9e05
KamSle/Python_100daysCourse
/hangman_100.py
1,992
4.21875
4
# 100 days with Python # Hangman game # DAY 7 import random from hangman_arch import stages from hangman_arch import logo from hangman_arch import word_list print(logo) # logo importing from hangman_arch file lives = 6 chosen_word = random.choice(word_list) # word is from the list of words we have in hangman_arc...
b99359d02a52a67d8443520e8120616e1777d6ec
macutko/dissertation_evaluation
/geth_db/create_mass_data.py
604
3.5
4
import csv import random import string import pandas as pd def get_random_string(length): # choose from all lowercase letter letters = string.ascii_lowercase result_str = ''.join(random.choice(letters) for i in range(length)) return result_str data = {} amount = 100 for i in range(amount): guid ...
ba08fea3c66da29393a2af34eaab270e17936c29
sukulmahadik/pluralsightcourses
/Python/Importing Data Python Playbook/03/demos/b-import-pandas.py
3,683
3.546875
4
import pandas as pd # Import data using pandas with read_csv posts_csv = pd.read_csv('posts-100.csv') type(posts_csv) posts_csv posts_csv.head() posts_csv.head(3) # You can get the numpy array from the DataFrame posts_csv.values() type(posts_csv.values()) # Import from a URL remote_file = 'https://raw.githubusercont...
fb8995f4ee17a2ddecb2ca74ca362315f7700592
sangeetha19399/pythonguvipgm
/concat.py
81
3.78125
4
word1,word2=input().split() word1=str(word1) word2=str(word2) print(word1+word2)
9a144f513532cbf6c13c16f396369265cecbc579
errai-/euler
/hundredplus/123/primenoms.py
529
3.640625
4
from collections import OrderedDict from operator import itemgetter primes = [2,3,5,7,11,13] def isprime(num): if num==1: return False elif all(num%i!=0 for i in primes[:primes.index(next(x for x in primes if x>num**0.5))]): return True else: return False for num in range(15,30000...
d690f7477c9484869d5840bb5d0320aaa3af9f58
goncalo-reis/Automate-Boring-Stuff-with-Python
/04. Fantasy Game Inventory.py
874
3.828125
4
inventory = {'rope':1, 'torch':6, 'gold coin':42, 'dagger':1, 'arrow':12} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def displayInventory(inventory): print('Inventory:') total = 0 for key, value in inventory.items(): print(str(value) + ' ' + key) total +=...
751237a50748f8789505db5a5470f527f404c326
316112840/TALLER-DE-HERRAMIENTAS-COMPUTACIONALES
/Clases/Programas/Tarea04/Problema3S.py
474
3.96875
4
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- ''' Marínez García Mariana Yasmin 316112840 Taller de Herramientas Computacionales Problema 3, SOLUCIONES''' import Problema3 Problema3.CeFa(78) Problema3.FaCe(172.4) z = input("¿Quiere transformar de °C a °F?(S/N) ") if z == "S" or z== "s": x = input("Escribe los °C q...
2f99449d3598d876777a98b4f10571b861f2c67f
safonovanastya/sciocomp
/Software_Design_Patterns/stats-variance
235
3.703125
4
#!/usr/bin/python3 import sys numbers = [] for line in sys.stdin: line = float(line) numbers.append(line) mean = sum(numbers) / len(numbers) variance = sum((x - mean) ** 2 for x in numbers) / len(numbers) print(variance)
df11949dff8ce9df435455389573853a0327d934
NishchaySharma/Competitve-Programming
/Codechef/Chef and Feedback.py
144
3.734375
4
t=int(input()) for test in range(t): s=input() if '101' in s or '010' in s: print('Good') else: print('Bad')