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 |
|---|---|---|---|---|---|---|
c9043fec3dd0977511baddcf02594914d32b3efc | bhanugudheniya/Python-Program-Directory | /CWH_Program_Practice_DIR/CH7_Loops_ForWithBreak.py | 197 | 3.90625 | 4 | fruits = ['apple', 'banana', 'orange']
for i in fruits:
print(i)
if i == 'banana':
break
# other
print('****************************')
for i in fruits:
if i == 'banana':
break
print(i) |
f4eb7877a49cca45074124096ace75dd5e89b72f | bhanugudheniya/Python-Program-Directory | /CWH_Program_Practice_DIR/CH5_DictionaryAndSets_DeclarationAndInitialization.py | 499 | 4.15625 | 4 | student = {
"name" : "bhanu",
"marks" : 99,
"subject" : "CS",
# "marks" : 98 # always print last updated value
}
print(student) # print whole dictionary
print(student["name"]) # print value of key "name"
print(len(student)) # print dictionary length
print(type(student)) # data types
# Access Dicti... |
712a99d2e071f6364c338a2362c9a226c7300450 | bhanugudheniya/Python-Program-Directory | /ClassPractical/Grade.py | 292 | 4.0625 | 4 | marks = int(input("Enter Marks"))
if(marks<=100 and marks>=0):
if(marks >= 90):
print("Grade A")
elif(marks>80 and marks<90):
print("Grade B")
elif marks>70 and marks<=80:
print("Grade C")
else:
print("Grade D")
else:
print("Invalid Marks") |
4db2741f8aefdfc1fdd8058368489d52d29cc703 | bhanugudheniya/Python-Program-Directory | /PythonLab Assignment 1/IdentityMatrix_SEVEN.py | 219 | 3.984375 | 4 | matrixInput = int(input("Enter Order of Matrix as same as Identity Value : "))
for i in range(0, matrixInput):
for j in range(0, matrixInput):
if i == j:
print("1", end=" ")
else:
print("0", end=" ")
print() |
9848ea959a40c6c8698d58d239d269a7d4140da1 | bhanugudheniya/Python-Program-Directory | /CWH_Program_Practice_DIR/CH8_Function&Recursion_PracticeSet/PR5_PatternFunction.py | 276 | 3.75 | 4 | # method 2
n = 3
for i in range(n):
print('*' * (n-i))
# *************
# method 1
# def pattern(n):
# i = 1
# num = 1
#
# while i <= n:
# j = 1
# while j <= i:
# print('*', end=' ')
# j -= 1
# num += 1
# print()
# i += 1
#
# pattern(3)
# ************
|
a5b68993538dbb09c0e6dbaade0682f920b14256 | bhanugudheniya/Python-Program-Directory | /PythonLab Assignment 2/LinearSearch_FOURTHEEN.py | 261 | 3.8125 | 4 | l=[]
n=int(input("Enter no. of elements you want in the list:"))
for i in range(0,n):
a=int(input("Enter a no."))
l.append(a)
key=int(input("Enter the key you want to search:"))
for i in range(0,n):
if(key==l[i]):
print(f"{key} present at position {i+1}")
|
a528a47e1d7c6c1c861e9128c43db7a6645ff453 | bhanugudheniya/Python-Program-Directory | /PythonHome/Input/UserInput_JTP.py | 705 | 4.25 | 4 | name = input("Enter name of student : ")
print("Student name is : ", name)
# 'name' is variable which store value are stored by user
# 'input()' is function which is helps to take user input and string are written in this which is as it is show on screen
# -------------------------------------------------------------... |
141b1eafcfbdbd8324b7f5004774ea9c3a2986e8 | gmaldona/Turtles | /runGame.py | 2,561 | 4.21875 | 4 | import turtle
import random
from tkinter import *
import time
### Class for each player object
class Player:
## Starting y coordinate
y = -250
## Initialing variables
def __init__(self, vMin, vMax, color):
self.player = turtle.Turtle()
self.player.showturtle()
self.pla... |
8d21998d10406b28f54f12293f6ac21b2c805051 | 106FaceEater106/Pythonparazumbis | /Lista 1/ex02.py | 172 | 3.921875 | 4 | #Escreva um programa que leia um valor em metros e o exiba convertido em milímetros
n = int(input("Numero: "))
c = n * 100
print("{}m em centrimetros {}cm".format(n,c)) |
cb728b5ca3b475d91569543a68542958a7daba72 | 106FaceEater106/Pythonparazumbis | /Lista 1/ex05.py | 290 | 3.671875 | 4 | #solicite o preço de uma mercadoria e o percentual de desconto. Exiba o valor do desconto e o
#preço a pagar.
p = float(input("Produto: "))
d = int(input("Desconto: "))
s = (p * d / 100)
total = p - s
print("O produto R${} com desconto de {} = {} saira por {}".format(p,d,s,total)) |
0ba11651ee41b6fb50b1694a5fe672d19c90cad0 | lzlandGb/data_pro1 | /data/1-IPython/softpo/sss.py | 271 | 3.84375 | 4 | # 该文件是外部文件
print('深圳的温度,好高呀')
def sum(l):
ret = 0
for i in l:
ret += i
return ret
def square_3(x):
ret = x*x*x
return ret
l = [3.14,6.28,2.713]
ret = sum(l)
print('调用方法得到了求和:',ret)
|
7c02ca753c412910d746f793022dde55b5754bc6 | Cadu12/UFF | /Lista1/3-distancia-entre-dois-pontos.py | 171 | 3.703125 | 4 | from math import sqrt
x1, y1 = [float(i) for i in input().split()]
x2, y2 = [float(i) for i in input().split()]
d = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(f"{d:.4f}") |
a517799521f51ff3c445a79ec9102e231390f16a | Cadu12/UFF | /Lista6/1-criptografia.py | 501 | 3.6875 | 4 | n = int(input())
for _ in range(n):
linha = input()
nova = ""
for i in linha:
ascii = ord(i)
if (ascii >= 65 and ascii <= 90) or (ascii >= 97 and ascii <= 122):
nova += chr(ascii + 3)
else:
nova += i
nova = nova[::-1]
crip = ""
for i in range(len(n... |
d10903c7619cf3b33222891a943377b77bc06a99 | Cadu12/UFF | /Lista3/2-notas-e-moedas.py | 1,677 | 3.75 | 4 | valor = float(input())
troco = valor
print("NOTAS:")
print(int(troco / 100), "nota(s) de R$ 100.00")
troco -= int(troco / 100) * 100
print(int(troco / 50), "nota(s) de R$ 50.00")
troco -= int(troco / 50) * 50
print(int(troco / 20), "nota(s) de R$ 20.00")
troco -= int(troco / 20) * 20
print(int(troco / 10), "nota(s)... |
fd4bc983692df7128eb93cacba8368bd1d7b1894 | Cadu12/UFF | /Lista1/5-idade-em-dias.py | 174 | 3.59375 | 4 | dias = int(input())
ano = int(dias / 365)
mes = int((dias % 365) / 30)
dia = dias - ((ano * 365) + (mes * 30))
print(ano, "ano(s)")
print(mes, "mes(es)")
print(dia, "dia(s)") |
d49506625b56429490633a6fccd2db319c7e50cb | Guttekk/learning_python | /word_guessing.py | 1,294 | 4.03125 | 4 | import random
def get_random_word():
words = ["cytryna", "banan","arbuz", "limonka", "malina"]
word = words[random.randint(0, len(words)-1)]
return word
def show_word(word):
for character in word:
print(character, end=" ")
print("")
def get_guess():
print("Enter a letter: ")
retu... |
b1ad78c322e65bf57fb6a4caec0f4f9908fdfb8f | Code-Law/Ex | /Cement_Gravel_Sand.py | 1,593 | 3.515625 | 4 | Type_of_sack = []
CementWeight = []
GravelWeight = []
SandWeight = []
RejectCementWeight = []
RejectGravelWeight = []
RejectSandWeight = []
Reject_Count_of_Cement = 0
Reject_Count_of_Gravel = 0
Reject_Count_of_Sand = 0
Count_of_Cement = 0
Count_of_Gravel = 0
Count_of_Sand = 0
while True:
s = int(input('input t... |
0aa3a7fddbe66a9fb10a00f251c5bc0519267e19 | Code-Law/Ex | /BYFassess.py | 2,097 | 4.15625 | 4 | def Student():
Student_num = int(input("please input your student number:"))
while Student_num < 4990 or Student_num > 5200:
Student_num = int(input("your student number is out of range, please input again!"))
while Student_num in Student_Numbers:
Student_num = int(input("this student number... |
0db72fc6ecaa40868db26d7ac3f6322aa6abc580 | Code-Law/Ex | /Help.py | 170 | 3.515625 | 4 | c=0
L=[]
Num = int(input("Input number:"))
for i in range (2*Num):
if i%3 != 0 and i%5 !=0:
c=c+1
L.append(i)
while c==Num:
break
print(L) |
1a7a97663687efc1bee19a4feb6e9420db6680be | Code-Law/Ex | /Function_Average.py | 190 | 3.890625 | 4 | def ca():
tn = 0
an = 0
for i in range(3):
n = int(input("Please input a number:"))
tn = tn + n
i = i + 1
an = float(tn / i)
return an
ca()
|
bf1d9e0b92b81760a0f5b13459f60bdbfc4bcd9e | Code-Law/Ex | /LocalGlobal.py | 124 | 3.515625 | 4 | # num = 100
# def func():
# n += 100
# print(n)
# func()
num = 100
def func():
num = 123
print(num)
func()
|
12014e402a4ff8822331a1cc74c36a6dfe37a4dd | Code-Law/Ex | /Function_ Power.py | 110 | 3.71875 | 4 | a = int(input("input a:"))
b = int(input("input b:"))
m = 1
while b > 0:
b = b - 1
m = m * a
print(m)
|
c12a106d7b171353a956357c1f50339a8c3f4eef | Code-Law/Ex | /cow.py | 635 | 3.875 | 4 | identity = []
yeild = []
ErrCheck = 0
weeklyyeild = 0
for i in range(2):
y = input("identity:") # it's the input of identity code
while len(y) != 3: # error checking
y = input("error!Please reinput:")
identity.append(y)
I = input("yeild:")
while I.isdigit == False:
I = input(" In... |
6d5fca0f42e625c894666d39fc35a7d188a19ae5 | Code-Law/Ex | /python/Function_ Power.py | 94 | 3.71875 | 4 | a=int(input("input a:"))
b=int(input("input b:"))
m=1
while b>0:
b=b-1
m=m*a
print(m)
|
2396c88af7f687758bb1557873c75facb6f66143 | Code-Law/Ex | /Fibonacci8.py | 287 | 3.515625 | 4 | def f(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return f(n - 1) + f(n - 2)
i = 1
while i > 0:
fi = f(i)
digits = list(str(fi))
if len(digits) == 8:
print(i)
print(f(i))
break
else:
i = i + 1
|
53cfca4b0869c5c8ffcd72ad0648c77f17339dbd | supriyashahane/Systeam_programing | /Encode_decode_assignment/source.py | 556 | 3.71875 | 4 | from sys import argv
script,filename = argv
with open (filename,'r') as input,open ("output1.txt","w") as output:
line = input.readline()
print line
while line!="":
words = line.split()
print words
for abc in words:
print abc
for ch in line:
print ch
... |
9c3ed9bbf45d937baab9af27b4d39f967886b701 | sagynangare/Data-Analysis | /pandas_html_reading.py | 1,335 | 3.703125 | 4 | #s="http://www.delhisldc.org/Loaddata.aspx?mode=25/07/2018"
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
# read the data from the downloaded CSV file.
data = pd.read_csv('https://s3-eu-west-1.amazonaws.com/shanebucket/downloads/uk-500.csv')
# set a numeric id for use as an index... |
13dd5721d12d89971d51536de25699472ecb8a33 | sagynangare/Data-Analysis | /Pandas_loc.py | 1,169 | 3.578125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# series
population = pd.Series({'Germany': 81.3, 'Belgium': 11.3, 'France': 64.3,
'United Kingdom': 64.9, 'Netherlands': 16.9})
#print("Series Data: \n", population)
# dataframe
data = {'country': ['Belgium', 'France', '... |
9a97067ab39f210c3b5a60cdd16f1a826e7d6330 | sagynangare/Data-Analysis | /data+visualization+with+python.py | 512 | 3.59375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('countries.csv')
#print(data.head())
#compare the population growth in the US and India
#print(data[data.country=='United States'])
us= data[data.country=='United States']
ind= data[data.country=='India']
plt.plot(us.year, us.po... |
787e0459b8d7d3e35d4e26028648422d76f9cbbf | JuveVR/Homework_2 | /Exercise_2.py | 941 | 3.859375 | 4 | #2.1
katet1 = 3
katet2 = 4
gipotenuza = (katet1**2 + katet2**2)**0.5
print(gipotenuza)
# 2.2
print(56 // 10)
# 2.3
c = str(156)
summa = 0
for i in c:
summa += int(i)
print(summa)
#second way
d = 344
d1 = d % 10
d = d // 10
d2 = d % 10
d = d // 10
d3 = d % 10
sum = d1 + d2 + d3
print(s... |
062ad9dc571345a7f470daa1d624c95fab71381b | MatsakB/Lesson3 | /2_date_time.py | 556 | 3.75 | 4 | from datetime import datetime, timedelta
date_today = datetime.now()
delta_days = timedelta(days=1)
delta_months = timedelta(days=30)
date_yesterday = date_today-delta_days
date_month_before = date_today-delta_months
print(date_today.strftime('%d.%m.%y'))
print(date_yesterday.strftime('%d.%m.%y'))
print(date_month_be... |
43624ddb794cc122bf493cbb055169b042824d1b | michaelmnicholl/reimagined-train | /module_grade_program.py | 555 | 4.21875 | 4 | marks = [0,55,47,67]
lowest = marks[0]
mean = 0
if len(marks) < 3:
print("Fail")
print("Your score is below the threshold and you have failed the course")
exit()
for item in marks:
if item < lowest:
lowest = item
for item in marks:
mean = mean + item
mean = mean - lowest
mean ... |
c16631173739fa96b670a7f0c50c53332f88ba9c | michaelmnicholl/reimagined-train | /function_truth_value.py | 317 | 4.0625 | 4 | def integer_0_or_1(x):
"""convert false to 0 and true to 1"""
if x == True:
integer_0_or_1 = 1
else:
integer_0_or_1 = 0
return integer_0_or_1
def and_binary(A, B):
if A == True and B == True:
output = 1
else:
output = 0
return output
|
97c8a1bd85c9c9eab352e07083396d37d9302999 | shi-jie-samuel-tan/dsaid_test | /section_1_data_pipelines/process_data.py | 1,393 | 3.65625 | 4 | import os
import pandas as pd
import datetime
def remove_prepend_zeros(price_string):
index = 0
# find out the index of the first non-zero value
while index < len(price_string) and price_string[index] == 0:
index += 1
# settle edge case where the entire string is just zeros
if index == le... |
a1743b7ff716362650906535fa5f570f1e733ec9 | KaramAbuMokh/Machine-Learning | /CNN/animals classification from cifar/data from cifar.py | 3,467 | 3.578125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow.keras.datasets import cifar10
# importing the data
def read_data():
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
return (X_train, y_train), (X_test, y_test)
if __name__ == '__main__':... |
44ad80c921e96c303ec5ff098b00868cae81ff58 | saitejas-janjur/Python_Basics | /Chapter_13__Files.py | 14,606 | 4.78125 | 5 | # Reading from a File
# -> An incredible amount of data is available in text files.
# Text files can contain weather data, traffic data, socioeconomic data, literary works, and more.
# Reading from a file is particularly useful in data analysis applications, but it’s also applicable to any situation in which you w... |
6b5d9f2d9b9a20edc5c0ad35c6a76fef9a90f5f4 | saitejas-janjur/Python_Basics | /Chapter3__Lists.py | 5,208 | 4.53125 | 5 | # -> A list is a collection of items in a particular order. You can make a list that includes the letters of the alphabet, the digits from 0–9, or names.
# -> In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas.
starwars = ['Anakin Skywalker', 'Darth Vader', ... |
30d1e90023019886600d687354e44e4ac7103320 | SandyaSarathi/BinarySearchTree | /BST.py | 2,124 | 3.734375 | 4 | class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right= None
class BST:
def __init__(self):
self.root=None
def create(self,val):
if self.root==None:
self.root=Node(val)
else:
current=self.root
while True:
if val<current.data:
... |
82002e71be41873ca7c2d93907dd79c92d7defbf | jordanhong/Auto_Chess_Player | /prelim_ttt/tttlib.py | 4,658 | 3.625 | 4 | from tree import *
import random
class board():
def __init__(self):
self.store=[];
self.player=["", "X", "O"];
self.state=0;
self.val=0;
self.length=9;
for i in range (0, self.length, 1):
self.store+=[0];
def printBoard(self):
display=[]
if not type(self.store)==list:
return False
if (no... |
219632a66aaa26291376814082b8cc8372b76a1e | genome2017/invitae_bioinfo_B | /translate_coordinate.py | 8,751 | 3.59375 | 4 | import os
import sys
import re
from argparse import ArgumentParser
from mappings import Mappings
class GenomicMapping:
"""
Class to hold the input information about the mappings (contents from inputfile1.txt)
:param transcriptName: string, transcript name
:param: chromosome: string, genomic chromsome
... |
d91cc1eee214bee0acb594ab49774fd44a63ed6e | htnguyen901/covid19_patient_BI | /data_cleaning.py | 1,113 | 3.53125 | 4 | import pandas as pd
df = pd.read_csv("D:/CODING/Projects/DataScience/Covid19_Patients/patient_information_vi_encoded.csv", encoding = 'utf-8', sep= ',')
# 1. patient info parsing
#create column status for patient's current status
df['status'] = df['Tình trạng'].apply(lambda x: 1 if x == 'Đang điều trị' else 0 if ... |
41e9ae805b19463cf2a5dbdf4cbce27f54d2fdcb | JeanAlmenar/HolaMundo | /controlDeFlujo.py | 819 | 4.28125 | 4 | if 2 < 5:
print("2 es menor que 5")
# a == b
# a < b
# a > b
# a != b
# a <= b
# a >= b
if 2 == 2:
print("2 es igual a 2")
if 2 == 3:
print("2 no es igual a 3, y no se ve")
if 2 > 5:
print("2 no es mayor y no se ve")
if 5 > 2:
print("Este si es mayor y se ve")
if 2 !=2:
... |
33a62d80ccecffa3577e73388656dfb9133f4686 | noufanpmc/Chapters-Python-HTML | /Python/twonumbers.py | 132 | 4 | 4 | x=int(input('Enter 1st number:'))
y=int(input('ENter 2nd number:'))
print "The first number is:",x
print "The second number is:",y
|
6a3436a1960010dada573c62997ede994a58a038 | noufanpmc/Chapters-Python-HTML | /Python/metals.py | 217 | 3.75 | 4 | tuple1=raw_input("Enter metals:")
tuple2=raw_input("Enter nonmetals:")
list1=tuple1.split(",")
list2=tuple2.split(",")
tuple1=tuple(list1)
tuple2=tuple(list2)
print "Metals are:",tuple1
print "Non Metals are:",tuple2
|
26b8619b4f3f5f500cbb18a1a0446b1c23387353 | binamify/66DaysOfData | /Day4/np_array.py | 830 | 4.09375 | 4 |
#2D Numpy Arrays
import numpy as np
data = [[1,11],[2,22],[3,33],[4,44]] #python list inside list
np_data = np.array(data) #python 2d numpy array
print(np_data) #(4,2)-4 rows,2 columns
print(np_data.shape) #number of rows and columns
#Accessing 2d array items
print(np_data[3][1]) # [ind... |
9515af561a3f8a1baedd55c2127f71cf0cc53403 | braxtonphillips/SDEV140 | /PhillipsBraxtonM02_Ch4Ex7.py | 1,042 | 4.09375 | 4 | #Braxton Phillips
#SDEV 140
#M02 Chapter 4 Exercise 7
#This program is used to calculate how much a person would make if they start with 1 penny and their compensation doubles everyday after.
print('Hello, this program will be used to calaculate a salary paid in pennies that doubles everyday.')
daysWorked = int(... |
1b5f0832809513821db10e2be39737d60209ea5f | braxtonphillips/SDEV140 | /PhillipsBraxtonM02_Ch3Ex12.py | 2,041 | 4.46875 | 4 | #Braxton Phillips
#SDEV 140
#M02 Chapter 3 Exercise 12
#This purpuse of this program is to calculate the amount a discount,
# if any, based on quantity of packages being purchased.
print('Hello, this progam will read user input to determine if a discount is applicable based on order quantity.')
packageQuantity ... |
4e31d151c7d8d2246a42e286263ae5af2cd87cb4 | nanihari/regular-expressions | /lower with __.py | 394 | 4.40625 | 4 | #program to find sequences of lowercase letters joined with a underscore.
import re
def lower_with__(text):
patterns="^[a-z]+_[a-z]+$"
if re.search(patterns,text):
return ("found match")
else:
return ("no match")
print(lower_with__("aab_hari"))
print(lower_with__("hari_krishna"))
p... |
e15765c217cc41d624aa18e1fb54d7490fde49ff | nanihari/regular-expressions | /replace_space_capital.py | 270 | 4.1875 | 4 | #program to insert spaces between words starting with capital letters.
import re
def replace_spaceC(text):
return re.sub(r"(\w)([A-Z])", r"\1 \2", text)
print(replace_spaceC("HariKrishna"))
print(replace_spaceC("AnAimInTheLifeIsTheOnlyFortuneWorthFinding"))
|
809214d38526ab39fa2026b0c05525ae34aaebde | nanihari/regular-expressions | /remove numbers.py | 278 | 4.375 | 4 | ##program to check for a number at the end of a string.
import re
def check_number(string):
search=re.compile(r".*[0-9]$")
if search.match(string):
return True
else:
return False
print(check_number("haari00"))
print(check_number("hari"))
|
80bcae00e491919c7f627182755948c19115cedf | nanihari/regular-expressions | /snake to camel convertion.py | 282 | 4.25 | 4 | ##program to convert snake case string to camel case string.
import re
def snake_camel(text):
return ''.join(x.capitalize() or '_' for x in text.split('_'))
print(snake_camel("harikrishna"))
print(snake_camel("hari__KRISHNA"))
print(snake_camel("HARI_krishna!!!@###"))
|
65d7d2b5fddaccc16bd56fcf8faab7fcf4924446 | KIMBEOBWOO/python-study | /practice-03/default.py | 470 | 4.09375 | 4 | comment = """
1. Add
2. Del
3. List
4. Quit
Enter Number : """
# n = 0
# while n != 4:
# print(comment)
# n = int(input())
test_list = [1, 2, 3, 4, 5, 6, 7]
test_tuple = (1, 2, 3, 4, 5, 6, 7,)
for l in test_list:
print(l)
print('-'*10)
for t in test_tuple:
print(t)
print('-'*10)
# 요소 값이 튜플임을 사용한... |
999fccea0d5a236aa69f470a00fa742463565809 | KIMBEOBWOO/python-study | /practice-06/multi3and5.py | 526 | 3.796875 | 4 | # 10 미만의 자연수에서 3과 5의 배수를 구하면 3, 5, 6, 9이다. 이들의 총합은 23이다.
# 1000 미만의 자연수에서 3의 배수와 5의 배수의 총합을 구하라.
# 내 풀이
# 1. 3의 배수를 모두 구한다
# 2. 5의 배수를 모두 구한다
# 3. 3과 5의 공배수를 제거한다 -> or 연산
def threeAndFive():
n = 1
origin = []
while n < 20:
if(n % 3 == 0 or n % 5 == 0):
origin.append(n)
n += 1... |
2bdc400abfb4d0eb9b83d3a3edb7d7d04734a383 | KIMBEOBWOO/python-study | /practice-06/paging.py | 393 | 3.53125 | 4 | # 게시물의 총 건수(m) 페이지당 보여줄 게시물 수(n) 총 페이지 수
# 5 10 1
# 15 10 2
# 25 10 3
# 30 10 3
def getTotalPage(m, n):
mantisa, fraction = divmod(m, n)
return mantisa + (fraction > 0 and 1 or 0)
dummy = [(5, 10), (15, 10), (25, 10), (30, 10)]
for i, (m, n) in enumerate(dummy):
print(i, "total page =... |
001f0c4e8da570d75093c2f9127983705ec0dda7 | KIMBEOBWOO/python-study | /practice-04/q3.py | 405 | 3.828125 | 4 | # 3과 6을 입력했을 때 9가 아닌 36이라는 결괏값을 돌려주었다.
# 이 프로그램의 오류를 수정해 보자.
input1 = input("첫번째 숫자를 입력하세요:")
input2 = input("두번째 숫자를 입력하세요:")
# input 의 리턴값은 문자열이다.
print(type(input1), type(input2))
total = int(input1) + int(input2)
print("두 수의 합은 %s 입니다" % total)
|
50929ea4cbf1a0ca13d4a9054c577055e71bb196 | ar1ndamg/algo_practice | /3.sorting_algos.py | 1,533 | 4.5 | 4 | def insertion_sort(arr: list):
""" Takes an list and sorts it using insertion sort algorithm """
l = len(arr)
#print(f"length: {l}")
for i in range(1, l):
key = arr[i]
j = i-1
while j >= 0:
if key < arr[j]:
# slide the elements what are greater than th... |
0c6e89d23d913a1234d8bcd95de548b6a5bd6a62 | hariprasadraja/python-workspace | /MoshTutorial/basics.py | 2,268 | 4.28125 | 4 | import math
"""
Tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=7729s
"""
course = 'Python learning tutorial'
print(course[0:-3])
print("Another variable: ")
another = course[:]
print(another)
# works only on python > 3.6
# formated_string = (f'this is an another course')
# print(formated_string)
print(le... |
a1fff21e1be943258de7870b4dbaf7ae56d6e963 | shubhang889/Hotel-Management-System | /calculator.py | 4,940 | 3.765625 | 4 | from tkinter import *
def btn(numbers):
global operator
operator = operator+str(numbers)
txt_input.set(operator)
def clear():
global operator
operator =''
txt_input.set('')
# Display.insert(0,'Start Calculating...')
def Equal():
global operator
sumup = float(eval(op... |
6252680112fff1d784fca06e481fc8e668da0f5b | DeepikaRao08/SDETAssignmentSubmission | /solution2.py | 334 | 3.546875 | 4 | N=int(input("N="))
X=int(input("X="))
Y=int(input("Y="))
T=int(input("T="))
ListA=[no for no in range(1,N+1) if no%X==0 ]
ListB=[no for no in range(1,N+1) if no%Y==0 ]
pairs=[]
for i in ListA:
for j in ListB:
if i+j==T:
pairs.append((i,j))
print('ListA =', ListA)
print('ListB =', ListB)
print(... |
970173a9b7f2b204a8583c7480a914f32b8987b1 | JacksonCho/pythonProject | /start.py | 411 | 3.5625 | 4 | print(886)
print('chorong:\'初珑\'')
name='chorong'
print(id(name))
print(176)
print(0x176) #374是十进制 176是十六进制#
print(0b10101)
n1 = 1.1
n2 = 3.3
print(n2-n1)
from decimal import Decimal
print(Decimal('3.3') - Decimal('1.1'))
F1 = True
F2 = False
print(F1+2)
print(F2+3)
str1 = '''真挺有意思,
有意思''' #三引号解锁#
print(str1... |
5aa0e0d6f82f4441ad8ddb66fb0ab1a5ac65520c | easyas123l1/hash-tables-2 | /applications/markov/markov.py | 1,694 | 3.78125 | 4 | import random
# Read in all the words in one go
with open("input.txt") as f:
words = f.read()
# TODO: analyze which words can follow other words
# Your code here
words = words.split()
cacheStart = {}
cacheMid = {}
cacheEnd = {}
punctuation = ['.', '?', '!']
for i in range(len(words) - 1):
# find if a start wo... |
ba785abefc90c1d15878514b9d93be99c7383f4f | Ankush-Chander/euler-project | /9SpecialPythagoreanTriplet.py | 539 | 4.28125 | 4 | '''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import sys
import os
if len(sys.argv) != 2:
print("Usage: python " + sys... |
187d5213a7f6cf3019875728f382186dbdf4d2e1 | fedor9ka/python_basic_07_04_20 | /lesson1/task5.py | 1,451 | 4.15625 | 4 | """Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает
фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыл... |
8478096d9b56d35cd04d2a454b999e8d9a2586c0 | tinctura13/lenta_test | /linear_algebra/main.py | 794 | 3.84375 | 4 | from linear_algebra import *
# Some samples
A = [[1, 4], [-2, 3]]
B = [[-2, 5], [6, 7]]
print('Matrix A:')
print_matrix(A)
print('Matrix B:')
print_matrix(B)
print('Addition of matrices A and B:')
# Addition
print_matrix(add_matrix(A, B))
print('Subtraction of matrices A and B:')
# Subtracti... |
8cc2e55ddd36c2aed47d893fc19c60b443b60dac | yyhangz/cs50 | /pset6/cash/cash.py | 580 | 3.8125 | 4 | from cs50 import get_float
def calc(value, change, total_coins):
coins = change // value
change -= (value * coins)
total_coins += coins
return total_coins, change
while True:
change = get_float("Change owed: ")
if change > 0:
change *= 100
break
coins = 0
# Calculate quarte... |
695cf573573bacb891ab7ff62f13bd60088697f9 | yyhangz/cs50 | /pset6/crack/crack.py | 931 | 3.765625 | 4 | from sys import argv
from sys import exit
import crypt
def click(char):
if not char:
char = 'A'
elif char == 'Z':
char = 'a'
elif char == 'z':
char = 'A'
else:
char = chr(ord(char) + 1)
return char
if len(argv) != 2:
print("usage: python crack.py hash")
exi... |
99c87093c7052cc97a7a2dd3a28f92d79a4dfd5c | Ivofil/dl_b101 | /hw06_easy.py | 3,679 | 4.15625 | 4 | # Задача-1:
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (... |
7c5a418e4cf22d3887c81d0af22e6e9824a03ef6 | Ivofil/dl_b101 | /hw11.py | 2,287 | 3.921875 | 4 | """
Реализовать решение следующей задачи:
«Есть два писателя, которые по очереди в течении определенного
времени (у каждого разное) пишут в одну книгу. Данная книга очень
популярна, у неё есть как минимум 3 фаната (читателя), которые
ждут не дождутся, чтобы прочитать новые записи из неё. Каждый
читатель и пи... |
42b7c238e7dba01ebefd1761ea635a53440ebcbc | tomasolodun/kolokvium | /43.py | 597 | 3.625 | 4 | '''Задано два натуральних числа a і b.
Змінній w привласнити значення істина, якщо в одновимірному цілочисельному масиві є хоча б один елемент, кратний а і не кратний b. '''
import random
array = [random.randint(0, 20) for i in range(20)]
print('Даний масив:\n', array)
a = int(input('Введіть a:'))
b = int(inpu... |
367c73a9354be8c1b57a4b71f4799a908c81efd2 | tomasolodun/kolokvium | /46.py | 563 | 3.984375 | 4 | '''Задана таблиця назв товарів, що випускаються заводом.
Визначте, чи повторюється в цій таблиці назва першого товару, і, якщо повторюється, видаліть назву першого товару з таблиці. '''
products = ['jeans', 'sweater', 't-shirt', 'jeans', 'dress', 'pants']
if products.count(products[0]) > 1:
productName = produc... |
18d6d3217d272df8d98d340744a567e94dbb87c5 | tomasolodun/kolokvium | /21.py | 723 | 3.84375 | 4 | '''Знайти добуток всіх елементів масиву дійсних чисел, менших заданого числа.
Розмірність масиву - 10. Заповнення масиву здійснити випадковими числами від 50 до 100. '''
import random
A = [random.uniform(50, 100) for i in range(10)]
print('Даний масив:\n', A)
B = int(input('Введіть число: '))
dob = 1
for j in ... |
cd3a71e505a76856171e87afc0a1ed45870f90ef | tomasolodun/kolokvium | /31.py | 684 | 3.84375 | 4 | '''Обчислити середнє арифметичне значення тих елементів одновимірного масиву, які потрапляють в інтервал від -2 до 10. '''
import random
array = [random.randint(-10, 20) for i in range(20)]
print('Даний масив:\n', array)
sum = 0
counter = 0
for i in range(len(array)):
if -2 <= array[i] <= 10:
sum ... |
f9bc9bf2cdcdeae336cd299a7ddbd15636378b0c | tomasolodun/kolokvium | /53.py | 477 | 3.65625 | 4 | '''В масиві X (1: n) кожен елемент рівний 0, 1 або 5. Переставити елементи масиву так,
щоб спочатку розташовувалися всі нулі, потім все одиниці, а потім всі п'ятірки. Додаткового масиву не заводити. '''
from random import randint
array = [randint(0, 1) if i % 3 == 0 else 5 for i in range(int(input()))]
print(sort... |
3024bc81c9740ed2df77189bbf708c028495d01a | tomasolodun/kolokvium | /10.py | 697 | 3.9375 | 4 | '''Дані про температуру повітря за декаду листопада зберігаються в масиві.
Визначити, скільки разів температура опускалася нижче -10 градусів. '''
import random
T = [random.randint(-20, 10) for x in range(10)]
print('°C, '.join(map(str, T)), end='°C\n')
count = 0
for i in range(len(T)):
if T[i] < -10:
... |
c5522add49d3c18bbc846ca8684743444813c7bd | tomasolodun/kolokvium | /36.py | 550 | 3.765625 | 4 | '''Знайти суму додатніх елементів лінійного масиву цілих чисел. Розмірність масиву - 10. Заповнення масиву здійснити з клавіатури. '''
array = [int(input(f'Введіть {i} елемент масиву: ')) for i in range(10)]
print('Даний масив:\n', array)
sum = 0
for i in array:
if i > 0:
sum += i
print('Сума додатні... |
5b0bbf14b56a35f78f2d3ecc413ecc054b94f65d | hermes-augusto/HacktoberFest2021 | /datacamp.py | 1,680 | 3.78125 | 4 | ########b Datacamp Python streamline exemples ###############
# Create dictionary to query API for cafes in NYC
parameters = {'term':"cafe",
'location':"NYC"}
# Query the Yelp API with headers and params set
response = requests.get(api_url,
parameters["term"],
parameters[... |
1df7dca01c15594555d5b19f63c50049229a4b05 | rudrasingh21/Python---Using-Examples | /27. Dict - Given Key Exists in a Dictionary or Not.py | 247 | 4.125 | 4 | # Given Key Exist in a Dictionary or Not
d={'A':1,'B':2,'C':3}
k = input("Enter Key which you want to search:- ")
if k in d.keys():
print("Value is present and value for the Key is:- ", d[k])
else:
print("Key is not present")
|
20b384829e6346d87a0c0207fd80c026ddff97c6 | rudrasingh21/Python---Using-Examples | /29. Dict - Sum All the Items in a Dictionary.py | 136 | 3.859375 | 4 | #Sum All the Items in a Dictionary
d={'A':100,'B':100,'C':200}
s = sum(d.values())
print("Sum of values in Dictionary is:- ",s) |
6958f52980d417abfb01324cebe6f4b6cf452eb3 | rudrasingh21/Python---Using-Examples | /11.Count the Number of Digits in a Number.py | 271 | 4.125 | 4 | #Count the Number of Digits in a Number
'''
n=int(input("Enter number: "))
s = len(str(n))
print(s)
'''
n=int(input("Enter number: "))
count = 0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are: ",count)
|
26ecc9df30d13fbeabe16387bfcf5dd79b3ee02d | rudrasingh21/Python---Using-Examples | /25. Dict - Add a Key-Value Pair to the Dictionary.py | 278 | 4.25 | 4 | #Add a Key-Value Pair to the Dictionary
n = int(input("Enter number of Element you want in Dictionary:- "))
d = {}
for i in range(1,n+1):
Key = input("Enter Key : ")
Value = input("Enter Value : ")
d.update({Key:Value})
print("Updated Dictonary is: ",d) |
d3deb26ceac103ba0293337edd8aea1479176160 | Oppac/AI | /matrix.py | 5,133 | 3.8125 | 4 | # Toy matrix class for implementing the neural network from scratch
from math import exp
from random import uniform
class Matrix:
# Matrix of size [rows * columns]
def __init__(self, nb_rows=1, nb_cols=1, values=None):
self.nb_rows = nb_rows
self.nb_cols = nb_cols
self.values = [[0 for... |
67dbfb3f3e81f9943ec47f0d3230f8f68d736317 | lukoucky/swimming_pool_attendance_prediction | /models/monthly_average.py | 2,153 | 3.71875 | 4 | from days_statistics import DaysStatistics
import numpy as np
import pickle
import os
class MonthlyAverageClassifier():
"""
Monthly average classifier. Using DaysStatistics to compute average
attance for each month. Each monthly average is also split to two
averages - one for weekend and one for weekday.
"""
def... |
24d5a4a15aa73741ff3970f42a1c0e0d52f1ad26 | torque19/todo-CLI-Python- | /todo.py | 7,785 | 3.640625 | 4 | ''' This is a code for Todo Command-Line Utility. It helps you manage your daily task and work'''
import sys
import argparse
import datetime
#this function place the text in todo.txt in proper manner
def copytoorg():
infile = "todo.txt"
outfile = "copy.txt"
delete_list = ["1", "2", "3", "4","... |
34d425b24aa0607afe9a99d757d8f85a78a26814 | kennyp13669/python_files | /minesweeper2.py | 8,898 | 3.78125 | 4 | ####################################################################
# This program is a minesweeper clone. The user must make selections
# and press enter each time.
#
# Modify GRIDSIZE to play a different size field.
#
# Modify CHANCE to allocate more bombs
#
# Created by Kenny Peel on 9/1/2021
#############... |
f0689ed643caf94fccd0fbe9cec7ddad49d7b43b | Onawa33/IDF-Class | /Python/Exercises1/BMI.py | 211 | 4.21875 | 4 | weight = float(input("Enter weight in pounds: "))
height = float(input("Enter height in inches: "))
kg = weight * .45359237
meters = height * .0254
BMI = kg / (meters**2)
print("Your BMI is: %.2f" %(BMI))
|
8da1012043bad947cb1f007c11e8a75e035a82d0 | arjun-krishna1/leetcode-grind | /3Sum.py | 2,367 | 4 | 4 | '''
GIVEN
INPUT
nums: integer array
OUTPUT
return all triplets [nums[i], nums[j], nums[k]] where i, j and k are unique
and nums[i] + nums[j] + nums[k] == 0
BRUTE FORCE O(n**3) time, O(1) space
three nested for loops
if indexes are all different and they sum to zero
add to list
HASHING
- how to ha... |
fb1a15610349daa7e8373194919206aec2454977 | arjun-krishna1/leetcode-grind | /valid_parentheses.py | 1,479 | 3.890625 | 4 | '''
GIVEN
INPUT
s: string containing '(', ')', '{', '}', '[' and ']'
OUTPUT
determine if string is valid
open brackets are closed by the same type of brackets
open brackets must be closed in the correct order
BRUTE FORCE O(N) time, O(1) space -> won't work, will miss some edge case... |
539552c2c68497b25948b6d33e55120bff34cb97 | arjun-krishna1/leetcode-grind | /numberOfIslands.py | 2,511 | 3.609375 | 4 | '''
GIVEN
INPUT
m by n 2D binary grid grid
represents a map of '1's (land) and '0's (water)
OUTPUT
return the number of islands
island is surrounded by water
formed by connecting adjacent lands horizontally or vertically
assume all four edges of the grid are all surrounded by water
ALGORITHM
BREADTH FIRST SEARCH
dirs... |
d063654808224d54d7ee8c41d6019dab24b458ac | arjun-krishna1/leetcode-grind | /mergeIntervals.py | 2,766 | 4.34375 | 4 | '''
GIVEN
INPUT
intervals: intervals[i] = [start of i'th interval, end of i'th interval]
merge all overlapping intervals
OUTPUT
return an array of the non-overlapping intervals that cover all the intervals in the input
EXAMPLE
1:
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
already sorted
the end of intervals[0] i... |
bfa3e1d040e71ec3ac9c9f59db211c99f22318ac | ianhuang0630/babar | /graph.py | 5,526 | 3.65625 | 4 | from collections import deque
# graph of obj's, connected by relation objs.
class Relation:
def __init__(self, name):
self.name = name
self.transitive = False
self.reflexive = False
self.symmetric = False
self.inverse_exists = False
self.inverse = None
def isSymmetric(self):
self.symmetric = True
d... |
7469ecd4f584b0b0b0477c5e9d24727b6a3206f0 | iklimah27/praxis-academy-1 | /novice/minggu-01/01-02/bubble_sort.py | 388 | 3.90625 | 4 | def function_buble_sort(list):
# Swap the elements to arrange in order
for number in range(len(list)-1,0,-1):
for index in range(number):
if list[index]>list[index+1]:
temp = list[index]
list[index] = list[index+1]
list[index+1] = temp
# list =... |
5a658e6e590ceebd32bd87b8ffb25caa146f4fba | Ritvik10/Quiz_Generator | /quiz app.py | 1,197 | 3.78125 | 4 | from tkinter import *
from tkinter import messagebox
window=Tk()
window.geometry("500x400")
window.title("QUIZ GENERATOR APPLICATION-RITVIK CHAWLA")
window["bg"]="#660033"
questions_list=[]
choices_list=[]
answers_list=[]
correct_answers=[]
n1=int(input("Number of questions to be taken:"))
for i in range... |
055424ff7fdb1a076a3ca150626418843a679b73 | climatebrad/dc-ds-100719 | /module-1/week-2/day-3-coding-best-practices/lint_tests/test.py | 279 | 3.53125 | 4 | """This is a sample code file for a lesson in linting.
It is the one of three modules.
This one is the simplest of the three."""
def multiply_by_two(val):
"""returns input multiplied by two
parameters:
val: input number
returns doubled val"""
return val * 2
|
e426f6f7ad00888123c2aaaf5fcc8bce539194a0 | kmb5/advent_of_code_2020 | /day6.py | 2,197 | 3.921875 | 4 | from helpers import readfile
def main():
"""Day 6 solution"""
data = readfile('inputs/day6_input.txt')
part1_solution = part1(data)
part2_solution = part2(data)
print(f'Part 1 solution: {part1_solution}')
print(f'Part 2 solution: {part2_solution}')
def part1(data: str) -> int:
"""Objec... |
6fe62ca5336f87c96fb8c4a924531a4483dbb6a3 | wsmorgan/py_dft | /pydft/poisson.py | 12,196 | 3.96875 | 4 | """This module contains methods used to solve the poisson equation."""
import numpy as np
def _generate_M(s):
"""This function finds the M matrix as described by
'https://www.youtube.com/watch?v=FJpqaax7G-Y'.
Args:
s (list int): The number of divisions along the 3
basis vectors.
... |
826a3993e35aece4c19e88969dd44439fc86b969 | ericdasse28/graph-algorithms-implementation | /depth-first-search.py | 1,334 | 4.3125 | 4 | """
Python3 program to print DFS traversal
from a given graph
"""
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representation
class Graph:
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
def add_ed... |
40a867cb13e82c92137838f1a9a0d7cfd515fdc2 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/ejercicio4.py | 939 | 4.40625 | 4 |
#ARRAY LISTS SIN CICLO FOR + SALIDA
the_list = ["love","sad","funny","crazy"]#My list of feelings
print(">> The list is (without for): "+str(the_list))#salida de mi lista de array
print("## The item in position '0' of the list is (without for): "+the_list[0])
print("## The item in position '1' of the list is (without... |
b1ae35069e1d1111bc0d3e8ce39057a31c8eabb9 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 4 MySQL/create_table_mysql.py | 3,443 | 4.6875 | 5 | # PYTHON MySQL CREATE TABLE #
#Creating a Table:
# > To create a table in MySQL, use the "CREATE TABLE" statement.
# > Make sure you define the name of the database when you create the connection
#Example: 'Create a table named (customers)':
import mysql.connector
"""
#Connection to MySQL Database:
myDB = mysql.connec... |
d86d291ac0a1a21683cd70d4a23bed601a90262a | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/appBirthday.py | 705 | 4.25 | 4 | dictionary = {}
while True:
print("--- APP BIRTHDAY ---")
print(">>(1) Show birthdays")
print(">>(2) Add to Birthday list")
print(">>(3) Exit")
choice = int(input("Enter the choice: "))
if choice == 1:
if(len(dictionary.keys()))==0:
print("Nothing to show..")
else:
... |
29c5eaa6897dbbbb6d3cbfe9d868c5110992366b | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/ejercicio24.py | 2,464 | 4.34375 | 4 | ## PYTHON JSON ##
# - JSON is a syntax for storing and exchanging data.
# - JSON is text, written with Javascript object notation.
# JSON IN PYTHON:
#Python has built-in package called json, which can be use
#to work with JSON data.
#Example:
# Import the json module:
import json
#Parse JSON - Convert from JSON t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.