blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f81888b47c87ceefa5f458913dbcc47319dfc185
chavadasagar/python
/fectorial.py
204
3.875
4
n = int(input("enter number")) fec = 1 for x in range(1,n+1): fec = fec * x print(fec) ''' # using recursion def fec(n): if n == 1: return 1 else: return n * fec(n-1) '''
a1d76dd2a74db5557596f2f3da1fbb2bf70474d2
chavadasagar/python
/reverse_string.py
204
4.40625
4
def reverse_str(string): reverse_string = "" for x in string: reverse_string = x + reverse_string; return reverse_string string = input("Enter String :") print(reverse_str(string))
6992e8064e8031e1b0023071471f937152b69263
Dakarai/war-card-game
/main.py
3,338
3.53125
4
import random suits = ('Clubs', 'Diamonds', 'Hearts', 'Spades') ranks = ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A') values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14} war_cards_count = 3 class Card: def __init__(self, suit...
4ca802795b88b9a184cb4fedd62ad242a5ba59e4
theballkyo/GetA
/classes/gradebar.py
1,594
3.53125
4
from tkinter import * class Progressbar(): obj_progress = False def __init__(self, root, max_width, max_height, score): bar = Label(root) bar.place(x=60,y=30) self.canvas = Canvas(bar, width=max_width-2, height=max_height) self.canvas.pack() self.color = self.get_color...
86643c2fe7599d5b77bdcbe3e6c35aa88ba98ecc
aemperor/python_scripts
/GuessingGame.py
2,703
4.25
4
## File: GuessingGame.py # Description: This is a game that guesses a number between 1 and 100 that the user is thinking within in 7 tries or less. # Developer Name: Alexis Emperador # Date Created: 11/10/10 # Date Last Modified: 11/11/10 ################################### def main(): #...
4978f92dab090fbf4862c4b6eca6db01150cf0b7
aemperor/python_scripts
/CalcSqrt.py
1,059
4.1875
4
# File: CalcSqrt.py # Description: This program calculates the square root of a number n and returns the square root and the difference. # Developer Name: Alexis Emperador # Date Created: 9/29/10 # Date Last Modified: 9/30/10 ################################## def main(): #Prompts user for a + num...
a7eda8fb8d385472dc0be76be4a5397e7473f724
petyakostova/Software-University
/Programming Basics with Python/First_Steps_in_Coding/06_Square_of_Stars.py
237
4.15625
4
'''Write a console program that reads a positive N integer from the console and prints a console square of N asterisks.''' n = int(input()) print('*' * n) for i in range(0, n - 2): print('*' + ' ' * (n - 2) + '*') print('*' * n)
62e95db13611d9a6ecbdbb070b9b176d673b81f2
petyakostova/Software-University
/Programming Basics with Python/First_Steps_in_Coding/04_Triangle_Of_55_Stars.py
300
3.984375
4
''' Write a Python console program that prints a triangle of 55 asterisks located in 10 rows: * ** *** **** ***** ****** ******* ******** ********* ********** ''' for i in range(1,11): print('*'*i) ''' for i in range(1, 11): for j in range(0, i): print('*', end="") print() '''
3f25e4489c087b731396677d6337e4ad8633e793
petyakostova/Software-University
/Programming Basics with Python/Simple-Calculations/08-Triangle-Area.py
317
4.3125
4
''' Write a program that reads from the console side and triangle height and calculates its face. Use the face to triangle formula: area = a * h / 2. Round the result to 2 decimal places using float("{0:.2f}".format (area)) ''' a = float(input()) h = float(input()) area = a * h / 2; print("{0:.2f}".format(area))
b8e9d1e43fb13bbe5056d92687169e83393add1a
Isaac51743/Algorithms-in-Python
/src/recursion/recursion1.py
739
4.0625
4
# 12/18/2020 def fibonacci(index): if index == 0 or index == 1: return index return fibonacci(index - 1) + fibonacci(index - 2) print(fibonacci(4)) # assuming a and b are both integer, return type is double def a_power_b(a, b): if a == 0 and b <= 0: return None elif a == 0 and b > 0:...
09ff50c23a5e27d558ed1c7769439bf28b0243e3
Isaac51743/Algorithms-in-Python
/src/bits_probability_dfs/probability.py
2,830
3.609375
4
import random as r import heapq as hq def shuffle_poker(array): if len(array) != 52: return for idx in range(52): random_idx = r.randint(idx, 51) array[idx], array[random_idx] = array[random_idx], array[idx] test_array = [i for i in range(52)] shuffle_poker(test_array) print(test_arr...
21e2669bf38725d1cd712ed2b7ffd2c01dfb5ed4
Isaac51743/Algorithms-in-Python
/src/code_review3.py
2,409
3.59375
4
import math def dropped_request(time_list): if len(time_list) == 0: return 0 dropped_num = 0 for index in range(len(time_list)): case1 = index >= 3 and time_list[index] - time_list[index - 3] + 1 <= 1 case2 = index >= 20 and time_list[index] - time_list[index - 20] + 1 <= 10 ...
b37c28841c34b9a4b44052326d39f4dd7f0c12ae
donaldex/code
/repeat_str.py
202
3.984375
4
def repeat_str(): s = input("Enter string: ") t = input("Enter int>=0: ") n = int(t) print(n*s) print("anni is stupid") # return "ddddd" ##repeat_str() print(repeat_str())
15e9c4495517c834dca50c81383cace908117392
larinanatalia/class
/hw6.py
1,875
3.9375
4
class Animal: satiety = 'hungry' def __init__(self, name, weight): self.name = name self.weight = weight def feed(self): self.satiety = 'animal ate food' class Bird(Animal): eggs = 'dont have eggs' def pick_eggs(self): self.eggs = 'we picked eggs' class Goose(B...
550a70f93c012bb9255ed755c18a74a203ed480f
nkhalili/py-samples
/02/08-conditional-operators.py
173
4
4
x = 5 y = True if x == 5 and y: print('true') # ternary operator hungry = 0 result = 'feed the bear now!' if hungry else 'do not feed the bear.' print(result)
9790fb0d75f15431ca643b1f65319a329460c902
nkhalili/py-samples
/02/11-loops-input.py
320
3.796875
4
secret = "secret" pw = '' while pw != secret: if pw == '123': break pw = input('Enter secret word:') else: # in case while breaks, else won't run print('>Secret key is correct.') animals = ('bear', 'bunny', 'dog', 'cat') for pet in animals: print(pet) else: print('>Items finished.')
3197f5ebde279a17087f81362239b07685067bba
nkhalili/py-samples
/02/03-blocks.py
307
3.84375
4
x = 42 y = 73 # Blocks define by indentation e.g. 4 spaces if x < y: z = 100 print("x < y: x is {}, y is {}".format(x, y)) ## in python blocks do not define scope, Functions, objects, module DO. # z has the same scope as x and y even though its block is different! print("z is: ", z)
d90948ed064194d3f86571ec3c38f3680a2a9552
TestardR/Python-algorithms-v1
/sentence_reversal.py
507
3.9375
4
def rev_word(str): return " ".join(reversed(str.split())) def rev_word1(str): return " ".join(str.split()[::-1]) def rev_word2(str): words = [] length = len(str) space = [' '] i = 0 while i < length: if str[i] not in space: word_start = i while i < leng...
bb2c102167c19e3531e76e3b29da34608283ece8
MikolajTwarog/Artificial-Intelligence
/connect4/board.py
3,330
3.6875
4
#!/usr/bin/env python3 class Board: def __init__(self): self.board = [[0]*7 for i in range(6)] self.moves = 0 self.end = False def check_vertical(self, row, column, who): line = 0 for i in range(row, 6): if self.board[i][column] == who: ...
87f5fd7703bafe4891fb042de2a7f1770c602995
BreeAnnaV/CSE
/BreeAnna Virrueta - Guessgame.py
771
4.1875
4
import random # BreeAnna Virrueta # 1) Generate Random Number # 2) Take an input (number) from the user # 3) Compare input to generated number # 4) Add "Higher" or "Lower" statements # 5) Add 5 guesses number = random.randint(1, 50) # print(number) guess = input("What is your guess? ") # Initializing Variables ans...
6a59184a4ae0cee597a190f323850bb706c09b11
BreeAnnaV/CSE
/BreeAnna Virrueta - Hangman.py
730
4.3125
4
import random import string """ A general guide for Hangman 1. Make a word bank - 10 items 2. Pick a random item from the list 3. Add a guess to the list of letters guessed Hide the word (use *) (letters_guessed = [...]) 4. Reveal letters already guessed 5. Create the win condition """ guesses_left = 10 word_bank = [...
392caa19570274c18bfbdffd11430f6a1180ef44
renard162/personal_library
/general/csvmanager.py
7,025
3.59375
4
# -*- coding: utf-8 -*- # %% """ Funções para manipular arquivos de texto contendo dados. """ import numpy as np import csv def csv_export(file_name, *lists, titles=None, separator='\t', decimal_digit='.', number_format='sci', precision=10): """ Função para salvar em arquivo de texto os dados de...
a7fa12618849376c1bbc3655b9ee4e1d0061477c
gugunm/test-kumparan
/model-v2.py
5,249
3.796875
4
""" Kumparan's Model Interface This is an interface file to implement your model. You must implement `train` method and `predict` method. `train` is a method to train your model. You can read training data, preprocess and perform the training inside this method. `predict` is a method to run the prediction using you...
6f3f133dbbc8fc6519c54cc234da5b367ee9e80d
stark276/Backwards-Poetry
/poetry.py
1,535
4.21875
4
import random poem = """ I have half my father's face & not a measure of his flair for the dramatic. Never once have I prayed & had another man's wife wail in return. """ list_of_lines = poem.split("\n") # Your code should implement the lines_printed_backwards() function. # This function takes in a list of strings...
79e2e4cb5ee662ca24a0a2e9154b5f5c5837cc60
akhan7/fss16groupG
/code/5/maxwalksat.py
4,532
3.765625
4
from __future__ import print_function import copy import random def r(a=0, b=1): return random.randint(a, b) class Osyczka: """ Utility class to solve the Osyczka2 equation """ def min_max(self, tries): """ Args: tries: number of tries / iterations Returns: A ...
da6af0c09f54f044d89eaa17ab549f219deb006b
akhan7/fss16groupG
/code/6/decision.py
325
3.515625
4
class Decision: """ Class indicating Decision of a problem """ def __init__(self, name, low, high): """ @param name: Name of the decision @param low: minimum value @param high: maximum value """ self.name = name self.low = low self.high = ...
7069fe6daf6fe7091471a9e4220569d58e9fcbe3
GWANGHYUNYU/Python_Tutorial
/quiz01.py
632
3.671875
4
# Quiz) 변수를 이용하여 다음 문장을 출력하시오. # # 변수명 : station # # 변수값 : "사당", "신도림", "인천공항" 순서대로 입력 # # 출력 문장 : xx 행 열차가 들어오고 있습니다. # station = ["사당", "신도림", "인천공항"] # for i in station: # print(i, "행 열차가 들어오고 있습니다.") station = "사당" print("{} 행 열차가 들어오고 있습니다.".format(station)) station = "신도림" print("{} 행 열차가 들어오고 있습니다.".format...
2ffa4f8025d643ad0b58f3a2f0bb30e0eec22a65
yilia13516877583/-git
/thread_lock.py
402
3.53125
4
""" 线程锁演示 """ from threading import Thread,Lock lock = Lock() # 锁对象 a = b = 0 def value(): while True: lock.acquire() if a != b: print("a = %f,b = %f"%(a,b)) lock.release() t = Thread(target=value) t.start() while True: with lock: # 上锁 a += 0.1 b += 0.1...
36eae5a4a0f55d15e6105e24fa7d4d64a1009b2e
YatreeLadani/CompetitiveProgramming
/LeetCode/4_Valid_Anagram.py
254
3.671875
4
def validanagram(s,t): if (1 <= len(s) and 1 <= len(t)) or (len(s) <= 5 * (10**4) and len(t) <= 5 * (10**4)): if sorted(s)==sorted(t): print("True") else: print("Flase") validanagram("rat", "art")
f356e0847e22fda7ce2621790bc4be4939f8037b
hasanahmed-eco/space-man
/**SPACEMAN FINAL**.py
2,077
4.03125
4
import random # change the guess array NameError # To DO: # 1) Ensure user doesn't enter a value twice letterCount = 0 word_list = [ "apple", "banana", "education", "house", "fridge", "game", "aaaaaaaab" ] print("--------------------") print("----SPACEMAN 2.0----") print("--------------------") def setUpGame...
ad87297b334864c573301f0aab7e1cbba65d5d33
usf-cs-spring-2019-anita-rathi/110-project-constellation-jychan4
/projectconstellationV5.py
2,092
3.796875
4
#Yew Journ Chan #May 30, 2019 #Version 5 import turtle #Starting with Point Alnitak turtle.hideturtle() #this command hides arrow symbols identified as "turtle" turtle.dot(10) #indicating the point starting at Alnitak turtle.write("Alnitak") #label point "Alnitak" #Point Betelgeuse turtle.left(110) #pivoting towards...
4afcb0749886f9c8807b970405d13d3a4993721c
tkf/compapp
/src/compapp/descriptors/links.py
3,978
3.5
4
from ..core import private, Descriptor def countprefix(string, prefix): w = len(prefix) n = len(string) i = 1 while i < n and string[i * w: (i+1) * w] == prefix: i += 1 return i class Link(Descriptor): """ "Link" parameter. It's like symbolic-link in the file system. E...
e42694efe84f29d3cb96dda98e8793d7613256c0
david-singh/Log-Analysis
/reportingtool.py
3,203
3.609375
4
# ! /usr/bin/env python3 import psycopg2 # What are the most popular three articles of all time? query_1_title = ("What are the most popular three articles of all time?") query_1 = """select articles.title, count(*) as views from articles inner join log on log.path like concat('%',articles.slug,...
4c5923e491d8527c4a255746510c568175334701
SamuelNarciso/Analizador_Sintactico
/AnalizadorSintactico/TreeString.py
1,172
3.609375
4
import Tree import alphabet # int v=10 # int v =10 # int v = 10 class Node: def __init__(self, value, alphabet): self.value = value self.alphabet = alphabet class TreeString: def CreateTree(self): alphabets = [ Node(31, [';']), Node(40, alphabet.Alphabet().Ge...
de78a9a1d734acc46b5403c9960f9ea372cfa242
udaypatel83/FirstRepositoryforPython
/Loops1.py
401
3.640625
4
# 1 # 123 # 12345 # 1234567 #123456789 # minline = 1 maxline = 5 i =1 j =5 numprint = 1 str1 = str(numprint) a = 1 b = 2 while minline <= maxline: while j>=i: print (' '*j, end="") print( str1) while a <= b: numprint = numprint +1 str1 = str1 + str(numprin...
637466a2c1e4300befe7497c5b1b63e530a565a4
edagotti689/PYTHON-13-RANDOM-PREDEFINE-MODULE
/1_ramdom.py
404
4
4
''' 1. random module is predeined module in python used to create a random values. 2. It is used to select a random number or element from a group of elements 3. random module mainly used in games and cryptography ''' import random # random() is used to return a random float number b/w 0 to 1 (0<x<1) l=ra...
472c1086db3decabcded78da1b77b6a67cf6d83b
stereoabuse/euler
/problems/prob_023.py
1,270
3.71875
4
################################################################################ # Project Euler Problem 023 # # https://projecteuler.net/problem=023 # # ...
1f49c039dc9e5d187221cbdeb75992063e20e3b7
zwamdurkel/2wf90-assignment-2
/method/displayField.py
588
3.75
4
# Input: INTEGER mod, POLY modPoly, POLY a # Output: STRING answer, POLY answer-poly # Functionality: Output a representative of the field element of F that represents a, # this means the unique polynomial f of degree less than the degree of q(x) that is congruent to a. # ...
a13982d0e87fa36afa55de7d25ab68a4eab07847
zwamdurkel/2wf90-assignment-2
/method/divisionField.py
761
3.515625
4
# Input: INTEGER mod, POLY modPoly, POLY a, POLY b # Output: STRING answer, POLY answer-poly # Functionality: Compute the element f = a / b in F. # Output f as pretty print string and as POLY. from method.addPoly import addPoly from method.displayField import displayField from...
16f4516dc01599206efe6d145d6cdb5eff29f874
CodeNeverStops/PythonChallenge
/02_ocr.py
207
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def solution(content): chars = [char for char in content if char.isalpha()] print "".join(chars) content = file('02_ocr.txt').read() solution(content)
14cfc68263a404e951421ddf9fa6780d8ae78de2
niharnandan/RA-Spring2020
/2020_1 Spring/OptimalStrategy Simulations/PYTHON - optimal strategy/Optimal Strategy/2. Data Simulation/data simulation distribution.py
9,342
3.875
4
# import packages import math import random import numpy as np import csv ############################### Explanation ############################### # This is a very similar code to 'data simulation.py'. But instead of simulating 40*25 sequences, # we simulate 100 samples, each with 25*4 sequences. We will calcul...
055972f2b5cb0fd63f8b0e67f1bcee03950917c2
bobotan/Python-100-Days
/Day01-15/Day08/demo1.py
220
3.546875
4
class Stu (object): def __init__(self,name,age): self.name=name self.age=age def sit(self): print(self.name) if __name__=="__main__": stu=Stu(name='123',age=5) stu.sit()
b8f6614b03593fa4d5eb94d5d983b172f7cbb0f1
bobotan/Python-100-Days
/Day01-15/Day07/demo.py
517
3.8125
4
# str1='a1b2c3d4e5' # print(str1[1]) # print(str1[2:5]) # print(str1[2:]) # print(str1.isdigit()) # print(str1.isalpha()) # print(str1.isalnum()) # print(str1[-3:-1]) # print(str1[::-1]) # 列表 # list1=[1,3,5,7,100] # print(list1) # list2=['fuck']*5 # print(list2) # print(list2[2]) # list2.append('you') # print(lis...
ea11406cfd4cccb20fa8f1d46bc581816dde3088
huyngopt1994/network-tool
/bit_Handler/bitreader.py
1,853
3.640625
4
""" Simple bitreader class and some utility functions. Inspired by http://multimedia.cx/eggs/python-bit-classes """ import sys class BitReadError(ValueError): pass class BitReader(object): """Read bits from bytestring buffer into unsigned integers.""" def __init__(self, buffer): self.buffer = bu...
846ac682c888800252b6562b70f5d88d60151a37
koendevolder/project-euler
/3/3.py
636
3.578125
4
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? ''' n = 600851475143 i = 2 while n != i: while n % i == 0: n = n / i i = i + 1 print n ''' def prime_number (var): for i in range(2, var): if (var % i == 0): retur...
816cfdedf274dbff93b9e23f361b5f690c6852c4
suprateek-sc19/Caesar-Cipher-in-Python-
/cipher.py
2,045
4
4
import time # encrypt and decrypt a message using Caesar Cipher key = 'abcdefghijklmnopqrstuvwxyz' # Encryption Function def encrypt(n, plaintext): """Encrypt the string and return the ciphertext""" #Start timer start = time.time() result = '' # Convert all lettes to lowercase ...
9b1f3c8d96a19e3da776c3413d4f2239187efa54
NguyenAnhDuc/pytemp
/src/libs/singleton/__init__.py
1,309
3.75
4
#!/usr/bin/python # -*- coding: utf8 -*- """ Author: Ly Tuan Anh github nick: ongxabeou mail: lytuananh2003@gmail.com Date created: 2017/04/28 """ class Singleton(object): """Singleton decorator.""" def __init__(self, cls): self.__dict__['cls'] = cls instances = {} def __call__(...
9d5b9a3d265ee3741b9f03a236003e6132a7010e
grey-area/avida-clone
/organism.py
9,206
3.515625
4
import random copy_mutation_rate = 0.0025 birth_insert_mutation_rate = 0.0025 birth_delete_mutation_rate = 0.0025 number_of_instructions = 26 class organism(): def randomColour(self): self.colour = (random.random(),random.random(),random.random()) # Determine which register to interact with def ...
7ac095090e1bd5c5301b0dd06af883ee02b4a9b5
marcinszymanski1978/training_Python_Programator
/test3.py
236
3.734375
4
x=9 print("X =",x) if x<=9: print("X nie jest większe od",x) else: print("X jest większe od",x) y = "Marcin Szymański" print(y,len(y)) if len(y)>x: print("Napis jest dłuższy od",x) else: print("Napis nie jest dłuższy od",x)
202a2c3c9310b7064966c5d7fe953fcd3a9d7c39
marcinszymanski1978/training_Python_Programator
/while1.py
225
3.84375
4
x=1 for x in range(5): print(x) dzien_tygodnia=['poniedzialek','wtorek','sroda','czwartek','piatek','sobota','niedziela'] for x in range(len(dzien_tygodnia)): print("Dzień tygodnia nr",x+1, "to",dzien_tygodnia[x])
955d4bebf2c1c01ac20c697a2bba0809a4b51b46
patilpyash/practical
/largest_updated.py
252
4.125
4
print("Program To Find Largest No Amont 2 Nos:") print("*"*75) a=int(input("Enter The First No:")) b=int(input("Enter The Second No:")) if a>b: print("The Largest No Is",a) else: print("The Largest No Is",b) input("Enter To Continue")
bdf9ee7ba513a401ed3d6b263cb6ab14f684734e
ObbieOnOblivion/Toyota-Supra-tuning
/toyota_supra_v3.py
16,680
3.734375
4
import random import time # import tkinter import my_function_3 class ToyotaSupraInternals: """ anything thing that cant be tuned and the features of the car Attributes: turbo(str): The name of the turbo turbo_type(str): The type of the turbo transmission(str): this shows the general ...
e6b2537be9801817e078d19cbdf34a047c1c777a
VendiolaRobin/vendiolarobin.github.io
/vendiola.py
134
4.375
4
x = int(input("Enter a number: ")) print(2*x) if (x % 3) == x: print("{x} is Even") else: print("your number is odd")
b87dedfda07df77c95d7a2ed20c1babfaaa1d763
xmartinbr/Python-Exemples
/Ej2-ProgFuncional.py
774
3.546875
4
#Función de nivel superior def saludo(idioma): def saludo_es(): print("Hola") def saludo_en(): print("Hello") idioma_func={"es":saludo_es, "en":saludo_en } #Devuelve el nombre de la función a utilizar en fucnión del valor #del parámetro [idioma] pas...
b77a89b15e672b9508c4437e8b674284dd3326d4
MinhTamPhan/LearnPythonTheHardWay
/Exercise/Day5.3/point2d.py
703
3.671875
4
class Point2d(object): """store 1 point two dim """ def __init__(self, x, y): self.x = x self.y = y """return point do or don't equal Another point""" def Equals(self, pointOther): if self.x == pointOther.x and self.y == pointOther.y: return True else: return False """return Decsition Up Dow Left Ri...
9302fbf822224f10935dc423d35b283bf41b2609
MinhTamPhan/LearnPythonTheHardWay
/Exercise/Day5.3/ex42.py
1,371
4.34375
4
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a object class Dog(Animal): def __init__(self, name): ## set attribul name = name self.name = name ## Cat is-a object class Cat(object): def __init__(self, name): ## set name of Cat self.name = na...
b939c070c0cbdfa664cea3750a0a6805af4c6a10
Yatin-Singla/InterviewPrep
/Leetcode/RouteBetweenNodes.py
1,013
4.15625
4
# Question: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. # Explanation """ I would like to use BFS instead of DFS as DFS might pigeonhole our search through neighbor's neighbor whereas the target might the next neighbor Additionally I'm not using Bi-directional ...
eba983fe4115fa01d9406bce360a1675b394c1cd
Yatin-Singla/InterviewPrep
/Leetcode/ListDepths.py
1,351
4.0625
4
# Question: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth # (eg if you have a tree with depth D, you'll have D linkedlists) # Solution from treeNode import Node from queue import LifoQueue as Queue # helper function def Process(node, level, result): if lev...
e92e09888bff7072f27d3d24313f3d53e37fc7dc
Yatin-Singla/InterviewPrep
/Leetcode/Primes.py
609
4.1875
4
''' Write a program that takes an integer argument and returns all the rpimes between 1 and that integer. For example, if hte input is 18, you should return <2,3,5,7,11,13,17>. ''' from math import sqrt # Method name Sieve of Eratosthenes def ComputePrimes(N: int) -> [int]: # N inclusive ProbablePrimes = [True...
b9a12d0975be4ef79abf88df0b083da68113e76b
Yatin-Singla/InterviewPrep
/Leetcode/ContainsDuplicate.py
730
4.125
4
# Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, # and it should return false if every element is distinct. # * Example 1: # Input: [1,2,3,1] # Output: true # * Example 2: # Input: [1,2,3,4] # Output: false # * ...
9fa036a40a99cf929410c823c38fec3d9b51b47a
Yatin-Singla/InterviewPrep
/Leetcode/BuyAndSellTwice.py
913
3.734375
4
''' Write a program that computes the maximum profit that can be made by buying and selling a share at most twice. The second buy must be made on another date after the first sale. ''' #returns profit and end index def BuyAndSell(prices, StartIndex) -> (int, int): if StartIndex < len(prices): return (0,-1) ...
b459e8a597c655f68401d3c8c73a68decfba186e
Yatin-Singla/InterviewPrep
/Leetcode/StringCompression.py
1,090
4.4375
4
''' Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabccccaa would become a2b1c5a3. If the compressed string would not become smaller than the original string, you method should return the original string. Assume the string has only uppercase an...
b2fab79f5aae295192628dd012fbe3717db2625a
Yatin-Singla/InterviewPrep
/Leetcode/Merge Sorted Array.py
744
3.6875
4
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ index = 0 begPtr1 = begPtr2 = 0 tempNums1 = nums1[:m] while begPtr1 < m and begPtr2 < n: if ...
195d8ee7cab08c68134a01a34c50f22b55e4b620
lzbgithubcode/Python-Study
/Base/Python使用小结.py
1,287
3.765625
4
#采集一个人的身高、体重、性别、年龄 计算输出体脂率是否正常 #计算BMI def computeBMI(weight,height): result = weight/height*height return result #计算体质率 def computebodyfatrate(bmi,age,sex): result = 1.2*bmi + 0.23*age -5.4-10.8*sex return result #判断是否正常 def judgeNormal(rate,sex): if sex == 0: #女 if rate >=0.25 and rate...
2e9773b65e90e66a07c5bce018a468ac31a7b3f0
lzbgithubcode/Python-Study
/Base/元祖操作.py
783
3.84375
4
'1.元祖定义:有序不可变集合''' # 1.1 元祖的定义 # l = (1,) # print(type(l)) # tup = 1,2,3,4,'zb' # print(tup) # 1.2 列表转化从元祖 # nums = [1,2,3,4,5,6] # result = tuple(nums) # print(result,type(result)) '''2.元祖的操作,不可变,没有增删改''' # 2.1 查询某个元素或者多个元素 # items = (1,2,34,4,5,5,6,7,8,9) # print(items) # print(items[2],items[:2:],items[::-1]) ...
97b89fcea4f35c9d899854eb87aa1999b1f095f2
JessicaGarson/MachineLearningFridays
/regularExpressions/regex_stepthrough.py
123
3.78125
4
f = open('regex_examples.txt','r') for line in f.readlines(): enter = input('') if enter == '': print(line)
d2bb5b64aa6bc8751844a356a3501f8c7af0fe55
WojciechSobierajski/FuelCounter
/FunctionsForFuelCounter.py
2,915
3.8125
4
import tkinter as tk from datetime import datetime def displaying_calculated(distance_driven, total_cost, cost_100km, fuel_consumption): dist=f"You've driven: {distance_driven} km" print(dist) trip_cost = f'It cost you: {total_cost} zł' print(trip_cost) cost_of_100km = f'100 km cost you: ...
cf0bb66cb20ad4d58c749bfc362ae8577f843f62
Indronil-Prince/Artificial-Intelligence-Project
/Utility.py
494
3.609375
4
import copy def numOfValue(board, value): return board.count(value) def InvertedBoard(board): invertedboard = [] for i in board: if i == "1": invertedboard.append("2") elif i == "2": invertedboard.append("1") else: invertedboard.append("X") r...
1668f71546bb5de1df2f4ba55a41d4dd76f54853
heidekrueger/f00b4r-Challenge
/Level 3.1 - b0mb-b4by/solution.py
2,568
3.875
4
def solution(m,f): """ Solution to the bomb-baby puzzle. Here, we are given some dynamical update rules, a pair (m,f) could be succeeded either by (m+f,f) or (m,m+f). Given two numbers (m,f), we are tasked with finding the shortest path (in generations) to generate (m,f) from (1,1), or to det...
0d3ba1b8a0884c431f64a996c0b9a5696e5c93fc
foulp/AdventOfCode2019
/src/Day22.py
2,648
3.53125
4
class Shuffle: def __init__(self, size_of_deck): self.deck_size = size_of_deck @staticmethod def cut(n): # f(x) = ax + b % deck_size, with a=1 and b=-n return 1, -n @staticmethod def deal_with_increment(n): # f(x) = ax + b % deck_size, with a=n and b=0 retur...
74d654a737cd20199860c4a8703663780683cea4
quanzt/LearnPythons
/src/guessTheNumber.py
659
4.25
4
import random secretNumber = random.randint(1, 20) print('I am thinking of a number between 1 and 20.') #Ask the player to guess 6 times. for guessesTaken in range(1, 7): print('Take a guess.') guess = int(input()) if guess < secretNumber: print('Your guess is too low') elif guess > secretNumb...
b3e1e98d777d82610e8215a3a44ae6803f3fe502
fucct/Algorithm-python
/leetcode/leetcode83.py
594
3.5
4
from leetcode.leetcode21 import ListNode class Solution83: def deleteDuplicates(self, head: ListNode) -> ListNode: result = [] while head: if not result: result.append(head.val) head = head.next continue if not head.val == res...
ea076830b85f656b4467da07eac0376eb5f9c1e3
fucct/Algorithm-python
/leetcode/leetcode9.py
335
3.734375
4
import functools class Solution9: def isPalindrome(self, x: int) -> bool: string = str(x) split_list = [char for char in string] reversed_list = split_list[:] reversed_list.reverse() return functools.reduce(lambda x, y: x and y, map(lambda p, q: p == q, split_list, reverse...
4e013101f7527171160a6b6d6e17a635557e288e
fucct/Algorithm-python
/leetcode/leetcode2.py
1,285
3.59375
4
from leetcode.leetcode21 import ListNode class Solution2: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: result = [] adder = 0 while l1 and l2: num = l1.val + l2.val + adder if num >= 10: result.append(num-10) adder ...
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',...
a2d8ccafa4d89411f84960155771597179447ea9
hungrytech/Practice-code
/Sort/firt print low grade.py
490
3.625
4
# 이것이 코딩테스트다 정렬 알고리즘 학습 # 문제를 읽고 직접 짜본 코드이다. # 알고리즘을 구상하다 모르겠으면 해답을보고 다시 구상해본다. # 문제: 성적이 낮은 순서로 학생 출력하기 n = int(input()) data=[] for i in range(n) : data_input = input().split() data.append((data_input[0],int(data_input[1]))) result= sorted(data, key=lambda student: student[1]) for student in result : ...
915bb8a872505cf0c476815b0045a36842f8687a
hungrytech/Practice-code
/python/UniversityProject2.py
479
3.84375
4
def slice (String) : # ACG로 시작하고 TAT로 종결되는 슬라이싱 함수 start_ACG=String.find('ACG') #ACG가 시작하는 index start_TAT=String.find('TAT') #TAT가 시작하는 index slice_String = String[start_ACG:start_TAT+3] #ACG시작하는 index 부터 TAT가 끝나는 index까지 slicing return slice_String sequence="TACTAAAACGGCCCTTGGGAACCTATAAAGGCAATATGCAGT...
2d9a7d0568cdf890ebf8b3fbbce6de67a8dc3dcb
hungrytech/Practice-code
/BaekJoon/BaekJoon1427myThink.py
169
3.578125
4
n = int(input()) n=str(n) data=list() for i in n : data.append(int(i)) data = sorted(data, reverse=True) result="" for i in data : result+=str(i) print(result)
b2e1cce90b9e3b64a5d21e00460b69136fcf3267
cjakuc/cs-module-project-recursive-sorting
/src/sorting/sorting.py
3,250
4.0625
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here if len(arrA) == 0: return list_right elif len(arrB) == 0: return list_left x = 0 y = 0 merged_id...
9689376936022dc428cb1f59960ee7d920e1d031
Great-special/sales-analysis_2
/Data-Insight/sales_analysis.py
7,985
4.1875
4
import pandas as pd import matplotlib.pyplot as plt ####### Loading Data/File ####### d_f = pd.read_csv('10000 sales records.csv') #print(d_f.head(10)) ## Getting the headers headers = d_f.columns # print(headers) # print(d_f.describe()) ####### Working with the loaded Data ####### ## Q1: Which columns(Country) ...
2cc359c82b856fe75eed2906e36f9fa18f6de8cc
BarbaraRafal/SDA_exercises
/testowanie_tdd/home_work/home_work_jadwiga.py
1,875
3.734375
4
from datetime import datetime from typing import Tuple class Book: ALLOWED_GENRES: Tuple = ( "Fantasy", "Science Fiction", "Thriller", "Historical", "Romance", "Horror", ) def __init__(self, title: str, author: str, book_genre: str) -> None: self.ti...
587d31d1aa464c529e14659857ff52d4629e5700
BarbaraRafal/SDA_exercises
/testowanie_tdd/tdd_day1/account.py
479
3.5
4
class Account: def __init__(self, balance_amount: float, user_status: str) -> None: self.balance_amount = balance_amount self.user_status = user_status def transfer(self, amount_of_money: float) -> float: try: self.balance_amount += amount_of_money except TypeError: ...
0a5d7f42c11be6f4fb2f9ede8340876192080d8d
Dana-Georgescu/python_challenges
/diagonal_difference.py
631
4.25
4
#!/bin/python3 ''' Challenge from https://www.hackerrank.com/challenges/diagonal-difference/problem?h_r=internal-search''' # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(): ...
9ae095de08c2cf599b1d731858f3cb0ab5e5be11
pedro-espinosa/matching_pennies
/stimuli.py
1,285
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Module containing functions for generating visual stimuli """ import os #%% Welcome, instructions and first choice welcome_text = """ Welcome! In this experiment you will play a game of 'Matching Pennies' against a computer. Each player has a coin. Every round, the pl...
0d38d3e0de7b6950364dff49b4592cd629e26408
lukejpie/Machine-Learning-Final-Project
/project-lpietra1/run_logistic_regression.py
4,516
3.6875
4
""" Run Logistic Regression: Author: Luke Pietrantonio Created: 5/7/19 Description: Transforming the linear regression problem into a logistic problem by having "high" and low days, as opposed to linear regression """ import math as m import matplotlib.pyplot as plt import numpy as np from utils import * from dataset ...
fec59c99e4a986c3d9a09abb51e8485cc2dc739f
NIHanifah/phyton-prak9
/nomor4.py
399
3.90625
4
#mengacak huruf pada kata #menggunakan shuffle import random import collections #membuat susunan huruf yang berbeda def shuffleString(x, n): kata = list(x) listKata = [] k = 0 while k < n: random.shuffle(kata) hasil = ''.join(kata) if hasil not in listKata: listKa...
b25933e9e0414b96f98c600606aebcfc1e7e8d73
chaemoong/SmartDelivery
/utils/module.py
1,682
3.546875
4
""" 위 모듈은 개발자 뭉개구름이 제작하였으며 무단으로 사용할 경우 라이선스 위반에 해당됩니다. """ import json class Module(): def __init__(self): self.module = 'JSON 모듈입니다!' def save(self, filename, data): print(f'[JSON MODULE] [작업시도] {filename} 파일을 저장중입니다...') with open(filename, encoding='utf-8', mode='w') as f: ...
537eb97c8fa707e1aee1881d95b2bf497123fd67
jeffsilverm/big_O_notation
/time_linear_searches.py
2,520
4.25
4
#! /usr/bin/env python # # This program times various search algorithms # N, where N is the size of a list of strings to be sorted. The key to the corpus # is the position of the value to be searched for in the list. # N is passed as an argument on the command line. import linear_search import random import sys corpu...
abbb02f14ecbea14004de28fc5d5daddf65bb63e
jeffsilverm/big_O_notation
/iterative_binary_search.py
1,292
4.1875
4
#! /usr/bin/env python # # This program is an implementation of an iterative binary search # # Algorithm from http://rosettacode.org/wiki/Binary_search#Python def iterative_binary_search(corpus, value_sought) : """Search for value_sought in corpus corpus""" # Note that because Python is a loosely typed language,...
2b0a86e5ff0a45d03c215f3a164b2e9882613c55
alklasil/SScript
/SScriptCompiler/src/common.py
215
3.671875
4
def flattenList(l): l_flattened = [] for item in l: if type(item) is list: l_flattened.extend(flattenList(item)) else: l_flattened.append(item) return l_flattened
8f623a197814365cb7aa43bd2bce8f6dace96e4a
DerrickKnighton/Min-Sum-Partition
/minsumpartition.py
3,589
3.671875
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 17:09:14 2019 @author: Derrick Found this problem online for interview prep and it didnt seem too bad so i gave it a try didnt take super long """ class Min_Sum_Partition(): import numpy as np def create_Random_Array(self,range...
ecc686dc19b4bdf92585421e6bb161e8e6b59dd8
chrisxwan/codeboola-game
/scaffold.py
4,382
3.609375
4
import random class Player(object): max_hp = 100 current_hp = 100 # Check if the player is still alive # by ensuring that his current hp is greater than 0 def is_alive(self): # Fill this in! # Return True or False depending on whether the Player's # attack was successful def successful_attack(self): # F...
d8b293f25173bbee6ddaa45118640f2ed7cdb1d0
VitorHSF/Programacao-Linear-E-Aplicacoes
/Exercicios- Matrizes III/EX03/ex03.py
853
3.703125
4
def getLinha(matriz, n): return [i for i in matriz[n]] def getColuna(matriz, n): return [i[n] for i in matriz] matriza = [[3, 4], [2, 3]] matrizalin = len(matriza) matrizacol = len(matriza[0]) matrizb = [[-1], [-1]] matrizblin = len(matrizb) matrizbcol = len(matrizb[0]) matRes = [] print(...
09d18759aa23f1c7625ac83b5a93d4d15fd281e4
VitorHSF/Programacao-Linear-E-Aplicacoes
/Exercicios - Matrizes/EX04/ex04.py
865
3.59375
4
from time import sleep matriz = [[1, -1, 0], [2, 3, 4], [0, 1, -2]] matrizresult = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] matrizt= list(map(list, zip(*matriz))) print('=-=' * 20) print('Dada a Matriz A, obtenha a matriz B tal que B = A + At') print('\nMatriz A:') for j in matriz: print('{}'.format(j)) p...
0fcbee7b0ba2d158317b40e5f47ff3242584fbef
wmackowiak/Zadania
/Zajecia07/fitmeter.py
369
3.59375
4
import bmi # podaj wagę i wrost weight = float(input("Podaj wagę w kg: ")) height = float(input("Podaj wzrost w m: ")) # wyślij wagę i wzrost do funkcji obliczjącej result_bmi = bmi.calculate_bmi(weight, height) state = bmi.get_state(result_bmi) print(state) filename = state.lower() + '.txt' with open(filename) as f...
e5416db47f43573132d34b69c15921ce623552e9
wmackowiak/Zadania
/Zajecia03/zad04.py
645
4.03125
4
#Stwórz skrypt, który przyjmuje 3 opinie użytkownika o książce. Oblicz średnią opinię o książce. # W zależności od wyniku dodaj komunikaty. Jeśli uzytkownik ocenił książkę na ponad 7 - bardzo dobry, ocena 5-7 przeciętna, 4 i mniej - nie warta uwagi. ocena1 = int(input("Jaka jest Twoja ocena ksążki?")) ocena2 = int(inp...
eb2c90826b55ccf8d43e3dba932787c72e33db74
wmackowiak/Zadania
/Zajecia04/dom06.py
357
3.953125
4
# 6▹ Utwórz listę zawierającą wartości poniższego słownika, bez duplikatów. # days = {'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30} for key in days.keys(): lista1 = list(set(days.keys())) for value in days.values(): lista2 = list(set(days.values())) prin...
69bd4880aac5e7c71c7fe580c11a8e2bc48361cd
wmackowiak/Zadania
/Dodatkowe/zad27.py
202
3.796875
4
# Proszę za pomocą pętli while napisać ciąg składający się z 5 wielokrotności liczby 6. # # 6 # 12 # 18 # 24 # 30 x = 6 for i in range(5): while x <= 30: print(x) x = x + 6
cfe325d65dd4a17391dad5839290b4a2ea569127
wmackowiak/Zadania
/Zajecia06/zad05.py
1,053
3.84375
4
# Rozpoznawanie kart. Utwórz plik zawierający numery kart kredytowych. Sprawdź dla każdej kart jej typ. # Podziel kart do plików wg typów np. visa.txt, mastercard.txt, americanexpress.txt. def is_card_number(number): return number.isdecimal() and len(number) in (13, 15, 16) def starts_with_correct_digits(number): ...
584d559437a74a7a34b4093d87ad6def1816c33a
wmackowiak/Zadania
/Zajecia03/dom4.py
373
3.546875
4
# Zapytaj użytkownika o numer od 1 do 100, jeśli użytkownik zgadnie liczbę ukrytą przez programistę wyświetl # komunikat “gratulacje!”, w przeciwnym razie wyświetl “pudło!”. liczba_uzytkownika = input("Podaj liczbę z przedziału od 1 do 100: ") moja_liczba = '45' if liczba_uzytkownika == moja_liczba: print("Gratul...