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 |
|---|---|---|---|---|---|---|
409314e49fecc6dc82f2750d740fa9e691a3fc23 | Biwoco-Playground/Learn-Docker_VNL | /Cookbook/Chapter4/4-11.py | 205 | 3.8125 | 4 | from itertools import zip_longest
a = [1,5,2,3,4,6,7]
b = ['c','a','b','d','a','f']
for x,y in zip(a,b):
print(x,y)
for x in zip(b,a):
print(x)
for x in zip_longest(b,a,fillvalue=0):
print(x)
|
187063b72c99ed11c117af2fa154c51a4b9dd899 | Biwoco-Playground/Learn-Docker_VNL | /Cookbook/Chapter2/2-14.py | 259 | 3.5625 | 4 |
def sample():
yield 'Is'
yield 'Chicago'
yield 'Not'
yield 'Chicago?'
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(' '.join(parts))
print(','.join(parts))
h = 'Vu'
l = 'Long'
n = 'Ngoc'
print(h,n,l,sep=' ')
print('+'.join(sample())) |
9d4d9c0a0fc1f8fea7533452b85ad53d1c5c4ab5 | Biwoco-Playground/Learn-Docker_VNL | /Cookbook/Chapter2/2-6.py | 194 | 3.734375 | 4 | import re
text = 'UPPER PYTHON, lower python, Mixed Python'
a = re.findall('python',text,flags=re.IGNORECASE)
b = re.sub('python','Long',text,flags=re.IGNORECASE)
print(text)
print(a)
print(b) |
b97dd0be85ef222c68510a16797d4c76e6f43a9d | Biwoco-Playground/Learn-Docker_VNL | /Cookbook/Chapter1/1-12.py | 386 | 4.28125 | 4 | from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
print(Counter(words))
print('In... |
e799a153964439565a312da1b5a37a8010a1cd45 | KhorowD/InformationTheory | /lab1/lab1.py | 2,168 | 3.8125 | 4 | from math import log2
def hartli_formula(N):
return log2(N)
def shennon_formula(N, p):
i = 0
H = 0
while i < N:
H += p[i]*log2(p[i])
i += 1
return -H
def redundancy(N, p):
H_max = hartli_formula(N)
H = shennon_formula(N,p)
return (H_max-H)*100/H_max
# first task:
# Какое количество состояний может прин... |
ce39214a8520855344428d7a6b4d643a4de920d5 | laurennchoii/shehacks_Python | /Team20_SheHacks_HO_Python.py | 2,532 | 4 | 4 | import random
def makeTesterNum(num):
if num[0] == '-':
return num[1:]
else:
return num
def makingLow():
lowNum = input("Choose the lower bound: ")
lowNumTester = makeTesterNum(lowNum)
while lowNumTester.isdigit() == False:
print ("Error. Only integers are allowed")
lowNum... |
a006d77db27edf66d222d2ef547cb9471acbe965 | hwj0418/Goblin-Solution | /src/question_type_select_frame.py | 4,931 | 3.796875 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class QuestionTypeSelectFrame(tk.Frame):
'''
Question Creation frame in which the user is able to specify
# of questions, due date and question type
'''
def __init__(self, parent, controller):
'''
Initializ... |
d322f4be4816e99c9fdefe628fd69e78d537d8be | MobileAppQueen/UniSchedule | /TimeBlock.py | 2,141 | 3.859375 | 4 | class TimeBlock:
"""start_time_hour=0
start_time_min=0
end_time_hour=0
end_time_min=0
day=1"""
#using 2 letter day abreviations Mo Tu We Th Fr
num_to_day = {1: "Mo",
2 : "Tu",
3 : "We",
4 : "Th",
5 : "Fr",
6 : "Sa",
}
day_to_num = {"Mo" : 1,
"Tu" : 2,
"We" : 3,
"Th" : 4,
"Fr" : 5,
"Sa" : 6,... |
8d075345b90ff5633e7e77a15e95781d2822550e | ankith26/My-PyChess | /chess/lib/ai.py | 2,991 | 3.796875 | 4 | """
This file is a part of My-PyChess application.
In this file, we implement a basic chess player algorithm in python.
This implementation is a weak player of chess.
This algorithm is not fast or efficient as any C impemenation of the same,
just an attempt to display the workings of the minimax algorithm with
... |
e511f0c278a17ed7fa60b04d64f6c24c516b6a3b | thanutpheeraphan/The-Internship | /internship_1.py | 383 | 3.703125 | 4 | ## Question1
words = []
lines = int(input("Input No. of lines: "))
cap_words = [""] * lines
for i in range(lines):
word_input = input("Word: ")
words.append(word_input)
for i in range(lines):
for letter in words[i]:
if (letter.isupper()):
cap_words[i] += letter
cap_words... |
5ce302b11c9418315697074f8e923c16fb6e563f | oriyocookie/Simple-Hangman | /hangman.py | 6,497 | 4.15625 | 4 |
import random #needed to randomize the word from the wordlist
class Hangman():
def main(self):
#ask the user if he wants to play
print("Hi, this is a very basic hangman game. Enjoy")
print("Press 1 to start the game. Other options to quit")
difficulty=int(input('Choose now: '))
... |
405eccc50639c4bd4f746241077e1cd303d199b7 | MingjuiLee/ML_PracticeProjects | /02_SimpleLinearRegression/main_pipeline.py | 690 | 3.671875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
dataset = pd.read_csv('Salary_Data.csv')
print(dataset.info()) # check if there is missing value
X = datas... |
903fa4b1f636803dd1f0d5459926a97e53207380 | MingjuiLee/ML_PracticeProjects | /02_SimpleLinearRegression/main.py | 1,595 | 4.125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Import dataset
dataset = pd.read_csv('Salary_Data.csv')
print(dataset.info()) # check if there is missing value
X = dataset.iloc[:, :-1].valu... |
965de5e75fe3f02bff54ddea3a58f8a1a51c9d72 | Oswoll/Assassin | /target.py | 240 | 3.53125 | 4 | import random
#people is a list of participant names ie ["John Smith","John Doe", "Joe Biden"]
def assign_targets(people):
new = random.shuffle(people)
ans = []
for x in range(0, len(new)):
ans.append({name:new[x],target:new[x+1]})
return ans |
68f561c9ccfe78c4aaa8e5ac14e41ec54556cf92 | ploypinkii/python | /homework6.py | 3,189 | 3.890625 | 4 | import sqlite3
conn = sqlite3.connect(r"D:\ED\term2\ED251007\ploychomphu_python\homework6.py")
def in_put():
while(True):
name_s = input("กรุณากรอกข้อมูล\nชื่อ-สกุลนักนักศึกษา:\t")
email_s = input("E-mail:\t")
sex_s = input("เพศ:\t")
age_s = input("อายุ:\t")
year_s = input("... |
c7d25a8e9b5656c2d349716c858758feb0dfe072 | ploypinkii/python | /midterm.py | 22,990 | 3.65625 | 4 | import sqlite3 as db
import sqlite3
conn = sqlite3.connect(r"D:\ED\term2\ED251007\ploychomphu_python\shipping.db")
c = conn.cursor()
global shipto
ntrack = []
def createdb():
conn = sqlite3.connect("shipping.db")
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS loei (tracking text,khonkaen text,nong... |
6ad879929d8086a7847a256b664e66887c8410b9 | SesameMing/LearningAlgorithms | /算法图解/4.快速排序/sum函数_py2_练习4.1.py | 301 | 3.625 | 4 | #!/usr/bin/env python2
# -*-coding:utf-8-*-
# Author:SesameMing <blog.v-api.cn>
# Email:admin@v-api.cn
# Time:2017-03-28 17:16
def sum(arr):
if len(arr) > 0:
return arr.pop() + sum(arr)
elif len(arr) == 0:
return 0
else:
return arr[0]
print sum([1, 2, 3, 100, 100000]) |
2441e373e0879d07fe72b994b1f3d7157ff5ac1f | JoshPritz/Spotify-Recommendations | /helpers/utilities.py | 4,702 | 3.5 | 4 | import os
import time
import traceback
import collections
import pandas as pd
#######################
# Data Frame Handling #
#######################
def flatten(d: dict, parent_key: str = '', sep: str = '_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
... |
38407b4a64dd2e80d36355633504168628dc9951 | 4GeeksAcademy/master-python-exercises | /exercises/020-factorial/solution.hide.py | 212 | 3.984375 | 4 | def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
x=int(input())
print (fact(x))
# or
# Your code here
import math
def factorial(num):
return math.factorial(num)
print(factorial(8)) |
7fc45fdb496f88a3d9737b2d6ff20b7f77d9ca50 | 4GeeksAcademy/master-python-exercises | /exercises/013-sum_of_digits/solution.hide.py | 296 | 4.375 | 4 | #Complete the function "digits_sum" so that it prints the sum of a three digit number.
def digits_sum(num):
aux = 0
for x in str(num):
aux= aux+int(x)
return aux
#Invoke the function with any three-digit-number
#You can try other three-digit numbers if you want
print(digits_sum(123)) |
68bb5a1aac0310906d9bb63fbac17b06a2199a51 | 4GeeksAcademy/master-python-exercises | /.learn/resets/007-hours_and_minutes/app.py | 218 | 3.59375 | 4 | #Complete the function to calculate how many hours and minutes are passed since midnight.
def hours_minutes(secs):
return None
#Invoke the funtion and pass any interger as its argument.
print(hours_minutes(3900)) |
5261c67f943e082073f3d6cc931acb0dd4bdd808 | Becomebright/I2CS-2019FALL | /GPA_Calculator.py | 2,735 | 3.921875 | 4 | # coding=utf-8
from typing import List
class Grade:
def __init__(self, course: str, credit: int, grade: float) -> None:
"""
初始化四个成员变量:course, credit, grade, gpa,其中gpa需要计算
输入: 课程名course, 学分credit, 成绩grade
输出:无
TODO: 初始化成员变量course, credit, grade, gpa(需要计算)
"""
... |
84a03999c133003993d504ee667ed72b224fdcca | Antonio-rl/Examen | /SalarioprofesorMARL.py | 277 | 3.8125 | 4 | def SalarioprofesorMARL():
salario=float(input("Digite el salario:"))
año=int(input("En cuantos desea el calculo:"))
i=int()
i=1
while i<=año:
salario=salario+(salario*0.1)
print("Es salario en el año",i," es de:",salario)
i = i+1
SalarioprofesorMARL() |
7b70e607e86a7aa5a7d46b31f5fb67488fd2fd5f | tr1ten/IndianBoardGames | /KMST.py | 3,421 | 3.53125 | 4 | # Author : Tri10
# NOTE : Poor Code ahead !
import random,time,sys
class KMST:
"""docstring for KMST, \n Use 'Start_game' function to play !"""
def __init__(self):
self.choices = {'Raja':1000,'Chor':0,'Mantri':800,'Sepai':500}
self.p = ['Raja','Chor','Mantri','Sepai']
self.totalscore = 0
self.score = 0
... |
5ddc5df3c64a3d8e4e3c73593a835f332620d6ce | lkwilson/cs320 | /pa3/heap.py | 7,251 | 3.96875 | 4 | import sys
import math
# BEGIN DO NOT MODIFY
db = False
swap_count = 0
heapify_call_count = 0
def reset_counts():
global swap_count
swap_count = 0
global heapify_call_count
heapify_call_count = 0
def swap(A, i, j):
global swap_count
swap_count += 1
A[i], A[j] = A[j], A[i]
def... |
e34bfc7fd0d6932dc95d7ec94f68510a5cf566b4 | bjarki88/Projects | /grid.py | 2,269 | 3.515625 | 4 | class Grid:
POS_X = 'x' #Fasti x fyrir staðsetningu a hnit
GRID_O = 'o' #Fasti o býr til hnitakerfið
START_POS = [0,0]
def __init__(self, height=0, width=0):
self.width = width
self.height = height
self.curr_pos = Grid.START_POS
def build_grid(self):
''' Býr ti... |
0627bc29400b783ed5bf32bd83ba5de53b3e152d | bjarki88/Projects | /prof1.py | 525 | 4.15625 | 4 | #secs = int(input("Input seconds: ")) # do not change this line
#hours = secs//(60*60)
#secs_remain = secs % 3600
#minutes = secs_remain // 60
#secs_remain2 = secs % 60
#seconds = secs_remain2
#print(hours,":",minutes,":",seconds) # do not change this line
max_int = 0
num_int = int(input("Input a number: ")) # D... |
3601e519212c6e3278503ddc01183011f95c1305 | UlyanaLes/hyperskill_Rock_Paper_Scissors | /Problems/Cipher/task.py | 79 | 3.53125 | 4 | string = "no clouds here to spy on pets"
print(*reversed(string[::5]),sep='')
|
93d40446b6efb5f802dfea6c495ec3de50714c98 | princegehlot/CST_JIET_Assignments | /Prince Gehlot/11May/Q1.py | 214 | 3.90625 | 4 | ls = []
n = int(input("Enter size of array:"))
print("Enter",n,"elements:")
for i in range(n):
ls.append(int(input()))
a = ls[0]
for i in range(1,n):
a = a^ls[i]
print("Enter that occurs ones:",a) |
368a72b76ee77d0293aac97b3531551c94f409fd | Suiname/CodeAdvent | /day1/part1.py | 227 | 3.640625 | 4 | if __name__ == "__main__":
fuel = 0
with open('input.txt') as masses:
line = masses.readline()
while line:
mass = line.strip()
fuel += (int(mass) // 3) - 2
line = masses.readline()
print('answer:')
print(fuel) |
24f5af661f6953de9ebe4e87d65253a37add58bf | mohammedgamal23/python-projects | /python psets solution CS50/bleep.py | 1,223 | 3.96875 | 4 | from sys import argv, exit
#from cs50 import get_string
def main():
# check if the command line arguments are correct
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
# assign the file to a variable
banned_file = argv[1]
# open the file to perform operations
... |
80fa5a41b2f32cf8fe094d30818f3af5e5bf2a1f | Hablakes/B_PROJECTS | /B_PROJECTS/B_FILE_RENAMER.py | 750 | 3.609375 | 4 | import os
def rename_files(folder_path, season, episode_start):
for i, file_name in enumerate(os.listdir(folder_path)):
# Get the file extension
file_extension = os.path.splitext(file_name)[1]
# Get the current file path
current_file_path = os.path.join(folder_path, file_... |
87f0b0245d8c6577d72b8792241ec439d37b1e41 | bibek1892/python_assignment3 | /TOH.py | 395 | 3.84375 | 4 | #i. Tower of hanoi
def tower_of_hanoi(n, start_node, target_node, aux_node):
if n == 1:
print(f'Move disk 1 from {start_node} to {target_node}')
return
tower_of_hanoi(n-1, start_node, aux_node, target_node)
print(f'Move disk {n} from {start_node} to {target_node}')
tower_of_hanoi(n-1,a... |
6d89923af8c0fcbe42554edd8e68f7cbdd8357b0 | ayushgoel1594/ShuffleSongsPython | /SongsShuffle.py | 3,175 | 3.890625 | 4 | import random
songsPlayed ={}
currentSong = 0
#this function will randomly shuffle the songs
def shuffleSongs(songsList):
#Everytime a unique list of songs will be generated
for i in range(0,len(songsList)):
randomNumber = random.randint(0,len(songsList)-1)
#swapping the songs in the list
... |
4c4e2d9c180004e1032dfc45c1ade77e62ad42f5 | Lcsundarraj/PythonPractice | /if_else.py | 402 | 4.0625 | 4 | a = 33
b = 200
if b > a:
print("b is greater than a")
a = 393
b = 290
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
a = 290
b = 290
if b > a:
print("b is greater than a")
elif a==b:
print("both are same")
else:
print("a is greater than b")
a = 333
b = 33
if b > a:print("b ... |
577db88fe09bd9506bf4f7d2e6402e2e97d0d59c | garsue/elorating | /lesson4_iterator.py | 4,526 | 4.125 | 4 | """
参考 イロレーティング
https://ja.wikipedia.org/wiki/%E3%82%A4%E3%83%AD%E3%83%AC%E3%83%BC%E3%83%86%E3%82%A3%E3%83%B3%E3%82%B0
このプログラムを理解するのに必要な知識
- イテレータ (iterator) https://docs.python.jp/3/tutorial/classes.html#iterators
- ジェネレータ (generator) https://docs.python.jp/3/tutorial/classes.html#generators
"""
# CSVファイル操作の関数を使う
im... |
41fdb5539c08e19775fb105d83fdc4448bbdb412 | ekpotosammuel/BUDGET | /Budget.py | 15,451 | 3.796875 | 4 | budgetDict = [{
"category": "food",
"amount": 0,
},{
"category": "cloths",
"amount": 0,
},{
"category": "entertainment",
"amount": 0,
}]
class Budget:
def __init__(self):
pass
def deposit(self):
print("Budget Options")
print("1. Food")
pri... |
cb65a40fcb43eaebb4dd0577049a2bb142e1fdd7 | cohen990/Danguage | /Types-tests.py | 2,759 | 3.5625 | 4 | import unittest
from Types import *
class TestObject___str__(unittest.TestCase):
def test_initializedWithEmptyValueAndEmptyType_ReturnsEmptyEverything(self):
thisObject = Object("", "")
self.assertEqual(str(thisObject), " <>")
def test_initializedWith15AndInt_Returns15_int(self):
thisObject = Object("15", "int... |
df87f1f9e0fc6a62e74f1c5b28573f039d7a580a | vdsperera/PythonTest | /excpFile.py | 200 | 3.9375 | 4 | def exists(file):
try:
f = open(fileName, "r");
f.close();
return True;
except:
return False;
fileName = input("Enter File Name : ");
print(exists(fileName));
|
cd3f85f0f3ba9c05565799d0624cac45af5672d4 | doseo/Credit-Card-Machine | /main.py | 1,551 | 3.84375 | 4 | #Dongmin Seo
from credit import Account
def main():
#Test Scenario 1
##A customer opens a credit card with a $1,000.00 limit at a 35% APR.
##The customer charges $500 on opening day (outstanding balance becomes $500).
##The total outstanding balance owed 30 days after opening should be $514.38.
##500 * (0.35 / 365) ... |
20198edc2742d160db704a992dd544f1627d5ac4 | B-Tech-AI-Python/Class-assignments | /sem-4/Lab1_12_21/sets.py | 680 | 4.28125 | 4 | print("\n--- Create a set ---")
set_one = {1, 3, 5, 7}
print(set_one)
print(type(set_one))
print("\n--- Add member(s) in a set ---")
set_two = {2, 3, 5, 7}
print(set_two)
print("Adding 11 to current set:", end=" ")
set_two.add(11)
print(set_two)
print(type(set_two))
print("\n--- Remove item(s) from a set ---")
to_r... |
5d2b637869dc20841c43b22ea3e8b7990d7b4822 | B-Tech-AI-Python/Class-assignments | /sem-4/Lab3_11_1/WaterJugProblem_BFS_DFS.py | 7,698 | 4.03125 | 4 | import collections
def get_index(node):
"""Returns a key value for a given node.
Attributes:
node (list): list of two integers representing current state of the jugs.
"""
return pow(7, node[0]) * pow(5, node[1])
def get_search_type():
"""Accepts an input for asking the choice for type ... |
6b41db45ecb0abc2198bb05fa99b1c7f00b2b7d7 | B-Tech-AI-Python/Class-assignments | /sem-3/7.JULY/30_Assignment.py | 3,642 | 4 | 4 | import time
import random
# Greatest common divisor
print("---Greatest common divisor---")
def gcd(x, y):
for num in range(1, max(x, y)+1):
if x % num == 0 and y % num == 0:
gcd = num
return gcd
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(... |
454fd566fe9e94e7bc375d1b2b522c76b110b7f0 | B-Tech-AI-Python/Class-assignments | /sem-3/Lab/Lab13/16_October_method-overloading.py | 407 | 3.6875 | 4 | # method overloading
from multipledispatch import dispatch
@dispatch(int,int)
def product(x,y):
result = x*y
print(f"int,int: {result}")
@dispatch(int,int,int)
def product(x,y,z):
result = x*y*z
print(f"int,int,int: {result}")
@dispatch(float,float,float)
def product(x,y,z):
result = x*y*z
pr... |
3e8127317c7492f1c2233349ad3f216224ee722c | B-Tech-AI-Python/Class-assignments | /sem-3/Lab/Lab9/11_September_file-handling.py | 2,251 | 4.0625 | 4 | # writing on file 1
f1 = open("file1.txt", "w")
f1.write("TThis is my line 1.\nThis is my line 2.\nThis is my line 3.\nThis is my line 4. ")
f1.close()
f1 = open("file1.txt", "r")
print("The data in file 1:\n")
print(f1.read())
f1.close()
# %% appending
f1 = open("file1.txt", "a")
input_string = input("Enter data... |
43d015b115f8b396ef4fc919ff2ccfa4b737ac97 | B-Tech-AI-Python/Class-assignments | /sem-3/Lab_File/exp_1.py | 892 | 4.21875 | 4 | # %%
# WAP to understand the different basic data types and expressions
print("Integer")
int_num = 1
print(int_num, "is", type(int_num))
# %%
print("Float")
float_num = 1.0
print(float_num, "is", type(float_num))
# %%
print("Complex Number")
complex_num = 1 + 8j
print(complex_num, "is", type(complex_num))
# %%
print... |
6a419424f1bea6adde883cb7cb651a05deb9f1fc | Fendo5242/Semana6lab | /Problema 1/problema3.py | 398 | 4.09375 | 4 | angulo = int(input("Ingrese el numero del angulo: "))
if angulo == 0:
print("nulo")
elif 0 < angulo < 90:
print("agudo")
elif angulo == 90:
print("recto")
elif 90 < angulo < 180:
print("obtuso")
elif angulo == 180:
print("llano")
elif 180 < angulo < 360:
print("concavo")
elif ... |
194af7eb05973b23d05851d9b90e2571abdbc8a1 | liuruitao/Python-liuruitao | /09-day/2-乘法口诀.py | 153 | 3.859375 | 4 | a = 1
while a <= 9:
print('1*%d=%d '%(a,a),end = '')
b = 2
while b <= a and b <= 9:
print("%d*%d=%d "%(a,b,a*b),end = '')
b+=1
print('')
a+=1
|
88bf7e2eaecd0c61ff917b0c70540c3f01a75495 | liuruitao/Python-liuruitao | /15-day/2手机号判断.py | 294 | 3.78125 | 4 | def check_phone(phone):
if phone.startswith("1") and len(phone) == 11:
return True
else:
return False
phone = input("请输入手机号:")
result = check_phone(phone)
if result == False:
print("注册的手机号不对")
phone2 = input("请输入手机号:")
result = check_phone(phone)
|
c548174c0803baebac563800e01dc0696ed9db2e | liuruitao/Python-liuruitao | /15-day/1计算器函数法.py | 386 | 3.703125 | 4 | def jisuanqi(x,y,l):#形参
if l == 1:
z=x+y
elif l == 2:
z=x-y
elif l == 3:
z=x*y
elif l == 4:
if y != 0:
z=x/y
else:
return "输入有误"
elif l == 5:
z=x**y
return z
while True:
x = int(input("请输入一个数字:"))
y = int(input("请再输入一个数字:"))
l = int(input("请选择一种运算方式:1.+ 2.- 3.* 4./ 5.**"))
jisuanqi(x,y,j)#实... |
e53549ac3379ab27f4b25efe209010a89a62448a | liuruitao/Python-liuruitao | /09-day/for猜数字.py | 226 | 3.796875 | 4 | import random
com_num = random.randint(1,100)
for i in range(1,10):
number = int(input("请输入:"))
if number > com_num:
print("大了")
elif number < com_num:
print("小了")
else:
print("对了%d"%number)
break
|
de9179a14a008ebe83153f1538b02441312fcfc5 | liuruitao/Python-liuruitao | /07-day/高富帅.py | 483 | 3.828125 | 4 | height = int(input("请输入身高:"))
money = int(input("请输入身价:"))
ss = int(input("请输入颜值分:"))
if hieght >= 180 and money <10 and ss >=90:
print("高帅")
elif hieght >= 180 and money > 1000000 and ss >= 90:
print("高富帅!!!!")
elif hieght < 180 and money > 1000000 and ss >= 90:
print("富帅~~")
elif height < 180 and money < 1000000 a... |
5fc579117b996954d7b922e6386e126b2becf191 | jackyho112/algorithms-on-strings | /bwt.py | 548 | 3.578125 | 4 | # python3
import sys
def BWT(text):
table = [text[i:] + text[:i] for i in range(len(text))]
table_sorted = table[:]
table_sorted.sort()
indexlist = []
for t in table_sorted:
index1 = table.index(t)
index1 = index1 + 1 if index1 < len(text) - 1 else 0
index2 = ta... |
9b40a71cf324a8e32c688665debc30bb7e0083e6 | markabrennan/code_challenges | /first_unique_number.py | 4,465 | 3.828125 | 4 | """
Leet Code April Daily Coding Challenge
First Unique Number
Couple of different ways to implement:
1) Linked List with hash map
2) Queue
3) Heap
"""
class FirstUnique:
class ListNode:
def __init__(self, val=None, next=None, prev=None):
self.val = val
self.next = next
... |
ff3df2583af5ca34ce74e1cd4b18b54a0a500396 | markabrennan/code_challenges | /max_subarray.py | 320 | 3.5625 | 4 | """
Leet Code "Maximum Subarray"
"""
def f(l):
mx = l[0]
running = l[0]
for i in l[1:]:
running += i
mx = max(mx, i, running)
running = max(i, running)
return mx
"""
TEST CASES
"""
l = [-2,1,-3,4,-1,2,1,-5,4] # expected result: [4,-1,2,1] has the largest sum = 6
print(f(l)) |
17932e97ff3da05e2b61597ddb09456548999773 | markabrennan/code_challenges | /buy_sell_stock.py | 2,028 | 3.640625 | 4 | """
Classic greedy search problem
from Interview Cake
Three Versions - third one is from Interview Cake
"""
def gf3(l):
mn = l[0]
mx = None
for i in range(1, len(l)):
cur = l[i]
if mx is None:
mx = cur - mn
else:
mx = max(cur-mn, mx)
mn = min(cur, mn... |
b5c5ad8ecefc26fcb8fba88a5ae26d1b27e6b301 | markabrennan/code_challenges | /container_with_most_water.py | 776 | 3.71875 | 4 | """
Leet Code Problem # 11: Container With Most Water
"""
def max_area(height):
"""
- Two pointers (i, j) move inwards;
- For each (i, j) pair, find the min
value, and then multiple min * min to derive
a new area;
- Re-set the area using the max of previous or current
area
"""
... |
666b45ad22bacfcb6594e3e8421f0a4c2bd7eb78 | markabrennan/code_challenges | /count_triplets.py | 845 | 3.796875 | 4 | """
HackerRank code challenge - Python solution code
is below, which I wanto to step through....
"""
def countTriplets(arr, r):
if len(arr) <= 2:
return 0
map_arr = {}
map_doubles = {}
count = 0
# Traversing the array from rear, helps avoid division
for x in arr[::-1]:
r_x = r*... |
3895b4763329284785b21c2aa6c06b3816934d0b | markabrennan/code_challenges | /cake_list.py | 989 | 4 | 4 | """
Some linked list work, based on Interview Cake
problems and code.
"""
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def print_list(node):
vals = []
n = node
while n:
vals.append(n.value)
n = n.next
return vals
"""
This i... |
340ebc5cfaec3d2a047abf7fefdaed74248e14c3 | markabrennan/code_challenges | /min_connections.py | 3,323 | 3.75 | 4 | """
Question #2 from Amazon Coding Challenge,
as described on Leet Code blog post:
https://leetcode.com/discuss/interview-question/797541/amazon-online-assessment-2-sde-1-new-graduate-2021-coding-2-questions-with-solutions
It appears to be a graph problem - minimum path.
"""
from collections import deque
class Node:... |
83dde3cec66949623288bf18f8b7c36af8fe0194 | markabrennan/code_challenges | /tripliets_sum_to_zero.py | 1,142 | 3.71875 | 4 | """
Grokking The Coding Interview:
Triplets Sum to Zero
"""
"""
Going to use a "two sum" algo for helping
"""
def two_sum(l, target):
i = 0
j = len(l) - 1
while i < j:
cur = l[i] + l[j]
if cur == target:
return [l[i], l[j]]
elif cur < target:
i += 1
e... |
da5e544e94c45ba18b37f530f17bf25643a68021 | markabrennan/code_challenges | /flood_fill2.py | 1,078 | 3.671875 | 4 | """
New attempt of Flood Fill
problem - trying to review
DFS for matrix problems
"""
def flood_fill(image, sr, sc, new_color):
def dfs(image, sr, sc, new_color, old_color):
if sr < 0 or sr >= len(image) or sc < 0 or sc >= len(image[sr]) or image[sr][sc] == new_color or image[sr][sc] != old_color:
... |
fe6c7df9f5b993368a2a39cc316dd2d4551412e0 | markabrennan/code_challenges | /add_strs_to_ints.py | 1,188 | 3.5625 | 4 | """
Leet Code Problem # 415: Add Strings
It was easy to convert a string to an int, then add;
but converting BACK to a string stumped me until I picked
up the 'get_pos_nums()' code
"""
def addStrings(self, num1: str, num2: str) -> str:
def get_pos_nums(num):
d = {0:'0', 1:'1', 2:'2', 3:'3', 4:'4', 5:'5', ... |
3d01c33db562dea8ee8f7b2b95270b3c2af848cb | markabrennan/code_challenges | /flood_fill.py | 986 | 3.5625 | 4 | """
Leet Code Problem # 733 - "Flood Fill"
This problem is much like the problem I was given
on my Skilled mock interview by the Amazon engineer,
and it is also similar to Number of Islands (though it's
easier)
"""
def floodFill(image, sr, sc, newColor):
def dfs(image, sr, sc, newColor, oldColor):
if image... |
168efec5e79f9df8e54fafe24a6c629fec7aca36 | markabrennan/code_challenges | /happy_number.py | 742 | 3.859375 | 4 | """
Grokking the Coding Interview
Happy Number
"""
def find_happy_number(nums):
sols = set()
n = nums
while True:
digits = []
while n:
digits.append(n % 10)
n = n // 10
digits = digits[::-1]
sq_sum = 0
for i in digits:
sq_sum += i... |
b37e5408010d4da242ec26f015a48cf747e266c4 | AdrianVazquezReyes/pythonCode | /templstr_finished.py | 998 | 4 | 4 | # demonstrate template string functions
from string import Template
def main():
# Usual string formatting with format()
print('*'*100)
str1 = 'you are reading the book: {0} by {1}'.format('Blue house', 'Edward Alan')
print(str1)
print('hello from terminal 1')
print('hello from terminal 2 in s... |
c436b29ac8c975677dd46c2d548bd33e852d746a | estherw1233/MiddleSchoolAcceptances | /ds_final_project.py | 8,600 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 02:23:36 2020
@author: esther
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
from sklearn.decomposition import PCA
from scipy import stats
from sklearn import linear_model
import statsm... |
7b03dd503d035fd9426d7723ac6b8c7bb01df54e | mbjallow6/free-steam-education | /src/components/sales.py | 459 | 3.875 | 4 | print("\n手机店打折活动进行中")
strWeek = input("请输入中文星期(如星期一): ") # 输入星期
intTime = int(input("请输入时间中的小时(范围0-23):")) # 输入时间
if (strWeek == "星期二" and (intTime >= 10 and intTime <= 11)) or (strWeek == "星期五" and (intTime >= 14 and intTime <= 15)):
print("恭喜您,获得了折扣参与资格!")
else:
print("对不起,您来晚一步,期待下次活动")
|
fbfb4a3f2ec2c433597d7e5e89e938efb1f18e72 | vkrajnak/binary_contraction | /binary_contraction_illustration.py | 1,249 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 19:22:36 2020
@author: vk17590
"""
def quadrant(point):
"""
Function returning the quadrant a point belongs to.
"""
return 0
def binary_contraction_step(points, points_q):
"""
Step in binary contraction procedure
"""... |
c6869ba306dc7d92fb308ffca6c7eeeee20b94d2 | cd-chicago-june-cohort/dojo_squeeze | /flatten.py | 418 | 3.6875 | 4 | def flatten(arr, i , newArr):
if i == len(arr):
return newArr
if isinstance(arr[i],tuple):
flatten(list(arr[i]),0,newArr)
elif isinstance(arr[i],list):
#return newArr.append(flatten(arr[i],0,newArr))
flatten(arr[i],0,newArr)
else:
newArr.append(arr[i])
return ... |
9d1b91951897d8967f64b5acde354fcf324507e4 | pypas/study | /big-o/ex4.py | 258 | 3.625 | 4 | def printUnorderedPairs(arrayA, arrayB):
for i in range(len(arrayA)):
for j in range(len(arrayB)):
if(arrayA[i] < arrayB[j]):
#O(1)
print(str(arrayA[i]) + " , " + str(arrayB[j]))
printUnorderedPairs([5,3,6],[1,4,2])
# The complexity is O(A*B) |
d3c29c09df8ea0f91d4f803dd2195d5cb6c6ed9b | pypas/study | /linked-list/linked-list.py | 491 | 3.96875 | 4 | # Linked List
class Node:
next = None
data = None
def __init__(self,d):
self.data = d
def appendToTail(self,d):
end = Node(d)
n = self
while(n.next != None):
n = n.next
n.next = end
def deleteNode(self, head, d):
n = head
if(n.data == d):
return head.next
while(n.next != None):
if(n.n... |
bde8ead585bb13b480d9dd60a77bd0d0ebb7e0b0 | pypas/study | /big-o/VI4.py | 148 | 3.78125 | 4 | def div(a, b):
count = 0
sum = b
while(sum <= a):
sum += b
count += 1
return count
a = 5
b = 2
print(div(a,b))
# The complexity is O(A/B) |
7868c26de9ba16814e1874a97baa67d003d4b8ae | tylerleesanti/Rock-Paper-Scissors | /Rock Paper Scissors.py | 2,927 | 4.03125 | 4 | import random
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
cls()
while True:
computer_random_choice = random.randint(1, 3)
if computer_random_choice == 1:
cpu_choice = 1
cpu_roll = "Rock"
if computer_random_choice == 2:
cpu_choice = 2
cpu_roll = "P... |
a4e85685b48f804fb3a66c25c9e8caf10cc25539 | chengxinmu/python_note | /game.py | 1,135 | 3.578125 | 4 | import random
print('*'*30)
print('欢迎进入澳门赌场!')
print('*'*30)
username = input('请输入顾客大名:')
money = 0
answer = input('确定进入游戏么?(y/n)?')
if answer == 'y':
while money <2:
n = int(input('金币不足,请充值(100元30币,充值必须为100的倍数):'))
if n%100==0 and n >0:
money = (n // 100)*30
print('当前游戏币是:{},玩一局游... |
9a9d1ba36d53ac344db7c8634f808ec12672c121 | sparkfish/augraphy | /augraphy/augmentations/jpeg.py | 1,618 | 3.546875 | 4 | import random
import cv2
import numpy as np
from augraphy.base.augmentation import Augmentation
class Jpeg(Augmentation):
"""Uses JPEG encoding to create compression artifacts in the image.
:param quality_range: Pair of ints determining the range from which to
sample the compression quality.
... |
1baeaeda2b4440e5adabb436c5a7fcf29316b54f | sparkfish/augraphy | /augraphy/augmentations/noisylines.py | 9,242 | 3.53125 | 4 | import random
import cv2
import numpy as np
from augraphy.base.augmentation import Augmentation
from augraphy.utilities.overlaybuilder import OverlayBuilder
class NoisyLines(Augmentation):
"""Create noisy lines by drawing horizontal or vertical lines in a fixed intervals.
:param noisy_lines_direction: Dire... |
f8ecc8e659d1263f6d5d6d8d8e81be6dabfec422 | sparkfish/augraphy | /augraphy/augmentations/hollow.py | 13,021 | 3.671875 | 4 | import random
import cv2
import numpy as np
from augraphy.base.augmentation import Augmentation
class Hollow(Augmentation):
"""Creates hollow effect by replacing detected contours with edges.
The detected contours are removed by using median filter operation.
:param hollow_median_kernel_value_range... |
3acccbf9db08ac8c139397f4b7fe18875125c7d2 | sparkfish/augraphy | /augraphy/utilities/meshgenerator.py | 5,521 | 3.828125 | 4 | """
Version: 0.0.1
*********************************
References:
- Perlin Noise: https://iq.opengenus.org/perlin-noise/
*********************************
"""
import math
import random
class Vector2:
"""
Gives a 2D vector based on the input parameters.
"""
def __init__(self, x, y):
"""
... |
3539ec508b058c8340245d2f090d0b7ba2ba8113 | sparkfish/augraphy | /augraphy/augmentations/sectionshift.py | 9,418 | 3.8125 | 4 | import random
import cv2
import numpy as np
from augraphy.base.augmentation import Augmentation
class SectionShift(Augmentation):
"""Shift single or multiple sections of image in horizontal, vertical or both directions to create an effect of shifted image sections.
:param section_shift_number_range: Tuple ... |
ff3134c834c903218aafa07dc0961f138b426015 | Bhavyasribilluri/python | /nom.py | 219 | 4.46875 | 4 | #to find largest number
list= []
num= int(input("Enter number of elements in the list:"))
for i in range(1, num + 1):
ele = int(input("Enter elements: "))
list.append(ele)
print("Largest element is:", max(list)) |
056f09663f25e2ab836669d199abd22e562483d3 | macroscopicentric/library_world | /formatting.py | 1,084 | 3.78125 | 4 | """
Because I'm an English major and have standards for natural English language
printouts for items/NPCS.
"""
def list_items(items):
singular = "There is "
plural = 'There are '
if len(items) == 1:
return singular + article(items[0]) + ' here.'
elif len(items) == 2:
return plural + ar... |
199974e6bc3db11aa958b27158d5833d312e1e3a | penut85420/PythonWork | /RPyG/Menu.py | 794 | 3.65625 | 4 | class Menu:
def __init__(self, menuItems, menuAllow=None):
if not menuAllow:
self.allow = [True] * len(menuItems)
else: self.allow = menuAllow
self.items = menuItems
def show(self):
for i, s in enumerate(self.items):
if self.allow[i]: print(s)
... |
f6ffb194459a78a77bb2b6a239f5100f774ce1d1 | Abhik-0101/task-1 | /printing positive number.py | 258 | 3.578125 | 4 | list1 = [12, -7, 5, 64, -14]
list2 = [12, 14, -95, 3]
pos_nos = [num for num in list1 if num >= 0]
print("input: ",*list1)
print("output: ", *pos_nos)
pos_nos = [num for num in list2 if num >= 0]
print("input: ",*list2)
print("output: ", *pos_nos)
|
194d66dd1fdf4914245404498ccaab7632fd08c7 | Dorzhievzhargal/ZHARGAL | /funtion.py | 613 | 3.96875 | 4 | """
def print_twice(arr):
c = 0
#return sum([x for x in arr if x > 0])
for x in arr:
if x>0:
c+=x
return c
print(print_twice([1,2,3,4]))
"""
"""def oposit(add):
return -add if add>0 else abs(add)
print(oposit(-102))
print(oposit(-3))
print(oposit(5))
"""
"""def print_twice(a... |
7e62f7973b702e95513b3467e0cebbba1fffa8bd | leonardobussi/graphList | /exercicio2.py | 1,154 | 3.703125 | 4 | aresta = list()
a = list()
def grafo():
repita = 's'
v = 1
print(f"vertice V{v}: ")
while repita == 's':
v = v + 1
n = int(input("quantas arestas: "))
for i in range(0,n):
a.append(int(input("digite as arestas: ")))
aresta.append(a[:])
del a[:]
repita = (input(f" deseja adicionar ... |
44a1d49282b23fbd5a7f205c7cfd75ed70cde1e5 | randyrollofson/cs533 | /philosophers/dp_shared_memory.py | 3,254 | 3.875 | 4 | import threading
import random
import time
from threading import Thread, Lock
program_duration = 60
number_of_runs = 50
philosophers = []
sum_wait_time = 0
sum_throughput = 0
class Philosopher(Thread):
running = True
total_wait_time = 0
times_eating = 0
def __init__(self, name, left_chopstick, rig... |
34ca3e7fac4ebcc9922d2f20cf36a5b21a94f1e8 | rangalo/dotfiles | /bin/numberFreq.py | 517 | 3.625 | 4 | #!/usr/bin/env python
import sys,operator
if (len(sys.argv) != 2):
print( "Usage: " + sys.argv[0] + " <filepath>")
exit()
fileName = sys.argv[1]
fIn = open(fileName,'r')
numDict = {}
for line in fIn:
key = line.strip()
if numDict.has_key(key):
numDict[key] = numDict[key] + 1
else:
... |
bd86e6424897395ee36c3352d52d6326d64818d3 | Joe656/CA104-01- | /List.py | 514 | 4.09375 | 4 | end = False
names= []
for x in range (0,10):
aname=input("Enter a name: ")
names.append(aname)
while not end:
print("At any time you can type End with the capital and no spaces to end your search")
print (names)
search = input ("Enter a name you wish to search for:")
if search == ("... |
f70ed501c8f07f43e36b37a2c85d98e6d643ab30 | piotrmludzik/Keymaker | /keymaker.py | 9,677 | 4.375 | 4 | # -------------------------------------------------------------------------------------------------
# Keymaker
# -------------------------------------------------------------------------------------------------
#
# Based on lower case letters, the program use a couple o... |
0667ccc62c5aa654604c19782545030cceaa31c0 | pinksi/Project-Euler-Solution | /problem9.py | 383 | 3.625 | 4 | # solution to project euler problem 9
def check_pythagorean_triplet(a, b, c):
return a ** 2 + b ** 2 == c ** 2
def main():
for i in range(1, 1000):
for j in range(i, 1000 - i):
for k in range(j, 1000 - j):
if i + j + k == 1000:
if check_pythagorean_trip... |
2572d397627fa648c878472b65cf30929e21f90f | cellois/AdvancedAlgorithms | /Approximation/AVC.py | 589 | 3.5 | 4 | def ApproximateVertexCover(graph, s):
cover = []
visited = [False for _ in range(s)]
for u in range(s):
if not visited[u]:
for v in graph[u]:
if not visited[v]:
visited[u] = True
visited[v] = True
cover.append(u... |
b66e1f756c71f4ecf65a7178da25186bcb728b8d | keshavcodex/college-assignment | /IT WORKSHOP/factorial.py | 137 | 4.1875 | 4 | n = int(input("Enter a number: "))
factorial = 1
for i in range(2, n+1):
factorial *= i
print(f'Factorial of {n} is {factorial}.') |
b3c28a1d0987ef90e35c84844fb55abc8802420b | lancekrogers/Useful_programs | /caroverpayment.py | 679 | 4.09375 | 4 | import sys
try:
cost = int(sys.argv[1])
term = int(sys.argv[2])
rate = float(sys.argv[3])
def overpay_for_car(cost, term, rate):
original = cost
for x in range(term):
a = cost * rate
cost = cost + a
return cost - original
print("You will pay {} over... |
b0c72eea5023893ed312f9d51b869013adde7548 | 317702550/THC | /OK/Python/Ejercicio01.py | 6,510 | 3.640625 | 4 | #!/usr/bin/python3
# Maximiliano Proaño Bernal
# Python 3.7.3
# 19/09/12
# 24/09/12
# Ejercicio 01
2 + 2 # Realiza y muestra el reslutado de la suma de 2 más 2
50 - 5*6 # Realiza y muestra el reslutado de la resta de 50 menos el producto de 5 por 6
(50 - 5*6) / 4 # Realiza y muestra el reslutado de la división de la r... |
85f028c5d6661ce84ca99e380fe090c3280ccd9f | 317702550/THC | /OK/Python/raizR.py | 419 | 3.859375 | 4 | #!/usr/bin/python3
# Maximiliano Proaño Bernal
# 21/11/19
# Python 3.7.3
# Calcula la raíz cuadrada de forma recursiva
from math import fabs
def raizR(b,h,x,e,i):
if fabs(b-h) > e:
print(b,h)
return(raizR((b+h)/2,x/((b+h)/2),x,e,i+1))
else:
print("fin")
return [b,i]
def raiz(x)... |
a201e0589f0abbe2af276b966fe55b91f6ee6cbf | 317702550/THC | /Python/MisFunciones.py | 3,826 | 4.15625 | 4 | # Maximilano Proaño Bernal, Antonino Equihua Lombera
# 10/10/19
# Python 3.7.3
# Define las diferentes funciones dadas
"""
Funciones definidas por el usuario
"""
def vabs(x):
'''Regresa el valor absoluto del numero x.
Regresa x si x es mayor que cero
Regresa -x si x es menor que cero
'''
if x >= 0:
res... |
2dc96e42c4fee775fcfe7f4021d54ca60774928e | 317702550/THC | /Python/ASEFE_PBS.py | 528 | 3.9375 | 4 | # Maximiliano Proaño Bernal
# 30/10/19
# 31/10/19
# Python 3.7.3
# Calcula una aproximación de la raíz cuadrada del valor dado
def rc(x):
b = x
h = 1
print("""
Proceso para la raíz de """ + str(x) + ":") # La función str() convierte una variable numérica a forma de texto para poder concatenarlo con más tex... |
43e63a35da3a10002ceaaa907fef411a0581b62e | 317702550/THC | /OK/Python/ASEFE_PBS_FuncSeno.py | 680 | 4.03125 | 4 | #!/usr/bin/python3
# Maximiliano Proaño Bernal
# 10/11/19
# 12/11/19
# Python 3.7.3
# Calcula el seno
from math import sin, pi, sqrt
def seno(alfa):
""" Calcula el seno de \
el ángulo alfa"""
b = alfa/(2**5)
for i in range(5):
c = 2*sin(b)*sqrt(1-sin(b)**2)
b = 2*b
resultado = c
ret... |
80efd2943dbc2f532ef0d83e170d7e51cda9390a | ldcrchao/PycharmProjects | /python基础语法/继承.py | 2,807 | 4.09375 | 4 | # 关联关系
# 继承关系之前的为关联关系 即多个类为平行关系
# class Book ;class Phone; class Person ;
# book = Book() ; phone = Phone(); person = Person()
# 在Person的__inint__函数中可以定义(self,book,phone)
# 书本类实例化和手机类实例化可以作为人类的两个形参
# 然后在送入实参person = Person(book,phone)
# 继承关系
# 1. 子类中如果不定义__init__则调用父类的super class的__init__
# 2.若子类定义了__init__ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.