blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
2bc1e9b1515837d057d6d33161ed769dab007c2c
league-python-student/level0-module1-DemirKaya7
/_03_if_else/_3_secret_message_box/secret_message_box.py
510
3.671875
4
from tkinter import messagebox, simpledialog, Tk if __name__ == '__main__': window = Tk() window.withdraw() password = "eee" secretMessage = simpledialog.askstring(title="Enter a secret message", prompt="Secret message = ") guess = simpledialog.askstring(title="Guess the password", prompt="Pass...
e3e8751bca8a99b27ba80a97c20c9640869f4ad9
league-python-student/level0-module1-DemirKaya7
/_05_for_loops/_1_my_ages/my_ages.py
98
3.5
4
for i in range(16): print("In the year " + str(2004 + i) + ", I was " + str(i) + " years old")
6eb31d6a7cdd0a50bbefe7c66b3f80f6871b3c35
Ajinkya2010/Python-Coding
/RockPaperScissor/RockPaperScissor.py
3,161
3.5
4
import random import tkinter as tk from tkinter import PhotoImage import os from tkinter import * window = tk.Tk() window.geometry("600x800") blank_space =" " # One empty space window.title(40*blank_space+"Rock Paper Scissors") My_Score = 0 Comp_Score = 0 My_Choice = "" Comp_Choice = "" def choice_to_number(choice...
c06135e6937add9b8703252d5d93dc770a69e18a
brijrajsingh/auto-pricepredict-amlworkbench
/linear-regression.py
1,843
3.71875
4
import numpy as np import pandas as pd from sklearn import linear_model from sklearn.cross_validation import train_test_split import pickle from matplotlib import pyplot as plt # Use the Azure Machine Learning data preparation package from azureml.dataprep import package # This call will load the referenced package ...
8ee4a5fc6821d42212dd709cd75e56f82cc07f5f
bella5065/programmers
/Make_a_weird_word.py
287
3.796875
4
'''이상한 문자 만들기''' def solution(s): answer = '' j=0 for i in s: if i == ' ': answer += i j = -1 elif j % 2==0: answer += i.upper() else: answer += i.lower() j +=1 return answer
1aa30bded191b9ee1cf8d540fe6e7b86106942d0
JSmith146/codingDojo_Python
/python/python_stack/_python/python_fundamentals/selectionSort.py
519
3.921875
4
# Implement the selection sort algorithm arr = [4,7,5,6,-2,0,1,-9,3] #Steps: #1. Iterate through the list and find the minimum value #2. Move the minimum value to the beginning of the list #3. Ignore the first position (it is sorted) #4. Repeat steps 1-3 # Set initial conditions for i in range(len(arr)): min_in...
07a77fa662dc86aaa17417a022d1a7b13f760950
scresante/codeeval
/mixedcontent.py3
566
3.53125
4
#!/usr/bin/python3 from sys import argv try: FILE = argv[1] except NameError: FILE = 'tests/115' DATA = open(FILE, 'r').read().splitlines() for line in DATA: if not line: continue els = line.split(',') words = [ e for e in els if e.isalpha() ] nums = [ e for e in els if e.isdigit() ] i...
877fe8b28feadb49c4b071d9d1e26a3796f466cc
scresante/codeeval
/crackFreq.py2
1,676
4.21875
4
#!/usr/bin/python from sys import argv try: FILE = argv[1] except NameError: FILE = 'tests/121' DATA = open(FILE, 'r').read().splitlines() for line in DATA: if not line: continue print line inputText = line #inputText = str(raw_input("Please enter the cipher text to be analysed:")).replace(" ", "...
cc63b19de237dc6446cd1b223c92301e7ae4718f
tchaitanya2288/NewAssignments
/Functions/Num to find in given range.py
199
3.84375
4
#!/user/bin/python def range_num(n): if n in range(1,50): print( "%s is in the range"%str(n)) else : print("%s is outside the given range"%str(n)) range_num(75) range_num(35)
f0b5f940a37acd4ac16a5ab76b9331b57dec7c57
kxhsing/dicts-word-count
/wordcount.py
1,258
4.28125
4
# put your code here. #putting it all in one function #will figure out if they can be broken later def get_word_list(file_name): """Separates words and creates master list of all the words Given a file of text, iterates through that file and puts all the words into a list. """ #empty list to ho...
3dbf48514471a7aaaadf6a5b083100694fe4b55d
Rasoul-neo/guess-the-word-game
/Main_code.py
314
3.921875
4
word ="lion" guess="" guess_count=0 guess_limit=3 out_of_guess=False while guess!=word and not (out_of_guess): if guess_count<guess_limit: guess=input("guess animal name:") guess_count+=1 else: out_of_guess=True if out_of_guess: print("You lose!") else: print("you win!")
7d03f8f9fb47c302912f530c9532fea95142cc7a
ottoguz/My-studies-in-Python
/aula002u.py
436
3.921875
4
#Calculate the final price and hte discount in % price = float(input('Type in the price of the product (R$):')) percentage = float(input('Type in the percentage of discout(%):')) discount = price*(percentage/100) final = price - discount print('The product costs R${:.2f} and the percentage of discount is {:.0f}% \...
7be2c009c62d5ad908258d9b6768e15e4b60fba6
ottoguz/My-studies-in-Python
/ex25b.py
129
3.96875
4
name = str(input('What is your name?')).strip() print('Does your name contain "SILVA"? {}' .format('silva' in name.lower()))
8435abbd08af8e52bf38f4a334a61254fbcb1ff5
ottoguz/My-studies-in-Python
/ex016b.py
101
3.53125
4
from math import trunc fnum = float(input('Type a value:')) int_num = trunc(fnum) print(int_num)
4e9e37db57f014e20bde5806050022a9911a99ed
ottoguz/My-studies-in-Python
/ex018a.py
343
4.34375
4
#Calculate an angle and its Sen/Cos/Tg import math ang = float(input('Type an angle:')) # Used the function math.radians() to turn numbers into radians print('Sine:{:.2f}' .format(math.sin(math.radians(ang)))) print('Cosene:{:.2f}' .format(math.cos(math.radians(ang)))) print('Tangent:{:.2f}'.format(math.tan(math....
c849f9d357a7b50924a329e1cb3b4e45f73fc445
ottoguz/My-studies-in-Python
/aula003h.py
217
4
4
#Exercíse 3.3.1 m1 = float(input('Average 1:')) m2 = float(input('Average 2:')) m3 = float(input('Average 3:')) if m1 >= 7 and m2 >= 7 and m3 >= 7: print('Passed!') else: print('Failed!')
93df2764f6fdcfb101521820aa3be80562e1bc47
ottoguz/My-studies-in-Python
/aula005s.py
816
4.125
4
#Function that receives an integer via keyboard and determines the range(which should comprehend positive numbers) def valid_int(question, min, max): x = int(input(question)) if ((x < min) or (x > max)): x = int(input(question)) return x #Function to calculate the factorial of a given number...
04e8594e3e4ceb9796b71a131a9a538a64116986
aribis369/Trend-Analyzer
/scraper/visualization.py
1,233
3.875
4
# This is a code to visualize the data stored in mongodb using pandas and matplotlib # This visualization code is specific to the movie "Tiger Zinda Hai" # We visualize the rating of the movie as shown on IMDB over the period of time and plot it on a graph # First the data stored is retrieved inside a cursor # Then for...
572a49da66f1ec79810a560b023cde25d42390f1
irfan5d7/LeetCodePython
/328 Odd Even Linked List.py
636
3.875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if head == None or head.next == None: return head ...
7f38278fbc3b39c7696dbc8342e7680d5c1ebb22
irfan5d7/LeetCodePython
/1669 Merge In Between Linked Lists.py
664
3.9375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: bTail = list2 while bTail.next: b...
6ae077f7d4e28cfdec2f757606f6d8b7924dee21
bartoszkruba/advent_of_code_2020
/day_6/main.py
1,067
3.65625
4
from string import ascii_lowercase with open('puzzle_inputs.txt') as f: inputs = [line.replace('\n', '') for line in f] def parse_forms(inputs): forms = [] form = {letter: 0 for letter in ascii_lowercase} form['total'] = 0 for input in inputs: if len(input) == 0: forms.append...
5dcf2a3551b1d40772f84512db78ebb2af1be2de
ActiveZ/cnam-monopoly
/prison.py
2,422
3.71875
4
from random import randint class Prison: def libere(self,j,carte_chance,carte_communaute): j.tour_prison += 1 if j.tour_prison == 3: # sortie de prison au 3ème tour print(j.nom,": 3ème tour, vous êtes libéré de prison") self._lance_de(j) ...
9708373e2ea5625d13d22d74fd8fa64b07471755
EzequielRomio/truco
/game_system.py
1,094
3.515625
4
envido_scores = { 'envido': 2, 'real envido': 3, } envido_order = ( 'envido', 'real envido', 'falta envido' ) truco_scores = { 'truco': 2, 'retruco': 3, 'vale cuatro': 4 } def falta_envido_result(looser_score): if looser_score < 15: return 30 else: return 30 - looser_score def truco_result(p1_card, ...
f95a00ba4d685cfdd5683e5b34d47d98c80b6509
natTP/2110101-comp-prog
/02_StringList/0202-ArabicNum.py
122
3.578125
4
n = ["zero","one","two","three","four","five","six","seven","eight","nine","ten"] i = int(input()) print(i," --> ",n[i])
c67344bd4f0f9d1e6234fa38246093c7d776bfc2
natTP/2110101-comp-prog
/07_Files/0731-DNA.py
846
3.75
4
dna = input().strip().upper() q = input() valid = True for c in dna: if c not in "ATCG": print("Invalid DNA") valid = False break if valid: if q == 'R': r_dna = "" for c in dna: if c == 'A': r_dna += 'T' elif c == ...
a4a9e9a64d0d0ee540b51239ae07a3fda3a49b20
natTP/2110101-comp-prog
/03_IfElse/03001-Median5.py
376
3.609375
4
a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) if a>b: t = a a = b b = t if c>d: t = c c = d d = t if a>c: t = b b = d d = t c = a a = e if a>b: t = a a = b b = t if c>a: t = b b = d d = ...
cf727974674f203df4d1bdd54c1e02acc50c097a
natTP/2110101-comp-prog
/07_Files/0733-FileMerge.py
1,528
3.546875
4
def read_next(f): while True: t = f.readline() if len(t) == 0: # ถ้าอ่านหมดแล้ว ออกจากวงวน break x = t.strip().split() # ลบ blank ซ้ายขวา if len(x) == 2: # แยกแล้วได้ 2 ส่วน --> ถูกต้อง ก็คืนผล return x[0], x[1] return "", "" # แฟ้มหมดแล้ว คืนสตริง...
11d77261be4fd32d5320c1447729be0635ddac89
natTP/2110101-comp-prog
/P1_Q1Prep/p102-RLE.py
583
3.578125
4
instruction = input() if instruction == "str2RLE": inp = input() previous = inp[0] encode = str(inp[0]) + " " cnt = 1 for ch in inp[1:]: if ch != previous: encode += str(cnt) + " " encode += ch + " " cnt = 1 else: cnt += 1...
b0e8ae2af1b568741d1c68f7463e29fd3ce3b299
slouchart/pypermute
/pypermute/__init__.py
17,423
3.625
4
__version__ = '0.1.1' __author__ = 'Sébastien Louchart:sebastien.louchart@gmail.com' __all__ = ['Permutation', 'PermutationBuilderError', 'PermutationStructuralError'] import random from typing import Any, Tuple, Union, Dict, Iterator, Sequence, Optional Cycle = Sequence[int] Representation = Optional[Sequence[Cycl...
5b928f4d9cfdd6bb4bcbca0500ffbdd6ac40c2c5
NinjaCodes119/PythonBasics
/basics.py
915
4.125
4
student_grades = [9, 8, 7 ] #List Example mySum = sum(student_grades) length = len(student_grades) mean = mySum / length print("Average=",mean) max_value = max(student_grades) print("Max Value=",max_value) print(student_grades.count(8)) #capitalize letter text1 = "This Text should be in capital" print(text1.upper())...
336c27bc6ace45ace941c6d7358a10035e94f5bf
rongqinglee/statemachinegenerator
/nusmv/model.py
1,747
3.6875
4
class Replacement: """Class is designed to store replacement information of the verification template such as module name, tag and range""" def __init__(self, module_name, tag, origin, length): if type(module_name) != str: raise TypeError("Expected string type for module_name") ...
0b1281fa76e4379219ec2637d53c94412547b52b
jemcghee3/ThinkPython
/05_14_exercise_2.py
970
4.375
4
"""Exercise 2 Fermat’s Last Theorem says that there are no positive integers a, b, and c such that an + bn = cn for any values of n greater than 2. Write a function named check_fermat that takes four parameters—a, b, c and n—and checks to see if Fermat’s theorem holds. If n is greater than 2 and an + bn = cn...
32ebb0dcbf831f71f2e24e72f38fdb3cb7af8fc1
jemcghee3/ThinkPython
/05_14_exercise_1.py
792
4.25
4
"""Exercise 1 The time module provides a function, also named time, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970. Write a script that reads the current time and converts it to a time of day in hours, mi...
8802e6c329edeac3b597edc61df1d82e7bacdf0c
jemcghee3/ThinkPython
/10_15_exercise_07.py
723
3.96875
4
"""Exercise 7 Write a function called has_duplicates that takes a list and returns True if there is any element that appears more than once. It should not modify the original list.""" def has_duplicates(input_list): # this function will consider 1 and 1.0 as duplicates for item in input_list: t = input_...
4beaf5482d4fe8a76d30bb5548ae33192d33f19b
jemcghee3/ThinkPython
/09_02_exercise_4.py
672
4.125
4
"""Exercise 4 Write a function named uses_only that takes a word and a string of letters, and that returns True if the word contains only letters in the list. Can you make a sentence using only the letters acefhlo? Other than “Hoe alfalfa”?""" def letter_checker(c, letters): for l in letters: if c == l: ...
fa53edb7fa96c64310f584cd9d7af86b0cc9ec24
jemcghee3/ThinkPython
/08_03_exercise_1.py
255
4.25
4
"""As an exercise, write a function that takes a string as an argument and displays the letters backward, one per line.""" def reverse(string): l = len(string) i = -1 while abs(i) <= l: print(string[i]) i -= 1 reverse('test')
2e55f9920fcf976b3027a7abf4bc175752fe2ec1
jemcghee3/ThinkPython
/10_15_exercise_02.py
682
4.28125
4
"""Exercise 2 Write a function called cumsum that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i+1 elements from the original list. For example: >>t = [1, 2, 3] >>cumsum(t) [1, 3, 6] """ def sum_so_far(input_list, n): # n is the number of i...
7d832e6a251f1d4a1abd229eb3ea409f76f2f164
jemcghee3/ThinkPython
/08_13_exercise_5.py
2,356
4.1875
4
"""Exercise 5 A Caesar cypher is a weak form of encryption that involves “rotating” each letter by a fixed number of places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so ’A’ rotated by 3 is ’D’ and ’Z’ rotated by 1 is ’A’. To rotate a word, rotate each l...
17df7ec92955ee72078b556e124938f1531f298a
jemcghee3/ThinkPython
/11_10_exercise_03.py
1,535
4.5
4
"""Exercise 3 Memoize the Ackermann function from Exercise 2 and see if memoization makes it possible to evaluate the function with bigger arguments. Hint: no. Solution: http://thinkpython2.com/code/ackermann_memo.py. The Ackermann function, A(m, n), is defined: A(m, n) = n+1 if m = 0 A(m−1,...
7e90113bc6bd97d3d3728d2527698e0e26b159a2
shiva111993/python_exercises
/set_code.py
2,213
4.1875
4
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. # myset = {"apple", "ball", "cat", "dag", "elephate"} # print(myset) # myset.add("fan") # print(myset) # myset.add("apple") # print(myset) # ---------removing # myset.remove("ball") # print(mys...
b359850fd64a7df22f24029afd4262e331c43f8c
adithm/pythonbatch11
/root.py
322
3.796875
4
def root(a, b, c): sq = b * b - 4 * a * c if sq < 0: r1 = str(pow(abs(b * b - 4 * a * c), 0.5)) + 'i' r2 = -b / 2 * a return str(r2) + ' + ' + r1, str(r2) + ' - ' + r1 else: return (-b + pow(b * b - 4 * a * c, 0.5)) / (2 * a), (-b - pow(b * b - 4 * a * c, 0.5)) / (2 * a) print root(2, 3, ...
d3faa51d5381da6458d9687c1c6ef759da489fb6
terry960302/Python-Algorithms
/스터디 7.14/프로그래머스 레벨3 과제_2_멀리뛰기.py
690
3.78125
4
#프로그래머스 레벨3 '멀리뛰기' 문제 from math import factorial as fac #팩토리얼 모듈 def combination(a,b): #조합(콤비네이션) 함수 return fac(int(a))/fac(int(b))/fac(int(a)-int(b)) def solution(n): sum=0 for i in range(0, (n//2)+1): sum+=combination(n-i,i) return int(sum)%1234567 #main n=1700 print(solution(n)) #n=6(짝수...
884be148595f948ce7651f742ec6d3b5c1434b16
terry960302/Python-Algorithms
/스터디 7.21/프로그래머스 레벨3 '거스름돈' - 복사본.py
400
3.5
4
#프로그래머스 레벨3 '거스름돈' 풀기1 def solution(n, money): sum=0 if 1 in money: for i in money: if n//i==n: n//i=1 sum+=n//i return sum #main n=5 money=[1,2,5] print(solution(n, money)) [1,1,1,1,1] [1,1,1,2] [1,2,2] [5] 7, [1,2,3] [1,1,1,1,1,1,1] [1,1,1...
75d9b44e0d6b8bff54933371ec8cab2699887dcd
terry960302/Python-Algorithms
/컴퓨터코딩및응용/실습문제/실습6/실습6_2.py
252
3.9375
4
#실습문제 6번-2번 words = ['hundred', 'school', 'theater', 'python'] longest_w=words[0] for w in words: if len(longest_w)<len(w): longest_w=w print('longest word: {}'.format(longest_w)) print('length: {}'.format(len(longest_w)))
d5814077f9f2bd78b6dd3779535fe6c682a03c7d
terry960302/Python-Algorithms
/컴퓨터코딩및응용/실습문제/실습9/실습9_2.py
538
3.609375
4
#실습문제 9번-2번 def CtoF(c): f=(9/5*c)+32 return f def FtoC(f): c=(f-32)*5/9 return c #main choice=input('선택 ---> ') if choice=='c' or choice=='C': C=int(input('섭씨 온도를 입력하십시오: ')) print('섭씨 {:5.2f}도는 화씨 {:5.2f}도입니다.'.format(C, CtoF(C))) elif choice=='f' or choice=='F': F=int(input('화씨 온도를 입...
b16d263b61720a0b4cccbcc5fded191daa14d280
terry960302/Python-Algorithms
/컴퓨터코딩및응용/연습문제/연습문제_1-1.py
671
3.578125
4
#연습문제 1번 f=open('airport.txt') D={} for line in f: line=line.split() D[tuple(line[:3])]=int(line[3]) #여기까지 사전으로 만들기 완료(아마 계속 텍스트 불러오는게 귀찮아서 그런듯) print('*** Category : city ***') print() city={} for w in D: if w[1] not in city: city[w[1]]=D[w] else: city[w[1]]+=D[w] for m, n in cit...
2a270664ddc77cdb55e9abdc8e40c4da33ff7d93
terry960302/Python-Algorithms
/컴퓨터코딩및응용/2차과제/H2_2017650009_1.py
995
3.578125
4
#중국어문화학과 2017650009 김태완 n=int(input('n: ')) if n<=0: print('양수를 입력하세요.') #입력값이 0이거나 그 이하이면 양수입력 elif n==1: #입력값이 1이면 소수가 아님 print(n, '는 소수가 아닙니다.') else: a=1 #약수는 1부터 대입 while a<=n: a+=1 #1씩 차례대로 증가 if n%a==0: ...
4684960e8637485279afdb1d5b9a7225f8db4a6d
plt3/matrix-class
/matrix.py
14,650
3.734375
4
from copy import deepcopy # Mat class creates matrix objects from a list of lists, defines: # matrix addition, subtraction, multiplication, scalar multiplication, # transpose, row-echelon form (REF), reduced row-echelon form (RREF), # inverse, determinant, and lets user input matrix values quickly using # Mat.from_in...
6c463adbd86c53f3a17f58f960d6932134f29783
emaustin/Change-Calculator
/Change-Calculator.py
2,259
4.125
4
def totalpaid(cost,paid): #Checking to ensure that the values entered are numerical. Converts them to float numbers if so. try: cost = float(cost) paid = float(paid) #check to ensure the amount paid is greater than the cost except: print("Please enter in a number value...
ec3430a6006e297063bd4badf351db36cd7bd75f
krishnareddyakkala/python-practices
/asynchronous/asyncio_generator.py
3,065
3.625
4
''' Up until python 3.3 this really was the best you could do. In order to do better you need more language support. In order to do better, Python would need some way to execute a method partially, halting execution, and maintain stack objects and exceptions throughout. If you’re familiar with Python concepts, you mi...
18dbd776ff100c2d0f4222fa3bee4dd0ba3783e8
naqveez/assignment2
/assignment2.py
501
3.546875
4
import random as r arr = [] for i in range(50): arr.append(r.randint(1,1000)) print(arr) exercise = arr[0] k = 0 for j in range(0, len(arr) ,1): if exercise > arr[j] : exercise = arr[j] k = j print("Min :", exercise, " index : ", k) for j in range(0, len(arr), 1): if exercise < arr[j]: ...
57d7213a906f538913eca31479663e842e2d0596
romulovieira777/Curso_Rapido_de_Python_3
/Seção 05 - Tuplas/tuplas.py
375
3.625
4
# Criando uma Tupla nomes = ('Ana', 'Bia', 'Gui', 'Ana') print(type(nomes)) print(nomes) # Para saber se um Nome está na Tupla print('Bia' in nomes) # Buscando um Dado Específico na Tupla print(nomes[0]) # Acessando mais de um Dado na Tupla print(nomes[1:3]) print(nomes[1:-1]) print(nomes[2:]) print(nomes[:-2]) ...
c674750f830792e233e5cb6cd0b7202dce23fddd
romulovieira777/Curso_Rapido_de_Python_3
/Seção 02 - Variáveis/variaveis.py
501
4.1875
4
# Definindo uma variável int e float a = 3 b = 4.4 print(a + b) # Definindo uma variável de texto texto = 'Sua idade é... ' idade = 23 print(texto + str(idade)) print(f'{texto} {idade}!') # Imprimindo string print(3 * 'Bom Dia! ') # Criando uma Interação com o Usuário pi = 3.14 raio = float(input('Informe o raio...
265dd483dd33f8997bcc776326dd3e0af3b71747
omaralaniz/Learning
/Learning Coding Challenges/PairOfSocks/Python/pair_of_socks.py
544
3.5
4
import math import os import random import re import sys def sockMerchant(n, ar): count = 0 value = 0 dumm = {} for sock in ar: if (sock in dumm): value = dumm.get(sock) dumm[sock] = sock + 1 else: dumm[sock] = 1 for sock in dumm: value = int(dumm.get(sock))...
d088ea607f59a028b6a045017de1d6182cb7820f
JunLeecus/Image-Stitch
/py/shrink_to_25.py
560
3.75
4
# -*- coding: utf-8 -*- """ Created on 2020-05-07 11:57:29 @Author: xxx @Version : 1 """ import os from PIL import Image def main(): while 1: file = input("input image path or drag image here:\n") try: image = Image.open(file) x, y = image.size image = image.re...
e207454150bb4b3864d983e2312be810eb41f7e2
mattfisc/cs240
/HW14program2inversion_recursion.py
1,135
3.953125
4
# merge two arrays in order def mergeInversion(a,b,count): c = [] #merge arrays while (len(a) > 0 or len(b) > 0): # if b is empty if len(b) <= 0: count += len(a) c.append(a.pop(0)) # if a is empty elif len(a) <= 0: count += len(a) ...
9ffa232cb7be6780c62bab3e12e3ef7cfc5dda5e
mattfisc/cs240
/addBinary.py
547
3.65625
4
def sumBinary(x,y): # x is longer if len(x) < len(y): x,y = y,x sum = 0 for i in range(len(x)-1,-1,-1): sum += x[i] + y[i] # remainder if sum > 1: x[i] = sum % 2 sum /= 2 # no remainder else: x[i] = sum % 2 ...
60e935d1878bde5c5ef92449d4127222dd4f2b59
mattfisc/cs240
/findMax.py
361
3.8125
4
def findMax(a): n = len(a) if n <= 1: return a[0] else: return max(findMax(a[1:]),a[0]) def findMaxR(a): n = len(a) middle = n/2 print(a[:middle],a[middle:]) if n <= 1: return a[0] else: return max(findMaxR(a[:middle]), findMaxR(a[middle:])) a = [1,2...
5c8af61748085a7bf39a1a6dea1a134a8843005e
mattfisc/cs240
/HW6program3_binary_to_decimal.py
598
4.15625
4
def binary_to_decimal(x): num = 0 twoPower = 1 for i in range(len(x)-1,-1,-1): num += x[i] * (2**twoPower) twoPower += 1 return num def compare_two_binary(binary1,binary2): b1 = binary_to_decimal(binary1) b2 = binary_to_decimal(binary2) if b1 > b2: return binary1, "...
510b9880ae688e30a21b304e4b9be3fc4e25c23e
mattfisc/cs240
/binary_greater_or_less.py
242
3.78125
4
def compare(a,b): for i in range(len(a)): if a[i] > b[i]: return "A is greater" elif b[i] > a[i]: return "B is greater" return "A is equal to B" a = [1,0,0,0] b = [1,0,0,1] print(compare(a,b))
cd736e4f096527ed9a012f7cb8e44b0c93f9d4df
eNobreg/holbertonschool-interview
/0x19-making_change/0-making_change.py
523
4.40625
4
#!/usr/bin/python3 """ Module for making change function """ def makeChange(coins, total): """ Making change function coins: List of coin values total: Total coins to meet Return: The lowest amount of coins to make total or -1 """ count = 0 if total <= 0: return 0 coi...
38081781cdc2550eeb3448fd23404c88e248b719
manuellah/bc-9-TDD
/sum/super_sum/super_sum_test.py
1,020
3.671875
4
import unittest from super_sum import super_sum class MySuperSumTest(unittest.TestCase): def test_empty_list(self): self.assertEqual(super_sum(), "empty tuple") def test_sum_of_numbers(self): self.assertEqual(super_sum(10, -20), -10) self.assertEqual(super_sum(10, 15), 25) ...
cfb9873cbbe384f9c065b1e68ddf14e3dad27d81
OlgaKosm/it-academy-bps
/src/count.py
203
3.96875
4
print('enter numbers:') list = input() list2 = [] for i in list: if list.count(i) >= 2: if list2.__contains__(i): continue else: list2.append(i) print(list2)
209f889004cb33e43327162f502e69e00a673887
ShebnaMathew/Align-Adventure
/Terminal Based/Game.py
12,508
3.8125
4
''' CS5001 Fall 2019 Homework 7 Shebna Mathew Game class Menu function ''' from room import * import pickle def menu(options): ''' Reusing lab menu function Input: list containing the list of options Returns: user choice Does: loops through the option list and displays it to the user and the...
817e99c28b85e23803b02891daff41e65391f329
JhordanRojas/t09_Rojas.Linares
/Rojas/app_11.py
177
3.5625
4
#11. Funcion que calcula el volumen de un cubo import os import library lado=os.sys.argv[1] elevn=library.vol_cube(lado) print("el volumen del cubo de lado",lado,"es:",elevn)
7a5e3ccc07584c6eabddc2963aae03ccd7335e7c
JhordanRojas/t09_Rojas.Linares
/Rojas/app_19.py
196
3.609375
4
#19. Funcion multiplicar 3 numeros import os import library n1=os.sys.argv[1] n2=os.sys.argv[2] n3=os.sys.argv[3] multi=library.mult_3(n1,n2,n3) print("el valor de la multiplicacion es:",multi)
17447ed8335f43bf9cbe81d090a056c6477d1dbf
JhordanRojas/t09_Rojas.Linares
/Rojas/app_7.py
206
3.671875
4
#7. Funcion que pide un nombre import os import library nombre=os.sys.argv[1] seve=library.valid_nombre(nombre) if seve==True: print("El nombre es ", seve) else: print(seve," no es un nombre")
b9b329934dc1865548940c95d89b3d6a1052f4a5
nikithapk/coding-tasks-masec
/fear-of-luck.py
423
4.34375
4
import datetime def has_saturday_eight(month, year): """Function to check if 8th day of a given month and year is Friday Args: month: int, month number year: int, year Returns: Boolean """ return True if datetime.date(year, month, 8).weekday() == 5 else False # Test cases prin...
1233f7474b05687ad28c7daa33efe5f0215c3517
mfbx9da4/mfbx9da4.github.io
/algorithms/16.5_factorial_zeroes_.py
422
3.71875
4
factorials = [1,2] def factorial(n): if len(factorials) > n: return factorials[n - 1] for i in range(len(factorials), n + 1): factorials.append((i + 1) * factorials[i - 1]) return factorials[n - 1] factorial(30) def num_zeros(x): string = str(x) count = 0 c = -1 while string[c] == '0': cou...
f13d82e4783cd64d886f3bfbd62f3f704d81a2c5
mfbx9da4/mfbx9da4.github.io
/algorithms/codeforces/non_zero/main.py
1,829
3.875
4
""" A. Non-zero time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard output Guy-Manuel and Thomas have an array 𝑎 of 𝑛 integers [𝑎1,𝑎2,…,𝑎𝑛]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index 𝑖 (1≤𝑖≤𝑛) an...
4af1334372a87cfde770924d209a1b5afc55a6de
mfbx9da4/mfbx9da4.github.io
/algorithms/knapsack.py
977
3.515625
4
def solve(items, total_weight): # for incremental values of calories, # what is the cheapest price + nutrients combination? # maybe do linear programming on the price + nutrients? memoized = [0 for x in range(total_weight + 1)] for item in items: weight, value = item print('weight, value', weight, va...
c886b5e680fbd1696033f10bb5dfc2ad44dc4a37
mfbx9da4/mfbx9da4.github.io
/algorithms/codeforces/string_palindromes/main.py
781
3.78125
4
""" """ def int_as_array(num): return list(map(int, [y for y in str(num)])) def array_as_int(arr): return int(''.join(map(str, arr))) def read_int(): return int(input()) def read_array(): return list(map(int, input().split(' '))) def array_to_string(arr, sep=' '): return sep.join(map(str, arr)) def matrix_t...
c5e2ac49b7fc208c40d4ed60d1acc70297eb2bc6
mfbx9da4/mfbx9da4.github.io
/algorithms/codeforces/banned_k/main.py
1,176
3.828125
4
""" """ from math import factorial from collections import defaultdict def int_as_array(num): return list(map(int, [y for y in str(num)])) def array_as_int(arr): return int(''.join(map(str, arr))) def read_int(): return int(input()) def read_array(): return list(map(int, input().split(' '))) def array_to_stri...
80b3330fde03f92ef3f65eda32060040138dd440
mfbx9da4/mfbx9da4.github.io
/algorithms/treasure_grid_game.py
5,681
3.78125
4
import pprint # Cruise Interview # treasure finding cave # 2d board = array of arrays => chars # num rows, num cols # treasure position (row, col) # all positions hidden, player reveals positions # player starts where he wants # betting site, find treasure on board # moves to next user HOTTER = 0 COLDER = 1 YAY = 2 ...
0b265f449f3029f1748134ac1df2fd8ce93a6579
mfbx9da4/mfbx9da4.github.io
/algorithms/codeforces/longest_pallindrome/main.py
1,873
3.609375
4
""" """ from collections import defaultdict def int_as_array(num): return list(map(int, [y for y in str(num)])) def array_as_int(arr): return int(''.join(map(str, arr))) def read_int(): return int(input()) def read_int_array(): return list(map(int, input().split(' '))) def int_array_to_string(arr, sep=' '): r...
a49b7c9e042179ba40a37926eaa98ceca3c3fdff
mfbx9da4/mfbx9da4.github.io
/algorithms/codeforces/coffee/main.py
587
3.859375
4
""" """ def int_as_array(num): return list(map(int, [y for y in str(num)])) def array_as_int(arr): return int(''.join(map(str, arr))) def read_int(): return int(input()) def read_array(): return list(map(int, input().split(' '))) def array_to_string(arr, sep=' '): return sep.join(map(str, arr)) def matrix_t...
4124282950991ddd3aea1e6bbf69e74c4e31dc6b
mfbx9da4/mfbx9da4.github.io
/algorithms/longes_valid_parentheses.py
1,349
3.5
4
def solve(s: str): i = 0 best_length = 0 while i < len(s): i = consume_invalid(s, i) i, length = consume_valid_section(s, i) best_length = max(best_length, length) i += 1 return best_length def consume_invalid(s, i): while i < len(s) and s[i] == ')': i += 1 ...
ee38d61cb51e1da273a2d8323face14bcd877fa3
anantpbhat/Python
/discounts.py
1,702
3.625
4
import re def quitnow(x): if x == "quit": print("Quiting at users request...") exit(0) exit(1) def ifstudent(x, y): ins = input("Are you a Student (y/n/q): ") if qy.search(ins): x += 0.1 y = " Student" return x, y elif qn.search(ins): return x, y ...
4c994f2caa7c78cef754355bbe00cf2b08665283
arubino322/Learn_Python_the_Hard_Way
/ex6.py
835
3.984375
4
#declaring x var, formatted to pull a variable x = "There are %d types of people" % 10 #binary and do_not are sre string variables binary = "binary" do_not = "don't" #y var is a string formatted to pull in other strings y = "Those who know %s and those who %s" % (binary, do_not) #printing them print x print y #%r put...
6d9846e6fb66d29761765d2af32bf139cf011320
arubino322/Learn_Python_the_Hard_Way
/ex40.py
1,032
3.921875
4
class Song(object): def __init__(self, lyrics, band): self.lyrics = lyrics self.band = band def sing_me_a_song(self, band): for line in self.lyrics: print line print "by " + self.band #This would create the first INSTANCE object of the Song class happy_bday = Song(["\nHappy birthday to you", "I don...
36c366b51c6f1b152ffdc513378bb6b310cdbfe4
jlopezh/PythonLearning
/co/com/test/DefaultValue.py
407
4.03125
4
"""Define a new function with default arguments using mutable and inmutable""" def f(a, inmutable="Hola ", mutable=[], castMutableOnInmutable=None): inmutable + a mutable.append(a) if castMutableOnInmutable is None: castMutableOnInmutable = [] castMutableOnInmutable.append(a) print(inmutable...
59393e10485dac53cf1538b79c9dc3f04c47bc07
rippedstrings/CP320-Exploration-Project
/Keypad_Class.py
1,129
3.5
4
import RPi.GPIO as GPIO import time HALF_BIT_TIME = 0.001 CHARACTER_DELAY = 5 * HALF_BIT_TIME NUM_BITS = 16 class Keypad(): def __init__(self, pin_scl, pin_sdo, pin_mode=GPIO.BCM): self.pin_scl = pin_scl self.pin_sdo = pin_sdo GPIO.setmode(pin_mode) GPIO.setup(pin_scl, GPIO.OUT) ...
3827f6116cb68c34aae886051b5dc99f02466206
Gabriel-Mbugua/Coding-Questions
/Python/SumOfOddNumbers/solution.py
271
3.765625
4
#my solution def row_sum_odd_numbers(n): lst = [] for i in range(n*(n-1), n * (n + 2)): if len(lst) < n and i % 2 != 0 : lst.append(i) return sum(lst) row_sum_odd_numbers(3) #actual solution def row_sum_odd_numbers(n): return n ** 3
2d4a3b294161959bed9c090fb70621fd262c0487
Zeeking99/Assignments-DSA
/Assignment-3.py
1,692
4.09375
4
class MovieNode: def __init__(self, movieName, relDate): self.movieName = movieName self.relDate = relDate self.next = None return class NetflixMovieList: def __init__(self): self.head = None def addMovie(self, movieName, relDate): new = MovieNode(movieName, relDate) if self.head == None: self.hea...
05faab76e373848d7593db2173188e25e59cdb40
zvikazm/ProjectEuler
/16.py
390
3.71875
4
""" 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ import math import time class P16(object): @staticmethod def run(): print(sum([int(c) for c in str(2**1000)])) if __name__ == '__main__': start_time = time.time() P...
7359fb54f366e1a261f06bf190c92f3ebc72d752
zvikazm/ProjectEuler
/9.py
583
4.28125
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ class P9(object): @staticmethod def run(): for i in range...
06ae04f87e99bff7570338c1387151cadce04e79
lsh931125/CoinAutoTrading
/class_1/ch3_3.py
158
3.609375
4
# 절차지향_2 p1_pos = 0 p2_pos = 0 def forward(pos): return pos + 20 p1_pos = forward(p1_pos) p2_pos = forward(p2_pos) print(p1_pos,p2_pos)
fdbbac9779a0e90595c1bdbfb930781c41abcf3e
phuc-noob/AI
/19110434_DFS_Hinh_4.py
588
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 6 11:01:20 2021 @author: PC """ graph={ '1':['2','3','4'], '2':['5','6'], '3':[], '4':['7','8'], '5':['9','10'], '6':[], '7':['11','12'], '8':[], '9':[], '10':[], '11':[], '12':[] } vis...
ea012647fc5862382839895f0402b12e548b68c8
phuc-noob/AI
/BreadthFirstSearch.py
654
3.875
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 6 12:03:18 2021 @author: PC """ graph ={ 'a':['b','c'], 'b':['d','e'], 'c':['f'], 'd':[], 'e':['f'], 'f':[], } # creat a empty list of visited visited =[] # creat a queue queue =[] def bfs(graph,visited ,node): visited.app...
16ad7279e3bd0371379783afc7e74117eb8f4990
frodogirl/learn.python
/hw1/read.py
879
3.84375
4
def calculate_read_time(text, speed): # Тут должен быть код, который рассчитывае время, которое # понадобится чтобы прочитать текст return len(text.split()) * speed if __name__ == "__main__": speed = None while not speed: try: speed = int(input("Олаф: Сколько сло...
ed8529d706c4caa1500c2977eb2d14fd46648ce2
kevinah95/bmc-fragments
/utils/utils.py
914
3.84375
4
import os def give_me_a_float(): while True: try: return float(input("Ingrese un número: ")) except: print("Vuelva a intentar...") pass def give_me_a_number(): while True: try: return int(input("Ingrese un número: ")) except: ...
02103e0b7a65d6b88ca336a6fd5eed926d8c7efb
tolaysha/lab3
/test2.py
79
3.734375
4
h=[1,2,3,4,5] a=[i**3 for i in h] print(a) print(list(map(lambda x: x**3, h)))
b155e638df20ccbe5d719c52c008e2a70a6a883f
aap488/meal_planner
/FoodMain.py
431
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 28 02:15:09 2018 @author: aap48 """ class Food(): """ Class to create food items from. """ def __init__(self, name='', calories=0, protein=0, carbs=0, fats=0): self.name = name self.calories = calories self.protein = prot...
3cb0eaa4b814306d5ca53f2094fcb7c545c025b5
glynnforrest/dotfiles
/bin/.bin/nato.py
1,426
3.875
4
#!/usr/bin/env python3 # Print the first argument (or stdin) using the NATO phonetic alphabet import sys import re words = { "A": "Alpha", "B": "Bravo", "C": "Charlie", "D": "Delta", "E": "Echo", "F": "Foxtrot", "G": "Golf", "H": "Hotel", "I": "India", "J": "Juliet", "K": ...
ed62d643b7021a9fb61d49d8754a0c4b4885c4d4
Ejigsonpeter/pythonbasics
/strinmap1.py
293
3.71875
4
name = ["peter", "jane","Giovanni","Avniel"] j = "|" teams = "yankes,Mets,Jets,Giants,Knicks,Nets" message = "join me for the party tonight" print(j.join(name)) #sseprtates text with the delimeter assignred to j print (len(message)) print (teams.split(",")) # turns a given text into a list
bf08905bdfaaadd3cc1b0d7673f997984fc27752
YsDTL/pythonOpencvLearning
/Image_Separate_merge.py
578
3.6875
4
# -*- coding: utf-8 -*- # 分离真彩图的三个通道并合并 import cv2 import numpy as np # 读入图片 img = cv2.imread("F:/Python/pythonWorkspace/ShawOpencvLearning/pythonOpencvLearning/lena.bmp") # 分离三通道 b,g,r = cv2.split(img) print(type(b)) cv2.imshow("Red", r) cv2.imshow("Green", g) cv2.imshow("Blue", b) # 合并三通道 # 蓝色通道 img[:,:,0] # 绿色通道 i...
f3687e26d7ff8bdf96a26e79b9a97cbabc9affde
hmly/Projects
/Python/weather.py
1,676
4
4
""" Fetch Current Weather A program that get the current weather given the user geo-location (latitude and longitude); other possible inputs include city name, zipcode, and city id . Replace <API key> with the one you obtained. Open Weather Map API: http://openweathermap.org/current """ import urllib.request as rq i...
690e1ca92d03d459ea72d04659a99346d522e529
hmly/Projects
/Python/mp3_player.py
4,191
3.84375
4
""" MP3 Player A simple program that plays your favorite music files. Install pygame for Python 3 Ref: http://www.python-forum.org/viewtopic.php?f=25&t=2716 Pygame documentation Ref: http://www.pygame.org/docs/ref/music.html#comment_pygame_mixer_music_get_busy """ from tkinter import * from tkinter.ttk import Style ...
1219a2c3e5bf22d5598a1fa44bc06edf97425630
MuhammadDhimasEkoWiyono068/PostTest-3
/Kasir Sederhana.py
3,511
3.859375
4
menu="ya" while menu=="ya" or menu=="Ya": print("=============================================") print("~~~~~~~~~~~Warung Bakso Mas Dhimas~~~~~~~~~~~") print("---------------------------------------------") print(" List Menu ") harga=0 diskon=0 tot...
dad00fea55460fb790d7b7c05b4338fd94dea540
alan-isaac/econpy
/tests/test_functions.py
4,062
3.671875
4
''' Unit tests for the `functions` package. :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 ''' __docformat__ = "restructure...