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 |
|---|---|---|---|---|---|---|
8a21d626471ee40247d391619d5c2d89ec8080a0 | TouailabIlyass/python_sys | /th2_2.py | 426 | 3.546875 | 4 | import threading
a=0
lock=threading.Semaphore(1)
def inc():
global a,lock
lock.acquire()
for x in range(1000000):
a=a+1
lock.release()
def main():
#global a,lock
#lock=threading.Lock()
#a=0
print('we start a = ',a)
t1=threading.Thread(target=inc,name='t1')
t2=threading.Thread(target=inc,name='t2')
t1.s... |
0a31a39fc54b6000dd04355a6c2588035740d0c0 | Taker2626/MauMau | /Move.py | 942 | 3.796875 | 4 | '''Lets a player make a move'''
def Move(Master,Player_lst,Turn):
from copy import copy
from Message import Clear,Card_display
Hand=Master[Player_lst[Turn]]
Clear()
print('Your current hand:\n')
Card_display(Hand)
if len(Master['Trash'])!=0:
Top=Master['Trash'][-1]
print(... |
fcdf4562ab9b593d77cc143da95c131b15e8c2e7 | Fabrizio-Yucra/introprogramacion | /Listas (Array)/ejercicio 3.py | 744 | 4 | 4 | base = float(input("Ingrese la base de su figura: "))
altura = float(input("Ingrese la altura de su figura: "))
numero = 1
lM = 0
lm = 0
if base > altura:
lM = base
lm = altura
else:
lM = altura
lm = base
no_entran = []
si_entran = []
while numero > 0:
radio = float(input("Ingrese un radio: "))
... |
82ed876cc4ca54552505c94f93e475ef9e6a42a5 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 11.py | 578 | 3.9375 | 4 | from datetime import date
print("Ingrese su fecha de nacimiento.")
dia = int(input("Día: "))
mes = int(input("Mes: "))
año = int(input("Año: "))
fecha_de_nacimiento = date(año, mes, dia)
hoy = date.today()
operacion = (hoy.year - fecha_de_nacimiento.year)
operacion_1 = (hoy.day - fecha_de_nacimiento.day)
operacion_2 ... |
c1f66fd41dc5001ba3889ffb4d27ddaf3910a497 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 3.py | 386 | 4 | 4 | numero_1 = int(input("Ingrese un numero entero: "))
numero_2 = int(input("ingrese un segundo numero entero: "))
if numero_1 % numero_2 == 0:
print(f"La division es exacta")
print(f"Cociente = {numero_1 / numero_2} ")
print(f"Resto = 0")
else:
print(f"La division no es exacta")
print(f"Cociente = {nu... |
98d41fcfec5ce89314bfd77dde2ee2c655b69b37 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 5.py | 442 | 3.859375 | 4 | variable_1 = input("Ingrese una palabra: ")
variable_2 = input("ingrese otra palabra: ")
if len(variable_1) > len(variable_2):
print(f"La palabra {variable_1} tiene {len(variable_1) - len(variable_2)} letras mas que {variable_2}")
elif len(variable_1) == len(variable_2):
print("Las dos palabras tienen el mismo ... |
a22ae353b847aaf12bc32aa1bef8e5cba1a54d77 | Fabrizio-Yucra/introprogramacion | /variables 2/ejercicio2.py | 225 | 3.78125 | 4 | dividendo = int(input("ingrese el dividendo :"))
divisor = int(input("ingrese el divisor :"))
operacion = dividendo % divisor
mensaje = f"El resto obtenido al dividir {dividendo} entre {divisor} es {operacion}"
print(mensaje) |
8a31d2d035ce465fc3627008172f5d69d2b8e305 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 4.py | 92 | 4 | 4 | numero = int(input("Ingrese un numero: "))
for a in range(0, numero + 1):
print(2 ** a)
|
b22a96344344d3dbfa349bbc83a4b0f6283d19ac | chiting765/LC_Everyday | /705_Design_HashSet.py | 787 | 3.5625 | 4 | class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769
self.buckets = [[] for i in range(self.keyRange)]
def add(self, key: int) -> None:
index = key % self.keyRange
if key not in self.buckets[index]:
... |
85d379bd305b6b7de56e87e54389a1c54a495610 | Jumaroag/tp-lights-out-python | /traductor.py | 433 | 3.71875 | 4 | import tablero
tablero.posciciones_del_tablero()
def traductor():
print("¿Qué poscición deseas jugar?")
a = input()
a = str(a)
a = a.lower()
if (a in tablero.posciciones_del_tablero()):
print(tablero.posciciones_del_tablero()[a])
elif (a not in tablero.posciciones_del_tablero()):
... |
98699800f9537bbe9e702fbe77b18f697f6ff0b5 | steve1281/mathquizer | /mathquiz.py | 6,669 | 3.53125 | 4 | #!/usr/bin/env python
import time
from math import ceil
import pygame
from quiz import quiz
from sprites import Chicken, Question, Answer, Feedback, TimerBox, ScoreBox
from colors import *
class Main():
def __init__(self):
pygame.init()
self.font = pygame.font.Font(None, 36)
self.clock = p... |
838399d50bf54c75975ad1ee7225f3fb237b712a | SamT16/CS1-Labs | /Python/Lab 72/frac_to_dec.py | 120 | 3.65625 | 4 | var1 = input("input the Numerator")
var2 = input("input the Denominator")
print var1,"/", var2,"=",
print var1/var2
|
cfd6b1b4b42ec2afac072e0fbcaa0043f6bd2d15 | PawningPawns/First-GitHub-Test | /return.py | 876 | 3.734375 | 4 | print("Hellow World!")
class Transaction:
sales_tax = 0.1
def __init__(self, total, discount_rate):
self.total = total
self.tax = Transaction.sales_tax * total
self.discount = disocunt_rate
self.total_discount = int(total - (total * discount))
def change_rate(self):
self.chan... |
0bdfcc13e4cb2faa012624babf6181f456923641 | teja0508/Clothing-Analysis-Forecasting---RNN | /Clothing Retail Sales -Seasonality Analysis And Forecasting - RNN.py | 5,167 | 3.640625 | 4 | """
Clothing Retail Sales -Seasonality Analysis & Forecasting With Recurrent Neural Networks -RNN :
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
#By Using Parse_Date=True , pandas will automatically detect date column as datetime object :
df=pd.read_csv('RSCCASN.c... |
1432a19e35b9e79f342d5c30dac680092a040db8 | james-lawlor/Lawlor_Utils | /print_random_lines.py | 1,962 | 3.625 | 4 | #Purpose: select random lines from a file
#Input: a text file with any headers/metatdata beginning with #
import sys
import getopt
from time import clock
from random import SystemRandom
def main(argv):
input_filename = ""
output_filename = ""
fraction_to_print = 0
added_metadata = False
try:
... |
b2996db8afbe2f952cf6bec133cfe69c1dbab752 | gurehf000109/python_big_and_small | /what's big.py | 256 | 3.734375 | 4 | def max(num1,num2):
if(num1>num2):
resert = num1
else:
resert = num2
return resert
x=eval(input("first number"))
y=eval(input("secend number"))
print(x,"와",y,"중 큰수는",max(x,y),"이고 작은수는",min(x,y),"이다")
|
e34df7e05d79e028fedd543098f2e2bf335f527b | AkshatBhat/Tic-Tac-Toe-Game | /MilestoneProject1.py | 4,227 | 4.03125 | 4 | def display_board(board):
print(' '+board[7]+' '+'|'+' '+board[8]+' '+'|'+' '+board[9]+' ')
print('--- --- ---')
print(' '+board[4]+' '+'|'+' '+board[5]+' '+'|'+' '+board[6]+' ')
print('--- --- ---')
print(' '+board[1]+' '+'|'+' '+board[2]+' '+'|'+' '+board[3]+' ')
def player_input():
... |
573ed22b1e142cdb4e136d7b6c39e697bfe6b917 | dosdarwin/BMI | /bmi.py | 410 | 4.21875 | 4 | height = (float(input('what is your height(in cm):')))/100
weight = float(input('what is your weight(in kg):'))
BMI = float(weight/(height*height))
if BMI < 18.4:
print('your BMI is',BMI, ',too light!')
elif 18.5 <= BMI <= 23.9:
print('your BMI is', BMI, ',perfect!')
elif 24 <= BMI <= 26.9:
print('your BMI ... |
19618a68a2ef38c0a2d35eb10c9e60ecbe0532d5 | gsantam/competitive-programming | /cracking_the_code/chapter_2/remove_node.py | 1,214 | 3.96875 | 4 | class Node():
def __init__(self,data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def appendNode(self,data):
node = Node(data)
if self.head == None:
self.head = node
else:
current_node ... |
2a2dd08a7e87992273c96c42418ad1d571d65e63 | gsantam/competitive-programming | /cracking_the_code/medium/ways_of_encoding.py | 564 | 3.5625 | 4 | """
data = "123"
ways_of_encodig("123")
ways_of_encodig("23") + ways_of_encodig("3")
1 + 1 +1
"""
def ways_of_encodig(message):
global ways_of_encofing
if len(message)==0:
return 1
if message[0]=="0":
return 0
if len(message)==1:
return 1
... |
ba2bfbc8460e4e45f6996c891b7ede22490d6f3d | gsantam/competitive-programming | /facebook_prep/colourful_numbers.py | 460 | 3.640625 | 4 | def is_colourful(number):
seen_numbers = set()
number_str = str(number)
for i,digit_str in enumerate(number_str):
product = 1
for j in range(i,len(number_str)):
product=int(number_str[j]) * product
if not (i==0 and j == len(number_str)-1):
if prod... |
55e9496a34932f667e1b5aecc18db85a2fb2313e | gsantam/competitive-programming | /hackerrank/preparation-kit/sort/fraudulent_activity_notifications.py | 1,472 | 3.765625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import os
def median(historical_expenditures,d):
i = 0
number_visited = 0
central_point = d//2 if d%2 == 0 else d//2 + 1
while number_visited < central_point:
number_visited+=historical_expenditures[i]
i+=1
i... |
12ef0a6b8a036b9061b44917cd054d28fa08b8ef | gsantam/competitive-programming | /leetcode/easy/valid-palindrome.py | 598 | 3.625 | 4 | class Solution:
def check_letter(self,char):
if (char>="a" and char<="z") or (char>="0" and char<="9"):
return True
return False
def isPalindrome(self, s: str) -> bool:
i = 0
j = len(s)-1
while i<j:
if not self.check_letter(s[i].lower()):... |
377d0acc018a61ddaf201a98b7857e4ad2463582 | gsantam/competitive-programming | /leetcode/easy/combinations.py | 440 | 3.53125 | 4 | class Solution:
def helper(self,current,n,k):
if len(current)==k:
self.all.append(current)
return
prev = 0
if len(current)>0:
prev = current[-1]
for i in range(prev+1,n+1):
self.helper(current+[i],n,k)
def comb... |
eded6122abdb10c2be9160b51b6d8755aa986e76 | gsantam/competitive-programming | /advent_of_code/2020/5/1.py | 464 | 3.71875 | 4 | seats = open("input.txt","r").readlines()
highest = 0
for seat in seats:
down = 0
up = 127
left = 0
right = 7
for letter in seat:
if letter == "F":
up = (down+up)//2
if letter == "B":
down = (down+up)//2
if letter == "R":
left = (left+right... |
df77d3ec7ca8b5999bd23811e11589311a4c36bb | gsantam/competitive-programming | /cracking_the_code/chapter_2/partition_by_x.py | 2,131 | 4 | 4 | class Node():
def __init__(self,data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def appendNode(self,data):
node = Node(data)
if self.head == None:
self.head = node
else:
current_node ... |
ca763b7533760c31f2e2c603dcfb82a6193d1dd4 | gsantam/competitive-programming | /leetcode/sort-characters-by-frequency.py | 443 | 3.5625 | 4 | class Solution:
def frequencySort(self, s: str) -> str:
count = dict()
for letter in s:
if letter not in count:
count[letter] = 0
count[letter] +=1
count = {k: v for k, v in sorted(count.items(), key=lambda item: item[1],reverse = True)}
... |
9877e9112764f61e99d7839cad687611a905ab21 | gsantam/competitive-programming | /advent_of_code/2019/6/2.py | 886 | 3.6875 | 4 | orbits = open("input.txt","r").read().split("\n")
orbit_dict = dict()
in_orbit = set()
for orbit in orbits:
if orbit!='':
planet_1 = orbit.split(")")[0]
planet_2 = orbit.split(")")[1]
if planet_1 not in orbit_dict:
orbit_dict[planet_1] = []
if planet_2 not in orbit_dict:
... |
cabdd31e43d25c7977ce15823d859f2e48e441c7 | riteshsharthi/botx | /FAQ/nlp_engine/extractors/email_extractor.py | 351 | 3.90625 | 4 | import re
def email_extractor(input):
match = re.search(r'[\w\.-]+@[\w\.-]+', input)
return match.group(0)
if __name__ == '__main__':
user_input=input("Enter Email information: ")
print(email_extractor(user_input))
#Ref: https://stackoverflow.com/questions/17681670/extract-email-... |
d9f6e6dc65781bdfdc6018f2817c35a0c3b4d6b4 | riteshsharthi/botx | /FAQ/nlp_engine/extractors/Date_Extractor_Month_name_Final.py | 1,071 | 3.921875 | 4 | from dateutil.parser import parse
import datetime
class DateMonthYear:
def __init__(self):
pass
#self.input = input
def date_extractor(self,input):
date = parse(input, fuzzy=True)
#d = dict({'month': date.month, 'year': date.year})
month=date.month
switche... |
d999688c971c11599747b52a8f1630c1f56e3542 | Ryandalion/Python | /Repetition Structures/Distance Travelled/Distance Travelled/Distance_Travelled.py | 777 | 4.4375 | 4 | # Function that asks the user to input the number of hours they have driven and the speed at which they were driving, the program will then calculate the total distance travelled per hour
distanceTravelled = 0;
numHours = int(input("Please enter the number of hours you drove: "));
speed = int(input("Please enter the ... |
9cd6a8de3348b4ce3d3209894b1b4bd896d36455 | Ryandalion/Python | /Functions/Home Insurance Cost Evaluator/Home Insurance Cost Evaluator/Home_Insurance_Cost_Evaluator.py | 884 | 4.09375 | 4 | # Function that calculates the home insurnace price given the replacement cost of the home
def calculatePrice(houseCost): # Function calculates the home insurance coverage the user should get based on the property value
replacement = houseCost * .80; # Coverage for 80 % of the home's value
print("The home insu... |
3d9f49a20ba365934e8a47255bde04df1db32495 | Ryandalion/Python | /Dictionaries and Sets/File Analysis/File Analysis/File_Analysis.py | 1,525 | 4.1875 | 4 | # Program will read the contents of two text files and determine a series of results between the two, such as mutual elements, exclusive elements, etc.
def main():
setA = set(open("file1.txt").read().split()); # Load data from file1.txt into setA
setB = set(open("file2.txt").read().split()); # Load data from f... |
8104fe235a31ab6451b31519e5c807892c13ef2f | Ryandalion/Python | /Functions/Odd Even Counter/Odd Even Counter/Odd_Even_Counter.py | 961 | 4.0625 | 4 | # Program generates 100 random numbers and determines the number of even and odd numbers in the batch
import random; # Import random module to access randint function
def even_odd(number): # Function determines wheter the parameter is even or odd
if(number % 2 == 0): # If the remainder of the number is zero than t... |
564b68912dd8b44e4001a22d92ff18471a55fbe4 | Ryandalion/Python | /Decision Structures and Boolean Logic/Age Calculator/Age Calculator/Age_Calculator.py | 568 | 4.4375 | 4 | # Function takes user's age and tells them if they are an infant, child, teen, or adult
# 1 year old or less = INFANT
# 1 ~ 13 year old = CHILD
# 13 ~ 20 = TEEN
# 20+ = ADULT
userAge = int(input('Please enter your age: '));
if userAge < 0 or userAge > 135:
print('Please enter a valid age');
else:
if userAge <... |
8a4d3456f828edb3893db4e6dd836873344b91e9 | Ryandalion/Python | /Functions/Future Value/Future Value/Future_Value.py | 1,862 | 4.59375 | 5 | # Program calculates the future value of one's savings account
def calculateInterest(principal, interestRate, months): # Function calculates the interest accumulated for the savings account given the arguments from the user
interestRate /= 100; # Convert the interest rate into a decimal
futureValue = principal... |
39cd605853421bafc6abaeda2b905e3bf06b6c6e | Ryandalion/Python | /Functions/Rock, Paper, Scissors!/Rock, Paper, Scissors!/Rock__Paper__Scissors_.py | 2,151 | 4.46875 | 4 | # Program is a simple rock paper scissors game versus the computer. The computer's hand will be randomly generated and the user will input theirs. Then the program will determine the winner. If it is a tie, a rematch will execute
import random; # Import random module to use randint
def generate_random(): # Generate a... |
5c7ddb25c658ac69730fa38f111e21dd1531a893 | Ryandalion/Python | /Repetition Structures/Tuition Increase/Tuition Increase/Tuition_Increase.py | 414 | 3.921875 | 4 | # Function that calculates the projected semester tuition amount for next 5 years conditional to a 3 percent increase in tuition each year
tuition = 8000;
increase = 0;
rate = .08;
totalCost = 0;
for x in range (0, 5, 1):
for y in range(0,4,1):
totalCost += tuition;
print("Tuition for year " + str(x +... |
456726f300be31e6ea1e3c7659b2370a3b77c53f | Ryandalion/Python | /Strings/Average Number of Words/Average Number of Words/Average_Number_of_Words.py | 3,028 | 4.40625 | 4 | # Program counts the number of words per each sentence in a text file.
def main():
inputFile = open('text.txt','r'); # Open the text file in read only mode
textFile = inputFile.readlines(); # Copy all the contents of the file into the textFile variable
inputFile.close(); # Close the input file
docLeng... |
c19b84caf9895177da8ccbcbd845ef5f03653e4d | Ryandalion/Python | /Functions/Fat and Carb Calorie Calculator/Fat and Carb Calorie Calculator/Fat_and_Carb_Calorie_Calculator.py | 1,465 | 4.34375 | 4 | # Function that gathers the carbohyrdates and fat the user has consumed and displays the amount of calories gained from each
def fatCalorie(fat): # Function calculates the calories gained from fat
calFat = fat * 9;
print("The total calories from",fat,"grams of fat is", calFat,"calories");
def carbCalorie(car... |
5d4fa6aaab3cc50ab1b67c9ab5add9ca49d2f25a | Ryandalion/Python | /Decision Structures and Boolean Logic/Roman Numeral Converter/Roman Numeral Converter/Roman_Numeral_Converter.py | 1,269 | 4.21875 | 4 | # Function converts a number to a roman numeral
userNum = int(input('Please enter a literal number between 1 ~ 10 you wish to convert to a Roman numeral: '));
if userNum < 0 or userNum > 10:
print('Please enter a number between 1 and 10');
else:
if userNum == 1:
print('I');
else:
if userNu... |
2b7ac8c5047791e80d7078a9f678b27c0c79d997 | Ryandalion/Python | /Lists and Tuples/Larger than N/Larger than N/Larger_than_N.py | 1,752 | 4.3125 | 4 | # Program generates a list via random generation and compares it to a user input number n which will determine if the elements within the last are greater than the number
import random; # Import the random module to generate a random integer
def main():
randNum = [0] * 10; # Intialize list with 10 elements of zer... |
b1ed47ef656c15a64464b1c29438a848b42e3665 | TartanLlama/filerover | /filetypechecker.py | 984 | 3.8125 | 4 | """Contains a method to check if a file is text or not
Derived from code found here http://code.activestate.com/recipes/173220-test-if-a-file-or-string-is-text-or-binary/"""
import string, sys
text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
_null_trans = string.maketrans("", "")
def istextfil... |
65d62036b3be07a9f956a7d1f22de61e92cfd780 | Carlos-Quixtan/practica1-lengusles-Formales- | /prueba2.py | 1,286 | 3.921875 | 4 | import json
from io import open
#print("-------------------------------------------------------------------------------")
#print este cogigo es el bueno para cargar multiples archivos
#print("-------------------------------------------------------------------------------")
datos = input("ingrese da... |
153851d6acdbaf3e1bd029148de295962b71a1c8 | sushantmishra/pythonbasics | /exceptional2.py | 206 | 3.796875 | 4 | def convert(s):
""" Convert to an int"""
try:
x = int(s)
print("Convertion succeeded! x=",x)
except ValueError:
print("Convertion failed")
x = -1
return x |
9b940938a12425ab4a83156b28cb7246803e8815 | Matheus-Nazario/Persistencia_de_Dados_em_Arquivos | /ler_imprimir_linha_por_linha.py | 176 | 3.734375 | 4 | # ler arquivo de texto linha por linha
arquivo = open("arquivo.txt", "r")
for linha in arquivo: # percorre o arquivo
print(linha) # implime cada linha
arquivo.close()
|
aa9d436ce702a0e1f5388612bfbd491d689165b1 | jackhamel16/MSU-EMresearch-Misc | /rings_method3.py | 3,021 | 3.84375 | 4 | """ Plots rings by checking if points on a plane are within the desired ring,
then plots those points. Also appends them to a file"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
###### FUNCTIONS ######
def create_plane (max_rad,dot_dist):
"""
Creates a plane of... |
b76a75995f2f4512e3cad477403cf22508da7d0a | jackhamel16/MSU-EMresearch-Misc | /min_dist_finder.py | 1,625 | 3.515625 | 4 | import numpy as np
dots_file = open("../sim_results/run16/dots.dat")
def get_coordinates(dots_file):
"""
grabs coordinates of dots from a dots file
returns n x 3 array of coordinates
"""
dots_line_list = [line for line in dots_file]
dot_pos_array = np.zeros((50,3))
dot_count = 0
f... |
daee14c84fcbbe19529eae9f874083297fc67493 | run-fourest-run/PythonDataStructures-Algos | /Chapter 3 - Python Data Types and Structures/Sets.py | 2,216 | 4.125 | 4 | '''
Sets are unordered collection of unique items. Sets are mutable, but the elements inside of them are immutable.
* Important distinctions is that the cannot contain duplicate keys
* Sets are typically used to perform mathmatical operations such as intersection, union, difference and complement.
Unlike sequence ty... |
541784722980135248e21e90d014e6114e95a7e5 | run-fourest-run/PythonDataStructures-Algos | /Chapter 5 - Algorithims/55_thinking_recursively.py | 733 | 3.796875 | 4 | from math import log10, ceil
'''
Python implementation of Karatsuba algo -
Demoing Recursion.
I really am totally lost here.
'''
def karasuba(x,y):
# the base case for recursion
if x < 10 or y < 10:
return x*y
# sets n, the number of digits of the highest input
n = max(int(log10(x) + 1 )... |
487ef0976d3e4c48df78864d75aa0c83f5339c7f | blqis/jeux | /Mini jeu.py | 2,661 | 3.609375 | 4 | class Aliment:
def __init__(self, nom, prix, point):
self.nom = nom
self.prix = prix
self.point = point
def acheter(self, perso):
if perso.argent >= self.prix:
print(self.nom + " achat possible")
perso.argent = perso.argent - self.prix
else:
... |
aa7224aef4f9c3d2b955f4f3fa08dccd43fba97e | Rifia/DSX | /labvsu/second.py | 2,694 | 3.65625 | 4 | # Лабораторная работа №2
# Input: текст и список слов (из файла и с клавиатуры)
# Задача: найти в тексте все слова, каждое из которых отличается от некоторого слова одной буквой
# и исправить такие слова на слова из списка
# FYI: 1й способ: в лоб, без стандартных встроенных функций по строкам 2й: с ними
# Output: если ... |
6bcc83323f6e28da180685293cbbae171a1d1927 | Bayuimamf/TugasADS | /nomor2.py | 180 | 3.953125 | 4 | n = int(input("n:"));
for i in range(1,n):
if i%5 ==0 and i%3 ==0:
print("FizzBuzz")
elif i%3 ==0:
print("Fizz")
elif i%5 ==0:
print("Buzz")
else :
print(i) |
aa727c6de6c93eeef66057a3967d611533d0b7b8 | rafaelvleite/TOTVS-Data-Challenge | /totvs-challenge.py | 4,079 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 14:27:47 2018
@author: rafaelleite
"""
# Recurrent Neural Network
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
dataset_train = pd... |
90e9a6e867b5601d2ce5fc2ed648d980eb904b17 | PWalis/Intro-Python-I | /src/10_functions.py | 495 | 4.28125 | 4 | # Write a function is_even that will return true if the passed-in number is even.
# YOUR CODE HERE
def is_even(n):
if n % 2 == 0:
return True
else:
return False
print(is_even(6))
# Read a number from the keyboard
num = input("Your number here")
num = int(num)
# Print out "Even!" if the numbe... |
65e41783b8468f030cf0371203be49b69cc4f259 | TBrockmeyer/clickprediction | /plot_descriptives.py | 3,794 | 3.921875 | 4 | # --- Code for creating scatter maps:
# Credits: Manoj Pravakar Saha on https://manojsaha.com/2017/03/08/drawing-locations-google-maps-python/
# --- Code for converting longitude and latitude values to cities:
# https://stackoverflow.com/questions/20169467/how-to-convert-from-longitude-and-latitude-to-country-or-c... |
dfe9013698659d952e1d873f2fcf6d19497e185c | RobertHan96/CodeUP_BASIC100_Algorithm | /1046.py | 327 | 3.90625 | 4 | # 세개의 숫자를 입력받아 합과 평균을 출력하는 함수
# 평균은 소수점 첫째자리까지만 반올림해서 표현
def calc() :
a , b, c = input().split(' ')
a = float(a)
b = float(b)
c = float(c)
sum = a+b+c
avg = (a+b+c)/3
print(int(sum))
print(round(avg, 1))
calc() |
0aedd43fd685c050f300b29d7899c85ac6a81eaa | RobertHan96/CodeUP_BASIC100_Algorithm | /1088.py | 637 | 3.75 | 4 | # 1부터 입력한 정수까지 1씩 증가시켜 출력하는 프로그램을 작성하되,
# 3의 배수인 경우는 출력하지 않도록 만들어보자.
# 예를 들면,
# 1 2 4 5 7 8 10 11 13 14 ...
# 와 같이 출력하는 것이다.
# 참고
# 반복문 안에서 continue;가 실행되면 그 아래의 내용을 건너뛰고, 다음 반복을 수행한다.
# 즉, 다음 반복으로 넘어가는 것이다.
def skipThree():
num = int(input("1~100 사이의 정수를 입력하세요"))
i = 0
while i < num:
i += 1
... |
a8c66d3b0a7a783d07b03b5f6b7fbb84294ac517 | RobertHan96/CodeUP_BASIC100_Algorithm | /1076.py | 266 | 3.8125 | 4 | # 소문자 a부터 입력한 문자까지 순서대로 공백을 두고 출력한다.
def printChar():
userInput = input()
inputAscii = ord(userInput)
i = ord('a')
while i <= inputAscii:
print(chr(i), end=" ")
i += 1
printChar()
|
7bed489506510173e2a236c8bf3be1fc372cdf15 | RobertHan96/CodeUP_BASIC100_Algorithm | /1054.py | 262 | 3.578125 | 4 | # 두개의 숫자를 입력받아 둘다 값이 1일때만 1을 출력하고, 아니면 0을 출력하는 함수
def calc():
a, b = input().split(' ')
a = int(a)
b = int(b)
if a and b == 1:
print(1)
else:
print(0)
calc()
|
ad0017b73937ba9313620bfc23101a2502707321 | Sumanthsjoshi/capstone-python-projects | /src/get_prime_number.py | 728 | 4.125 | 4 | # This program prints next prime number until user chooses to stop
# Problem statement: Have the program find prime numbers until the user chooses
# to stop asking for the next one.
# Define a generator function
def get_prime():
num = 3
yield 2
while True:
is_prime = True
for j in range(3,... |
8c99ba43d3481a6190df22b51b93d2d94358f68c | abhic55555/Python | /Assignments/Assignment2/Assignment2_3.py | 440 | 4.15625 | 4 | def factorial(value1):
if value1 > 0:
factorial = 1
for i in range(1,value1 + 1):
factorial = factorial*i
print("The factorial of {} is {}".format(value1,factorial))
elif value1==0:
print("The factorial of 0 is 1 ")
else:-
print("Invalid number")
... |
3725b66c142dece6d0192de11e620e5288fa8c6e | abhic55555/Python | /Assignments/Assignment1/Assignment1_10.py | 178 | 4 | 4 | def getlength(value):
print("Length of {} is {}".format(value, len(value)))
def main():
value=input("Enter name : ")
getlength(value)
if __name__ == "__main__":
main() |
2ba3f3e3d780bbf16068d11e234adeb70655f175 | CHEN-LI-ff/data-analysis | /【链表】singlelinklist_test.py | 3,373 | 3.671875 | 4 | #! usr/bin/env python3
# -*- coding:utf-8 -*-
class Node(object):
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkList(object):
def __init__(self):
self.__head = None
# 单向链表的操作
def travel(self): # 遍历
cur = self.__head
... |
f06acfc27979f222274d5b400cfffc84eb25b7f5 | stoogoff/python-to-javascript | /test-e2e/python/list_comprehension_test.py | 749 | 3.5625 | 4 | import unittest
class ListComprehensionTests( unittest.TestCase ):
def test_ListComprehension_01( self ):
vz = ( 1, 2, 3, 4 )
l = [ v * 3 for v in vz ]
assert l == [ 3, 6, 9, 12 ]
def test_ListComprehension_02( self ):
vz = ( 1, 2, 3, 4 )
l = [ v * 3 for v in vz if 10 ... |
8ba1f78a8d9ddaab71530743a28f3a0a4589cd09 | unikom2016/strukdat | /week2/insertion.py | 504 | 3.8125 | 4 | #!/usr/bin/env python
import string
def create(data):
for n in range(0,5):
data.append(0)
def traverseInput(data):
for i in range(0,5):
data.append(raw_input("Fill your data: "))
def traverseShow(data):
for x in range(0,5):
print(data[x])
def swap(dataA, dataB):
temp = dataA
dataA = dataB
d... |
a7e37d533bae15d8571f2cc00a653238e00dc590 | QAMichaelPeng/algs4-python | /algs4/commonutils/random_utils.py | 2,668 | 3.78125 | 4 | import random
from math import sqrt, log, ceil, exp
class StdRandom:
@staticmethod
def set_seed(seed=None):
random.seed(seed)
@staticmethod
def uniform():
"""
Generate a float number in [0.0, 1.0)
:return: a float number in [0.0, 1.0)
"""
return random... |
8aad1cc8337cead4ed82ba6ba20f1f9f9b0e3ad2 | anujism/d6tstack | /d6tstack/read_excel_adv.py | 7,970 | 3.5625 | 4 | import numpy as np
import pandas as pd
from .helpers_ui import *
from openpyxl.utils import coordinate_from_string
def read_excel_advanced(fname, remove_blank_cols=False, remove_blank_rows=False, collapse_header=False,
header_xls_range=None, header_xls_start=None, header_xls_end=None, nrows_pr... |
6844d8f64eb744883982d316af2822abee8548c2 | csdeep189/FullStackEngineer | /ReverseHash.py | 1,307 | 3.953125 | 4 | class RHash:
def __init__(self):
self.letters = 'acdegilmnoprstuw'
self.h = 7
#Function to reverse the hash given in the problem
#reverse of the given algorithm
# Int64 hash (String s) {
# Int64 h = 7
# String letters = "acdegilmnoprstuw"
# for(Int32 i = 0;... |
6f47d6cea76b8b29adfaf491e234496344442c08 | DavidZong/LEDPi | /ledmanual.py | 422 | 3.84375 | 4 | ## This program allows for the manual on off of the LEDs
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
while True:
print "Enter command: "
print "on, off or quit"
next = raw_input("> ")
if next == "quit":
GPIO.output(11, False)
break
elif next == "on":
GPIO.output(11, True)
el... |
17a51bf7ac1f42e8d862bb3eb0c7e23f9d8b0b7a | gaurabdey126/GitDemo | /Practice Questions/7. OOPs.py | 6,277 | 4.4375 | 4 | # OOP Exercise 1: Create a Vehicle class with max_speed and mileage instance attributes
# class Vehicle:
# def __init__(self, max_speed, mileage):
# self.max_speed = max_speed
# self.mileage = mileage
#
# car1 = Vehicle('100 km/hr', '11 ltr')
# car2 = Vehicle('150 km/hr', '9 ltr')
#
# print ('car1 ... |
cc94a6f66b8c0eebef52e77556690aad8a308dc2 | gaurabdey126/GitDemo | /Practice Questions/Function.py | 3,500 | 3.90625 | 4 | #Create a function that can accept two arguments name and age and print its value
# def personal(name, age):
# print(name)
# print(age)
#
# personal('Gaurab', 32)
######################################################################################################
#Exercise 4: Create a function showEmployee()... |
54018601625787d61a411ca80063ae79f639285e | gaurabdey126/GitDemo | /Initial Practice/Inheritance_Hands On.py | 4,621 | 3.96875 | 4 | #No link any of the classes
# class A:
# def feat1(self):
# print ('feat1 is working')
#
# def feat2(self):
# print ('feat2 is working')
#
# class B:
# def feat3(self):
# print('feat3 is working')
#
# def feat4(self):
# print('feat4 is working')
#
# class C:
# def fea... |
c6d023d790603e312690c71bcdbe4200b9e2472c | Nilesh7756/python-learning-scripts | /session-scripts/square.py | 85 | 3.5 | 4 | import sys
def square_num(num):
sq = num * num
print (sq)
square_num(5) |
6b89934c7911e7f1c24db7c739b46eb26050297c | Tyler668/Code-Challenges | /twoSum.py | 1,018 | 4.1875 | 4 | # # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# # (i.e., [0, 1, 2, 4, 5, 6, 7] might become[4, 5, 6, 7, 0, 1, 2]).
# # You are given a target value to search. If found in the array return its index, otherwise return -1.
# # You may assume no duplicate exists in th... |
1027294d654d81120d1435e7512a67d4bed764a2 | Tyler668/Code-Challenges | /functions.py | 583 | 4.03125 | 4 | # pass-by-reference vs pass-by-value
# define a function that multiplies its input by 2
# Single values typically passed by value
def mult_by_2(x):
x = x*2
return x
y = 12
z = mult_by_2(y)
print(z)
myList = [1, 2, 3]
# Typically data structures passed into a function are passed by reference
def mult2_... |
3d98d0a42963ab744fb4151ed58055a2678acb2b | Tyler668/Code-Challenges | /classes.py | 1,091 | 3.984375 | 4 | # Classes
class MedianFetcher:
def __init__(self): # Constructor self = this
# Define attributes
self.median = None # None = null and must be capitalized
self.numbers = []
# Inserts the value n into our class
def insert(self, n):
self.numbers.append(n)
self... |
35c294e745ede8519ec47c83d4e9b583a52f3c9c | SaiJyothiGudibandi/Python_CS5590-490-0001 | /Assignments/Assignment7/Source/file_funs.py | 1,276 | 3.65625 | 4 | import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from collections import Counter
import string
text1 = ""
fr = open("sample").read()
sw = set(stopwords.words('english')) #stop words
for s in fr.lower().split():
if s not in sw:
text1 ... |
15be302b0b417de9eb462b731ad20a0d78e448d8 | SaiJyothiGudibandi/Python_CS5590-490-0001 | /ICE/ICE1/2/Reverse.py | 328 | 4.21875 | 4 | num = int(input('Enter the number:')) #Taking nput from the user
Reverse = 0
while(num > 0): #loop to check whether the number is > 0
Reminder = num%10 # finding the reminder for number
Reverse = (Reverse * 10) + Reminder
num = num // 10
print('Reverse for the Entered number is:%d' %Reverse)
... |
e4682da4df50f7d7d22362843807ef0dfe54923c | PaperMadeGames/elements | /ai.py | 3,984 | 3.796875 | 4 | from board import Board
from copy import deepcopy
from random import choice
class AI:
def __init__(self, color):
# 'color' is the color this AI will play with (B or W)
self.color = color
def minimax(self, current_board, is_maximizing, depth, turn):
# Tries to find recursively the best value depending on whi... |
b14c3c6c1964d07f09fd4ca6bacb91844d61df60 | PaperMadeGames/elements | /piece.py | 4,488 | 3.96875 | 4 | from utils import get_position_with_row_col
class Piece:
def __init__(self, name):
# Example: <position><color><isKing?> 16WN
self.name = name
self.has_eaten = False # True if the piece instance has eaten a piece in its last move
def get_name(self):
return self.name
de... |
badb56f269035fdfb3c8b1c7af469bdf0816f797 | Pato38/EDI | /ejercicios python/tp3 prog-Piccadaci.py | 9,054 | 4.15625 | 4 | #1. Implementaremos una clase llamada Persona que tendrá como atributo (variable) el nombre de la persona y dos métodos (funciones).
# El primero de los métodos inicializará el atributo nombre y el segundo mostrará por pantalla el contenido del mismo.
# Definir dos instancias (objetos) de la clase Persona.
class Person... |
71a0ae58b46c26804fc5b973720df51ff6769597 | Pato38/EDI | /ejercicios python-1/cerveceria.py | 1,270 | 3.9375 | 4 | #carga cerveza por tipo
def leer_barril():
barril={
'producto':input("ingrese producto: "),
'litros':int(input("ingrese los litros por barril: ")),
'proveedor':input("ingrese proveedor: "),
'porc_amarg':int(input("ingrese porcentaje de amargura: ")),
'porc_alcohol':int(input("ingrese porcentaje de alco... |
53242aece8a7e2d465b0731d0beae34d5c24f718 | Pato38/EDI | /ejercicios python-1/jyfjhgjhjh.py | 272 | 3.828125 | 4 |
m_2=[[1,2],
[4,5]]
m_1=[[1,2],
[3,4]]
#busqueda secuencial del numero mayor en una matriz
objetivo=0
maximo=4
i=0
def busqueda_secuencial(m_1,diml,i):
while maximo!=objetivo and i<diml:
i=i+1
return maximo
maximo=busqueda_secuencial(m_1,2,i)
print(maximo)
|
43bdb82fb66a7b7a3ed86286fdf47ae5f2d04e2c | Pato38/EDI | /ejercicios python-1/suma recursiva.py | 509 | 3.609375 | 4 | #suma
n=10
def suma(n):
if n ==0:
return 0
else:
return n+suma(n-1)
suma(10)
print(suma(10))
#maximo recursivo
diml=4
max=0
i=0
arreglo=[]
def encontrar_maximo_recursivo(arreglo,i,diml,max):
if i == (diml):
return max
else:
if arreglo[i]> max:
return encontrar_maximo_recursivo(arreglo,i+1,diml,arre... |
fd277e3d0bf4085ab27e8904ac2ca689f2220d00 | Pato38/EDI | /ejercicios python/gestor-tp4.py | 2,076 | 3.6875 | 4 | from io import open
import pickle
#inicializamos la clase personajes con sus atributos
class Personaje:
def __init__(self, nombre={},vida=0, ataque=0, defensa=0, alcance=0):
self.nombre = nombre
self.vida = vida
self.ataque = ataque
self.defensa= defensa
self.alcance = alcance
#esta función imprime
def __... |
c29dcf41ae48e6ae08f641eb2ebaaa7c15d63027 | e459621485/leetcode | /generateParenthesis.py | 1,020 | 4 | 4 | '''
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
有效括号组合需满足:左括号必须以正确的顺序闭合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
n = 3
import copy
def generat... |
7f7fa454c18f1e2f99e7b29f029eeec50efe9613 | payoj21/Leetcode | /flower_bed.py | 795 | 3.8125 | 4 | def canPlaceFlowers(flowerbed,n):
def consecutivethreezeros(arr):
count = 0
i = 3
if len(arr) < i:
if arr[0] == 0:
count += 1
return count
else:
if arr[0] == 0 and arr[1] == 0:
count = count + 1
if arr[l... |
5043e51dbab062be2061e2ef34dacae01c4da24b | payoj21/Leetcode | /Nested_list_weight_sum.py | 435 | 3.640625 | 4 | def depthSum(nestedList):
tot_sum = 0
sum_list = []
if len(nestedList) == 0:
return 0
for i in nestedList:
sum_list.append((i,1))
while sum_list:
element,depth = sum_list.pop(0)
if element.isInteger():
tot_sum += depth*element.getInteger()
els... |
88b2810ad085c37bd9d6077957a6beb452c14ff2 | dburtnja/gomoku_python | /pattern_controller.py | 6,689 | 3.828125 | 4 | from abc import abstractmethod
from board import Board, COLUMNS, ROWS, EMPTY_CELL, FIRST_PLAYER, SECOND_PLAYER
FILLED_CELL = 'X'
EMPTY_CELL_CHAR = '-'
CHECK_DIRECTIONS = [
(-1, -1),
(1, -1),
(-1, 1),
(1, 1),
(0, 1),
(0, -1),
(1, 0),
(-1, 0)
]
class Pattern:
"""
Base Pattern ... |
684dba9a9265b5867782ca23dd12e646972bf8b8 | lorinatsumi/lista3 | /ex2.py | 496 | 4.1875 | 4 | #1 Escreva um algoritmo que permita a leitura das notas de uma turma de 5 alunos, armazenando os dados numa lista. Depois calcule a média da turma e conte quantos alunos obtiveram nota acima desta média calculada. Escrever a média da turma e o resultado da contagem.
notas = []
for i in range(5):
nota=int(input("Di... |
d49c33fc7fbda236f79ec73167610557b8d346f1 | gmacario/learning-python | /lpbook/ch3/multiple.sequences.py | 295 | 3.53125 | 4 | # multiple.sequences.py
# Reference: w_pacb43.pdf, page 81
people = ['Jonas', 'Julio', 'Mike', 'Moz']
ages = [25, 30, 31, 39]
print(type(people))
print(enumerate(people))
for position in range(len(people)):
person = people[position]
age = ages[position]
print(person, age)
# EOF
|
063d011f766e37f3aa5c0fefb37317ebf5420117 | radhalvy/random_game | /main.py | 1,908 | 3.859375 | 4 | import random
import math
def get_first_range():
num_range_1 = int(input("\nEnter the first number of the range: "))
return num_range_1
def get_second_range():
num_range_2 = int(input("\nEnter the second number of the range: "))
return num_range_2
def get_user_guess():
user_guess = int(input("... |
475ec010d457d16aa1d1a4f446a1d075d69e6d58 | justhonor/python-script | /closure/Closure.py | 1,528 | 3.640625 | 4 | #!/usr/bin/python
# coding:utf-8
##
# Filename: closure.py
# Author : aiapple
# Date : 2017-07-18
# Describe:
##
#############################################
origin = [0,0] # 坐标系统原点
legal_x = [0,50] # x轴方向的合法坐标
legal_y = [0,50] # y轴方向的合法坐标
def create(pos):
def player(direction,step):
# 这里应该首先判断参... |
89f11f0c9f388301a43935c2aefacd211c67c6ae | yumy-yumy/topic-model | /src/ioFile.py | 2,850 | 3.703125 | 4 | import csv
import pickle
import json
'''
Output
'''
def dataToFile(item, fname):
"""Function which writes each line to the file"""
with open(fname, 'a') as fileWriter:
fileWriter.write(item)
def abstractsToFile(all_abstract, fname):
"""Writes abstract to the txt file"""
with op... |
bb0b85fbe5e9fe5c3e05dfb28f35feba48e2d0d7 | jarturomora/learningpython | /ex16bis.py | 834 | 4.28125 | 4 | from sys import argv
script, filename = argv
# Opening the file in "read-write" mode.
my_file = open(filename, "rw+")
# We show the current contents of the file passed in filename.
print "This is the current content of the file %r." % filename
print my_file.read()
print "Do you want to create new content for this f... |
8e81b8f7d46c6257d8a6dbabfd677297149148be | jarturomora/learningpython | /ex44e.py | 863 | 4.15625 | 4 | class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Child(object):
def __init__(self):
self.other = Other() # The composition begins here
... |
b265f84cea66095258b6ff524d080d43ef49aa92 | jarturomora/learningpython | /ex43.py | 6,514 | 4 | 4 | from sys import exit # To allow exit the infinite loop
from random import randint # To generate random integer numbers
class Scene(object):
def enter(self):
"""This method describes each scene"""
print """
This scene is not yet described,
implement enter() on the subclass.
... |
48181fe62978caf5aedd0a912d8b47bebcb3cbb5 | Yadoloveel/Yadoloveel | /Homework1.py | 812 | 4.09375 | 4 | name1 = input('Enter your name: ')
age1 = input('Enter your age: ')
gender1 = input('Enter your gender: ')
alldata1 = 'Hello! My name is ' + name1 + ". I'm " + age1 + " and I'm a " + gender1
print('1', alldata1)
alldata11 = '%s%s%s%s%s%s' % ('Hello! My name is ', name1, ". I'm ", age1, " and I'm a ", gender1)
print('2... |
51004d01f1219a936afbf5e1bca330edbae4079e | abigail-hyde/flood-agh54-bjw68 | /floodsystem/flood.py | 1,319 | 3.546875 | 4 | from .station import MonitoringStation
from .utils import sorted_by_key
def stations_level_over_threshold(stations, tol):
# creates an empty list
flood = []
# iterates through the list and adds a stationif its data is consistent and its above the tolerance
for station in stations:
if station i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.