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 |
|---|---|---|---|---|---|---|
b2d70e29f02f7ae5e05fdd1e2c91589a4f52888c | Juantamayo26/Train | /ICPC/ukiepc2020problems/generatorgrid/generators/maxcase.py | 168 | 3.828125 | 4 | #!/usr/bin/env python3
print("100000 100000")
n = 10**5
for i in range(1, n+1):
print(str.format("{} 1000000000", i))
print(' '.join(str(10**9) for _ in range(n)))
|
4ee9a70ff0b75ee20f24f624cce9eb55dbf619b4 | Juantamayo26/Train | /ICPC/ukiepc2020problems/divvyingup/submissions/accepted/rgl.py | 107 | 3.625 | 4 | #!/usr/bin/env python3
n = int(input())
print('yes' if sum(map(int, input().split())) % 3 == 0 else 'no')
|
f680dfbceabddc00ca062bf040705b21a412a827 | Juantamayo26/Train | /ICPC/ukiepc2020problems/kleptocrat/generators/everything-minimal.py | 790 | 3.5 | 4 | #!/usr/bin/env python3
import sys
import random
random.seed(sys.argv[1])
# Set sizes
n = random.randrange(1, 10000)
m = random.randrange(n-1, min(100000, n*(n-1)//2))
print(str.format("{} {} {}", n, m, 10**5))
# Set values
values = [random.randrange(0, 10**17) for i in range(n)]
edges = set()
# Assure connectedness
... |
c419b39aa97fc80aad41c2046278d7344f817556 | yparam98/SFWRTECH3RQ3-Python-Test-Suite | /customization.py | 1,184 | 3.734375 | 4 | from team import Team
from name import Name
from number import Number
from branding import Branding
class Customization:
"""Customization class"""
# default constructor
def __init__(self):
self.team = Team("")
self.name = Name()
self.number = Number()
self.branding = Brand... |
72bbfab5a298cda46d02758aae824188c0703f8c | josan5193/CyberSecurityCapstone | /CapstoneMain.py | 859 | 4.1875 | 4 | def main():
while True:
Test1Word = input("What's your name?: ")
try:
Test1Num = int(input("Please choose one of three presidential candidates: \n 1. Donald Trump \n 2. Joe Biden \n 3. Bernie Sanders \n"))
if Test1Num >= 1 and Test1Num <= 3:
print("Congratulations," , Test1Word, ", you have voted!")
... |
7665ca656c74e56ee5d201d44f8393c70b28265e | ilya0296/Artezio-Academy | /Lesson 1/ex2.py | 100 | 3.609375 | 4 | from collections import Counter
text = input("Input text")
count = (Counter(text))
print(count)
|
72069b537c2a414ab645c67e5755bd22a1fb3e69 | CodecoolBP20172/pbwp-3rd-si-game-statistics-DeboraCsomos | /part2/reports.py | 3,653 | 3.546875 | 4 | #!/usr/bin/env python
# Report functions
import math
# processes the given database so the other functions can use it
def file_processing(file_name):
try:
with open(file_name, "r") as file:
games_list = [line.strip().split("\t") for line in file]
return games_list
except FileNotFo... |
e5596aa26a6a60cfea8fc2b00cee4fc93290601f | srdea93/DataStructuresandAlgorithms | /Algorithms/Sorting/CodeQuestions.py | 3,348 | 4.4375 | 4 | # -------------------------------- Basic Sort Implementations --------------------------------
# largest item "bubbles" up to the top
def bubble_sort(array):
for i in range(len(array)-1):
for j in range(len(array)-1):
if array[j] > array[j+1]:
# swap
temp = array[... |
dc3cc2ef7006bcd0f8ca418f2ce3fc8a9080845b | srdea93/DataStructuresandAlgorithms | /DataStructures/LinkedList/doublylinkedlist.py | 2,452 | 3.8125 | 4 | from DataStructures import Node
class DoublyLinkedList():
def __iter__(self):
self.head = None
self.tail = None
def __repr__(self):
if self.head is None:
return None
else:
node = self.head
nodes = ""
while node.next != None:
... |
e3c95fb9ab1b54fed20d7215fbd6d9a503070dbe | reaganflew/IA-241 | /my first python.py | 488 | 3.640625 | 4 |
# coding: utf-8
# # lab 1
# In[5]:
print ("hello world")
1+2
a=3
# In[8]:
a=4
b=3
print (a+b)
# In[6]:
print (a)
# ## demo
# 1. item 1
# 2. item 2
# 3. item 3
#
# JMU [website](https://www.jmu.edu/)
# In[7]:
5+4
# In[9]:
get_ipython().run_line_magic('matplotlib', 'inline')
# In[10]:
import ... |
7c85c2dc828222408f4b3ebbbca189d50f76f3cf | eneskrts/alghoritms | /capitalizer.py | 184 | 3.765625 | 4 |
def capitalization(x):
a=x.split(" ")
for i in range(0,len(a)):
a[i]=a[i][0].upper() + a[i][1:]
return " ".join(a)
print(capitalization("abcd efgh ijklm"))
|
5f741047ed73208207b126fa76a280f041ab4e1a | Drozdovsimple/project_first | /star_3.py | 248 | 3.703125 | 4 | import turtle
n = 7
angle = (180-360/n)/3
turtle.speed(6)
while True:
turtle.forward(100)
turtle.left(180-angle)
if abs(turtle.pos()) < 1:
break
turtle.mainloop()
print(angle)
|
faaf2fa8ed4b6aff88659b492da1d3863e48f3ef | 3pacccccc/effictive_python_learning | /4-3(如何调整字符串中文本的格式).py | 539 | 3.734375 | 4 | """
实际案例:
某软件的log文件,其中的日期格式为'yyyy-mm-dd':
......
2016-02-23 werqrew
2016-02-23 werqrew
2016-02-23 werqrew
2016-02-23 werqrew
......
把所有的2016-02-23替换为mm/dd/yyyy格式
"""
import re
# 解决方案:使用re.sub函数
result_1 = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', log) # log为log日志文件,str格式 \1表示第一组即年
# 也可以为每一组分别命名
result_2 = re.s... |
0b69e0feab646e10ba70415a30eb98b49050e195 | 3pacccccc/effictive_python_learning | /2-3(如何统计序列中元素的出现频度).py | 1,022 | 3.515625 | 4 | from collections import Counter
from random import randint
import re
"""
场景一:某随机序列[12, 5, 6, 4, 53, 56...]中,找出出现次数最高的三个元素,他们出现次数是多少?
"""
def counter_study():
data = [randint(0, 20) for x in range(
30)] # 得到一个例如[8, 0, 0, 8, 14, 10, 6, 20, 7, 11, 7, 17, 3, 4, 6, 8, 19, 12, 1, 11, 19, 6, 9, 7, 7, 19, 4, 4, ... |
49d2f9a2183b3fc93c29d450ae3e84923ceefea8 | python-packages/decs | /decs/testing.py | 907 | 4.4375 | 4 | import functools
def repeat(times):
"""
Decorated function will be executed `times` times.
Warnings:
Can be applied only for function with no return value.
Otherwise the return value will be lost.
Examples:
This decorator primary purpose is to repeat execution of some test fu... |
4fa7fd28ad43e83a3daded87a10290ecc3900b0e | crsanderford/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/rpg_queries.py | 2,789 | 3.6875 | 4 | import sqlite3
conn = sqlite3.connect('rpg_db.sqlite3')
cur = conn.cursor()
#/*How many total Characters are there?*/
cur.execute("SELECT COUNT(character_id) FROM charactercreator_character;")
print('total characters: ',cur.fetchall())
#/*How many of each specific subclass?*/
cur.execute("""SELECT COUNT(character_i... |
7e4c85c264ca1da0ab9f20a959f961828b68b484 | lalitkumar-123/Python-AlarmCreate | /alarm.py | 591 | 3.609375 | 4 | import time
import winsound
from win10toast import ToastNotifier
def timer(reminder,minutes):
notificatior = ToastNotifier()
notificatior.show_toast("Reminder",f"""Alarm will go off in (minutes) Min.""",duration=50)
time.sleep(minutes * 60)
notificatior.show_toast(f"Reminder",reminder,dur... |
a311f72c4e90f70e3e1ee3e3e0c8347bdb7c358e | dnsbob/tinyencrypt | /tinyencrypt-testing.py | 5,306 | 3.75 | 4 | #!/usr/bin/env python
'''tinyencrypt-testing.py'''
# minimal encryption in python for low memory micro-controller
# rotation substitution cipher
# rotate among common password characters only
# only encrypt the passwords
# to do:
# hide the length of the password with padding
# combine duplicate code
# to be python2... |
902dd532b6aea4f2774c2acb88ec969d3812c4d8 | alebrrr/OEPScode | /mnecoursescripts/bonus1_filtering.py | 4,778 | 3.5625 | 4 | # In this script we will take a closer look at the effect of filtering on the data
# For this we will not use real EEG recordings but rather simulate them.
# The advantage of simulated data is that we know what they are made of so we can tell apart signal and artifacts
import numpy
import scipy.signal
from matplotlib ... |
0b68962f4abe9db0a559903e2a0eb0bf466092b5 | vieozhu/dl_book | /my_test/function.py | 1,184 | 3.75 | 4 | # coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
def relu(x):
# relu函数
return np.maximum(0, x)
def sigmoid(x):
# sigmoid函数
return 1 / (1 + np.exp(-x))
def step_function(x):
# 阶跃函数
return np.array(x > 0, dtype=np.int) # 先计算bool值,再转成int
def show(x, y, ylim):
# 画图
... |
9279ba88a2f2fd3f7f3a5e908362cb0b0449c97d | KendallWeihe/Artificial-Intelligence | /prog1/main[Conflict].py | 1,477 | 4.15625 | 4 | #Psuedocode:
#take user input of number of moves
#call moves ()
#recursively call moves() until defined number is reached
#call main function
import pdb
import numpy as np
#specifications:
#a 0 means end of tube
#1 means empty
red_tube = np.empty(6)
red_tube[:] = 2
green_tube = np.empty(5)
gre... |
d10b0ea8fb273a3c076925a0a5ad68f909fb8a5b | Gahina/python_new | /extractdigits.py | 193 | 3.515625 | 4 | str1=input()
if str1[0]=='-':
newstr="-"
else:
newstr=""
l1=['0','1','2','3','4','5','6','7','8','9']
for i in str1:
if i in l1:
newstr+=i
print(newstr)
|
93887ec4b8b0d9659a12f24f69c680c63800187c | GekoTree/hacktoberfest2021-9 | /Python/CheckArmstrongNumber.py | 387 | 4.03125 | 4 | #PYTHON PROGRAM FOR ARMSTRONG NUMBER CHECKING
#take input from user
from math import *
a = int(input("Enter the number : "))
r = 0
y = 0
t = a;
while (t!= 0):
t =int(t / 10)
y = y+ 1
#Check ifnumber is armstrong
t = a
while (t != 0):
rem = t % 10
r = r + pow(rem, y)
t = int(t/10)
if(r == a):
pr... |
bd829bda239481936702fb1762f3245a1fd07f6e | GekoTree/hacktoberfest2021-9 | /Python/crossingroad/player.py | 467 | 3.625 | 4 | STARTING_POINT = (0,-200)
MOVE_DISTANCE = 10
FINISH_LINE_y = 200
import turtle as t
class Player(t.Turtle):
def __init__(self):
super().__init__()
self.penup()
self.shape("turtle")
self.goto(0,-230)
self.color("green")
self.setheading(90)
def g... |
e77679c27b5d303cb57c9b2061e9e5dc354aa5aa | bsy167508/pythonPractice | /pythonCapitalize.py | 154 | 3.859375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
s=raw_input().split(' ')
print " ".join([s[i].capitalize() for i in range(len(s) )]) |
3cc799a7f50528b54390b4e9540f71ad61fce5e6 | bsy167508/pythonPractice | /pythonloops.py | 153 | 3.671875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
#!/bin/python
n = int(raw_input().strip())
i=0
while i<n:
print (i*i)
i+=1
|
0590a68b411bf58d3dde4d62057507f98b6b2307 | bsy167508/pythonPractice | /pythonlists.py | 422 | 3.96875 | 4 | #!/bin/python
x=int(raw_input().strip())
l=[]
for i in range(x):
comm = raw_input().split(' ')
if comm[0]=="insert":
l.insert( int(comm[1]), int(comm[2]) )
elif comm[0]=="print":
print l
elif comm[0]=="remove":
l.remove( int(comm[1]) )
elif comm[0]=="append":
l.append( int(comm[1]) )
elif comm[0]=="sort"... |
2d9839729324f027252c750fe56c6fab9bc4cd34 | nogahm/WebScraping | /WebScrapping/hw1.py | 9,031 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# import the library used to query a website
import urllib.request
import pandas as pd
from bs4 import BeautifulSoup
# specify the url
wiki = "https://en.wikipedia.org/wiki/Gal_Gadot"
# Query the website and return the html to the variable 'page'
page = urllib.request... |
1ae1528e97a395ce2dbf58c6ed484806c8473992 | BarberAlec/ByteDance_interview_Q | /MC_ByteDanceQ.py | 9,065 | 3.5 | 4 | '''10 small balls are randomly divided into 12 boxes. You need to find the probability that exactly 10 boxes are empty with a program.
The program is required to simulate 100,000 times in order to calculate the probability with “brute-force”.'''
import random
import numpy as np
import matplotlib.pyplot as plt
impor... |
a369f9136c45d35e528017500bf6d282ae1d1284 | inaccare/Jeopardy | /ClueParser.py | 7,746 | 3.796875 | 4 | #!/usr/bin/env python
# CS124 Homework 5 Jeopardy
# Original written in Java by Sam Bowman (sbowman@stanford.edu)
# Ported to Python by Milind Ganjoo (mganjoo@stanford.edu)
import sys
import itertools as it
from NaiveBayes import NaiveBayes
import re
class ClueParser:
def __init__(self):
# TODO: if your i... |
02d6a82bc366390f9b7b8596c6158d988c6c1117 | yoniosin/Dynamic_Leraning | /ex1/Q1.py | 749 | 3.828125 | 4 | import numpy as np
# Function Name: calcpairs
# Description: calculates the number of possible arrangements of N natural numbers which sums up to X
# Inputs: int X - required sum, int N- amount of natural integers (must also be a positive)
# Output: number of possible arrangements (0 if impossible)
def calcpairs(n, x... |
edb5273ec637a4e47086f5498e69c93d8be25d6e | SaiWeb5/python-project-lvl1 | /brain_games/games/calc.py | 632 | 4.03125 | 4 | import random
import operator
HINT = 'What is the result of a expression?'
MIN_NUNBER = 1
MAX_NUMBER = 100
def get_calc():
num_1 = random.randint(MIN_NUNBER, MAX_NUMBER)
num_2 = random.randint(MIN_NUNBER, MAX_NUMBER)
operators = ('+', '-', '*')
random_operator = random.choice(operators)
task = '{}... |
1a0cde686ba8ab18a1c7cc0f7d97d0f2b9e3a20a | MayelleCarvalho/Multimidia | /Socket_aplication/Aplication/TCP_aplication/Server.py | 1,373 | 3.546875 | 4 | import socket
import _thread
# host = ''
# porta = 2523
#
# def conectado(con, cliente):
# print('Conectado por', cliente)
#
# while True:
# msg = con.recv(1024)
# if not msg: break
# print(cliente, msg)
#
# print ('Finalizando conexao do cliente', cliente)
# con.close()
# _... |
5e75f65168145a34080530bc01726db905b0588c | ZepaDorji/MusicPlayer- | /zepa.py | 1,015 | 3.84375 | 4 | # def solution(x):
# stop_num = 0
# new_num = 2
# while new_num != 1:
# if x % 2 == 0:
# new_num = x / 2
# stop_num = stop_num + 1
# x = new_num
# else:
# new_num = 3 * x + 1
# stop_num = stop_num + 1
# ... |
81722270d398f5ad739a39043aefd4544484d220 | HBlack09/ICTPRG-Python | /Examples/numbers01.py | 221 | 3.578125 | 4 | infile = open('numbers.txt','r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
infile.close()
total = num1 + num2 + num3
print("Numbes: ", num1,num2,num3)
print("Total: ",total) |
e93fd80152398f23d6c145c28d053877c8831584 | HBlack09/ICTPRG-Python | /Examples/Week 8-2.py | 299 | 3.671875 | 4 | a = [2.3, 7.9, -3.4, 4.2]
print("a: ",a)
print("len(a): ",len(a))
print("min(a): ", min(a) )
# Initialise the counter variable
i=1
# Current minimum
minval = a[0]
while i<len(a):
print("minval: ", minval)
if a[i] < minval:
minval = a[i]
i = i+1
print("final min val: ", minval)
|
162abb34df287eacba96a2eb8e09dd018046ed2c | HBlack09/ICTPRG-Python | /Examples/arrayloop01.py | 287 | 3.90625 | 4 | #for num in [1,2,3,4,5,6]:
# print(num)
#arr = [1,2,3,4,5,6]
#for num in arr:
# print(num)
for nm in ["Fred", "Sally", "William"]:
print(nm)
print()
for name in ['Greg', 'Tom', 'James', 'William']:
print(name)
print()
arr2 = [2.3, 4.5, 8.0, 8.1]
for x in arr2:
print(x) |
4ad624e1b08eedc6d305df9f5eb891c2cb40a8b0 | HBlack09/ICTPRG-Python | /Examples/nestedloop2.py | 199 | 3.78125 | 4 | sz = 10
for count in range(sz):
# cleverly increase to count+1
for y in range(count+1):
# end='' does not print the end of line character
print('x', end='')
print()
|
057fd50327100b0babb4c1060d3573a550a17062 | HBlack09/ICTPRG-Python | /Examples/tempurature2.py | 199 | 3.875 | 4 | # Test temperatures
t1 = eval(input('Enter temperature deg celsius: '))
if t1 < 0:
print('Freezing')
if t1 > 100:
print('boiling')
if t1 >= 0 and t1 <= 100
print('0 <= temperatur <= 100') |
bcba9b380be301537afa9bed31b5632114b77c3f | HBlack09/ICTPRG-Python | /Examples/test02.py | 203 | 3.875 | 4 | inMsg = input("Input message: ")
inNum = input("Input integer: ")
# Convert the number to an integer.
inNumVal = int(inNum)
num2 = inNumVal * 2
msg2 = inMsg + ". " + inNum + " * 2 = "
print(msg2, num2 ) |
12e50b4e5f7bb6b13357309997c0dcb28154cd02 | HBlack09/ICTPRG-Python | /Examples/forloop01.py | 141 | 4.0625 | 4 | for x in range(0,5):
print(x)
# print("loop",x)
# print("----")
print("end of loop")
print()
for num in range (5):
print(num)
|
2236cf59b1b688ddcbf49eb3d6134f0018ca0d1a | HBlack09/ICTPRG-Python | /Examples/shop02.py | 448 | 4.09375 | 4 | # Build a shopping list
print("Enter")
# Display message to user
print("Hi! Please enter an item for the shopping list")
print("Enter x to finish the list")
#Initialise variables
shoppinglist=[]
userInput = ""
#Accept user input
while (True):
userInput = input("Enter Item: ")
print("userInput:",userInput)
i... |
761e26a615b127f0b4c36397b954610144ccf8bb | HBlack09/ICTPRG-Python | /Introduction to Repetition Quiz/Question 1.py | 110 | 3.59375 | 4 | #starting from 0
count = 0
#start a counting string
while count <= 25:
print (count)
count += 1 |
14709bc0146ea083df29d1d42f0c23abeae1d0d8 | HBlack09/ICTPRG-Python | /Examples/upperlower.py | 225 | 4.375 | 4 | # upper/lower case example
txt = "Hello my friends"
txt2 = txt.upper()
print(txt)
print(txt2)
txt3 = txt.lower()
print(txt3)
t1 = "aBc"
t2 = "AbC"
print("t1: ", t1)
print("t2: ", t2)
print(t1 == t2)
print(t1.upper() == t2.upper())
|
967164cc2ebca8de4b075f3bbf41fa9d55dc7614 | HBlack09/ICTPRG-Python | /Examples/mark.py | 189 | 3.6875 | 4 | mark = 49
if (mark >= 70):
print("You scored an A")
elif (mark >= 60):
print("You scored a B")
elif (mark >= 50):
print("You scored a C")
else:
print("You failed the test.") |
af53017cdb5c79ae0d2852e0023192d4a3c6eb6d | fancy1013/blog | /source_code/bezier_curve.py | 763 | 3.578125 | 4 | def draw_curve(p_list):
"""
:param p_list: (list of list of int:[[x0, y0], [x1, y1], ...])point set of p
result: (list of list of int:[[x0, y0], [x1, y1], ...])point on curve
"""
result = []
P = []
P = p_list.copy()
r = len(p_list)
for i in range(0, 20923): #2020/09/23
t = i/20923
x, y = de_Casteljau(r, P,... |
f0e4d86271398dba551b2cc65a69b4b7b644e77a | GalacticGarry69/lucky_unicorn | /00_sandbox.py | 151 | 3.984375 | 4 | name = "Your Name"
while name.lower() != "xxx":
name = input("Who are you again? ")
print(name)
print()
print("We are done here, welcome back!")
|
a3abb6976bf42ada60d6874cf24a40f73fda70ba | sarvasvkulpati/Philosophical_Bot | /quoteExtractor.py | 2,773 | 3.578125 | 4 | # BrainyQuote Web Scraper (By Keyword)
# SPECIAL POMMUNISM EDITION
# Alaina Kafkes
import requests
from bs4 import BeautifulSoup
example_key = "lemons"
example_author = "kurt_vonnegut"
def getQuotes(keyword=example_key, numpages=7):
"""
Given a keyword and the number of HTML pages of quotes to parse, uses Re... |
597e1e68abef18723dd5fd3304c6e0c79f30d346 | kirschovapetra/B-PROG1 | /05 17.10/01 kreslenie/07 X.py | 245 | 3.734375 | 4 | n=5
M=[]
for i in range(n):
m=[]
for j in range(n):
m.append('.')
M.append(m)
for i in range(n):
M[i][i]='x'
M[i][n-1-i]='x'
for i in range(n):
for j in range(n):
print(M[i][j],end=' ')
print('\n')
|
372b74c744139971779adc425867246b6ceb27d3 | kirschovapetra/B-PROG1 | /06 24.10/03 Zakladna enumeracia/04 Collatzova postupnosť!.py | 151 | 3.765625 | 4 | def Collatz(n):
x = [n]
if (x[0]%2 == 0):
x.append(x[0]/2)
print(x)
else:
x.append(3*x[0]+1)
print(x)
Collatz(2)
|
d6379a7a65d495b089360bc1b0e1eb8d31c7b3df | kirschovapetra/B-PROG1 | /06 24.10/04 dalsie/01,02 cisla z intervalu.py | 118 | 3.625 | 4 | def f(od,do,step):
if (step<0):
od,do = do,od
for i in range(od,do,step):
print(i)
f(2,20,-3)
|
cd46320539fafae508d887e35fa890a8c404bd1c | kirschovapetra/B-PROG1 | /03 3.10/01 zoznam/5 rotacia o 1 dolava, o x doprava.py | 429 | 3.71875 | 4 | list = []
for i in range(5):
list.append(i)
print(list)
print('\n')
'''prvy = list[0]
for i in range(4):
list[i] = list[i+1]
for i in range(4):
print(list[i])
print(prvy)
print('\n')'''
x = int(input('zadaj x '))
for i in range(x):
posledny = list[len(list)-1]
j = len(list)-1
while (j... |
f73afe89e0d9770cc3d95b2053530e58edbfd2fb | tktnskan/TIL-1 | /04_flask/first_app/hanman.py | 1,585 | 3.75 | 4 | import re
def hangman(answer, letters=None, count=0):
if letters == None:
letters = []
print('먼저 글자의 개수를 알려주지.\n' + len(answer) * '*')
return hangman_input(answer, letters, count)
def hangman_input(answer, letters, count):
while True:
try:
input_str = input('소문자로 알파벳 하나... |
2b859eb87dea3899871b54d11fde8eb013b24cb2 | DaraJin/Python-CS101 | /Search Engine/5.1-hash table buckets.py | 1,842 | 3.671875 | 4 | def make_hashtable(nbuckets): #empty hash table
table = []
for unused in range(0,nbuckets):
table.append([])
return table
def hash_string(keyword,buckets):
out = 0
for s in keyword:
out = (out + ord(s)) % buckets
return out
def hashtable_get_bucket(htable,keyword):
retur... |
d128319f3114e6e1293bad9ad320206c48b1dc6d | johnta0/AtCoderSolutions | /abc/142/a/main.py | 118 | 3.703125 | 4 | n = int(input())
if n % 2 == 0: print(0.5)
elif n == 1: print(1.0)
else:
odd = (n - 1) / 2 + 1
print(odd / n)
|
53da82de3f18b9151775d3e36975705ddcd7fe51 | innovationwonder/LearnPython | /Chapter 5 文件与IO/01.py | 1,146 | 3.578125 | 4 | # open(), read(), readline(), seek(), write(), close()
# file1 = open('name.txt','w',encoding='utf-8')
# file1.write('周瑜')
# file1.close()
#
# file2 = open('name.txt',encoding='utf-8')
# print(file2.read())
# file2.close()
#
# file3 = open('name.txt','a',encoding='utf-8')
# file3.write('孔明')
# file3.close()
# file4 = ... |
24fe29f2d2a9889835a8bfe62d79d4354f6ac1e2 | innovationwonder/LearnPython | /Chapter 11 机器学习/02-Panads.py | 1,544 | 3.71875 | 4 | # Pandas 用于数据预处理和数据清洗
# 优点:1.自动对齐显示数据 2.灵活处理数据 3。使用SQL语句
from pandas import Series, DataFrame
import pandas as pd
obj = Series([2,3,5,-2])
# print(obj)
# print(obj.values)
# print(obj.index)
obj2 = Series([2,31,412,2], index=['a','b','c','q'])
# print(obj2)
# obj2['q'] = 8
# print(obj2)
# print('a' in obj2)
# 导入字典
... |
f1f502adfe5862c9b1be27f67d60f2ef1a8eb6c8 | JennaB17/April-28-1 | /main.py | 111 | 4.03125 | 4 | import math
a = int(input("What is the number?"))
b = a/3
print(str(a)+"/3 =",b)
x = math.floor(b)
print(x) |
07181fb1f0b0df64f61b869d8a311a20c6b7c65c | nikunicke/codewars | /4kyu_matrix_determinant/matrix_determinant.py | 1,030 | 3.765625 | 4 | def define_submatrix(matrix, index):
length = len(matrix)
submatrix = [[0 for i in range(length - 1)] for j in range(length - 1)]
if (length <= 1):
return matrix
i = 1
while (i < length):
j = 0
k = 0
while (j < length):
if(j != index):
... |
6dec318a5ea72ecf318376cecbd09bc858dfd983 | swapnilborkar/MITx-6.00.1x | /WEEK2/findRoot.py | 415 | 3.75 | 4 | def findRoot2(x, power, epsilon):
if x < 0 and power%2 == 0:
return None
# can't find even powered root of negative number
low = min(0, x)
high = max(0, x)
ans = (high+low)/2.0
while abs(ans**power - x) > epsilon:
if ans**power < x:
low = ans
else:
... |
abcc237b45e70b73f23724c13557189357205e6a | pierofre/python-school | /ciclofor.py | 157 | 3.5 | 4 | Prefissi = "JKLMNOPQ"
Suffisso = "ack"
for i in Prefissi:
if i == "Q":
print (i+"u"+Suffisso)
else:
print (i + Suffisso)
#come faccio
|
91c45364f262c56bf1b8dfef3354c430015cb791 | YaqoobAslam/Python3 | /Chapter03/Example01.py | 175 | 3.90625 | 4 |
def append_if_even(x,lst=None):
if lst is None:
lst=[]
if x%2==0:
lst.append(x)
return lst
x=10
result =append_if_even(x)
print(result) |
712ed57d0cd6da4ac6812539630d2d1d257176b7 | YaqoobAslam/Python3 | /Assignment/Count the number of blank present in a text file named OUT.TXT.py | 246 | 4 | 4 | Write a function to count the number of blank present in a text file named "OUT.TXT". solution
spaces=0
fread = open('OUT.TXT','r')
for line in fread:
spaces += line.count(' ')
print("Total space is:",spaces)
output:
Total space is: 12 |
51e5cceb808a9d7a4bd163be02a8cbc73af992f9 | YaqoobAslam/Python3 | /Chapter04-Conditional/Conditional Statement.py | 1,906 | 3.96875 | 4 | 5==5
Out[11]: True
5==6
Out[12]: False
type(True)
Out[13]: bool
type(False)
Out[14]: bool
//----------------------------------------------------
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y #... |
cc315e7aa80c04128721d665deb4c1eadf081d8f | YaqoobAslam/Python3 | /Assignment/Count and display the number of lines not starting with alphabet 'A' present in a text file STORY2.TXT.py | 863 | 4.53125 | 5 | Write a function in to count and display the number of lines not starting with alphabet 'A' present in a text file "STORY.TXT".
Example:
If the file "STORY.TXT" contains the following lines,
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the pass... |
1f739eabf6e6a10db81856f1cb758362e177388b | YaqoobAslam/Python3 | /Chapter06-Iteration_Loop/While Loop break.py | 174 | 3.890625 | 4 | import math
while True:
line = input('> ')
if line == 'done':
break
print(line)
print("Done!")
output:
> hello
hello
> good
good
> bye
bye
> done
Done! |
8d6e34e1091a67b8ebfb713762ac4065b25bf119 | YaqoobAslam/Python3 | /Assignment/string to the disk file OUT.TXT.py | 407 | 3.625 | 4 | Write a program, which initializes a string variable to the content
"Time is a great teacher but unfortunately it kills all its pupils. Berlioz"
and outputs the string to the disk file OUT.TXT.
you have to include all the header files if required. solution
fopen = open('OUT.TXT','w')
line ='Time is a great teache... |
def80fb31af293fd5ee23a56ed6f2366464e56ca | YaqoobAslam/Python3 | /Chapter06-Iteration_Loop/While Loop.py | 75 | 3.6875 | 4 | import math
n= 5
while n >0:
print(n)
n = n -1
output:
5
4
3
2
1
|
6e0c0113ffce1b625e2f80fbec0ed0d2c2c205fa | Nithi593/Python-Programming | /week2/07_add_binary_strings.py | 245 | 4 | 4 | s1 = input("Enter string 1 : ")
s2 = input("Enter string 2 : ")
sum = int(s1,2) + int(s2,2)
sum = bin(sum)
print(sum)
"""
Sample Input :
Enter string 1 : 1101
Enter string 2 : 100
Sample Output:
10001
"""
|
792eaa346d50c845f989c1751b8cc73e2a8e3b9f | sagarchhadia24/AWS-StaticAnalysis | /StaticAnalysis/testFiles/Python Files/DiceRollingSimulator.py | 213 | 3.875 | 4 | import random
def dice1():
print random.randint(1,6)
dice1()
while True:
input = raw_input("Would you like to roll again?[y/n]")
if input=="y":
dice1()
else :
break
|
6ccdc1a7095b1a3473c72e52f3ac7dfc1bad08b7 | el-micha/sudoku | /sudoku/main.py | 4,567 | 3.578125 | 4 |
class Board:
all = {1,2,3,4,5,6,7,8,9}
def __init__(self):
self.cells = list(range(81))
self.row_cons = [{1,2,3,4,5,6,7,8,9} for i in range(9)]
self.col_cons = [{1,2,3,4,5,6,7,8,9} for i in range(9)]
self.block_cons = [{1,2,3,4,5,6,7,8,9} for i in range(9)]
self.cnt = 0... |
e1cc86ce3d6ec88a63cf4bfe101118fa87b5c487 | wangpeilin/pygame- | /bomb.py | 981 | 3.578125 | 4 | # 爆炸特效
import pygame
class Bomb(pygame.sprite.Sprite):
def __init__(self, screen):
super(Bomb, self).__init__()
self.screen = screen
self.image = [pygame.image.load("images/bomb-" + str(i) + ".png") for i in range(1, 8)]
self.index = 0
self.interval = 20
self.interv... |
52df758c44a0cc601d8768f40cd47c212647e45f | dejac001/chem_util | /src/chem_util/io.py | 1,059 | 4.0625 | 4 |
def read_csv(f_name: str, delimiter: str):
"""
:param f_name: name of file
:param delimiter: delimiter separating columns
"""
with open(f_name) as f:
keys = next(f).rstrip('\n').split(delimiter)
data = {key: [] for key in keys}
for line in f:
vals = line.rstrip('... |
460306703d70308b5970b4db34eaa8f07f82ab13 | Mark7E/coding_dojo | /python/fundamentals/oop/users_w_bank.py | 3,009 | 4.5 | 4 | '''
Update your existing User class to have an association with the BankAccount class.
You should not have to change anything in the BankAccount class. The method signatures
of the User class (the first line of the method with the def keyword) should also remain the same.
For example, our User class currently has a ... |
2e54f9ee0938beb93b9caa2c5417bf60a8870e2d | pasinducmb/Python-Learning-Material | /Genarator Expressions.py | 811 | 4.1875 | 4 | # Generator Expressions
from sys import getsizeof
# Comprehension for Lists and Tuples
value = [(x + 1)**2 for x in range(10)]
print("List: ", value)
value = ((x + 1)**2 for x in range(10))
print("Tuple: ", value)
# (reason for error is due to tuples are not coprehendible objects as Lists, sets and dictionaries, th... |
3afebb3b8dad58c010e07e028949012a5f2e0de7 | wobedi/algorithms-and-data-structures | /src/implementations/graphs/representations/graph_undirected.py | 5,250 | 3.71875 | 4 | from functools import reduce
from pandas import DataFrame
class Graph:
"""Implement three graph representation variants for illustration.
(List of edges, adjacency matrix, adjacency list)
All representations represent vertices as integers.
Supports self loops but not parallel edges.
"""
def ... |
f15f1cc97586bb5fc23b23499328542f93204ea5 | wobedi/algorithms-and-data-structures | /src/implementations/sorting/quicksort.py | 1,074 | 4.15625 | 4 | from random import shuffle
from src.implementations.sorting.basic_sorts import insertion_sort
from src.implementations.helpers.partition import three_way_partition
def quicksort(arr: list) -> list:
"""Sorts arr in-place
by implementing https://en.wikipedia.org/wiki/Quicksort
"""
shuffle(arr) # shuff... |
ac318511b95f4566985bbe95436348c9077d06cb | DanieleOrnelas/4Linux_Python | /aula4/objetos.py | 2,858 | 4.5625 | 5 | #!/usr/bin/python3
# Uma classe associa dados (atributos) e operações (métodos) numa só estrutura.
# Um objeto é uma instância de uma classe - uma representação da classe.
class Carro():
def __init__(self, marca, modelo, ano):
self.marca = marca
self.modelo = modelo
self.ano = ano
self.hodometro = 0
def de... |
4ba0168721fbd3bc17cac579b53e962d8a0a6ca3 | DanieleOrnelas/4Linux_Python | /aula4/exercicios/objeto1.py | 2,174 | 4.21875 | 4 | #!/usr/bin/python3
# PROGRAMA PARA:
# Classe User
# ATRIBUTOS: Nome / Sobrenome / Username / Senha / Numero de Tentativas
# METODOS: Descrever / Saudacao / Login (usando input) / Incrementar tentativas / Reseta Tentativas
# PROGRAMA DO TIO
class Usuario():
def __init__(self,nome,sobrenome,username,password):
se... |
747127ae5bc94de4e0ec85a285c9290130c800f7 | pagelj/airs | /modules/auxiliary_functions.py | 471 | 3.578125 | 4 | #!/usr/bin/env python2.7
# coding=utf-8
"""
Awesome Information Retrieval System (AIRS) - Auxiliary Functions
Contributors: Prajit Dhar, Janis Pagel
University of Stuttgart
Institute for Natural Language Processing
Summer Term 16
08/12/2016
"""
import re
def natural_sortkey(string):
# Function for sorting in... |
937b97723b7efac877308f0aa74f31f733b5d38d | DustyPage/python_example_programs | /prime_check.py | 224 | 3.796875 | 4 | """
Program to check if a user-provided integer is prime.
"""
def is_prime(n):
"""Given an integer n, return True if n is prime and False if not.
"""
return True
if __name__ == "__main__":
pass
|
55e3ac37f644ea67052a1c21aea38dac9b2e7b52 | EcoFiendly/CMEECourseWork | /Week2/Code/test_control_flow.py | 1,387 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Some functions exemplifying the use of control statements
"""
__appname__ = '[test_control_flow.py]'
__author__ = 'Yewshen Lim (y.lim20@imperial.ac.uk)'
__version__ = '0.0.1'
__license__ = "License for this code/program"
## Imports ##
import sys # module to interface our program with the o... |
d3c463e5a6a6dee3569b5c84398c08b2fb39a8bc | EcoFiendly/CMEECourseWork | /Week2/Code/sysargv.py | 538 | 3.828125 | 4 | #!/usr/bin/env python3
"""
argv is the 'argument variable'. Such variables are necessarily very common
across programming languages, and play an important role - argv is a variable
that holds the arguments passed to the script when it's ran.
"""
__appname__ = '[sysargv.py]'
__author__ = 'Yewshen Lim (y.lim20@imperia... |
9fd4ea33278bd1c477c4d7451e5367e426633409 | hebertmello/pythonWhizlabs | /estudo_tuples.py | 810 | 4.40625 | 4 | # Tuples in Python
# -------------------------------------
# - It is a similar to a list in python
# - It is ordered an unchangeable
# - It allows duplicate elements
tuple = ()
print(tuple)
tuple = (1, 2, 3)
print(tuple)
tuple = (1, "hello", 4, 5)
print(tuple)
tuple = ("mouse", [8, 4,5], (1, 2, 3))
... |
5c96975d02b72a1519f58eb440f497c617f64b9f | hebertmello/pythonWhizlabs | /project1.py | 581 | 4.15625 | 4 | import random
print ("Number guessing game")
number = random.randint(1, 20)
chances = 0
print("Guess a number between 1 and 20")
while(chances < 5):
guess = int(input())
if (guess == number):
print("Congratulations you won!!!")
break
elif guess < number:
print(... |
16afd830fd23371cfff9db3ad6767ce2d6b89168 | hebertmello/pythonWhizlabs | /estudo_geral.py | 1,159 | 4.09375 | 4 | # Variables
# -------------------------------------
a, b, c = 5, 10, "hello"
print(a)
print(b)
print(c)
d = 10
print(d)
x = 30
x = 40
x = 50
print(x)
# StringBasics
# -------------------------------------
str = "hello world"
print(str)
print("My name is %s and my roll number is %d" % ('hebert'... |
9cf18fd8d46e4aa2cf12c1c51ce563ee7f85c43f | AxolotlDev/PruebasPython | /Ej3.py | 447 | 4.15625 | 4 | #Ejercicio 3
#Dados los catetos de un triángulo rectángulo, calcular su hipotenusa.
import math
CatetoMayor = int(input("Introduzca el valor del cateto mayor: "))
CatetoMenor = int(input("Introduzca el valor del cateto menor: "))
Hipotenusa = (math.sqrt(math.pow(CatetoMenor,2)+math.pow(CatetoMayor,2)))
print(f"Si... |
4cd1b2752a0eaee5ebf012f619211e5a77ef22c3 | AxolotlDev/PruebasPython | /IfEj6.py | 437 | 3.984375 | 4 | #Ejercicio 6
#Programa que lea una cadena por teclado y compruebe si es una letra mayúscula.
let=str(input("ingrese una letra: "))
if let>='a' and let<='z':
print( "la letra es miniscula.")
elif let>='A' and let<='Z':
print("la letra es mayuscula.")
elif let=='ñ':
print( "la letra es miniscula.... |
3df42240b6ddd5916bc1ec5e15def0f16bfa7260 | AxolotlDev/PruebasPython | /Ej6.py | 308 | 3.734375 | 4 | #Ejercicio 6
#Calcular la media de tres números pedidos por teclado.
import statistics as st
n1 = int(input("Ingrese numero 1: "))
n2 = int(input("Ingrese numero 2: "))
n3 = int(input("Ingrese numero 3: "))
media=[n1,n2,n3]
m= st.mean(media)
print(f"La media de los 3 numeros ingresados es {m}")
|
899b6ce60d8757405dd620d7a8e895e56963890c | AxolotlDev/PruebasPython | /Ej5.py | 291 | 4.09375 | 4 | #Ejercicio 5
#Escribir un programa que convierta un valor dado en grados Fahrenheit a grados Celsius. Recordar que la fórmula para la conversión es:
#C = (F-32)*5/9
F = int(input("Ingresar grados Fahrenheit: "))
C = ((F-32)*5/9)
print(f"{F}° Fahrenheit equivalen a {C}° Celsius.") |
cc8e5c295453c6ce967e6b302bec73b7858bae04 | OmarBahmad/Projetos-Python | /Exercícios Python/DESCOBRINDO TRIANGULO.py | 1,182 | 4.15625 | 4 | print('\033[33m-='*30)
print('DESAFIO DOS TRIANGULOS V2.0')
print('-='*30)
print('\033[37mINTRUÇÕES: Adicione 3 lados de um triangulo e descubra se ele existe e qual formato ele tem.')
print('\033[m')
a = int(input('LADO A: '))
b = int(input('LADO B: '))
c = int(input('LADO C: '))
print('')
if abs(b-c) < a < b+c and a... |
c173be9c731e5e8c438b21a617a38447f3f46069 | wx702983/nmb | /lemon_78/python_class/lesson4.py | 3,498 | 4.3125 | 4 | '''
Python内置函数及函数
函数:一段代码重复使用、将代码进行封装---调用这个函数
作用:提高代码复用率
格式:
注意:函数名命名规则遵循标识符规则、
函数定义完后没有被调用不会被执行、
写函数名调用函数、
函数里可能变化的内容不建议写成参数
def 函数名():
函数体(函数实现具体功能的代码)
返回值
返回值:函数如果有数据给调用函数的人使用、把这个数据设置成函数返回值
1、返回值一定在最后、返回值后面的代码不会被执行---标志函数结束
2、返回值可以没有---None
def good_job(): #定义函数
salary = 8000
... |
f67a51e49f29abe524af7a868d139a76a47155ad | anshikatiwari11/PythonPractice | /Anshika work.py | 429 | 3.859375 | 4 | # count=0
# print('Printing numbers from 0 to 9')
# while(count<10):
# print('The count is ',count)
# count=count+1
# print("Bye")
# def factorial (number):
# factorial=1
# for i in range(1,number+1):
# factorial*=i
# print("factorial")
# def custom_max(l):
# max=l[0]
# for i... |
7e92cbb2a57c7e38a5bed0f8f605127d0e3fe794 | hahahayatoo/write-docker-actions | /.github/actions/cat-facts/src/main.py | 881 | 3.671875 | 4 | import requests
import random
import sys
# Make an HTTP GET request to the cat-fact API
cat_url = "https://cat-fact.herokuapp.com/facts"
r = requests.get(cat_url)
r_obj_list = r.json()
# Create an empty list to store individual facts in
# This will make it easy to select a random one later
fact_list = []
... |
eeb25c21388dd65322ccff256ca4d19985043e3c | abikishoresai/sde | /14.py | 61 | 3.5 | 4 | y=input()
for i in range(0,len(y),3):
print(y[i],end="")
|
14ab65b0291b13e0e1916605f3010446808a0440 | kailinghuang/tictactoe-ai | /Board.py | 3,372 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 20:29:16 2018
@author: yiqian
"""
X = 1
O = -1
Empty = 0
Dead = -2
Column = 15
Row = 15
m=7
class Error(Exception):
def __init__(self, arg):
self.args = arg
class BOARD():
def __init__(self, Column_Num, Row_Num, m_Num, p... |
303b3e3b746a16b0e2faa376be8780407965b1c8 | ucb-art/laygo | /generators/future/refactor.py | 22,401 | 3.640625 | 4 | # refactor
import re, os
def convert_pos_to_named(filename_i, filename_o, func_name):
"""
Convert positional arguments to named arguments for further refactoring under following assumptions.
1. Refactoring functions defined in GridLayoutGenerator.py
2. GridLayoutGenerator is instantiated as... |
1f3eeaf7543e3b3457b27d7bc8ec5f53e6aceedf | CernatMonicaRoxana/py-labs | /lab1/ex1.py | 363 | 3.953125 | 4 | def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
if __name__ == '__main__':
numbers = input()
numbers = [int(no) for no in numbers]
print(numbers)
a = numbers[0]
b = numbers[1]
gcd_a_b = gcd(a, b)
for i in range(2, len(numbers)):
gcd_a_b = gc... |
3fd89c7548b7efa315b8ebc561c99d16906d0b05 | CernatMonicaRoxana/py-labs | /lab1/ex2.py | 230 | 3.96875 | 4 | def vowel_counter(sentence):
vowels = 'aeiou'
count = 0
for c in sentence:
if c.lower() in vowels:
count += 1
return count
if __name__ == '__main__':
print(vowel_counter('Ana are mere'))
|
18ce441e493e3251351d425022c7ecad1859f40d | ugant2/python-snippate | /file and Exception/valueError.py | 281 | 3.671875 | 4 |
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("please input correct value")
except Exception:
print("exception not identified") #parent exception
finally:
print("resource haldled") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.