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 |
|---|---|---|---|---|---|---|
84c143e84c3e985ef1b63a0e0ec78a7221d14dbc | MicheleCattaneo/USI_Algo_Bible | /DynamicProgramming/maxIncreasingSubsequence.py | 781 | 3.984375 | 4 | '''
Find the subsequence which has the biggest sum:
S is the sequence
i current index
prev previous element picked
sum the current sum
seq the sequence that adds up to that sum
'''
def maxIncSub(S):
return maxIncSub_(S, 0, float("-inf"), 0, "")
def maxIncSub_(S, i, prev, sum, seq):
end... |
777e7bba64dda1724841f981e968cb667a2d50ac | MicheleCattaneo/USI_Algo_Bible | /Sorting/miracleSort.py | 251 | 3.578125 | 4 | def miracleSort(A):
sorted = True
for i in range(len(A) - 1):
if (A[i] < A[i + 1]):
sorted = False
if (sorted):
return A
else:
miracleSort(A)
A = [5, 6, 12, 8, 4, 10, 3, 12, 11, 1]
miracleSort(A) |
c3b75dcb6f2d9ac02adc1dc982998810c7a029e5 | MicheleCattaneo/USI_Algo_Bible | /Sorting/binarySearch.py | 354 | 3.90625 | 4 | def binarySearch(A, x):
# Assume A is sorted
if len(A) == 0:
return False
m = len(A) // 2
if x > A[m]:
return binarySearch(A[m+1:len(A)], x)
elif x < A[m]:
return binarySearch(A[0:m], x)
else:
return True
A = [1, 3, 4, 5, 6, 8, 10, 11, 12, 12]
print(binarySearch... |
c3697cd3793f2d0113e3fa998b4e27c0d9f34b8e | Bigbys-Hand/crash_course_git | /tuples.py | 447 | 4.09375 | 4 | # Tuples are exactly like lists except their values cannot be modified. Written with (), not []
first_tuple = (200, 50)
print(first_tuple[0])
print(first_tuple[1])
# first_tuple[0] = 250
# Trying to change a value in a tuple results in an error.
# The way to change a tuple is to assign a new value to the variable rep... |
f8e7e4d62b96922babb17092190c0db50bab1139 | Bigbys-Hand/crash_course_git | /guest_list_exercise.py | 2,346 | 3.875 | 4 | guest_list = ['Abraham Lincoln', 'Buddhadama', 'Angela Merkel', 'Elizabeth Warren']
print(guest_list)
Abe_invitation = f"Mr. {guest_list[0]}, would you please join me for dinner?"
BD_invitation = f"Mr. {guest_list[1]}, would you please join me for dinner?"
AM_invitation = f"Mrs. {guest_list[2]}, would you please join ... |
522bc730e6d05cc957a853f5d667e553229474ff | Bigbys-Hand/crash_course_git | /functions.py | 2,909 | 4.4375 | 4 | def greet_nerds():
"""Display a simple greeting"""
print("Live long and prosper")
def better_greeting(username):
"""Display a simple greeting, pass name to function"""
print(f"Live long and prosper, {username.title()}!")
#This function is similar to the first one, but we created the PARAMETER 'usernam... |
73c7dbde93fa554623d52b7154be2d80bdec4026 | bonheml/tc_study | /tc_study/utils/string_manipulation.py | 234 | 3.765625 | 4 | def remove_prefix(string, prefix):
return string[len(prefix):]if string.startswith(prefix) else string[:]
def remove_suffix(string, suffix):
return string[:-len(suffix)] if (suffix and string.endswith(suffix)) else string[:] |
48f0d4132919cdae29fe3591b01b235869c65af6 | HenrikSamuelsson/python-crash-course | /exercises/chapter_03/exercise_03_07/exercise_03_07.py | 2,758 | 4.21875 | 4 | # 3-7 Guest List
guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_l... |
0863ee17bcee27dce7dde011c54ffba6ed6736b3 | nojhan/aapssfc | /src/devine_ordi_2.py | 2,093 | 3.90625 | 4 | #encoding: utf-8
#############
# Fonctions #
#############
import random
def try_to_guess( nb_min, nb_max ):
"""Choisi un nombre compris entre un min et un max et le renvoie."""
if nb_min == nb_max or nb_min > nb_max:
# Au cas où cette erreur apparait, il est préférable de signaler l'erreur
... |
68d28a4e857432b1d3f7309c95c7236da8164ab1 | luomeng007/Pytorch | /T03_linearRegression.py | 1,198 | 3.578125 | 4 | # -*- coding:utf-8 -*-
"""
author: 15025
time: 10.08.2021 16:53:09
software: PyCharm
Description:
"""
# 使用pytorch手动来完成线性回归
import torch
import matplotlib.pyplot as plt
learning_rate = 0.01 # 学习率
# 1. 准备数据
# y = 3x + 0.8
x = torch.rand([500, 1])
y_true = x * 3 + 0.8
# 2. 通过模型计算y_predict
w ... |
31da6faad8c99d5b6e92c06eed3e15b6e1ab8c1f | ovnny/HarvardCS50-Intr2CS | /6python/exercicios/teste3.py | 734 | 4.03125 | 4 | from sys import argv, exit
import re, csv
if len(argv) != 3:
print("Errno 1: Two arguments required\nUsage: sequences/filename.csv database/filename.txt")
exit(1)
with open(argv[1], mode= 'r') as csv_file, open(argv[2], mode= 'r') as txt_file:
if not re.search('csv$', argv[1]) and not re.search('t... |
b06fe113e6b7c496cca988987f4f4c56f8931766 | ovnny/HarvardCS50-Intr2CS | /6python/exercicios/teste.py | 312 | 4.21875 | 4 | x = int(input("x: "), 2) #Tipagem como função int()
y = int(input("y: "), 8) #Escolha do modelo de base
z = int(input("z: "), 16) #numérica no fim da função.
print(f"x is: {x}\ny is: {y}\nz is: {z}\n") #Binário, Octal e Hexadecimal |
89bacd93cfc86e2f61e4504dcee0851dba423946 | ankita462/Python | /array/gcd_array.py | 300 | 3.875 | 4 | def gcd(a,b):
while((a%b)>0):
gcd=a%b
a=b
b=gcd
return b
arr=[]
num=int(input("Enter size: "))
print("Enter Elements: ")
for i in range(num):
ele=int(input())
arr.append(ele)
temp=arr[0]
for i in range(num):
temp=gcd(arr[i],temp)
print("GCD =",temp) |
2c388e95f7a92ac05d468d9d5ce8e927915dce10 | InnocentSuta/PythonChallenges | /04_Leap Year.py | 316 | 4.28125 | 4 |
#Program to check wether a year is a leap year or not.
year = int(input("Please Enter a year : "))
#check if the year is divisible by 4 and 400 and not by 100
if year % 4 == 0 and (year % 400 == 0 or year % 100 != 0):
print(year, "is a leap year ")
else:
print(year, "is not a leap year ")
|
5d40801b679cd7469773a11535c56ec1efb8c63e | weixuanteo/cs_foundation | /string_splosion.py | 474 | 4.28125 | 4 | # Given a non-empty string like "Code" return a string like "CCoCodCode".
# Sample input
s = "Code"
def string_splosion(str):
result = ""
# On each iteration, add the substring of the chars
for i in range(len(str)):
print("str[:i+1]: ", str[:i+1])
# [Python slicing] Returns from begining o... |
643c5c84d5d4fda81b4f1aa1b9a24f6e2d79ef2c | AlmightyFuzz/AOC20 | /day1.py | 1,146 | 3.671875 | 4 | test_data = """1721
979
366
299
675
1456"""
def find_two_2020(values):
for i in range(0, len(values)):
first = values[i]
rest = values[i+1:]
for j in range(0, len(rest)):
second = rest[j]
if(first + second == 2020):
return (first, second)
def fi... |
7c05270e35342a04120e4b8e2ad2c6db8a75a461 | DJCordhose/dtreeviz | /dtreeviz/interpretation.py | 7,109 | 3.671875 | 4 | """
Prediction path interpretation for decision tree models.
In this moment, it contains "plain english" implementation, but others can be added in the future.
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas
from dtreeviz.colors import adjust_colors
from dtreeviz.models.shadow_decision_tree import... |
03ae4574c6776448a2f09a13ea00dafe0bceeab3 | PamelaVI/actividades | /isla_pamela/actividad005/actividad005.py | 514 | 4 | 4 | """05-
Función que reciba como parametros dos números (a y b), y
devuelva una tupla con todos los números primos que se encuentra entre
a y b (incluyendo a y b si son primos).
Por defecto a=0, y b=100"""
#numeros primos son divisibles por 1 y por si mismo
#Numeros Primos
#rango de 0 a 100
def numero_primo(a... |
466fe644c7aa4d8904ee8c71ae5b9f12141413a8 | HerrVeloxx/morpion-terminal | /morpion_fonction.py | 1,594 | 3.765625 | 4 | import sys
def numero_case(j) :
print(" ")
print("C'est le tour du joueur", j)
case=str(input("Entrez la case : "))
print("Vous avez joué la case", case)
return case
def grille(L) :
print(" ")
print(" 0 1 2")
print(" -------------")
for i in range(3):
print(chr(65+i... |
0f110cb6ab3d3ea2c6f6d85cd14dd24b9a7fdcde | ryuzakizh/hello-world | /hackerrank/medium_task(find_angle_MBC).py | 116 | 3.6875 | 4 | import math
AB = int(input())
BC = int(input())
degr = round(math.degrees(math.atan2(AB,BC)))
print(str(degr)+"°")
|
87145bfd77ab97ac412360b6ba82728adce6fc43 | algo-ryth-nic/ADA-Algorithms-with-their-Analysis | /Graph Coloring Problem/graph_coloring_problem.py | 3,365 | 3.625 | 4 | # Graph Coloring Decision Problem / m coloring problem
from timeit import default_timer as timer
import networkx as nx
from matplotlib import pyplot as plt
import numpy as np
# Graph class
class Graph():
# constructor method
def __init__(self, graph):
"""
Parameters: A 2d list th... |
4571e6939cb51d56dd8e3778c0ffea92fc23876c | UNSK/aoj_answers | /icpc/1172.py | 338 | 3.609375 | 4 | from math import sqrt
size = 123456
primes = [x for x in range(2, 2*size+1) if x == 2 or x % 2 == 1]
for i in range(2, int(sqrt(2*size))):
primes = [x for x in primes if x % i != 0 or x == i]
while True:
n = int(input())
if n == 0: break
nums = [x for x in primes if x > n and x <= 2*n]
... |
c84790fd040e9f69ceab7f51edf36ddeefe060b7 | CristianLazoQuispe/ITMO-Training-Camp-2021 | /Classes/Class-08/contest-08/D.py | 1,782 | 3.71875 | 4 | from collections import defaultdict
class my_Graph:
def __init__(self,vertices):
self.V = vertices
self.graph = {}
def addEdge(self,u,v,w):
if u in self.graph:
self.graph[u].append([v,w])
else:
self.graph[u] = [[v,w]]
def topologicalSortUtil(self,v,v... |
68deee037b16ba33f8534c93a333f6e782d022b5 | CristianLazoQuispe/ITMO-Training-Camp-2021 | /Classes/Class-06/contest-06/D1.py | 1,346 | 3.5 | 4 | # Function that returns the longest increasing subsequence
def answer(arr):
n = len(arr)
fenwick_tree = [0]*(n+1)
sorted_arr = sorted(arr)
dictionary = {}
for i in range(n):
dictionary[sorted_arr[i]] = i+1
for i in range(n):
arr[i] = dictionary[arr[i]]
for i in range(n):
... |
47a1d28bb330c64ac969df41d36970e3aa1d2380 | karacanil/ProjectEuler | /euler34.py | 679 | 3.625 | 4 | #Project Euler 34
import time
start_time=time.time()
def factorial( n ):
if n <1:
return 1
else:
return n * factorial( n - 1 )
def isTrue(x):
number=x
factorial_sum=0
length=len(str(number))
digits=[]
for i in range(length):
digits.append(x%10)
... |
2482e07d8ad3c2327314e48c866c69d6a13e8f5a | cesarschool/cesar-school-fp-2018-2-lista1-victoroliveirab | /questoes/questao_5.py | 1,000 | 4.0625 | 4 | ## QUESTÃO 5 ##
# Escreva um programa para calcular a redução do tempo de vida de um fumante.
# Pergunte a quantidade de cigarros fumados por dia e quantos anos ele já fumou.
# Considere que um fumante perde 10 minutos de vida a cada cigarro, calcule
# quantos dias de vida um fumante perderá. Exiba o total em dias. ... |
0e9bbd1aef2f920e35ead4e7b969504cb63d04b1 | happyAyun/MSA_TIL | /python_workspace/basic_grammer/13_classv_test.py | 790 | 4.125 | 4 | class ClassTest:
class_v = 10 # 클래스 변수 : 클래스 타입의 모든 instance 공유하는 변수 클래스 이름으로 참조.
def __init__(self,instance_v):
self.instance_v = instance_v
c1 = ClassTest(10)
c2 = ClassTest(10)
c1.instance_v += 1
c2.instance_v += 1
c3 = ClassTest.class_v
c3 += 1
c4 = ClassTest.class_v
c4 += 1
ClassTest.class_v ... |
c72327d594362697ad1b65db7530a19d564b74da | saintsavon/PortfolioProjects | /Interview_Code/Palindrome.py | 1,434 | 4.21875 | 4 | import re
import sys
# Used to get the word list file from command line
# Example command: 'python Palindrome.py test_words.txt'
input_file = sys.argv[1]
def palindrome(word):
"""
Checks if word is a palindrome
:param word:
:return Boolean:
"""
return word == word[::-1]
palindrome_dict = {}... |
45721737059b83576d2d0b751dc926d1a8ec72ec | xingyu-long/matplotlibTutorials | /Axis.py | 918 | 3.859375 | 4 | # func: 设置某一个点(x,y)为原点 画出axis 并且隐藏右边和上边
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
# set figure 3
plt.figure()
plt.plot(x, y2)
# set style
plt.plot(x, y1, color='red', linewidth=1.0, linestyle=':')
# set range
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# set lab... |
4d5734808eff4cabde439ce66301147e41f73d6d | Blaze20014/01-Guessing | /main.py | 1,828 | 3.625 | 4 | import sys, random
import sys, time
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
compRandom = random.randint(1, 100)
correctGuess = False
guesses = 0
print("Running GLaDOS_Installer_V1.14.2")
time.sleep(1)
print("GLaDOS booting up...")
time.sleep(1)
print("GLaDOS: Hello player; I see ... |
bbb97d71f19164792466373c7cadf6a8185ed541 | KremenenkoAlex/Python | /lesson8/exp1.py | 1,126 | 3.796875 | 4 | class Date:
def __init__(self, day_month_year):
self.day_month_year = str(day_month_year)
@classmethod
def extract(cls, day_month_year):
my_date = []
for i in day_month_year.split():
if i != "-": my_date.append(i)
return int(my_date[0]), int(my_date[1]), int(my_... |
d02e1d046d53dbe8aa15c0a1cf9d913fa07084f2 | KremenenkoAlex/Python | /lesson6/exp4.py | 1,745 | 3.90625 | 4 | class Car:
def __init__(self, name, speed, color, is_police=False):
self.speed = speed
self.color = color
self.name = name
self.is_polis = is_police
def go(self):
return 'Машина {} едит.'.format(self.name)
def stop(self):
return '\nМашина {} остановилась.'.... |
888294213c352409c2e5f05254724a8df35aed0e | KremenenkoAlex/Python | /lesson1/exp4.py | 254 | 3.6875 | 4 | n = int(input("Введите целое положительное число "))
max = n % 10
while n >= 1:
n = n // 10
if n > max:
max = n
else:
print("Максимальное цифра в числе ", max)
break |
e571a6eddf209f69dfa02be155eb353da2f2a4ee | absupriya/Artificial-Intelligence | /Tweet_Classification/geolocate.py | 10,031 | 3.546875 | 4 | #!/usr/bin/env python2
# geolocate.py : Tweets classification
# Supriya Ayalur Balasubramanian, 26-Oct-2018
# A classic application of Bayes Law is in document classification. Let's examine one particular classification problem:
# Estimating where a Twitter "tweet" was sent, based only on the content of the tweet itse... |
11a39da4784ff32c31419d5bb891893ec22f810e | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /14. Dictionaries/125. iterating_dict.py | 1,365 | 4.25 | 4 | instructor = {
"name":"Cosmic",
"num_courses":'4',
"favorite_language" :"Python",
"is_hillarious": False,
44 : "is my favorite number"
}
# Accessing all values in a dictionary
# We'll loop through keys, loop through values, loop through both keys and values
# Values Print .values() ... |
04f2e04b76ddcc89bf4d108fad60b08b9f316304 | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /08. and 09. ConditionalLogic and RPS/marvel_quotes_generator.py | 5,181 | 3.84375 | 4 | print("\nHeyy there! Welcome to Marvel quotes machine.\n")
print("What is your name human ?\n")
user_name = input()
print(f"\nHeyy {user_name}, select corresponding numbers in front of your favorite superhero/villain to get one or two quotes related to them ;) ")
print("\n 1. Captain America\n 2. Iron Man\n 3. Spid... |
a9b3cedf7ae1dae5eb5ce3246552c15df6bf59eb | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /12. Lists/104. list_methods.py | 1,127 | 4.1875 | 4 | first_list = [1,2,3,4]
first_list.insert(2,'Hi..!')
print(first_list)
items = ["socks", 'mug', "tea pot", "cat food"]
# items.clear()
#Lets the items list to be a list but clears everything within it.
items = ["socks", 'mug', "tea pot", "cat food"]
first_list.pop() # Remove the last element
first_list.pop(1... |
71e7a3aba947fc2ec04abe048a588815e526fdeb | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /13. Lists Comprehension/vertices.py | 396 | 3.59375 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if y1==y2:
yn = (x1,y1+abs(x1-x2))
xn = (x2,y2+abs(x1-x2))
print(yn)
print(xn)
ba = (2**0.5)*(abs(x1-x2))
print(format(ba,'.2f'))
else:
yn = (x1+abs(y1-y2),y1)
xn = (x2+abs(y1-y2),y2)
print(yn)
... |
f4724113c5118d7bd8a03d862cf6010ba588539f | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /08. and 09. ConditionalLogic and RPS/game_of_thrones.py | 1,970 | 4.15625 | 4 | print("Heyy there! Welcome to GOT quotes machine.")
print("What is your name human ?")
user_name = input()
print("\n Select from numbers 1 through 5 and we will give a quote (or two) based on your name. e.g. 1 or Tyrion or TL (case sensitive)\n \n")
# or First Name or Initials
print("What's your character's name?\... |
aaaf8d5decbabeede4a42c2630fc1f31ec387a58 | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /08. and 09. ConditionalLogic and RPS/bouncer.py | 1,367 | 4.375 | 4 | #Psuedo Code: Ask for age
# 18-21 Wristband and No Drinks
# Method1
# age = input("How old are you: ")
# age = int(age)
# if age != "":
# if age >= 18 and age < 21:
# print("You can enter, but need a wristband ! Also no drinks for you ese!")
# # 21+ Normal Entry and Drinks
# elif a... |
103e0bfbb16891385efb90d3ea138d8fd2fab585 | dudrbs703/codeup-python-100 | /print_6074.py | 118 | 3.5625 | 4 | # print_6074.py
end = ord(input())
start = ord('a')
while start <= end:
print(chr(start), end=' ')
start+=1 |
34526d08dc01b8f060373992203a91a1e75b7216 | ThomasDeruel/Algorithme-python | /python/24.01.18/tableau-2-dimensions.py | 386 | 3.921875 | 4 | import numpy as np
n = 3
t = np.empty((n,n))
i = 0
while i<n :
y=0
while y<n :
print('saisir l\'élément ligne',i,'colonne',y,end=": ")
t[i][y] = int(input())
y = y + 1
i = 1 + i
i=0
print("les éléments du tableau vallent : ",end="")
while i<n :
y=0
while y<n :
print(t... |
65c83f24957a06c4022f8552d537f17ece50425e | ydong5dyh/portfolio | /abtesting/yihang_dong.py | 8,566 | 3.953125 | 4 | from scipy import stats
from scipy.stats import t as t_dist
from scipy.stats import chi2
# You can comment out these lines! They are just here to help follow along to the tutorial.
# print(t_dist.cdf(-2, 20)) # should print .02963
# print(t_dist.cdf(2, 20)) # positive t-score (bad), should print .97036 (= 1 - .2963)
#... |
5b0c1bfd0903bc15ccf36f798bc13c2b8ee13aad | JakeMittleman/Othello | /ai.py | 2,070 | 4.09375 | 4 | """
CS5001
Fall 2018
Jake Mittleman
HW 7
"""
import turtle
import time
def ai_take_turn(board):
if board._ai_player and board.check_turn() == "white":
time.sleep(1)
turtle.onscreenclick(None)
ai_turn(board)
turtle.onscreenclick(board.clicked)
def... |
0f9837be4824b829f8a3a1936c29daccfc1cd499 | ChrisEngstrom/Py-PE-2 | /main.py | 555 | 3.9375 | 4 | #!/usr/bin/env python3
fibValueLimit = 4000000
n = 0
nMinusOne = 1
nMinusTwo = 0
sumOfEvenFibs = 0
def Fibonacci(limit):
global n
global nMinusOne
global nMinusTwo
global sumOfEvenFibs
n = nMinusOne + nMinusTwo
if (n > limit):
return sumOfEvenFibs
else:
if (n % 2 == 0):
... |
af6f172f19f164fde731939c900db3bee702b715 | yufeng97/Python003-003 | /week08_09/3.py | 798 | 3.921875 | 4 | """
实现一个 @timer 装饰器,记录函数的运行时间,注意需要考虑函数可能会接收不定长参数。
"""
import time
from functools import wraps
def timer(func):
@wraps(func)
def inner(*args, **kwargs):
start = time.time()
ret = func(*args, **kwargs)
print(f"{func.__name__} run time: {time.time() - start}")
return ret
retu... |
9cdeebafe539131ad9bdfb788038786c2a7f9d02 | alraune-esk/nlp-algorithms | /syntax_parser.py | 3,838 | 3.5625 | 4 | import json
class TreeNode:
"""
Class for representing parse trees. Contains some useful utilities for printing and reading/writing to string.
"""
def from_list(lst):
root = TreeNode(lst[0])
root.children = [TreeNode.from_list(ls) for ls in lst[1:]]
return root
... |
303a6af3f6294ae3f74863ebe8b539919ff4c423 | iroshan/python_practice | /Ubbi_dubbi.py | 465 | 3.875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def translate(word: str) -> str:
""" tanslate word to ubbi subbi"""
s = [('ub' + c if c in 'aeiou' else c) for c in word]
return ''.join(s)
def main():
while True:
word = input('enter word to translate (blank to quit): ').strip().lower()
... |
a7da3d1981b85b0afc3febab7212531053ea9345 | iroshan/python_practice | /dictdiff.py | 548 | 4.03125 | 4 |
def dictdiff(a, b):
"""returns the difference between a and b dictionaries """
# new dict to add data
c = {}
# make a set with unique keys
for k in set([*a.keys(), *b.keys()]):
# if both items are same, pass
if a.get(k, None) == b.get(k, None):
continue
# else ad... |
f96111974debd6f8a56e9eb3d964bcf2d40517d7 | iroshan/python_practice | /recursive_sum.py | 588 | 4.28125 | 4 | def recursive_sum(n=0):
''' recursively add the input to n and print the total when the input is blank'''
try:
i = input('enter a number: ')
# base case
if not i:
print(f'total = {n}')
# check if a number
elif not i.isnumeric():
print("not a number... |
65fb533a490dfcaf5ed1462f217047f7a8ae5f74 | iroshan/python_practice | /guess_the_number.py | 783 | 4.125 | 4 | from random import randint
def guess_num():
''' guess a random number between 0 and 100. while users guess is equal to the number provide clues'''
num = randint(0,100)
while True:
try:
# get the number and check
guess = int(input('enter your guess: '))
if num > g... |
cacbdc3406f8a22b653d6d447921dc826a2e68c2 | iroshan/python_practice | /tail.py | 670 | 3.9375 | 4 | '''
Unix-based operating systems also typically include a tool named tail.
It displays the last 10 lines of a file whose name is provided as a command line parameter.
Write a Python program that provides the same behavior.
Display an appropriate error message if the file requested by the user does not exist or if th... |
ebfcfd2080c938b2f842bebf1e0e21a2a75b8cd6 | jayfro/Lab_Python_04 | /Minimum Cost.py | 866 | 4.3125 | 4 | # Question 4 c
groceries = [ 'bananas', 'strawberries', 'apples', 'champagne' ] # sample grocery list
items_to_price_dict = { 'apples': [ 1.1, 1.3, 3.1 ], 'bananas': [ 2.1, 1.4, 1.6, 4.2 ],
'oranges': [ 2.2, 4.3, 1.7, 2.1, 4.2 ],
'pineapples': [ 2.2, 1.95, 2.5 ]... |
752e448ae3eaf8d76579da5008af8ea78e38615a | Spector255/izdruka | /uzdevumi/uzd_if_else_15_02.py | 2,052 | 3.921875 | 4 | a = 15
b = 2.5
c = 4.78
######################################
if a > b and a > c:
print("a ir vislielākais skaitlis")
if b > c:
print("c ir vismazākais")
else:
print("b ir vismazākais")
elif b > a and b > c:
print("b ir vislielākais skaitlis")
if a > c:
print("c ir vismazāka... |
02eabbf980d371405f296479b72f90d687f3eb80 | Spector255/izdruka | /materials/funk_spele.py | 713 | 3.765625 | 4 | from random import shuffle
def shuffle_list(mylist):
shuffle(mylist)
return mylist
def mans_minejums():
minejums = ""
while minejums not in ["1","2","3"]:
minejums = input("Izvēlies skaitli - 1, 2, 3: ")
return int(minejums)
def parbaudi_minejumu(lists,minejums):
if lists[minejums-1] ... |
904a8492344f813d8dd3cd843a61d988b7b8f431 | Spector255/izdruka | /materials/operatori.py | 364 | 3.546875 | 4 | #salīdzināšana
print(2 == 2)
print(2 == "2")
print(2 == 2.0)
print(2 * 2 != 5)
a = 50
b = 24.36
c = 4
print(a > b, b != c, c == a)
print(a >= b, b == c, c <= a)
#logiskie operatori - and/or/not
print(True or False)
a = 5
b = 10
c = 14
print(a > 5 and b > 20)
print(a >= 5 and b >= 7 and a < c or b >= c)
print(not a > 7... |
6b6880b800d0c2ed136a05006412ae59cec75768 | Spector255/izdruka | /uzdevumi/uzd_07_05.py | 955 | 3.65625 | 4 | #Lietotājs ievada divus vārdus, funkcija pārbauda kurā vārdā ir vairāk burtu, un par cik burtu ir vairāk.
def salidz(pirmais, otrais):
if (len(pirmais)) > (len(otrais)):
print(f"Pirmais vārds ({pirmais}) ir garāk nēka otrais({otrais}) uz {len(pirmais)-len(otrais)} burtu/burtiem")
elif (len(otrais)) > (l... |
2f96562010585d4313ee962b2100db2da5dc19be | Spector255/izdruka | /materials/noderigi_operatori.py | 1,679 | 4.03125 | 4 | #vienkārši piepildīt list ar elementiem
saraksts = list(range(0, 11, 2)) #izdrūka massīvu kurā ir ielikti pāra skaitļi no 0 līdz 11
print(saraksts)
print("========================")
#enumerate - parāda indeksus tuple formā
vards = "banans"
for i in enumerate(vards):
print(i)
print("========================")
#at... |
5d2a3a49765aa94904f86796419439162b09cb0c | Spector255/izdruka | /materials/while_cikls.py | 626 | 3.84375 | 4 | print("Hello world!")
i=1
while i<=5:
print("Sveiki!")
i += 1 #i=i+1
print ("i tagad ir", i)
j = 0
while j<5:
print("Nr.",j)
j += 1
while i>0:
print("skaitām atpakaļ",i)
i -= 1
# ar soli 2
i = 20
while True:
if i > 26:
break
print("i ir", i)
i += 2
####################... |
c8a215a90697d64b3eac7fea2ddf326e1c7e0e1c | Gastove/test-demo | /demo_src.py | 1,027 | 3.796875 | 4 | """
This is a tic-tac-toe victory checker. It looks at a tic-tac-toe board,
represented by an array of arrays, and determines if x won, y won, or the board
is a draw.
"""
def row_status(row):
s = set(row)
if len(s) == 1:
return row[0]
else:
return "no winner"
def check_for_winner(parsed_... |
1d1c305d28d0ab537902638455e679888457be22 | natedog334/TechnicalQuestionPractice | /Strings/uniqueString.py | 462 | 4 | 4 | # Determine if a string has all unique characters
# Time Complexity: O(n) - single pass through the string
# Space Complexity: O(n) - create a set that contains potentially every character in the string
def isUnique(str):
if len(str) == 0:
return True
seen = set()
for c in str:
if c in seen... |
ea4a79b77314ae45088a94a5ab02b6a7878093e8 | parkr/rarkr | /python/beginners.py | 770 | 3.78125 | 4 | #! /usr/bin/env python
# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
####### Math ########
print 2+2
print 2+2 # and a comment on the same line as code
print (50-5*6)/4
# Integer division retur... |
78c8198fc179fae06bda7ccccae056897e4e7bb4 | ak-akkinapelli/450_DSA_problems | /cyclically rotate elements.py | 118 | 3.828125 | 4 | #Cyclically rotate an array by one
def rotate( arr, n):
y = arr.pop(n-1)
arr.insert(0,y)
return arr
|
5b9e06ae96e430bf6b400e17128f944419f3f457 | mitrokhina/Polynomial | /test_cases.py | 5,465 | 3.5 | 4 | import unittest
from Polinomial import Polynomial
class TestPolynomial(unittest.TestCase):
def test_init_correct_int_coeff(self):
p = Polynomial([1, 2, 3])
self.assertEqual(p.coeffs, [1, 2, 3])
self.assertEqual(p.degree, 2)
def test_init_correct_float_coeff(self):
... |
a3b6a12ec18d72801bf0ee0bb8a348313ddb62fa | AZSilver/Python | /PycharmProjects/test/Homework 05.py | 2,286 | 4.4375 | 4 | # -------------------------------------------------------------------------------
# Name: Homework 05
# Purpose: Complete Homework 5
# Author: AZSilverman
# Created: 10/21/2014
# Desc: Asks the user for the name of a household item and its estimated value.
# then stores both pieces of data in a text file called HomeInv... |
84eb060e38fddd8e364ed1abd485c832a5d28917 | youdiandai/learn_Python_cookbook | /Data_Structures_and_Algorithms/1_6.py | 767 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'changxin'
__mtime__ = '2018/3/28'
"""
"""
可以一个键映射多个值的字典,multidict
"""
"""
可以用元组或者列表做字典的值
"""
from collections import defaultdict
#defaultdict可以创建一个multidict
#与记录分组有很强关联
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['a'].append(3)... |
97db740cf6ba3e09c917d9e1fbf0ba6421882b12 | DanielAdeyemi/CS50_Web_Python_practice | /classes.py | 819 | 4 | 4 | class Point():
def __init__(self, x, y): # create an object, self references object itself
self.x = x
self.y = y
p = Point(2, 8) # initiate new Point and print the data from inside
print(p.x)
print(p.y)
class Flight():
def __init__(self, capacity):
self.capacity = capacity
... |
cd1942abf9abc840e3e976984e21f3107da71cbc | sramirezh/Developing | /Tutorial_SimpleTeacherAPI/python-sample-code/tests/test_traversal.py | 1,336 | 3.796875 | 4 | """Unit tests for the traversal module."""
from binary_trees import binary_search_tree
from binary_trees import traversal
def test_binary_search_tree_traversal(basic_tree):
"""Test binary search tree traversal."""
tree = binary_search_tree.BinarySearchTree()
for key, data in basic_tree:
tree.ins... |
7c2f98d71d98d5d779fa626c6301ec53d6eb4d27 | zbalkan/ITC8240-Cryptography-Autumn-2021 | /src/crypto/transmissionCipher.py | 1,416 | 3.640625 | 4 | class TransmissionCipher:
def __init__(self):
print("An instance of class ", type(self).__name__, " is initiated.")
def __str__(self):
return "Encrypt/decrypt text with Transmission (Permutation) Cipher."
#region Public Methods
def encrypt(self, plain_text:str, key: str, padding: str) ... |
a42d3a2f7151e064e079a0226b1017b3c5197402 | Bromaniuk/Python-Single-User-Dungeon | /a4_unit_tests/test_riddle_answer_letter_check.py | 602 | 3.546875 | 4 | from unittest import TestCase
from game import riddle_answer_letter_check
class TestRiddleAnswerLetterCheck(TestCase):
def test_riddle_answer_letter_check_true(self):
guess = "h"
actual = riddle_answer_letter_check(guess)
self.assertEqual(actual, True)
def test_riddle_answer_letter_c... |
af98a2f5a7e28691e73b51218cf644686ec6590d | sjcorreia/python_foundation | /mindstorms.py | 3,873 | 3.796875 | 4 | import turtle
from math import sin,cos,pi
def ellipse(pen, x, y, width, height):
pen.penup()
pen.goto(x + width / 2, height)
pen.pendown()
penX, penY = pen.pos()
for i in range(0, 360):
penX += cos(i*pi/180)*width/180
penY += sin(i*pi/180)*height/180
pen.goto(penX, penY)
... |
c3d95e7c990e6cebcf8adf734c2b8ae114883603 | JJack27/evrythg | /fakultaet.py | 292 | 3.859375 | 4 | def iterativ (n) :
"""
Iteratively compute $n!$
"""
r = 1
for i in xrange (1 , n +1) :
r *= i
return r
def rekursiv (n) :
"""
Recursively compute $n!$
"""
if n == 0:
return n * rekursiv (n -1)
return 1
if __name__ == ' __main__':
print rekursiv (int(sys.argv[1]))
|
c7c1b39be333b1be048268ad3979c4d57057deb0 | sumit2010/ds_codes | /test/graph.py | 3,802 | 3.6875 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u] = v
self.graph[v] = u
def dfs(self):
def do(u):
visited.add(u)
print u
for v in self.graph[u]:
... |
5701e47b29fd6af15086bca78210c1340346cca5 | mateussantos21/PythonStudyAED | /L9.py | 904 | 4.0625 | 4 | Lista 9
#Funes recursivas
#Fatorial
#dados: x inteiro
def fatorial(x):
if x==0:
return(1)
else:
return x*fatorial(x-1)
#somatorio
#dados: n inteiro
def somatorio(n):
if n==1:
return(1)
return n+somatorio(n-1)
#contar algarismos
#dados: n inteiro
def qtddealgarismos(n):
if ... |
80362d4c4583ac93806eecab6064fed8eab86d52 | mash9738/PythonBasics | /OppsInstanceVariable.py | 201 | 3.828125 | 4 | class Car:
def __init__(self):
print("mil and com is instance variable")
self.mil = 10
self.com = "BMW"
c1 = Car()
c2 = Car()
print(c1.com, c1.mil)
print(c2.com, c2.mil) |
7b0133f1f7c594c8dad0c08927dabcb845acfdc6 | mash9738/PythonBasics | /primeNumber.py | 707 | 4.09375 | 4 | number = int(input("Enter Number: \n"))
if number > 1:
for i in range(2, number):
if number % i == 0:
print("Number not Prime")
break
else:
print("Number is Prime")
else:
print("Number is not prime")
lower = 900
upper = 1000
prime_number =[]
print("Prime number be... |
5d2ba115bfadec56bed01f428562093521419c14 | mash9738/PythonBasics | /hacker-Rank/append_delete2.py | 690 | 3.515625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the appendAndDelete function below.
def appendAndDelete(s, t, k):
end=0
for i in range(min(len(t), len(s))):
if s[i]==t[i]:
end+=1
else:
break
maxIter=len(s) + len(t)
minIter=ma... |
ed2a6ce0eb870f6860a7a47040bdf0bc62c64f8b | mash9738/PythonBasics | /ErrorFormat.py | 520 | 3.890625 | 4 | try:
a = int(input("enter a= \n"))
b = int(input("enter b = \n"))
print(a / b)
except IndentationError as e:
print("IndentationError", e)
except ZeroDivisionError as e:
print("ZeroDivisionError", e)
except ValueError as e:
print("invalid input", e)
except SyntaxError as e:
print(e)
except Sy... |
c33303b54934016740dbab60f2fef5a2bb29fcb9 | mash9738/PythonBasics | /ConvertlisttoDict.py | 146 | 3.96875 | 4 | my_list = ['u', 's', 'q', 'a', 'b', 'u', 'h', 'q']
my_dict = {}
for a in my_list:
my_dict[a] = my_list.index(a)
print('my_dict=', my_dict)
|
a083199ec877f95c9d1adc498418b257f3b7fc68 | mash9738/PythonBasics | /LamdaForFilter.py | 214 | 3.75 | 4 | nums = [3, 2, 6, 8, 4, 2, 9]
evens = list(filter(lambda n: n , nums))
print(evens)
functions = []
for i in range(10):
functions.append(lambda i : i + 1)
for f in functions:
print(f())
print(functions) |
7afc2b02b9dbd3010651ce3d4ab43ad792de62f6 | mash9738/PythonBasics | /BasicsOfRecursion.py | 368 | 3.5 | 4 | import sys
print("below section is to under the recursion ")
print("recursion limit modification ")
print(sys.getrecursionlimit())
sys.setrecursionlimit(2000)
print(sys.getrecursionlimit())
i = 0
def greet():
global i
i += 1
print("Hello", i)
if i <= 50:
greet()
greet()
print("------------... |
0385e75cbd4e3d1da6e0bd55b5272e284f377ff8 | mash9738/PythonBasics | /MultidimentionalArray.py | 284 | 3.53125 | 4 | from numpy import *
arr1 = array([
[1,2,3,6,2,9],
[4,5,6,7,5,3]
])
arr2 = arr1.flatten()
print(arr1, arr1.dtype, arr1.ndim, arr1.shape, arr1.size)
print(arr2)
arr3 = arr2.reshape(3, 4)
print(arr3)
arr4 = arr2.reshape(2, 2, 3)
print(arr4) |
b08713d9fbe6555f46823714214c87bd7a2dff6b | RocketHTML/nowhere_kids_python | /nowhere_kids/levels.py | 1,458 | 3.734375 | 4 | import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
CYAN = (179, 255, 255)
COLORS = {
"GREEN":GREEN,"RED":RED,
"BLUE":BLUE,"BLACK":BLACK,
"WHITE":WHITE, "CYAN":CYAN
}
def draw_square(screen,x,y,color):
## takes x y of first cyan 25x25 rectangle
## ... |
52b25724b00ccab1459e9dfcce086158794d6a5e | lkmcl37/Implementation-of-Machine-Learning-Algorithms | /perceptron model/test.py | 611 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from Perceptron import Perceptron
def f(x):
return 1 if x > 0 else 0
def train_and_test():
input_vec = [[1, 1], [0, 1], [1, 0], [0, 0]]
labels = [1, 0, 0, 0]
#learning rate = 0.1
#input number = 2
#activation function = f
#number of iterations = 1... |
646b780857ef3b2beab24f94b3b6e2b4ba738a55 | amurshak/Practice-Scripts | /reverse_string.py | 131 | 4.46875 | 4 | #Reverse by Alex Murshak
#reverses a given string
word = str(input("Please enter a word for me to reverse:"))
t = word[::-1]
print(t)
|
3e3a2e97e3b3b97952c6f93037d48af1829c922e | raisboualem250/raisboualem250 | /partie_02/liste_de_course_json.py | 1,967 | 3.90625 | 4 | import sys
import json
chemin = r"C:\Users\kenzi\Documents\FORMATION_PYTHON\partie_02\course_json.json"
with open(chemin,"r") as f:# read the first time from the json file
LISTE = json.load(f)
#print(LISTE)
MENU = """Choisissez parmi les 5 options suivantes :
1: Ajouter un élément à la liste
2: Retirer un élé... |
dc3eafe199d2caaeea71c30a040c15d6dd887c7b | u4ece10128/Problem_Solving | /ProblemSolving/Math.angleMBC.py | 294 | 3.703125 | 4 | import math
side_AB = float(input())
side_BC = float(input())
# calculate length of hypo
side_AC = math.sqrt((side_AB*side_AB) + (side_BC*side_BC))
side_MC = side_AC / 2
# print(side_MC, side_BC)
theta = math.degrees(math.acos(side_MC/side_BC))
print(str(round(180 - 90 - theta)) + '°')
|
6c64f1505db0b69276f2212bc96e8ec89ef81734 | u4ece10128/Problem_Solving | /DataStructures_Algorithms/10_FactorialofAnyNumber.py | 719 | 4.5 | 4 | # Find the factorial of a given number n
def factorial_iterative(n):
"""
Calculates the factorial of a given number
Complexity: O(N)
:param n: <int>
:return: <int>
"""
result = 1
for num in range(2, n+1):
result *= num
return result
def factorial_recursive(n):
"""
... |
e880d316e6c73a540fbe6bffe5cabf8a8a585194 | u4ece10128/Problem_Solving | /Codecon/Q2MaxOutfit.py | 1,114 | 3.765625 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
#
# Complete the 'getMaximumOutfits' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY outfits
# 2. INTEGER money
#
def getMaximumOutfits(outfits, money):
#... |
3d2c5ebe3389b332ebd49c47eeb290ac2a61a0a5 | morph1nX/Python- | /RandomGuesser.py | 972 | 4.03125 | 4 |
#Guess a random number
import random
u = int(input("Set a range. Guess from "))
v = int(input(" to "))
a = random.randint(u, v)
print("I have guessed a number.")
n = int(input("How many chances do you want?"))
print("Guess the number now.")
i = 0
while i < n:
i = i + 1
b = int... |
e7b4c41348118e99ffc6f98aaed67eefa930c245 | Narcolapser/PyGameLearningByDoing | /Old PyGame stuff/snake/snake.py | 2,886 | 3.953125 | 4 | #################################3##################################################################
# Name: Pygame Snake Experiement
# Purpose: Make a simple pygame game to get a handle on PyGame
# Date: 2013/12/22
# Programmer: Toben "Littlefoo" "Narcolapser" Archer
# Version: 0.1
##################################... |
aaf7cf4f4afb0026ba861f6cedb0ecfa67447037 | Nishant1027/Deep_Learning | /code2/errorhandling.py | 880 | 3.9375 | 4 | # The data point you will make a prediction for
input_data = np.array([0, 3])
# Sample weights
weights_0 = {'node_0': [2, 1],
'node_1': [1, 2],
'output': [1, 1]
}
# The actual target value, used to calculate the error
target_actual = 3
# Make prediction using original weights
mo... |
0216ad777af05770a315f4881b80d33c5ea64a89 | inmaugarc/Rossmann2 | /preprocess.py | 10,361 | 3.65625 | 4 | '''
This file is to prepare data for a machine learning model, so it includes:
- data pre-processing
- feature engineering (creation, deletion, extraction, scaling)
'''
# Let's import libraries
import pandas as pd # to handle dataframes
import os
import numpy as np
import matplotlib.pyplot as plt
... |
de2e1abde37e6fd696a8f50d6143d491d8fb5d05 | if412030/Programming | /Python/HackerRank/Introduction/Division.py | 1,658 | 4.40625 | 4 | """ In Python, there are two kinds of division: integer division and float division.
During the time of Python 2, when you divided one integer by another integer, no matter what, the result would always be an integer.
For example:
>>> 4/3
1
In order to make this a float division, you would need to convert one of t... |
0fdb20e59477fd96d05f5c3d2ed9abcbb0201e39 | if412030/Programming | /Python/HackerRank/Introduction/ModDivmod.py | 1,002 | 4.5 | 4 | """ One of the built-in functions of Python is divmod, which takes two arguments aa and bb and returns a tuple containing the quotient of a/ba/b first and then the remainder aa.
For example:
>>> print divmod(177,10)
(17, 7)
Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7.
Task
Read... |
9cb4703bcdefdf68107f687d7157f90e80f5c2f4 | Ganeshrockz/Security-Lab | /ELGAMAL/q2.py | 559 | 3.640625 | 4 |
def sendToA ( P , G , Y ):
print "In Alice"
M = input("Enter message to send : ")
A = 59
i = 1
while True:
if (G**i)%P == A:
break
i = i + 1
print "K value is " + str(i)
B = ((Y**i)*M) % P
print "C2 value " + str(B)
P = input("Enter Prime Number 1 : ")
G = input("Enter Prime Number 2 : ")
X = inpu... |
905edf82924e773f72417888719db1c61e9f2fad | opentechfn/medhavi | /api/json_parser.py | 1,359 | 3.640625 | 4 | import json
import os
import sys
class JsonParser(object):
def __init__(self, file):
self.file = file
def validate_json_data_type(self, data):
"""Validate the data type of json content
:param data: python object.
"""
if isinstance(data, dict):
for k, v in... |
a4b3cdb19f303ca88fb6f7442d00f9a5c2731c36 | ddjking123/lemon84 | /python_class/python01.py | 3,274 | 3.921875 | 4 | """标识符:python里面自己取得名字==命名规则 变量 函数==取名
#只能包含字母、数字和下划线
不能以数字开头
不能使用关键字
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async',
'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', ... |
ccd8a5449a93be626ab7257a06c271779fa8650d | jasDestiny/Data-Science | /Project scheduler/Source code/src.py | 1,356 | 3.53125 | 4 | #Made by John Arthur Samuel D
#All rights reserved ©2020
import pandas as pd
fileName=str(input("Please enter file name"))
rf=pd.read_csv(fileName)
#sparation of morning and afternoon slots
colName=str(input("Enter column name that identifies slot"))
val=str(input("Enter value that identifies morning batch"))
aftern... |
1699b92e6ecfe738b50ebdea2f40a2875de6ee29 | akozlovaa/algorythms_lab_1 | /managers/bubble_sort.py | 476 | 3.921875 | 4 | class BubbleSort:
comparison_counter = 0
swap_counter = 0
def bubble_sort_descending(given_list):
n = len(given_list)
for i in range(n - 1):
for j in range(0, n - i - 1):
if given_list[j].avg_rate < given_list[j + 1].avg_rate:
BubbleSort.compa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.