The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code: DatasetGenerationError Exception: ArrowInvalid Message: JSON parse error: Column(/trace_run_status) changed from string to boolean in row 2 Traceback: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 160, in _generate_tables df = pandas_read_json(f) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 38, in pandas_read_json return pd.read_json(path_or_buf, **kwargs) File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/json/_json.py", line 815, in read_json return json_reader.read() File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/json/_json.py", line 1025, in read obj = self._get_object_parser(self.data) File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/json/_json.py", line 1051, in _get_object_parser obj = FrameParser(json, **kwargs).parse() File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/json/_json.py", line 1187, in parse self._parse() File "/src/services/worker/.venv/lib/python3.9/site-packages/pandas/io/json/_json.py", line 1403, in _parse ujson_loads(json, precise_float=self.precise_float), dtype=None ValueError: Trailing data During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1854, in _prepare_split_single for _, table in generator: File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 686, in wrapped for item in generator(*args, **kwargs): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 163, in _generate_tables raise e File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 137, in _generate_tables pa_table = paj.read_json( File "pyarrow/_json.pyx", line 308, in pyarrow._json.read_json File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status pyarrow.lib.ArrowInvalid: JSON parse error: Column(/trace_run_status) changed from string to boolean in row 2 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1412, in compute_config_parquet_and_info_response parquet_operations, partial, estimated_dataset_info = stream_convert_to_parquet( File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 988, in stream_convert_to_parquet builder._prepare_split( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1741, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1897, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | content
string | trace_augmented_code
null | trace_type
null |
---|---|---|---|---|---|---|---|---|
55884a59514464a78f8002779532a7eb01b8331c | sudajzp/jzp-s-python | /FBNQ_py/Fib_circle.py | 854 | 3.84375 | 4 | #coding utf-8
'''
斐波那契数列-循环法
'''
def Fib_circle():
while True: # 去掉while循环,只用for循环
num_1 = 0
num_2 = 1
fib_array = [0] # 用于存储计算出的FB数列值
m = input('你想要查找的起始项:')
n = input('你想要查找的结束项:')
if m.isdigit() and n.isdigit(): # 在这个实现函数中,不要进行检验。每个函数只做一个事情
m = int(m) # 将输入化为整数型
n = int(n)
for i in range(n):
num_1, num_2 = num_2, num_1 + num_2
fib_array.append(num_1)
print(f'你要查找的数列为{list(enumerate(fib_array[m:], m))}')
break
else:
print('请输入有效的正整数')
if __name__ == '__main__':
Fib_circle()
| null | null |
379509ed51eb7ac9484e7b9a5acbb537b4de7c5b | shudongW/python | /Exercise/Python09.py | 287 | 4 | 4 | # -*-coding: UTF-8 -*-
#笨办法学编程py3-输入
print("How old are you?",end="")
age = input()
print("How tall are you?",end="")
height = input()
print("How much do you weight?",end="")
weight = input()
print("So you're %r old,%r tall and %r heavry." %(age,height,weight))
| null | null |
7dcdb9f9d1ee10795021f722200cc9324744ee29 | ctemelkuran/py4e | /ex8.5.py | 565 | 4.03125 | 4 | #From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
#You will parse the From line using split() and
# print out the second word in the line(i.e. the entire address of the person).
#Then print out a count at the end.
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
line = line.rstrip()
if not line.startswith('From:'): continue
pieces = line.split()
count = count + 1
print(pieces[1])
print("There were", count, "lines in the file with From as the first word")
| null | null |
efdccd8d87863e0aaa75ef8c76c9b761bb2dd275 | clkadem/Goruntu-Isleme | /intensity_inverse_example.py | 1,811 | 3.515625 | 4 | # intensity transformation
# intensity inverse example
# gamma correction
import os
import matplotlib.pyplot as plt
import numpy as np
print(os.getcwd())
path = "C:\\Users\\Adem\\PycharmProjects\\GörüntüIsleme"
file_name_with_path = path + "\pic_1.jpg"
print(file_name_with_path)
img_0 = plt.imread(file_name_with_path)
plt.imshow(img_0)
plt.show()
print(img_0.ndim,img_0.shape)
print(np.min(img_0),np.max(img_0))
def convert_rgb_to_gray_level(im_1):
m=im_1.shape[0]
n=im_1.shape[1]
im_2=np.zeros((m,n))
for i in range(m):
for j in range(n):
im_2[i,j]=get_distance(im_1[i,j,:])
return im_2
def get_distance(v,w=[1/3,1/3,1/3]):
a,b,c=v[0],v[1],v[2]
w1,w2,w3=w[0],w[1],w[2]
d=((a**2)*w1+(b**2)*w2+(c**2)*w3)*5
return d
def my_f_1(a,b):
assert a>=0;"intensity pozitive","error intensity not pozitive"
if(a<=255-b):
return a+b
else:
return 255
def my_f_2(a):
return int(255-a)
img_1 = convert_rgb_to_gray_level(img_0)
plt.imshow(img_1,cmap='gray')
plt.show()
m,n=img_1.shape
img_2 = np.zeros((m,n),dtype="uint8")
for i in range(m):
for j in range(n):
intensity = img_1[i,j]
#increment = 50
img_2[i,j] = my_f_2(intensity)
plt.subplot(1,2,1)
plt.imshow(img_1,cmap='gray')
plt.subplot(1,2,2)
plt.imshow(img_2,cmap='gray')
plt.show()
x = np.array(list(range(100)))
y1 = np.power(x/float(np.max(x)),1)
y2 = np.power(x/float(np.max(x)),10)
y3 = np.power(x/float(np.max(x)),1/10)
plt.plot(x,y1)
plt.plot(x,y2)
plt.plot(x,y3)
plt.show()
def my_f_3(image_001,gamma):
return np.power(image_001/float(np.max(image_001)),gamma)
x = img_0
img_100 = np.power(x/float(np.max(x)),1)
plt.imshow(img_100)
plt.show() | null | null |
a15bad952e9b61639ce81901c7ac605ebf21e711 | AK-1121/code_extraction | /python/python_414.py | 215 | 3.578125 | 4 | # Is there a way to get all the directories but not files in a directory in Python?
def listfiles(directory):
return [f for f in os.listdir(directory)
if os.path.isdir(os.path.join(directory, f))]
| null | null |
e5a0fb9bd8186b10e0bf147e33860d88a42d1c40 | DavidLewinski/CA116 | /week08/tt-module-codes.py | 226 | 3.6875 | 4 | #!/usr/bin/env python3
timetable = []
s = input()
while s != "end":
timetable.append(s)
s = input()
i = 0
while i < len(timetable):
tokens = timetable[i].split()
print(tokens[3])
i = i + 1
| null | null |
fd9435912655021c274f70ae9220d7e55f750794 | eidanjacob/advent-of-code | /2020/12.py | 1,430 | 3.6875 | 4 | actions = open("input.txt").readlines()
turn = {"E" : { "L" : "N", "R" : "S"},
"N" : { "L" : "W", "R" : "E"},
"W" : { "L" : "S", "R" : "N"},
"S" : { "L" : "E", "R" : "W"}}
current_direction = "E"
current_x = 0
current_y = 0
for action in actions:
a = action[0]
m = int(action[1:])
if a == "F":
a = current_direction
if a == "E":
current_x += m
elif a == "W":
current_x -= m
elif a == "S":
current_y -= m
elif a == "N":
current_y += m
else:
while m > 0:
current_direction = turn[current_direction][a]
m -= 90
print(abs(current_x)+abs(current_y))
def rotate_left(waypt):
return -1 * waypt[1], waypt[0]
def rotate_right(waypt):
return waypt[1], -1 * waypt[0]
ship_x = 0
ship_y = 0
waypt_x = 10
waypt_y = 1
for action in actions:
a = action[0]
m = int(action[1:])
if a == "N":
waypt_y += m
elif a == "S":
waypt_y -= m
elif a == "W":
waypt_x -= m
elif a == "E":
waypt_x += m
elif a == "L":
while m > 0:
waypt_x, waypt_y = rotate_left([waypt_x, waypt_y])
m -= 90
elif a == "R":
while m > 0:
waypt_x, waypt_y = rotate_right([waypt_x, waypt_y])
m -= 90
elif a == "F":
ship_x += m * waypt_x
ship_y += m * waypt_y
print(abs(ship_x) + abs(ship_y))
| null | null |
7b8b8d5d79a9f3bffa5b35d366c007b16282e094 | Yodjji/Encryption | /main.py | 715 | 4 | 4 | from encryption import *
from decryption import *
def get_path_to_file():
path_to_file = input("Введите путь до файла: ")
return path_to_file
def get_file_password():
password = input("Введите пароль: ")
return password
def choose_the_action():
choose = input("Выберите\nЗашифровать/расшифровать файл(ы): ")
if choose == "зашифровать":
dir_walk(get_path_to_file(), get_file_password())
elif choose == "расшифровать":
dir_walk_1(get_path_to_file(), get_file_password())
else:
print("Error")
if __name__ == '__main__':
while True:
choose_the_action()
| null | null |
5bb64dbd9bc7a8f6a5156396d0e58a09129eac38 | singhj22/String-Slicing-HW | /String_Slicing_Homework.py | 711 | 4.03125 | 4 | '''
Created on Oct 22, 2018
@author: Jugat Singh
Python Period 5 even
String Slicing HW
'''
#input from user
string= input("Please enter a String: ")
start = int(input("Please enter the index where you would like to start slicing: "))
stop = int(input("Please enter the index where you would like to stop slicing: "))
access = int(input("Please enter the index of the character you would like to access: "))
#variable
character= string[access]
#display output
print("\nOriginal String: ", string)
print("Length of the String: ",len(string))
print("Substring from index ", start, "to index ", stop, ": ", string[start:stop])
print("Character at index ", access, ": ", character) | null | null |
13ca18375b426575e997833460d791f3a2093f27 | pingany/leetcode | /reverseWords.py | 598 | 4.0625 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import os,re,sys,commands,glob
reload(sys)
sys.setdefaultencoding("utf-8")
def reverseWords(s):
l = [x for x in s.strip().split(' ') if x]
l.reverse()
return " ".join(l)
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
return reverseWords(s)
def sp(x, y):
assert Solution().reverseWords(x) == y
def test():
sp("", "")
sp("1", "1")
sp("1 2", "2 1")
sp(" 1 2 ", "2 1")
sp(" 11 2 ", "2 11")
pass
if __name__ == '__main__':
main(sys.argv[1:]) | null | null |
e8512576db826d332dea90e3c3a6abde2f09418b | claymaks/python_switch | /python_switch.py | 711 | 3.625 | 4 | def func1():
print("Hello")
def func2():
print("Goodbye")
def func3():
print("Default")
def inline_try(x):
try:
return int(x)
except ValueError:
return x
switch = {
1 : func1,
2 : func2,
}
if __name__ == "__main__":
import time
start = time.time()
for i in range(5):
if i == 1:
func1()
elif i == 2:
func2()
else:
func3()
print(f"Time for if/elif/else: {time.time() - start}")
start = time.time()
for i in range(5):
switch.get(i, func3)()
print(f"Time for switch: {time.time() - start}")
while True:
switch.get(inline_try(input(": ")), func3)()
| null | null |
7d3d8c430b0eadbc1f57797a657dd84dfa7e9b69 | Madhiyarasan/Ancit_practice | /tsk3_sum of odd & even num.py | 278 | 4.0625 | 4 | X = int(input(" A= "))
Y = int(input(" B= "))
even = 0
odd = 0
for number in range(X,Y + 1):
if(number % 2 == 0):
even = even + number
else:
odd = odd + number
print("The Sum of Even Numbers " ,even)
print("The Sum of Odd Numbers ",odd)
| null | null |
a6208f4a6e4ea3d39dc1736bdf992fe26f309038 | rymo90/kattis | /estimatingtheareaofacircle.py | 292 | 3.609375 | 4 | import math
stop = False
while not stop:
r, m, c = map(float, input().split())
if r == 0 and m == 0 and c == 0:
stop = True
else:
areaOne = math.pi * math.pow(r, 2)
temp = (c / m)
areaTwo = temp * math.pow(2 * r, 2)
print(areaOne, areaTwo)
| null | null |
440d948350d2b66218a97d682dbd5786532fb6f0 | will8595/PILED | /city.py | 1,462 | 3.609375 | 4 | #!/usr/bin/env/ python
import time
import effects
when = input("Current 24 hr time: ")
hr = int(str(when)[:2])
min = int(str(when)[-2:])
hr *= 3600
min *= 60
when = hr + min
print(hr, min, when)
length = input("How long in minutes? ")
length *= 60
start = time.time()
end = time.time()
firstRun = True
diff1 = time.time()
diff2 = time.time()
while (end - start) < length:
if firstRun:
diff = 0
firstRun = False
else:
diff = diff2 - diff1
diff1 = time.time()
when += diff
print(start, end, when, diff1, diff2, diff)
if when <= 14400:
r = 75
g = 10
b = 0
elif when <= 18000:
r = 85
g = 13
b = 1
elif when <= 21600:
r = 100
g = 18
b = 2
elif when <= 25200:
r = 200
g = 36
b = 4
elif when <= 39600:
r = 255
g = 125
b = 25
elif when <= 54000:
r = 255
g = 255
b = 255
elif when <= 61200:
r = 255
g = 125
b = 25
elif when <= 64800:
r = 200
g = 36
b = 4
elif when <= 68400:
r = 100
g = 18
b = 2
elif when <= 72000:
r = 85
g = 13
b = 1
elif when <= 86400:
r = 75
g = 10
b = 0
else:
when = 0
effects.rgbInstance(r, g, b)
time.sleep(5)
diff2 = time.time()
end = time.time()
effects.kill()
| null | null |
82e1ab9b3298d3b298956414c454779742f6fed0 | leonlee603/Python_projects | /password_generator.py | 5,210 | 4.375 | 4 | """
:::Password Generator:::
This is a programme which generates a random password for the user.
Ask the user how long they want their password to be.
Then the programme will generate a password with a mix of upper and
lowercase letters, as well as numbers and symbols.
The password should be a minimum of 8 characters long which contain at
least two of each type of character.
"""
from random import choice, shuffle, randint
import string
import os
os.system("clear")
def main():
"""The main body of the programme."""
#Get the length of the password from user.
length = length_pw()
#Generate the password with user's designed length.
pw = gen_pw(length)
#Randomly change the order of the password generated.
shuffle(pw)
#Show the generated password to user.
print("Your password is: " + "".join(pw))
#Check if user want to save the password to "pw.txt".
save_pw(pw)
#Check if user want to generate another password again.
try_again()
def gen_pw(length):
"""Generate a password and save it in a list."""
#Creating variable for 8 characters password.
#Make sure the password contain at least 2 of each type of character.
upper_case_letter_1 = choice(string.ascii_uppercase)
upper_case_letter_2 = choice(string.ascii_uppercase)
lower_case_letter_1 = choice(string.ascii_lowercase)
lower_case_letter_2 = choice(string.ascii_lowercase)
number_1 = choice(string.digits)
number_2 = choice(string.digits)
symbol_1 = choice(string.punctuation)
symbol_2 = choice(string.punctuation)
#Creat a list to store the password.
password = [
upper_case_letter_1,
upper_case_letter_2,
lower_case_letter_1,
lower_case_letter_2,
number_1,
number_2,
symbol_1,
symbol_2,
]
if length == 8:
#If user want a password with 8 characters.
return password
else:
#If user want a password more than 8 characters.
#Add the extra characters with random type of characters.
extra_index = length - 8
for extra_pw in range(0,extra_index):
random_type = randint(0,3)
if random_type == 0:
extra_pw = choice(string.ascii_uppercase)
password.append(extra_pw)
elif random_type == 1:
extra_pw = choice(string.ascii_lowercase)
password.append(extra_pw)
elif random_type == 2:
extra_pw = choice(string.digits)
password.append(extra_pw)
elif random_type == 3:
extra_pw = choice(string.punctuation)
password.append(extra_pw)
return password
def shuffle_pw(password):
"""Shuffle the password generated as a list by gen_pw()."""
shuffle(password)
return password
def length_pw():
"""Get the length of password that user wants."""
while True:
message = "\nHow many characters do you want as a password? "
length = input(message)
try:
length = int(length)
except ValueError:
print("[Invaild input] Please enter a positive interger larger than or equal to 8.")
continue
else:
if length <=7:
print("[Invaild input] Please enter a positive interger larger than or equal to 8.")
continue
else:
return length
def greeting():
"""Display the basic information that only shows once when the programme start."""
print("This is a Password Generator")
print("I can generate a random password of 8 or more characters for you.")
print("In order to createu a strong password, ")
print("each password will contain and mix the following elements:")
print("- at least 2 uppercase letters from A to Z")
print("- at least 2 lowercase letters from a to z")
print("- at least 2 digits from 0 to 9")
print("- at least 2 punctuation signs such as !,?,',# etc")
print("Let's start creating password!")
def try_again():
while True:
again = input("\nDo you want to genetate another password? (y/n): ")
if again.lower() == "y":
return main()
elif again.lower() == "n":
print("See you next time!")
break
else:
print("[Invaild input] Please enter y/n.")
continue
def save_pw(pw):
from datetime import datetime
while True:
save = input("\nDo you want to save the password? (y/n): ")
if save.lower() == "y":
with open("pw.txt", "a") as f:
t = datetime.today()
formatted_t = t.strftime("%Y-%m-%d %H:%M")
content = "\nDate and time of the password generated: " + formatted_t
content += "\nPassword: " + "".join(pw) + "\n"
print("The password is saved at pw.txt!")
f.write(content)
break
elif save.lower() == "n":
break
else:
print("[Invaild input] Please enter y/n.")
continue
#Run the programme.
if __name__ == "__main__":
greeting()
main()
| null | null |
aa382979b4f5bc4a8b7e461725f59a802ffe3a4e | aduV24/python_tasks | /Task 14/task1.py | 340 | 4.59375 | 5 | # This python program asks the user to input a number and then displays the
# times table for that number using a for loop
num = int(input("Please Enter a number: "))
print(f"The {num} times table is:")
# Initialise a loop and print out a times table pattern using the variable
for x in range(1,13):
print(f"{num} x {x} = {num * x}") | null | null |
c116516eaa8d833f3b7db5b3b52a6718db6bf353 | sbowl001/cs-module-project-hash-tables | /applications/histo/histo.py | 371 | 3.578125 | 4 | # Your code here
with open("robin.txt") as f:
words = f.read()
split_words = words.split()
cache = {}
for word in split_words:
if word not in cache:
cache[word] = '#'
else:
cache[word] += '#'
items = list(cache.items())
items.sort(key = lambda x: x[1], reverse= True)
for key, value in items:
print(f'{key: <18} {value}') | null | null |
56fe0d6a863dc1d1cb5479ec2fded1d298eeb561 | Fastwriter/Pyth | /Daulet Demeuov t1/A.py | 335 | 3.65625 | 4 | #STUDENT: Daulet Demeuov
#GROUP: EN1-C-04
#TASK: Task1 problem A
#Description: Read five-digit number; find sum and product of digits.
while True:
a = str(input('Enter number '))
b = int(a[0])+int(a[1])+int(a[2])+int(a[3])+int(a[4])
c = int(a[0])*int(a[1])*int(a[2])*int(a[3])*int(a[4])
print('Sum:',b)
print('Product:',c)
| null | null |
d6aead41f21280a466324b5ec51c9c86a57c35e6 | NickLuGithub/school_homework | /Python/課堂練習/b10702057-課堂練習7-1.py | 802 | 4.15625 | 4 | print("1")
list1 = [1,2,3,4]
a = [5, 6, 7, 8]
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("2")
list1 = [1,2,3,4]
a = 'test'
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("3")
list1 = [1,2,3,4]
a = ['a', 'b', 'c']
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("4")
list1 = [1,2,3,4]
a = '阿貓'
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("5")
list1 = [1,2,3,4]
a = ['阿貓', '阿狗']
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("6")
list1 = [1,2,3,4]
a = 0
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1) | null | null |
6caa36efec61cd233576a4dcb9b3e925ab259fae | briangfang/COGS-18 | /functions.py | 9,522 | 3.8125 | 4 | """Collection of functions used in my project"""
from datetime import date
import pandas as pd
def create_food(food, quant, exp, categ):
"""Creates dictionary of preset keys paired with input parameters
as corresponding values.
Parameters
----------
food : string
String of food name.
quant : integer or float or string
Quantity of food in inventory.
exp : datetime.date
Expiration date of food.
Format is `date(year, month, day)`.
categ : string
String of food category.
Returns
-------
output_dict : dictionary
Dictionary of preset keys paired with input parameters
as corresponding values.
"""
output_dict = {}
# create keys for food information
output_dict['food'] = food
output_dict['quant'] = quant
output_dict['exp'] = exp
output_dict['categ'] = categ
return output_dict
def init_df(food, quant, exp, categ):
"""Creates a dataframe with labeled columns for corresponding
input parameters.
Parameters
----------
food : string
String of food name.
quant : integer or float or string
Quantity of food in inventory.
exp : datetime.date
Expiration date of food.
Format is `date(year, month, day)`.
categ : string
String of food category.
Returns
-------
df : pandas.core.frame.DataFrame
Dataframe with labeled columns for corresponding
input parameters.
"""
# make a df from dict in create_food function
dict_1 = create_food(food, quant, exp, categ)
df = pd.DataFrame([dict_1])
return df
def add_food(df, food, quant, exp, categ):
"""Adds input parameters as a new row to an existing dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe to which the input parameters below are added.
food : string
String of food name.
quant : integer or float or string
Quantity of food in inventory.
exp : datetime.date
Expiration date of food.
Format is `date(year, month, day)`.
categ : string
String of food category.
Returns
-------
df : pandas.core.frame.DataFrame
Input dataframe updated with a new row of other input parameters.
"""
# add to existing df from dict in create_food function
# ignore_index = True parameter continues numerical row indexing
# of input df
df = df.append(create_food(food, quant, exp, categ), ignore_index = True)
return df
def in_inventory(df, food):
"""Checks if input food is in the 'food' column of input dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food will be searched for.
food : string
String of food name to be searched.
Returns
-------
output : boolean
Returns False if input food not in 'food' column of input dataframe.
Returns True if input food is in 'food' column of input dataframe.
"""
# turns df 'food' column into str and searches for
# input str food in 'food' column
if food not in str(df['food']):
print('Food not found. Inventory unchanged.')
output = False
else:
output = True
return output
def remove_food(df, food):
"""Removes row of input food from input dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food is to be removed.
food : string
String of food name to be removed.
Returns
-------
output : NoneType or pandas.core.frame.DataFrame
Returns NoneType if input food not in 'food' column of input dataframe.
Otherwise returns input dataframe with input food row removed.
"""
if in_inventory(df, food) == False:
output = None
return output
else:
# turns tuple into list and extracts the
# first element of list which is the number
# of rows in df and stores in var `rows`
rows = list(df.shape)[0]
counter = 0
# loop set to run for the same number of
# times as there are rows in the input df.
# each row is turned into a str and
# searched for a match with input str food.
# a successful match will drop that row
# and reset the row indexing to prevent
# an error in future usage of this function
while counter < rows:
if food in str(df.loc[counter]):
df = df.drop([counter])
df = df.reset_index(drop = True)
break
else:
counter += 1
output = df
return output
def edit_quant(df, food, new_quant):
"""Changes corresponding quantity of input food in input dataframe.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food quantity will be changed.
food : string
String of food name to change quantity.
new_quant : integer or float or string
New quantity of input food to be changed to.
Returns
-------
output : NoneType or pandas.core.frame.DataFrame
Returns NoneType if either input food is not in 'food' column
of input dataframe or new_quant is equal to the existing quantity
stored in the input dataframe. Else returns input dataframe with
updated input food quantity.
"""
if in_inventory(df, food) == False:
output = None
return output
else:
# turns tuple into list and extracts the
# first element of list which is the number
# of rows in df and stores in var `rows`
rows = list(df.shape)[0]
counter = 0
# loop set to run for the same number of
# times as there are rows in the input df.
# each row is turned into a str and
# searched for a match with input str food.
# a successful match will replace the original
# food quantity with the input quantity after
# the original quantity is stored in a var
while counter < rows:
if food in str(df.loc[counter]):
old_quant = df.at[counter, 'quant']
df.at[counter, 'quant'] = new_quant
break
else:
counter += 1
# confirms to user that food quantity has been changed
if new_quant != old_quant:
print(str(food) + ' quantity changed from ' + \
str(old_quant) + ' to ' + str(new_quant) + '.')
output = df
# alerts user input quantity == original quantity so
# the df has not been updated
else:
print('The new ' + food + ' quantity is the' + \
' same as the old one. Inventory unchanged.')
output = None
return output
def is_expired(df, food):
"""Checks if input food in input dataframe is expired.
Also prints out how many days the input food has until
expiration or has been expired accordingly.
Parameters
----------
df : pandas.core.frame.DataFrame
Dataframe in which input food will be checked for expiration.
food : string
String of food name to be checked for expiration.
Returns
-------
output : NoneType or boolean
Returns NoneType if input food is not in 'food' column
of input dataframe. Else returns boolean. Boolean will
be False if input food expires on or after the current
date. Boolean will be True if input food expires before
current date.
"""
if in_inventory(df, food) == False:
output = None
return output
else:
rows = list(df.shape)[0]
counter = 0
# loop set to run for the same number of
# times as there are rows in the input df.
# each row is turned into a str and
# searched for a match with input str food.
# a successful match will then check if the input
# food has expired and print the appropriate response
while counter < rows:
if food in str(df.loc[counter]):
if df.at[counter, 'exp'] > date.today():
output = False
days_til_exp = df.at[counter, 'exp'] - date.today()
print('This food has not yet expired. It will ' + \
'expire in ' + str(days_til_exp.days) + ' days.')
elif df.at[counter, 'exp'] == date.today():
output = False
print('This food expires today!')
elif df.at[counter, 'exp'] < date.today():
output = True
days_exp = date.today() - df.at[counter, 'exp']
print('This food has expired. It expired ' + \
str(days_exp.days) + ' days ago.')
return output
break
else:
counter += 1 | null | null |
a60d7394dcc2b73e5627dcdfb42235049ba3875a | Florins13/How-to-Think-Like-a-Computer-Scientist | /7. Iteration.py | 7,762 | 4.0625 | 4 | # -------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: florins
#
# Created: 25/12/2018
# Copyright: (c) florins 2018
# Licence: <your licence>
# -------------------------------------------------------------------------------
import turtle
import sys
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
# def test_suite():
def seq3np1(n):
""" Print the 3n+1 sequence from n,
terminating when it reaches 1.
"""
while n != 1:
print(n, end=", ")
if n % 2 == 0: # n is even
n = n // 2
else: # n is odd
n = n * 3 + 1
print(n, end=".\n")
def num_zero_and_five_digits(n):
count = 0
while n > 0:
digit = n % 10
if digit == 0 or digit == 5:
count = count + 1
n = n // 10
return count
# EX1
def odd_numbers(n):
count = 0
for a in n:
if a % 2 != 0:
count += 1
print(count)
return count
# EX2
def sum_up(n):
count_list = 0
for a in n:
if a % 2 == 0:
count_list += a
return count_list
# EX 3
def sum_up_negative(n):
count_negative = 0
for a in n:
if a < 0:
count_negative += a
return count_negative
# EX 4
def count_words_5(n):
count = 0
for a in n:
if len(a) == 5:
count += 1
print(count)
return count
# Ex 5
# --neintelegere, am crezut ca nu trebuie adunat primul numar par.
def sum_even_n(n):
sum = 0
first_ocurrence = True
for a in n:
sum += a
if a % 2 == 0 and first_occurence == True:
sum = sum - a
first_occurence = False
print(sum)
return sum
# --varianta corecta -- oprestete la primul numar par
def sumexclude(data):
"Sum all the elements in a list up to but not including the first even number."
count = 0
for i in data:
if i % 2 == 0:
break
count += i
print(count)
return count
# EX 6
def sum_all_elem(n):
count = 0
for a in n:
count += 1
if a == "sam":
break
return count
# EX 7
def sqrt(n):
approx = n/2.0 # Start with some or other guess at the answer
while True:
better = (approx + n/approx)/2.0
print("approx = ", approx)
print("better = ", better)
if abs(approx - better) < 0.001:
print("better 1 = ", better)
return better
approx = better
# EX 8
def print_multiples(n, high): # argumentele n=1 si high = 2
for i in range(1, high+1): # i intre 1 si 3
print(n * i, end=" ") # printeaza n*i=1*1,1*2 spatiu
print()
def print_mult_table(high): # avem un parametru high, 2 spre ex
for i in range(1, high+1): # plecam de la 2 pana la 3
print_multiples(i, i+1) # printam i=1,2 si i+1 = 2,3
#print_multiples(1, 2)
#print_multiples(1, 3)
#print_multiples(1, 4)
#print_multiples(1, 5)
# print_mult_table(4)
# EX 9
def print_triungular_numbers(n):
for x in range(1, n+1):
print(x, "\t", int(x*(x+1)/2))
# EX 10
def is_prime(n):
if n % 2 != 0 and n % 3 != 0 and n > 2 and n % 5 != 0:
return True
else:
return False
# EX11
'''
wn = turtle.Screen()
tess = turtle.Turtle()
data = [(160, 20), (-43, 10), (270, 8), (-43, 12)]
def pirate_drunk(list):
for (x, y) in list:
print("Y = ", y)
tess.forward(y)
print("X = ", x)
tess.right(x)
# pirate_drunk(data)
# EX12
#pairlist = [(100, 90), (100, 90), (100, 90), (100, 135), (141, 90), (70, 90), (70, 90), (141, 90)]
# EX 13
pairlist1 = [(0, 135), (70, 90), (141, 90), (70, 90), (141, -135), (100, -90),
(100, -90), (100, -135), (141, 90), (70, 90), (70, 45), (100, 0)]
# 1,2,5 si 6 grafic eulerian
def shape(list):
for (f, a) in list:
tess.forward(f)
tess.left(a)
tess.speed(1)
shape(pairlist1)
wn.mainloop()
'''
# EX 14
def num_digits(n):
count = 0
while True:
count = count + 1 # 1 --> 710//10=71, 2 --> 71//10 = 7, 3 --> 7//10=0, BREAK
# print(count)
# print(n)
n = n // 10
if n == 0 or n == -1:
break
print(count)
return count
# EX15
def num_even_digits(n):
count = 0
while True:
print(n)
if n % 2 == 0:
count = count + 1
print("Aici avem + 1")
n = n // 10
if n == 0 or n == -1:
break
return count
# EX6
def sum_of_squares(xs):
count = 0
for a in xs:
count = count + a**2
return count
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test_suite()
# Purpose:
#
# Author: florins
#
# Created: 26/12/2018
# Copyright: (c) florins 2018
# Licence: <your licence>
# -------------------------------------------------------------------------------
# Your friend will complete this function
# Last EXO
def play_once(human_plays_first):
"""
Must play one round of the game. If the parameter
is True, the human gets to play first, else the
computer gets to play first. When the round ends,
the return value of the function is one of
-1 (human wins), 0 (game drawn), 1 (computer wins).
"""
# This is all dummy scaffolding code right at the moment...
import random # See Modules chapter ...
rng = random.Random()
# Pick a random result between -1 and 1.
result = rng.randrange(-1, 2)
print("Human plays first={0}, winner={1} "
.format(human_plays_first, result))
return result
def play(result1):
counthuman = 0
countcomputer = 0
countdraws = 0
winingpercentage = 0
while True:
result1 = play_once(print(input(
"Type \"True\" if you want to play first or \"False\" if you want the computer to start first.")))
print(result1)
if result1 == 0:
countdraws = countdraws + 1
winingpercentage = ((counthuman + 0.5*countdraws) /
(countcomputer+countdraws+counthuman))*100
print("game drawn!")
print("Current draws are: ", countdraws)
print("The wining % for human is: ", winingpercentage, "%")
newgame = input("Do you want to play again? yes/no")
if result1 == -1:
counthuman = counthuman + 1
print("I win!")
print("Human won ", counthuman, " times.")
newgame = input("Do you want to play again? yes/no")
if result1 == 1:
countcomputer = countcomputer + 1
print("Computer wins!")
print("Computer won ", countcomputer, " times.")
newgame = input("Do you want to play again? yes/no")
if newgame == "":
print("Goodbye")
break
if newgame == "yes":
continue
if newgame == "no":
print("Goodbye")
break
else:
break
# play(True)
| null | null |
a6bf335219d08bfeb6471b9135b530baee1245e2 | tatiana-kim/contest-algorithms | /contest4/C_most_frequent_word.py | 494 | 3.578125 | 4 | # C_most_frequent_word.py
f = open("C/input.txt", "r")
words = f.read().strip().split()
f.close()
count = {}
maxval = -1
tmp = ""
for i in words:
if i not in count:
count[i] = 0
count[i] += 1
if count[i] > maxval:
maxval = count[i]
tmp = i # intermediate result = one of most frequent word
most_frequent_words = []
for i, j in count.items():
if j == maxval:
most_frequent_words.append(i)
if i < tmp:
tmp = i
print(tmp)
| null | null |
5df9b99440b11611715bcd857315518e77020cdc | M0673N/Programming-Fundamentals-with-Python | /09_regular_expressions/exercise/02_find_variable_names_in_sentences.py | 122 | 3.734375 | 4 | import re
data = input()
pattern = r"\b[_]([A-Za-z0-9]+\b)"
result = re.findall(pattern, data)
print(",".join(result))
| null | null |
d2e92863159f613bf175485cfb7a9f624f8962ff | ClauMaj/pyHomework | /printSquare1and2.py | 117 | 3.859375 | 4 | # Ex. 9
i = 1
while (i <=5):
print("*****")
i +=1
# Ex. 10
i = int(input("How big is the square? "))
| null | null |
d5286f33dd6d3b53406f9bc4df05f60700ba2bab | ashrafishaheen/python_mini_projects | /rename.py | 572 | 3.640625 | 4 | import os
def rename_files():
#(1) get file names from folder
file_list = os.listdir(r"C:\Users\shahid\Downloads\Compressed\prank")
#print(file_list)
save_path = os.getcwd()
print("Current Working Directory is"+save_path)
os.chdir(r"C:\Users\shahid\Downloads\Compressed\prank")
#(2) Rename each file name with removig numbers.
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(save_path)
rename_files()
| null | null |
39cd605853421bafc6abaeda2b905e3bf06b6c6e | Ryandalion/Python | /Functions/Rock, Paper, Scissors!/Rock, Paper, Scissors!/Rock__Paper__Scissors_.py | 2,151 | 4.46875 | 4 | # Program is a simple rock paper scissors game versus the computer. The computer's hand will be randomly generated and the user will input theirs. Then the program will determine the winner. If it is a tie, a rematch will execute
import random; # Import random module to use randint
def generate_random(): # Generate a random number that corresponds to either rock,paper, or scissors
randNum = random.randint(1,3);
return randNum; # Return the generated number to caller
def calculate_winner(userHand, computerHand): # Function calculates the winner between computer and user
if(userHand == 1 and computerHand == 3):
print("User Wins");
elif(userHand == 2 and computerHand == 1):
print("User Wins");
elif(userHand == 3 and computerHand == 2):
print("User Wins");
elif(userHand == 3 and computerHand == 1):
print("Computer Wins");
elif(userHand == 1 and computerHand == 2):
print("Computer Wins");
elif(userHand == 2 and computerHand == 3):
print("Computer Wins");
else: # If it is a draw then we set tie status to true and return to caller
print("It is a tie");
tieStatus = 0;
return tieStatus;
def main(): # Function is responsible for getting user input and calling the appropriate functions and handling the while loop
status = 1;
while(status != -1): # Keep looping until status equals -1
computerHand = generate_random(); # Generate a random number and assign it to computer hand
print("Select your move");
print("1. Rock");
print("2. Paper");
print("3. Scissors");
userHand = int(input()); # Get user's selection
status = calculate_winner(userHand, computerHand); # Send the user's and the computer's hand as arguments to the calculate_winner function
if(status == 0): # If the return value from calculate_winner is 0, a tie has occured and we execute another round
status = 1;
else: # There was a winner and we assign status -1 to exit the while loop and program
status = -1;
print("Rock, Paper, or Scissors");
print();
main(); | null | null |
0eda42b293a5816c846e25cba58e006b19ef3770 | barmi/CodingClub_python | /LV2/SourceCode/ch1/myMagic8Ball.py | 1,125 | 3.65625 | 4 | # My Magic 8 Ball
import random
# 답변을 입력해봅시다.
ans1="자! 해보세요!"
ans2="됐네요, 이 사람아"
ans3="뭐라고? 다시 생각해보세요."
ans4="모르니 두려운 것입니다."
ans5="칠푼인가요?? 제 정신이 아니군요!"
ans6="당신이라면 할 수 있어요!"
ans7="해도 그만, 안 해도 그만, 아니겠어요?"
ans8="맞아요, 당신은 올바른 선택을 했어요."
print("MyMagic8Ball에 오신 것을 환영합니다.")
# 사용자의 질문을 입력 받습니다.
question = input("조언을 구하고 싶으면 질문을 입력하고 엔터 키를 누르세요.\n")
print("고민 중 ...\n" * 4)
# 질문에 알맞은 답변을 하는 일에 randint() 함수를 활용합니다.
choice=random.randint(1, 8)
if choice==1:
answer=ans1
elif choice==2:
answer=ans2
elif choice==3:
answer=ans3
elif choice==4:
answer=ans4
elif choice==5:
answer=ans5
elif choice==6:
answer=ans6
elif choice==7:
answer=ans7
else:
answer=ans8
# 화면에 답변을 출력합니다.
print(answer)
input("\n\n마치려면 엔터 키를 누르세요.")
| null | null |
3a53ab12f8144942fbfcb56bbb56d407c32bdf3e | autumnalfog/computing-class | /Week 2/a21_input_int.py | 345 | 4.21875 | 4 | def input_int(a, b):
x = 0
while x != "":
x = input()
if x.isdigit():
if int(x) >= a and int(x) <= b:
return x
print("You should input a number between " + str(a) + " and " + str(b) + "!")
print("Try once more or input empty line to cancel input check.")
| null | null |
ab105ea16b1b7eaa79ded84ca64dd55396f972e7 | armenuhiarakelyan1978/python_task | /x.py | 175 | 3.796875 | 4 | #!/usr/bin/python
n1 = int(input("Input int "))
n2 = 0
while n1 > 0:
digit = n1 % 10
n1 = n1 / 10
print (n1)
n2 = n2 * 10
n2 = n2 + digit
print (n2)
| null | null |
b923c92371e62b576bb23e2c72d615fd1952fd0b | abhishek-kumaryadav/CSL443_LabAssignment1 | /prg1.py | 666 | 3.8125 | 4 | import sys
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def find_divisors(arr):
if len(arr) == 0:
return
else:
gccd = arr[0]
for i in range(1, len(arr) - 1):
gccd = gcd(gccd, arr[i])
divisors = set()
i = 1
while i * i <= gccd:
if gccd % i == 0:
divisors.add(i)
divisors.add(int(gccd / i))
i += 1
return divisors
def main():
arr = [int(i) for i in sys.argv[2:]]
divisors = find_divisors(arr)
print(" ".join(str(x) for x in sorted(divisors)), end="")
if __name__ == "__main__":
main()
| null | null |
e09c64d065f889680dacc7f98bc63a247935ef94 | karinamonetti/curso_universidadPython | /notas_universidadPython.py | 599 | 3.875 | 4 | x=2
print(type(x))
title=input("Tell me the title of the book: ")
author=input("Tell me the author of the book: ")
print(title, "was write for ", author)
print(f"{title} was write for {author}") # --> idem que ${} en JS
alto=int(input("Dime el alto del rectángulo...:"))
ancho=int(input("Dime el ancho del rectángulo...:"))
area=alto*ancho
perimetro=(alto+ancho)*2
print(f"el area del rectángulo es de {area} y su perimetro es de {perimetro}")
# -- operador ternario (NO ES RECOMENDABLE)
numero=int(input("Dime un número: "))
print("Mayor a 5") if numero>5 else print("Menor o igual a 5")
| null | null |
f41baf09646cb49661b3f54acaf289e49426b9bc | PriyanshiPanchal/python | /Matplotlib/Cinema Entertainment/Cinema_Interface.py | 1,849 | 3.8125 | 4 | import Cinema_Functions
restart = ['Yes', 'YES', 'Y', 'yes']
while restart not in ['NO', 'No', 'no', 'N', 'nO', 'n']:
choice1 = int(input('1.Yearly Collection Of All Branchesn\n2.Quaterly Collection(Gross)\n'
'3.Quaterly Collection(Branch Wise)\n4.Performance of a Branch on given Date Range\n'
'5.Collection of Whole Year For Selective Branch\n'
'6.Find Total shares of all branches with reeespect to Revenue Type(MonthWise)'))
if choice1 == 1:
Cinema_Functions.yearly_Colection()
elif choice1 == 2:
Cinema_Functions.quaterly_Collection()
elif choice1 == 3:
b_name =input("Enter Branch Name")
Cinema_Functions.quaterly_Collectio(b_name)
elif choice1 == 4:
d_from=input('From:')
d_to=input('To')
Cinema_Functions.perfomance(d_from, d_to)
elif choice1 == 5:
b_name= input("Enter Branch Name")
Cinema_Functions.collection_Whole_Year(b_name)
elif choice1 == 6:
choice2 = int(input('1.Screen-1\n2.Screen-2\n3.Screen-3\n4.Food & Beverages\n5.Advertisment'))
if choice2==1:
r_name='Screen-1'
Cinema_Functions.revenue_Type(r_name)
elif choice2==2:
r_name='Screen-2'
Cinema_Functions.revenue_Type(r_name)
elif choice2==3:
r_name='Screen-3'
Cinema_Functions.revenue_Type(r_name)
elif choice2==4:
r_name='Food & Beverages'
Cinema_Functions.revenue_Type(r_name)
elif choice2==5:
r_name='Advertisment'
Cinema_Functions.revenue_Type(r_name)
else:
print("Invalid Choice")
else:
print('Invalid Choice')
restart=input("Do you want to continue?")
| null | null |
b43f3dc11cc4b367dc7148973fc7f5096d01704c | dlapochkin/project.6 | /main.py | 6,431 | 3.875 | 4 | from string import *
from random import *
def main():
"""
Main function
:return: None
"""
board, stats = cleaner(preparation())
table(board, stats)
turn(board, stats)
def preparation():
"""
Creates board pattern and dictionary, containing board values
:return: Shuffled board
"""
pattern = '123456789' \
'456789123' \
'789123456' \
'234567891' \
'567891234' \
'891234567' \
'345678912' \
'678912345' \
'912345678'
clear = dict(zip([(x, y) for x in 'abcdefghi' for y in range(1, 10)], [x for x in pattern]))
return shuffler(clear)
def shuffler(board):
"""
Shuffles board values using random rows and columns swaps and transposition of the board
:param board: dictionary, containing board values
:return: board with shuffled values
"""
shuffling = {0: rows_moving, 1: columns_moving, 2: transposition}
for shuff in range(256):
board = shuffling[randint(0, 2)](board)
return board
def transposition(board):
"""
Swaps rows and columns of the board
:param board: dictionary, containing board values
:return: transposed board
"""
transposed = {}
for (x, y) in board:
transposed[(x, y)] = board[(chr(y + 96), ord(x) - 96)]
return transposed
def rows_moving(board):
"""
Swaps two random rows in one sector
:param board: dictionary, containing board values
:return: board with moved rows
"""
sectors = {0: 'abc', 1: 'def', 2: 'ghi'}
rows = sectors[randint(0, 2)]
x = choice(rows)
rows = rows[:rows.find(x)] + rows[rows.find(x) + 1:]
y = choice(rows)
for z in '123456789':
temp = board[(x, int(z))]
board[(x, int(z))] = board[(y, int(z))]
board[(y, int(z))] = temp
return board
def columns_moving(board):
"""
Swaps two random columns in one sector
:param board: dictionary, containing board values
:return: board with moved columns
"""
sectors = {0: '123', 1: '456', 2: '789'}
columns = sectors[randint(0, 2)]
x = choice(columns)
columns = columns[:columns.find(x)] + columns[columns.find(x) + 1:]
y = choice(columns)
for z in 'abcdefghi':
temp = board[(z, int(x))]
board[(z, int(x))] = board[(z, int(y))]
board[(z, int(y))] = temp
return board
def cleaner(board):
"""
Hides random squares, leaves given amount of hints
:param board: dictionary, containing board values
:return: prepared board, start statistic
"""
stats = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0, 'turn': 0}
i = 81 - int(input('Введите число подсказок (рекомендуется использовать числа в диапазоне от 30 до 35): '))
while i > 0:
a, b = choice(list('abcdefghi')), randint(1, 9)
if board[(a, b)] == '0':
continue
stats[board[(a, b)]] += 1
board[(a, b)] = '0'
i -= 1
return board, stats
def table(board, stats):
"""
Prints game board, statistics
:param board: dictionary, containing board values
:param stats: dictionary, containing game statistics
:return: None
"""
tree = board.copy()
for key in tree:
if tree[key] == '0':
tree[key] = ' '
simple = list(tree.values())
print('+---' * 9 + '+', '{: ^9s}'.format(''), '+{:-^7s}+'.format('Числа'))
for x in range(9):
print('|{:^3s}:{:^3s}:{:^3s}|{:^3s}:{:^3s}:{:^3s}|{:^3s}:{:^3s}:{:^3s}|'.format(*simple[x * 9:x * 9 + 9]),
ascii_lowercase[x], '{:^7s}'.format(''), '|{:^7s}|'.format(str(x + 1) + ': ' + str(stats[str(x + 1)])))
if x in [2, 5, 8]:
print('+---' * 9 + '+', '{:^9s}'.format(''), '+{:-^7s}+'.format(''))
else:
print('+...' * 9 + '+', '{:^9s}'.format(''), '+{:-^7s}+'.format(''))
print(' {:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}{:^4d}'.format(*[x for x in range(1, 10)]),
'{:^9s}'.format(''), '{:^9s}'.format('Ход: ' + str(stats['turn'])), '\n')
def turn(board, stats):
"""
Recursive function representing a game move
:param board: dictionary, containing board values
:param stats: dictionary, containing game statistics
:return: None
"""
try:
move = input().split()
key = list(move[0])[0], int(list(move[0])[1])
if len(move) == 1:
if board[key] != '0':
stats[board[key]] += 1
board[key] = '0'
else:
print('Клетка уже пуста. Попробуйте еще раз.')
return turn(board, stats)
else:
value = move[1]
if value not in '123456789':
print('Ошибка ввода. Попробуйте еще раз.')
return turn(board, stats)
if stats[value] == 0 and board[key] != value:
print('Ошибка. Данное число уже использовано 9 раз.')
return turn(board, stats)
if board[key] != '0':
stats[board[key]] += 1
board[key] = value
stats[value] -= 1
stats['turn'] += 1
table(board, stats)
if sum(stats.values()) - stats['turn'] == 0 and checker(board):
print('Поздравляем. Судоку решено за', stats['turn'], 'ходов.')
exit()
except KeyError:
print('Ошибка ввода. Попробуйте еще раз.')
return turn(board, stats)
return turn(board, stats)
def checker(board):
"""
Checks if board filled in correctly (with no repetitions)
:param board: dictionary, containing board values
:return: True or False
"""
lines = {}
for x in 'abcdefghi':
lines[x] = [board[(x, 1)]]
for y in range(2, 10):
lines[x].append(board[(x, y)])
for x in range(1, 10):
lines[x] = [board[('a', x)]]
for y in 'bcdefghi':
lines[x].append(board[(y, x)])
for line in list(lines.values()):
for z in range(1, 10):
if line.count(str(z)) > 1:
return False
return True
if __name__ == '__main__':
main()
| null | null |
5140383e35da66e6580510032738e21154d63cd2 | minhminh12/Python-Basic-ACT | /minhduc_day03.py | 3,166 | 3.75 | 4 | print("+--------------MENU-----------------+")
print("|Chon C de tao hoa don |")
print("|Chon R de xem thong tin hoa don |")
print("|Chon T de tinh tong doanh thu |")
print("|Chon A de tinh tong hang hoa ban ra|")
print("|Chon E de thoat |")
print("+-----------------------------------+")
while True:
danhsachhoahon=[]
x=input("=> chon chuc nang:")
print("=> ban da chon chuc nang:",x)
if x == 'C':
tiep=input("tiep tuc?y/n?")
while tiep == 'y':
print("moi ban tao hoa don")
hoadon={}
banghoadon={}
stt = input("nhap so thu tu:")
stt_x=str(stt)
for i in range(len(stt_x),7):
stt_x= ' '+stt_x
tenhanghoa= input("nhap ten hang hoa muon mua :")
for i in range(len(tenhanghoa),16):
tenhanghoa = tenhanghoa + ' '
so=[]
soluong=input("nhap so luong:")
soluong_x=str(soluong)
for i in range(len(soluong_x),8):
soluong_x = ' '+soluong_x
so.append(soluong)
dongia= input("nhap gia cua san pham:")
dongia_x=str(dongia)
for i in range(len(dongia_x),13):
dongia_x=' '+dongia_x
tien=[]
thanhtien=int(dongia)*int(soluong)
thanhtien_x=str(thanhtien)
for i in range(len(thanhtien_x),16):
thanhtien_x=' '+thanhtien_x
tien.append(thanhtien)
hoadon["sohoadon"]=input("nhap so hoa don :")
hoadon["ngaysuat"]=input("nhap ngay tao hoa don:")
hoadon["tenkhachhang"]=input("nhap ten khach hang:")
tiep=input("ban muon tiep tuc ko?y/n?")
if x== 'R':
print(" HOA DON MUA HANG ")
print("so hoa don:",hoadon["sohoadon"])
print("ngay xuat:",hoadon["ngaysuat"])
print("ten khach hang:",hoadon["tenkhachhang"])
print("_____________________________thong tin hoa don_______________________________")
print("+----------+------------------+----------+---------------+------------------+")
print("| STT | hang hoa | so luong | don gia | thanh tien |")
print("+----------+------------------+----------+---------------+------------------+")
print("| "+stt_x+" | " +tenhanghoa+ " | "+soluong_x+" | "+dongia_x+" | "+thanhtien_x+" |")
print("+----------+------------------+----------+---------------+------------------+")
print("| "+stt_x+" | " +tenhanghoa+ " | "+soluong_x+" | "+dongia_x+" | "+thanhtien_x+" |")
print("+----------+------------------+----------+---------------+------------------+")
if x== 'T':
print("tong doanh thu bang")
t_sum = 0
tien=[]
for num in tien:
t_sum = t_sum + num
print(t_sum)
if x== 'A':
print("so hang hoa ban ra")
a_sum = 0
so=[]
for j in so:
a_sum = a_sum + j
print(a_sum)
if x== 'E':
print("^_^ bye ^_^")
break
| null | null |
407d7edba48b4a97c133ac7741ba6f1262cf3448 | Sergey-Laznenko/Coursera | /Fundamentals of Python Programming/2 week(loops-if-else)/sum_follow.py | 90 | 3.765625 | 4 | n = int(input())
total = 0
while n != 0:
total += n
n = int(input())
print(total)
| null | null |
509e1fd051492bccb5ff9a2b9c92cbf39dc9e165 | rustamovilyos/python_lessons | /py_lessons_for_github/dars_3/Vazifa-6.py | 655 | 3.8125 | 4 | а = int(input('введите число для а: '))
б = int(input('введите число для б: '))
с = int(input('введите число для с: '))
д = int(input('введите число для д: '))
if (а+б)%4 == 0:
print("а + б")
else:
print("а + б:", False)
if (б+с)%4 == 0:
print("с + б")
else:
print("а + б:", False)
if (с+б+а)%4 == 0:
print("а + б + с")
else:
print("а + б + с:", False)
if (д+б+с)%4 == 0:
print("б + с + д")
else:
print("б + с + д:", False)
if (а+с+б+д)%4 == 0:
print("а + б + с + д")
else:
print("а + б + с + д:", False) | null | null |
dbd0ed785c9af1889311a980ad5911e9d0ae6c88 | BrandonMayU/Think-Like-A-Computer-Scientist-Homework | /6.13 Problems/6.13-14.py | 499 | 3.6875 | 4 | import math
def mySqrt(n):
initialGuess = n/2
for i in range(10):
newGuess = (1/2)*(initialGuess + (n/initialGuess))
initialGuess = newGuess
count = i + 1
print("Guess #", count,": ", newGuess)
trueSQRT = math.sqrt(n)
print("True Square root value = ", trueSQRT)
print("Intilizing the function")
value = int(input("Please enter value you want to find the square root of: "))
mySqrt(value) #Execute the function
print()
print("End of Program!") | null | null |
1b00aac23ad6f8c35ac1e5dd520630abc28ababb | shirdha/ss | /factplay.py | 150 | 3.859375 | 4 | n=int(input(""))
fact=1
if(n<=0):
print(fact)
elif(n==1):
print(fact)
if(n>1):
for i in range(1,n+1):
fact=fact*i
print(fact)
| null | null |
ddc4112ca99f04ff02838546bd3543b03e0cf3a1 | shade9795/Cursos | /python/problemas/Estructura de programación secuencial/problema2.py | 245 | 3.984375 | 4 | num1=int(input("num 1: "))
num2=int(input("num 2: "))
num3=int(input("num 3: "))
num4=int(input("num 4: "))
suma=num1+num2
producto=num3*num4
print("el resultado de la suma es:")
print(suma)
print("el resultado del producto es")
print(producto)
| null | null |
69b77563ddc8412aae3112b23ad7acba907e1c36 | marvjaramillo/ulima-intro210-clases | /s022-guia02/p10.py | 530 | 3.890625 | 4 | tiempo_h = int(input("Ingrese cantidad de horas de estacionamiento: "))
tiempo_min = int(input("Ingrese cantidad de minutos de estacionamiento: "))
#Si se estaciono menos de una hora >> no se paga estacionamiento
if(tiempo_h == 0):
print("No tiene que pagar estacionamiento")
else:
#Si hay minutos (fraccion de hora) >> paga la hora completa
if(tiempo_min > 0):
tiempo_h = tiempo_h + 1
#Pagar por las horas de estacionamiento
monto = 2.5 * tiempo_h
print("El monto por estacionamiento es:", monto) | null | null |
af6678ae4824f149d21d7f3aa3e2ff2abc581102 | jimmahoney/umber | /src/model.py | 72,913 | 3.578125 | 4 | """
model.py
The data class definitons and methods,
built on the pewee ORM with a sqlite3 database.
The following tests assumes that the database has been created
and that populate_database() has been run; see ../database/init_db.
The script ../bin/umber_test runs these and other tests.
# Find the people and their role in a course given its name.
>>> democourse = Course.get(Course.name == 'Demo Course')
>>> for (uname, rname) in sorted(democourse.username_to_rolename.items()):
... user = Person.by_username(uname)
... print("{} is {} in {}.".format(user.name, rname, democourse.name))
...
Jane Q. Doe is student in Demo Course.
Johnny Smith is student in Demo Course.
Tammy Tutor is tutor in Demo Course.
Ted Teacher is faculty in Demo Course.
# Find a person from their username.
>>> john = Person.get(username='johnsmith')
>>> print(john.name)
Johnny Smith
# test last, first
>>> john.get_last_first()
'Smith, Johnny'
# Change their name.
>>> john.name = 'John Z. Smith'
>>> rows_changed = john.save()
# See the change.
>>> newjohn = Person.get(username='johnsmith')
>>> print(newjohn.name)
John Z. Smith
# Change it back.
>>> john.name = 'Johnny Smith'
>>> rows_changed = john.save()
Another example: all registrations for democourse :
>>> rs = list(Registration.select().where(Registration.course==democourse))
>>> len(rs) # (jane, john, ted, tammy) in demo course
4
See docs/model_notes.txt for more about the database model.
Jim Mahoney | mahoney@marlboro.edu | MIT License
"""
import os, yaml, re, mimetypes, shutil, random
from functools import reduce
from flask import url_for
from werkzeug.security import generate_password_hash, check_password_hash
from peewee import ( SqliteDatabase, Model, TextField, IntegerField,
PrimaryKeyField, ForeignKeyField )
from bs4 import BeautifulSoup
from utilities import ( markdown2html, link_translate, static_url, md5, Time,
ext_to_filetype, filetype_to_icon, size_in_bytes,
stringify_access, print_debug, clean_access_dict )
from settings import ( os_db, umber_url, protocol, hostname, umber_mime_types,
os_root, os_courses, photos_url, url_base,
os_default_course, site_course_path, site_home,
due_grace_hours )
import gitlocal
db = SqliteDatabase(os_db)
class BaseModel(Model):
class Meta:
database = db # (peewee requires this 'database' name)
def __repr__(self):
# e.g.
fields = ', '.join(["{}={}".format(x[0],repr(x[1]))
for x in list(self.__dict__['_data'].items())])
return '<{}({}) at 0x{:X}>'.format(self.__class__.__name__,
fields, id(self))
@classmethod
def first(cls):
return cls.select().first()
@classmethod
def all(cls):
return list(cls.select().execute())
class Person(BaseModel):
class Meta:
db_table = 'Person'
person_id = PrimaryKeyField(db_column='person_id')
username = TextField(unique=True)
password = TextField()
name = TextField()
email = TextField()
notes = TextField()
_by_username = {} # cache
_admins = None
@staticmethod
def from_comma_string(comma_string):
""" Return people list from a string of usernames e.g. "john,mary" """
return list(map(Person.by_username, comma_string.split(',')))
@staticmethod
def searchname(partialname, maxresults=32):
""" search for a name or username - returning up to a given number """
people = Person.select().where( \
Person.name.contains(partialname) | \
Person.username.contains(partialname)) \
.order_by(Person.username).limit(maxresults)
return [p.username for p in people]
@staticmethod
def create_person(username, name, email, password='', is_admin=False):
# TODO : restrict legal usernames ...
# * prohibit leading '_' (reserved for system)
# * lowercase_only? underbar? numbers?
# * enforce uniqueness
with db.atomic():
(user, created) = Person.get_or_create(username=username)
if created:
user.name = name
user.email = email
if not password:
password = str(random.getrandbits(32))
user.set_password(password)
user.save()
# enroll_site has in it db.atomic() too ...
# the docs say its OK to nest them.
Course.enroll_site(user, is_admin=is_admin)
return user
@staticmethod
def edit_person(username, name, email, password):
try:
with db.atomic():
user = Person.by_username(username)
user.name = name
user.email = email
if password != '':
user.set_password(password)
user.save()
except:
print_debug('OOPS : Person.edit_user(username="{}") failed' \
.format(username))
def course_data(self):
""" return courses that this person is registered in
as a dict with keys role,course,url,semester """
registrations = list(Registration.select()
.where(Registration.person == self))
registrations.sort(key=lambda r: r.course.name)
registrations.sort(key=lambda r: r.course.start_date, reverse=True)
return [{'role':r.role.name,
'course':r.course.name,
'url':r.course.url,
'semester':Time(r.course.start_date).semester()}
for r in registrations if not r.course.name == 'Umber']
def get_username(self, username):
return Person.by_username(username)
def make_admin(self):
""" Turn this person into a site admin """
with db.atomic():
umber = Course.get_site()
site_registration = Registration.get(course=umber, person=self)
site_registration.role = Role.by_name('admin')
site_registration.save()
def works(self, course):
query = (Work.select()
.where( Work.person == self,
Work.course == course ))
return list(query.execute())
def _save(self):
""" save to database and invalidate caches """
try:
del Person._by_username[self.username]
except KeyError:
pass
Person._admins = None
self.save()
def set_password(self, passwordtext):
with db.atomic():
self.password = generate_password_hash(passwordtext)
self._save()
def check_password(self, passwordtext):
return check_password_hash(self.password, passwordtext)
def get_role(self, course):
""" Return role of this person in that course """
if self.username in course.username_to_role:
return course.username_to_role[self]
else:
return Role.by_name('visitor')
def get_last_first(self):
names = self.name.split(' ')
return names[-1] + ', ' + names[0]
# -- Flask-Login methods & tools --
@staticmethod
def get_anonymous():
""" Create and return an anonymous Person """
# Not saved to database (i.e. save() not called).
# Not logged in.
anon = Person(name='anonymous', username='')
anon.anonymous = True
return anon
def is_authenticated(self):
return not self.is_anonymous()
def is_active(self):
return not self.is_anonymous()
def is_anonymous(self):
try:
return self.anonymous
except:
return False
def is_admin(self):
""" return True if this user is an admin, false otherwise """
return self.username in Person.admins()
def get_id(self):
if self.username == None:
return str('')
else:
return str(self.username)
def get_photo_url(self):
return photos_url + '/' + self.username + '.jpg'
@staticmethod
def generic_photo_url():
return photos_url + '/generic_student.png'
@staticmethod
def by_username(username):
""" Returns anonymous person if not found """
if username not in Person._by_username:
try:
person = Person.get(username = username)
#person = Person.select() \
# .where(Person.username==username).first()
except:
return Person.get_anonymous()
Person._by_username[username] = person
return Person._by_username[username]
@staticmethod
def by_rolename(rolename):
""" Return list of users who have a given type of registration """
# ... in any registration record i.e. any course
return list(Person.select()
.join(Registration)
.where(Registration.role == Role.by_name(rolename))
.execute())
@staticmethod
def admins():
""" Return list of administrators """
if not Person._admins:
Person._admins = {p.username : True
for p in Person.by_rolename('admin')}
return Person._admins
class Course(BaseModel):
class Meta:
db_table = 'Course'
course_id = PrimaryKeyField(db_column='course_id')
active = IntegerField()
assignments_md5 = TextField()
credits = IntegerField()
end_date = TextField()
name = TextField()
name_as_title = TextField()
notes = TextField()
path = TextField(unique=True)
start_date = TextField()
_site_course = None # course for site data
def prepared(self):
""" setup this instance after it's attributes are set """
# This method is essentially __init__ for these database objects.
self._set_users()
self.assignments = self._get_assignments()
if not self.start_date:
self.semester = ''
else:
self.semester = Time(self.start_date).semester()
# url without request though that info is also in request
self.url = umber_url + '/' + self.path
self.abspath = os.path.join(os_courses, self.path)
def __getattr__(self, key):
# Define some attributes (.url, .abspath, .students, ...)
# when they're needed.
#
# June 2019 : there is no "prepared" in python3's peewee;
# see https://github.com/coleifer/peewee/issues/1479
# So I need another way to call this after instantiating a Course.
# See docs.python.org/3/reference/expressions.html#attribute-references;
# ... I can override __getattr__ to fill 'em in when first accessed.
if not 'abspath' in self.__dir__():
self.prepared()
return self.__getattribute__(key)
def _set_users(self):
""" define self.students, .faculty, .guests, .username_to_role """
# .students includes tutors;
# username_to_rolename lists their role as 'tutor'
registrations = list(Registration.select()
.where((Registration.course == self)
& (Registration.status != 'drop')))
self.students = [reg.person for reg in registrations
if reg.role == Role.by_name('student')]
self.faculty = [reg.person for reg in registrations
if reg.role == Role.by_name('faculty')]
self.guests = [reg.person for reg in registrations
if reg.role == Role.by_name('guest')]
self.students.sort(key=lambda s: s.name)
self.faculty.sort(key=lambda s: s.name)
self.username_to_role = {reg.person.username : reg.role
for reg in registrations}
self.username_to_rolename = {reg.person.username : reg.rolename()
for reg in registrations}
@staticmethod
def get_all():
""" Return all but the 'Umber' course, sorted by semester & name """
result = [c for c in Course.all() if not c.name == 'Umber']
result.sort(key=lambda c: c.name)
result.sort(key=lambda c: c.start_date, reverse=True)
return result
@staticmethod
def create_course(name, path, start='', name_as_title='',
copyfrom=os_default_course, user=None):
if name_as_title == '':
name_as_title = name
if start == '':
now = str(Time())
now_year = now[:4]
now_month = now[5:7]
if now_month < '06':
start = now_year + '-' + '01-01' # spring
elif now_month < '09':
start = now_year + '-' + '06-01' # summer
else:
start = now_year + '-' + '09-01' # fall
with db.atomic():
(course, created) = Course.get_or_create(
name = name,
path = path,
start_date = start,
name_as_title = name_as_title
)
# Create a disk folder for a course by copying
# files from some other course.
# (If 'copyfrom' isn't defined, then those course files
# had better already exist ... which is the case
# for defaultcourse and democourse.)
if copyfrom:
abspath = os.path.join(os_courses, path)
abscopyfrom = os.path.join(os_courses, copyfrom)
shutil.copytree(abscopyfrom, abspath)
# remove the old copied .git folder
shutil.rmtree(os.path.join(abspath, '.git'), ignore_errors=True)
gitlocal.init_add_commit(course, user) # initalize its .git folder
return course
@staticmethod
def get_site():
""" return site admin course 'Umber' """
if not Course._site_course:
Course._site_course = Course.get(name='Umber')
return Course._site_course
@staticmethod
def create_site():
""" create site couse 'Umber' """
# for site resoruces i.e. help files, user id photos etc.
with db.atomic():
(sitecourse, created) = Course.get_or_create(
name = 'Umber',
name_as_title = 'Umber<div>a course<br>managment<br>system</div>',
path = site_course_path,
start_date = '2018-01-01')
return sitecourse
def get_shortname(self):
""" used in html title ; see Page.html_title """
# TODO : ... something shorter ?
return self.name
def is_site(self):
""" true if this is the site course """
return self.path == site_course_path
def person_to_role(self, person):
""" Return role of person in course, or visitor """
return self.username_to_role.get(person.username,
Role.by_name('visitor'))
def username_is_member(self, username):
return username in self.username_to_role
def _get_assignments(self):
return list(Assignment.select() \
.where(Assignment.course == self) \
.order_by(Assignment.nth))
def drop(self, user):
""" Drop user (Person or username) from this course """
# (Students who are registered may have submitted work.
# Rather than delete their files and database records,
# I'm just changing their status to 'drop', and ignoring
# those people in _set_users
try:
person = user
name = person.name # Is this a Person object?
except AttributeError:
person = Person.by_username(user) # No - treat it as a username.
name = person.name
if name == 'anonymous' or name == '':
return "error in drop with user '{}'".format(str(user))
with db.atomic():
registration = Registration.get(person=person, course=self)
registration.status = 'drop'
registration.date = str(Time())
registration.save()
# refresh course data
self._set_users()
return "OK, dropped {}.".format(name)
def get_profile_url(self):
# site course ends with / ; others don't ... slightly different behavior.
if self.url[-1] == '/':
return self.url + 'sys/user'
else:
return self.url + '/sys/user'
def get_home_url(self):
""" return url for course home page """
if self.is_site():
# special case : Umber course home is docs/home,
# so that all public stuff can be in docs/*
home_path = site_home
else:
home_path = 'home'
return os.path.join(self.url, home_path)
def get_registered(self, rolename=None):
registrations = list(Registration.select()
.where((Registration.course == self)
& (Registration.status != 'drop')))
if rolename == 'tutor':
people = [reg.person for reg in registrations if reg.grade == 'tutor']
elif not rolename:
people = [reg.person for reg in registrations]
elif rolename == 'student':
people = [reg.person for reg in registrations
if (reg.role.name == rolename and reg.grade != 'tutor')]
else:
people = [reg.person for reg in registrations
if reg.role.name==rolename]
people.sort(key=lambda p: p.get_last_first())
return people
def email_everyone_html(self):
return "mailto:" + ','.join([p.email for p in self.get_registered()])
def has_username(self, username):
return username in self.username_to_role
def get_faculty_data(self):
""" return {'email', 'name'} of faculty """
return [{'email':person.email, 'name':person.name}
for person in self.faculty]
def grade_data_list(self, student):
""" return student's view grade list for templates/grades.html """
# See the description below for the faculty grid.
result = list(self.get_assignments_with_extras())
for ass in result:
# Hmmm - not sure why this needs .person_id here, but errors without.
# Maybe something about how the jinja2 template treats variables?
# Or because the assignment has had its fields modified??
ass.work = ass.get_work(student.person_id)
(grade, css_grade) = ass.work.get_grade_css(faculty_view=True)
ass.work_grade = grade
ass.work_css_grade = "grade-{}".format(css_grade)
ass.duedate = Time(ass.due).assigndate()
return result
def grade_data_grid(self):
""" return faculty's grade grid for templates/grades.html """
# Returned data is list of dicts, one per student.
# Each student dict includes list of student works, one per assignment.
# The grade will be shown as
# '…' if not submitted and not yet due
# 'overdue' if not submitted and past due date
# 'ungraded' if submitted and not graded
# work.grade if submitted and graded
#
# The grade css class is "grade-*"
# where * is one of (green,darkgreen,darkred,red,black)
# for faculty viewing the color is :
# red overdue : due > today and not submitted
# brown faculty modified date > student seen date
# darkgreen student modified date > faculty seen date
# green ungraded : student has submitted; faculty hasn't graded
# black none of above
# for student viewing the color is :
# brown ungraded : student has submitted; faculty hasn't graded
# brown student modified; faculty hasn't seen
# dark green faculty modified; student hasn't seen
# green overdue : due > today and not submitted
# black none of above
#
# The basic idea of the colors is that
# green-ish means the viewer should respond (i.e. "go")
# red-ish means that the other person should do something
# (i.e. a problem)
#
result = []
for stud in self.students:
# skip grade line for student if they are a tutor
if self.username_to_rolename[stud.username] == 'tutor': continue
works = []
for ass in self.assignments:
work = ass.get_work(stud)
(grade, css_grade) = work.get_grade_css(faculty_view=True)
works.append({'url': work.get_url(),
'css_grade': 'grade-{}'.format(css_grade),
'grade': grade,
'id': work.work_id
})
result.append({'email': stud.email,
'name' : stud.name,
'works': works
})
return result
def get_assignment_by_nth(self, nth):
""" Return nth assignment in this course """
try:
return Assignment.select() \
.where(Assignment.course == self, \
Assignment.nth == nth) \
.first()
except:
return None
def update_assignments(self, assignments_data):
""" Update course assignments from
a dict of assignments_data[nth][name, due, blurb] """
# Note: passed argument is *not* made up of Assignment objects.
# Note: this is designed to update *all* assignments.
db_assignments = {a.nth : a for a in self._get_assignments()}
with db.atomic():
for nth in assignments_data:
if nth not in db_assignments:
(db_assignments[nth], status) = Assignment.get_or_create(
course=self, nth=nth)
db_assignments[nth].name = assignments_data[nth]['name']
duedate = assignments_data[nth]['due']
db_assignments[nth].due = str(Time.parse(duedate))
new_blurb = assignments_data[nth]['blurb']
old_blurb = db_assignments[nth].blurb
#print_debug(f" debug update_assignments : '{duedate}'")
#print_debug(f" md5(new_blurb) = '{md5(new_blurb)}'")
#print_debug(f" new_blurb = '{new_blurb}' ")
#print_debug(f" ass.blurb_hash = '{db_assignments[nth].blurb_hash}'")
#print_debug(f" ass.blurb = '{old_blurb}' ")
#print_debug(f" new == old ? {new_blurb == old_blurb}")
if md5(new_blurb) != db_assignments[nth].blurb_hash: # is this changed?
db_assignments[nth].blurb = new_blurb # yes: update it
db_assignments[nth].blurb_hash = md5(new_blurb)
db_assignments[nth].blurb_html = markdown2html(
link_translate(self, new_blurb))
#print_debug(" updating cache ")
#else:
#print_debug(" NOT updating cache ")
db_assignments[nth].save()
self.assignments = self._get_assignments()
def get_assignments_with_extras(self):
""" Return list of assignments in this course with extra info """
# ... i.e. prepare the data for html display
now = Time()
# print(" now = " + str(now))
if len(self.assignments) == 0:
self.assignment_nth_plus1 = 1
else:
self.assignment_nth_plus1 = self.assignments[-1].nth + 1
for ass in self.assignments:
duedate = Time(ass.due)
if duedate < now:
#print(" PAST : duedate = " + str(duedate))
ass.dateclass = 'assign-date-past'
else:
#print(" FUTURE : duedate = " + str(duedate))
ass.dateclass = 'assign-date'
ass.date = duedate.assigndate() # for assignment list display
ass.ISOdate = duedate.assignISOdate() # ditto
return self.assignments
def nav_page(self, user):
""" return course's navigation page """
# TODO: put this in a "try" and do something reasonable if it fails.
# (otherwise, pages in courses without sys/navigation.md will crash.)
# TODO: should this be cached to self._nav_page ?
# (Need it for both displaying and editing course's navigation page.)
return Page.get_from_path(os.path.join(self.path,
'sys', 'navigation.md'), user=user)
def nav_html(self, user, page):
""" Return html for course's navigation menu
for a given user & a given page """
return self.nav_page(user).nav_content_as_html(page)
@staticmethod
def enroll_site(person, datestring=None, is_admin=False):
""" enroll a person in the site course """
# All users should be in this course.
if not datestring:
datestring = str(Time())
site_course = Course.get_site()
if is_admin:
site_role = Role.by_name('admin')
else:
site_role = Role.by_name('member')
with db.atomic():
(reg, created) = Registration.get_or_create(
person = person,
course = site_course)
if created or is_admin: # update role & date
reg.role = site_role
reg.date = datestring
reg.status = ''
reg.save()
site_course._set_users()
def make_student_work_folders(self):
for person in self.students:
student_abspath = os.path.join(self.abspath,
'students', person.username)
if not os.path.exists(student_abspath):
Page.new_folder(student_abspath, user=person,
accessdict= {'read':person.username,
'write':person.username})
work_abspath = os.path.join(student_abspath, 'work')
if not os.path.exists(work_abspath):
Page.new_folder(work_abspath, user=person)
def enroll(self, person, rolename, datestring=None, create_work=False):
""" Enroll a person in this course with this role. """
# If there is an existing registration for the course&person, modify it.
# Also enroll this person in the site couse if they aren't already
# and if this isn't the site course itself.
# Optionally create their work folder (if it doesn't already exist)
#
# add tutors by using student role with registration.grade='tutor'
is_tutor = rolename=='tutor'
if rolename == 'tutor':
rolename = 'student'
if not datestring:
datestring = str(Time())
with db.atomic():
(reg, created) = Registration.get_or_create(
person = person,
course = self)
reg.role = Role.by_name(rolename)
reg.grade = 'tutor' if is_tutor else ''
reg.status = '' # if re-enrolling would have been 'drop'
reg.date = datestring
reg.save()
if not self.name == 'Umber':
Course.enroll_site(person, datestring=datestring)
if create_work:
# Create folder for student work within the course folder.
# The absolute path for their student work folder is
# e.g. course/students/johnsmith/ with its .access.yaml
# & course/students/johnsmith/work/
student_abspath = os.path.join(self.abspath,
'students', person.username)
Page.new_folder(student_abspath, user=person,
accessdict= {'read':person.username,
'write':person.username})
work_abspath = os.path.join(student_abspath, 'work')
Page.new_folder(work_abspath, user=person)
# refresh students
self._set_users()
class Page(BaseModel):
# --- path, filename, url definitions ---
# With settings on my laptop development machine as
# os_courses /Users/mahoney/academics/umber/courses
# then for the 'notes/week1' file within a course at 'fall/math' ,
# the parts are
# url: http://127.0.0.1:5000/ umber / fall/math / notes/week1
# protocol hostname url_base path...................
# file: /Users/mahoney/academics/umber/courses / fall/math / notes/week1
# os_courses path...................
# Following python's os.path phrasing, other terms used here are
# basename last word in address (same as os.path.basename)
# abspath e.g. /Users/mahoney/.../fall/math/notes/week1
# dirname e.g. /Users/mahoney/.../fall/math/notes
# This url would have in its flask request object the attributes
# request.url_root 'http://localhost:8090/'
# request.path '/umber/fall/math/notes/week1'
#
# Note that Page.path (e.g. fall/math/notes/week1)
# does not have a leading slash or contain the url_base,
# while request.path (e.g. /umber/fall/math/notes/week1) does.
#
# The Page object will also contain various extra data
# that isn't stored in the sql database but is instead
# pulled from the filesystem.
class Meta:
db_table = 'Page'
# Each course has some sys/* pages which get special treatment.
# Also here are site/sys/* pages for editing users and courses,
# which are only accessible within the 'site' course.
system_pages = ('assignments', 'navigation', 'error', 'folder',
'grades', 'roster', 'user', 'users', 'course',
'courses', 'registration', 'newuser', 'newcourse')
editable_system_pages = ('assignments', 'navigation',
'grades', 'user', 'course')
page_id = PrimaryKeyField(db_column='page_id')
html = TextField()
html_lastmodified = TextField()
notes = TextField()
path = TextField(unique=True)
course = ForeignKeyField(model=Course,
db_column='course_id',
to_field='course_id')
_mime_types = None
@staticmethod
def new_folder(abspath, accessdict=None, user=None):
""" Create a new folder with the given abspath.
Add it into the github repo.
Optionally create its .access.yaml file. """
if os.path.exists(abspath):
# bail without doing anything of this already exists
# print_debug(' new_folder {} already exists '.format(abspath))
return None
try:
os.makedirs(abspath) # makes intermediate folders if need be.
except:
# bail with error message if the OS system won't do it.
print_debug(' os.makdir("{}") failed '.format(abspath))
return None
# Add an empty .keep file in this new folder,
# as a workaround to force git to include this new folder.
# (Git pays attention to files, not folders.)
open(os.path.join(abspath, '.keep'), 'w').close() # unix 'touch'
# Create the new folder object.
path = os.path.relpath(abspath, os_courses)
folder = Page.get_from_path(path, user=user)
if accessdict:
# don't do a git commit here - wait to do whole folder
folder.write_access_file(accessdict, do_git=False)
gitlocal.add_commit(folder)
return folder
@classmethod
def get_from_path(cls, path, revision=None, action=None, user=None):
""" Get or create a Page and set up all its internal data
i.e. course, file info, user permissions, etc """
(page, iscreated) = Page.get_or_create(path=path)
if user == None:
user = Person.get_anonymous()
page.user = user
page.action = action
page.revision = revision
page._setup_file_properties() # sets page.is_file etc
page.gitpath = os.path.join(os_courses, page.path_with_ext)
page.login_google_url = url_for('login_google', pagepath=path)
page.course = page.get_course()
try:
if page.course.page_error:
### Unexpected (to me anyway) behavior here :
### page.course = None
### if page.course: # This throws an error!
### ...
### Apparently the peewee database code has put hooks into
### the Page object to do tricky stuff for "page.course",
### seems to drop into peewee and complain.
### I'm avoiding this by returning the Umber site course
### but with a .page_error attribute set.
### In umber.py this will turn the request into 404 not found.
return page
except AttributeError:
# .page_error field not set; keep going.
pass
page.relpath = page._get_relpath()
page._setup_sys() # do this before .get_access()
page.access = page.get_access() # gets .access.yaml property.
page._setup_user_permissions() # sets page.can['read'] etc
if revision or action=='history':
page._setup_revision_data() # sets page.history etc
page._setup_attachments() # sets .has_attachments
page._setup_work() #
page.html_title = page.get_html_title()
return page
def get_html_title(self):
""" Return string for the <title></title> html tag. """
try:
return self.course.get_shortname() + ' : ' + self.relpath
except:
return self.path
def get_gitpath(self, abspath=None):
""" Return file path of page (or abspath file) relative to course path,
including file extension if any """
# This abspath option is used in gitlocal.py and umber.py:ajax_upload ;
# for attachments the page is not the upload file.
_abspath = self.abspath if abspath==None else abspath
return os.path.relpath(_abspath, self.course.abspath)
def _get_relpath(self):
""" Return path of page relative to course path,
e.g. notes/home for path=demo/notes/home in course 'demo' """
# self.course must be already set.
return os.path.relpath(self.path, self.course.path)
def attachments_folder(self):
return self.abspath.replace(self.ext, '.attachments')
def _setup_attachments(self):
if self.is_file and self.ext == '.md':
attach_dir = self.attachments_folder()
if os.path.exists(attach_dir) and os.path.isdir(attach_dir):
self.attachments = self.children(abspath=attach_dir)
else:
self.attachments = []
self.has_attachments = len(self.attachments) > 0
else:
self.attachments = []
self.has_attachments = False
def _setup_work(self):
""" see if this is a students/<name>/work/<number> student work page;
define .is_work and .work, set up .work for html display,
update
"""
# print(' _setup_work : relpath = {}'.format(self.relpath))
m = re.match(r'students/(\w+)/work/(\d+)(\?.*)?', self.relpath)
if m:
now = Time()
self.is_work = True
(work_username, work_nth, ignore) = m.groups()
work_nth = int(work_nth)
self.work_person = Person.by_username(work_username)
self.work_assignment = self.course.get_assignment_by_nth(work_nth)
self.work = self.work_assignment.get_work(self.work_person)
duedate = Time(self.work_assignment.due)
self.work_due = duedate.assigndatedetail()
# ... but give students a extra grace period of a few hours
# before marking things as "late";
# this let's me get "end of day" to something reasonable,
# without changing server timezone
duedate.arrow = duedate.arrow.shift(hours=due_grace_hours)
if self.work.submitted:
submitdate = Time(self.work.submitted)
self.work_submitted = submitdate.assigndate()
self.work_is_late = submitdate > duedate
else:
self.work_submitted = ''
self.work_is_late = now > duedate
self.work_grade = self.work.grade
# update *_seen fields in the database
# TODO : think about whether there's a better
# transactional way to update the database here.
if self.user_role.name == 'faculty':
self.work.faculty_seen = str(now)
self.work.save()
if self.user.username == work_username:
self.work.student_seen = str(now)
self.work.save()
else:
self.is_work = False
#self.work = None
#self.work_assignment = None
#self.work_person = None
#self.work_due = ''
#self.work_submitted = ''
#self.work_is_late = False
#self.work_grade = ''
def _setup_sys(self):
""" define .is_sys.
if it is, also define .sys_template, ./sys_edit_template """
# If relpath is 'sys/assignments', then is_sys will be true,
# the template will be 'umber/sys/assignments.html'
# and the edit template will be 'umber/sys/edit_assignments.html',
# (and the access permissions will be in the first line of the template.)
self.is_sys = self.relpath[:4] == 'sys/'
# -- default values for sys templates for all pages --
if self.is_sys:
which = self.relpath[4:]
if which == '':
which = 'folder'
if which not in Page.system_pages:
which = 'error'
self.sys_template = 'sys/' + which + '.html'
if which in Page.editable_system_pages:
self.sys_edit_template = 'sys/edit_' + which + '.html'
else:
self.sys_edit_template = 'sys/editerror.html'
def get_course(self):
""" return this page's course """
# And if there is no course for this page,
# return the site course but also set an error within it.
#
# extract path pieces e.g. ['demo', 'home']
path_parts = self.path.split('/')
# build partial paths e.g. ['demo', 'demo/home']
# (stackoverflow.com/questions/13221896/python-partial-sum-of-numbers)
paths = reduce(lambda x,y: x + [x[-1]+'/'+y],
path_parts[1:], path_parts[0:1])
# build peewee's "where condition" to find matching courses.
condition = Course.path
for c in paths:
condition = condition | Course.path % c
# Get list of matching courses from database.
# Choose the one with the longest path,
# if more than on was found ...
# which would only happen for courses directories
# embedded within another course, which shouldn't happen.
# TODO: make sure to test for that issue during new course creation
query = Course.select().where(condition)
courses = list(query.execute())
#
if courses:
return max(courses, key=lambda c: len(c.path))
else:
# Couldn't find a course for that page, so return
# the default course with a flag indicating the error.
umber = Course.get_site()
umber.page_error = True
return umber
def write_access_file(self, accessdict, do_git=True):
""" Given an access dict from user input e.g.
{'read':'students', 'write':['faculty','bob']} ,
write it to a .access.yaml file, and return its abspath. """
assert self.is_dir # this page should be a folder
accesspath = os.path.join(self.abspath, '.access.yaml')
accessfile = open(accesspath, 'w') # open or create
# replace yaml permissions
# (yaml.dump turns u'string' into ugly stuff so I convert to str().
accessfile.write(yaml.dump(clean_access_dict(accessdict)))
accessfile.close()
if do_git:
# I've left an option to avoid this to handle
# the case of a new folder efficiently, since
# we can in that case commit the whole folder in one go
# after this .access.yaml is created.
gitlocal.add_commit(self)
return accesspath
def get_access(self):
""" Return .access dict from .access.yaml in an enclosing folder
or from the first line of a sys_template
"""
# e.g. {'read': ['janedoe', 'johnsmith'], 'write': 'faculty'}
# default if we don't find it.
#access_dict = {'read':'all', 'write':'faculty'}
if self.is_sys:
## navigation is a special case : since it's a faculty editable file,
## I'll fill it it manually and not require that it have
## the {# #} first line.
if self.relpath == 'sys/navigation' or \
self.relpath == 'sys/navigation.md':
access_dict = {'read':'member', 'write':'faculty'}
else:
## all other system files have an access spec as their first line
## e.g. {# {'read':'all', 'write':'faculty' #}
template = os.path.join(os_root, 'templates', self.sys_template)
firstline = open(template).readline()
try:
access_dict = eval(firstline.replace('{#','').replace('#}',''))
except:
# something fairly safe as a fall-back
access_dict = {'read':'faculty', 'write':'faculty'}
else:
if self.is_dir:
abspath = self.abspath
else:
abspath = os.path.dirname(self.abspath)
while len(abspath) >= len(os_courses):
accesspath = os.path.join(abspath, '.access.yaml')
if os.path.exists(accesspath):
accessfile = open(accesspath)
# see https://msg.pyyaml.org/load
access_dict = yaml.full_load(accessfile)
accessfile.close()
if type(access_dict) == type({}):
# OK, we found an access dict, so stop here.
break
abspath = os.path.dirname(abspath) # i.e. "cd .."
if 'read' not in access_dict:
access_dict['read'] = ''
if 'write' not in access_dict:
access_dict['write'] = ''
# clean up for display :
self.read_access = stringify_access(access_dict['read'])
self.write_access = stringify_access(access_dict['write'])
return access_dict
def _setup_user_permissions(self):
""" Set page.can['read'], page.can['write'],
page.user_role, page.user_rank
from page.user, page.access, and page.course """
# Note that admins who are faculty in a given course
# will have a displayed role of 'faculty' in that course
# but will have admin access to nav menus etc.
assert self.course != None # call self.set_course() first.
assert self.access != None # call self.set_access() first.
assert self.user != None
self.user_role = self.course.person_to_role(self.user)
# this includes 'tutor' even though there is no 'tutor' role;
# and so I'm using this one in the displayed login role
try:
self.user_rolename = self.course.username_to_rolename[
self.user.username]
except:
self.user_rolename = 'visitor'
self.user_rank = self.user_role.rank
if self.user_role.name in ('faculty', 'admin') and not self.is_sys:
# faculty & admin can read or write anything
# ... but not system pages - I don't want 'edit' tab on all pages.
self.can = {'read': True, 'write': True}
return
if self.user.is_admin():
# Let site admins do what they want in any course.
# Change their display name to 'admin' if it isn't 'faculty'.
# i.e. leave 'faculty' or 'student' display names as is.
self.user_rank = Role.by_name('admin').rank
if self.user_role.name != 'faculty':
self.user_role = Role.by_name('admin')
self.can = {'read':False, 'write':False} # default is deny access
for permission in ('read', 'write'):
yaml_rights = self.access[permission]
access_needed = 10 # i.e. more than anyone has by default
# can be list e.g. ['faculty', 'bob'] or string 'students'
if type(yaml_rights) == type(''):
yaml_rights = [ yaml_rights ]
for name_or_role in yaml_rights:
if name_or_role == self.user.username:
self.can[permission] = True
break
elif name_or_role in Role.name_alias:
access_needed = min(access_needed, \
Role.by_name(name_or_role).rank)
if self.user_rank >= access_needed:
self.can[permission] = True
def get_mimetype(self):
""" Return e.g. 'image/jpeg' for '.jpg' file """
if not Page._mime_types:
mimetypes.init()
Page._mime_types = mimetypes.types_map.copy()
for key in umber_mime_types:
Page._mime_types[key] = umber_mime_types[key]
if self.ext == '':
return 'text/plain'
return Page._mime_types.get(self.ext, 'application/octet-stream')
def children(self, abspath=''):
""" return page for each file or folder below this folder """
result = []
if abspath == '':
abspath = self.abspath
try:
path = os.path.relpath(abspath, os_courses)
for name in sorted(os.listdir(abspath)):
if name[0] == '.': # skip invisible files e.g. .access.yaml
continue
result.append(Page.get_from_path(os.path.join(path, name), user=self.user))
except OSError: # i.e. if abspath isn't a directory.
pass
return result
def icon_url(self):
""" return url for icon for this file type """
return static_url(filetype_to_icon[self.filetype])
def _setup_revision_data(self):
""" read and store within page the git file revision data """
# The log is a list of tuples [(revision, date, author), ...]
log = gitlocal.get_history(self)
if len(log) == 0:
link = self.url
date = self.lastmodified.daydatetimesec()
author = ''
self.githashes = tuple()
self.history = ([link, 'current', date, author], )
self.revision_date = date
self.revision_commit = ''
self.revision_prev_url = ''
self.revision_next_url = ''
self.revision_count = 1
self.revision = None # No git revision stored.
else:
self.githashes = tuple((githash for (githash, date, author) in log))
self.history = [None] * len(log)
for i in range(len(log)):
# say len(log) == 4
# nth => (new) current 3 2 1 (old)
# i => 0 1 2 3 (old)
if i == 0:
nth = 'current'
url = self.url
else:
nth = len(log) - i
url = self.url + '?revision={}'.format(nth)
# history => 0:url 1:nth 2:date 3:author
self.history[i] = tuple((url, nth, log[i][1], log[i][2]))
self.revision_count = len(log)
self.revision_date = self.history[0][2]
if self.revision:
self.revision = int(self.revision)
index = self.revision_count - self.revision
self.revision_date = self.history[index][2]
self.revision_commit = self.githashes[index]
self.revision_next_url = self.url + '?revision={}'.format(
min(self.revision + 1, len(log)))
self.revision_prev_url = self.url + '?revision={}'.format(
max(self.revision - 1, 1))
def _setup_file_properties(self):
""" given self.path, set a bunch of information about the file
including self.absfilename, self.exists, self.is_file, self.is_dir,
self.lastmodified, self.breadcrumbs
"""
self.abspath = os.path.join(os_courses, self.path)
self.path_with_ext = self.path # default, unless modified below
if not os.path.exists(self.abspath):
for ext in ['.md', '.html']:
if ext == '.md' and os.path.exists(self.abspath + ext):
self.abspath = self.abspath + ext
self.path_with_ext = self.path + ext
(ignore, self.ext) = os.path.splitext(self.abspath)
self.exists = os.path.exists(self.abspath)
#print_debug(f'debug _setup_file_properties : path={self.path} exists={self.exists} ')
if not self.exists and self.ext == '':
# creating a new file, so make it a .md markdown file
self.ext = '.md'
self.abspath += '.md'
self.name_with_ext = os.path.split(self.abspath)[-1]
if self.ext == '':
self.name = self.name_with_ext
else:
self.name = self.name_with_ext[: - len(self.ext) ]
# self.name_underlined = self.name + '\n' + '='*len(self.name)
self.path_no_name = self.path[: - len(self.name) ]
self.is_file = os.path.isfile(self.abspath)
self.is_dir = os.path.isdir(self.abspath)
if self.exists:
stat = os.stat(self.abspath)
#print_debug(f'debug _setup_file_properties : stat={str(stat)}')
self.lastmodified = Time(stat.st_mtime)
if self.is_dir:
self.size = None
self.filetype = 'directory'
self.name_with_ext += '/'
elif self.is_file:
self.size = stat.st_size
self.filetype = ext_to_filetype.get(self.ext, 'unknown')
else:
self.size = None
self.filetype = 'unknown'
else:
self.lastmodified = None
self.size = None
# -- build url links for page breadcrumbs --
url_list = [url_base] + self.path.split('/')
urlsofar = protocol + hostname
self.breadcrumbs = '<a href="{}">{}</a>'.format(urlsofar, urlsofar)
while url_list:
pathpart = '/' + url_list.pop(0)
urlsofar += pathpart
self.breadcrumbs += ' ' + '<a href="{}">{}</a>'.format(
urlsofar, pathpart)
self.url = umber_url + '/' + self.path
self.url_for_print_version = self.url + '?print=1'
self.bytesize = size_in_bytes(self.size)
def revision_content_as_html(self):
content = gitlocal.get_revision(self)
content_with_links = link_translate(self.course, content)
return markdown2html(content_with_links)
def content(self):
""" Return file or github (revision) data for a page """
# python3 gotchas:
# for text, I convert to a python3 string (utf8)
# but for other (i.e. binary) data, I leave as python3 bytes
if self.exists and self.is_file:
if self.revision:
text = gitlocal.get_revision(self)
else:
with open(self.abspath, 'rb') as _file:
text_bytes = _file.read()
try:
text = text_bytes.decode('utf8')
except:
text = text_bytes # e.g. *.png files
else:
text = ''
#print_debug(" page.content : page.action = '{}'".format(page.action))
return text
def write_content(self, new_content):
""" Write new data to page's file; return number of bytes written """
if self.can['write']: # shouldn't get here without this anyway
with open(self.abspath, 'wb') as _file:
# open as binary ... need to write bytes.
try:
new_bytes = new_content.encode('utf8')
except:
new_bytes = new_content
bytes_written = _file.write(new_bytes)
return bytes_written
def content_as_html(self):
""" Return file contents as html. """
# This also handles revisions since self.content() does.
if not self.exists:
return ''
elif self.ext == '.md':
# I'm caching the html version of .md pages in the sql database
# (for the current version)
# checking to see if the cache is stale with
# the file's lastmodified and a sql db html_lastmodified fields.
#print_debug(f" debug content_as_html cache")
#print_debug(f" lastmodified='{self.lastmodified}' ; " + \
# f"html_lastmodified='{self.html_lastmodified}'")
if self.revision:
content = self.content() # pull from git repo
content_with_links = link_translate(self.course, content)
self.html = markdown2html(content_with_links)
self.html_lastmodified = str(self.lastmodified)
elif str(self.lastmodified) != self.html_lastmodified:
#print_debug(f" updating {self.path}")
with db.atomic():
content = self.content() # pull from file
content_with_links = link_translate(self.course, content)
self.html = markdown2html(content_with_links)
self.html_lastmodified = str(self.lastmodified)
self.save()
#else:
#print_debug(f" using cache {self.path}")
# cache : just use .html already read from sql
html = self.html
else:
# Not markdown, so send the file (txt, html, ...) as is.
html = self.content() # from file or git repo
return html
def action_query(self):
""" Return empty string or '&action=edit' if editing """
if self.action == 'edit':
return '&action=edit'
else:
return ''
def nav_content_as_html(self, page):
""" Return authorized parts of html & markdown at html . """
# Here self is the navigation.md page.
# TODO: unlinkify current page
# TODO: This implementation is pretty ugly.
# Perhaps just do this explicitly without BeautifulSoup?
# And make some tests ...
# Each course has a menu navigation page which is a mixture of html
# and markdown, including access tags that look like this :
# <div access='student'>
# ...
# </div>
# This method converts the content of that file to html,
# keeping only the parts that this user is allowed to see.
#
# And do the link_translate first, before any markdown stuff,
# so that it can see the context.
content = self.content()
content = link_translate(self.course, content)
#
parser = BeautifulSoup(content, 'html.parser')
for role in list(Role.name_rank.keys()):
divs = parser.find_all('div', access=role)
if self.user_rank < Role.by_name(role).rank:
for div in divs:
div.extract() # remove this div from its parent parser
insides = []
marker = '.~*#!#*~.' # something that won't be in the html.
for divm in parser.find_all('div', markdown=1):
contents = ''.join(divm.stripped_strings)
mstring = markdown2html(contents)
insides.append(mstring)
divm.string = marker
html = str(parser) # convert beautiful soup object to formatted unicode
while insides:
inside = insides.pop(0)
html = html.replace(marker, inside, 1)
# If the current page is one of the links in the nav menu,
# that link should be unlinkified ... which I'm doing
# with another (ugh) pass through BeautifulSoup,
# now that markdown has run.
# -------------
# TODO do the right thing for file.md, file.html,
# and folder ; currently only "file" and "folder/" will work
# in the nav markdown; the other non-canonical with redirectrs won't.
# (So check other options in a loop, eh?)
parser = BeautifulSoup(html, 'html.parser')
anchor = parser.find('a', href=page.url)
if anchor:
span = parser.new_tag('span')
span['class'] = 'thispage'
span.string = anchor.string
parser.find('a', href=page.url).replace_with(span)
html = str(parser)
return html
class Assignment(BaseModel):
class Meta:
db_table = 'Assignment'
assignment_id = PrimaryKeyField(db_column='assignment_id')
nth = IntegerField(null=False, unique=True)
active = IntegerField()
blurb = TextField()
blurb_hash = TextField()
blurb_html = TextField()
due = TextField(null=True)
name = TextField()
notes = TextField()
course = ForeignKeyField(model=Course,
db_column='course_id',
to_field='course_id')
def get_url(self):
return '{}/sys/assignments#{}'.format(self.course.url, self.nth)
def name_smaller(self):
""" return html version of assignment name with <br> instead of spaces """
return self.name.replace(' ', '<br>')
def get_work(self, person):
""" Return Work for this assignment by given student """
# i.e. work = assignment.get_work(student)
with db.atomic():
(work, created) = Work.get_or_create(assignment = self,
person = person)
if created:
work.grade = '' # | I would have expected this to be
work.notes = '' # | created with the sql defaults ...
work.submitted = '' # | but apparently not.
work.student_modified = ''
work.faculty_modified = ''
work.student_seen = ''
work.faculty_seen = ''
work.page = 0
work.save()
return work
class Role(BaseModel):
class Meta:
db_table = 'Role'
role_id = PrimaryKeyField(db_column='role_id')
name = TextField()
rank = IntegerField()
name_rank = {'admin': 5,
'faculty': 4,
'student': 3,
'member': 2,
'visitor': 1
}
name_alias = {'admin': 'admin',
'administrator': 'admin',
'faculty': 'faculty',
'student': 'student',
'students': 'student',
'tutor': 'student',
'class': 'student',
'guests': 'member',
'guest': 'member',
'member': 'member',
'all': 'visitor',
'any': 'visitor',
'visitor': 'visitor'
}
_cache = {}
@staticmethod
def by_name(name):
if not name in Role.name_rank:
if name in Role.name_alias:
name = Role.name_alias[name]
else:
name = 'visitor'
if not name in Role._cache:
Role._cache[name] = Role.get(name=name)
return Role._cache[name]
@staticmethod
def unalias(alias):
""" Convert alias to its standard role name. """
return Role.name_alias[alias]
@staticmethod
def create_defaults():
with db.atomic():
for (name, rank) in list(Role.name_rank.items()):
Role.get_or_create(name=name, rank=rank)
class Registration(BaseModel):
class Meta:
db_table = 'Registration'
registration_id = PrimaryKeyField(db_column='registration_id')
credits = IntegerField()
date = TextField(null=True)
grade = TextField()
midterm = TextField()
status = TextField()
course = ForeignKeyField(model=Course,
db_column='course_id',
to_field='course_id')
person = ForeignKeyField(model=Person,
db_column='person_id',
to_field='person_id')
role = ForeignKeyField(model=Role,
db_column='role_id',
to_field='role_id')
def rolename(self):
""" return rolname for this registration, including 'tutor' """
return 'tutor' if self.grade=='tutor' else self.role.name
class Work(BaseModel):
class Meta:
db_table = 'Work'
work_id = PrimaryKeyField(db_column='work_id')
grade = TextField()
notes = TextField()
submitted = TextField()
student_modified = TextField(db_column='student_modified')
student_seen = TextField(db_column='student_seen')
faculty_modified = TextField(db_column='faculty_modified')
faculty_seen = TextField(db_column='faculty_seen')
assignment = ForeignKeyField(model=Assignment,
db_column='assignment_id',
to_field='assignment_id')
person = ForeignKeyField(model=Person,
db_column='person_id',
to_field='person_id')
page = ForeignKeyField(model=Page,
db_column='page_id',
to_field='page_id')
@staticmethod
def edit_grades(id_grade_dict):
""" id_grade_dict is web form with some {'work_<id>':new_grade}
extract id's & change grades """
# the dict also has other keys i.e. 'submit_work'; ignore them.
try:
with db.atomic():
for key in id_grade_dict:
if key[:5] == 'work_':
id = int(key[5:])
work = Work.get(work_id=id)
# See get_grade_css for special grades ...,
# The special grades "...", "overdue', 'ungraded'
# are created when the actual grade is not set yet.
grade = id_grade_dict[key]
if grade in ('…', '...', 'overdue', 'ungraded'):
grade = ''
work.grade = grade
work.save()
except:
print_debug('OOPS : Work.edit_grades(id_grade_dict="{}") failed' \
.format(id_grade_dict))
def get_url(self):
# Also see templates/assignments.html
return '{}/students/{}/work/{}.md'.format(self.assignment.course.url,
self.person.username,
self.assignment.nth)
def get_grade_css(self, faculty_view):
css_class = 'black' # the default
#
duedate = Time(self.assignment.due)
duedate.arrow = duedate.arrow.shift(hours=due_grace_hours)
now = Time()
before_due_date = now < duedate
#
# Set blank times to '1901' to avoid errors.
faculty_modified = self.faculty_modified or '1901'
faculty_seen = self.faculty_seen or '1901'
student_modified = self.student_modified or '1901'
student_seen = self.student_seen or '1901'
#print_debug(" faculty_modified = '{}'".format(faculty_modified))
#print_debug(" faculty_seen = '{}'".format(faculty_seen))
#print_debug(" student_modified = '{}'".format(student_modified))
#print_debug(" student_seen = '{}'".format(student_seen))
if faculty_view:
if Time(faculty_modified) > Time(student_seen):
css_class = 'brown'
if Time(student_modified) > Time(faculty_seen):
css_class = 'darkgreen'
if not self.submitted:
if before_due_date:
grade = '…'
else:
grade = 'overdue'
css_class = 'red'
else:
if not self.grade:
grade = 'ungraded'
css_class = 'green'
else:
grade = self.grade
else:
if Time(student_modified) > Time(faculty_seen):
css_class = 'brown'
if Time(faculty_modified) > Time(student_seen):
css_class = 'darkgreen'
if not self.submitted:
if before_due_date:
grade = '…'
else:
grade = 'l͟a͟t͟e͟' # l͟a͟t͟e͟
css_class = 'green'
else:
if not self.grade:
grade = 'ungraded'
css_class = 'brown'
else:
grade = self.grade
if self.grade: # If a grade has been assigned, show it. Period.
grade = self.grade
return (grade, css_class)
def init_db():
""" Create base database objects """
# i.e. roles & site course.
# The Roles data must be in place for the login system to work.
# And the Umber course must exist for user photos and site docs
# and admin user role.
# The sql database must already exist; see bin/init_db .
# All these are "get_or_create", so running 'em multiple times won't hurt.
Role.create_defaults()
Course.create_site()
def populate_production_db(interactive=False):
""" create initial objects for production database """
# see umber/bin/init_db
from utilities import toggle_debug
toggle_debug()
make_admin = False
if interactive:
make_admin = input(' Create admin? (y/n) ').lower()[0] == 'y'
if admin:
admin_username = input(' Admin username? ')
admin_name = input(' Admin full name? ')
admin_passwd = input(' Admin password? ')
admin_email = input(' Admin email? ')
with db.atomic():
defaultcourse = Course.create_course(
name = 'Default Course',
name_as_title = 'Default<br>Course',
path = 'default_course',
start = '2018-01-01',
copyfrom = False
)
if make_admin:
(admin, created) = Person.get_or_create(username = admin_username)
if created:
admin.name = admin_name
admin.email = admin_email
password = admin_passwd
else:
if interactive:
print(f' username "{admin_username}" already exists')
print(' ... setting their is_admin=True')
print(' ... leaving their name & email unchanged.')
admin.is_admin = True
admin.save()
toggle_debug()
def populate_db():
""" Create test & example development objects """
# i.e. democourse, jane, ted, john, adam; examples and tests.
#print("Populating development database.")
from utilities import toggle_debug
toggle_debug()
with db.atomic():
student = Role.by_name('student')
faculty = Role.by_name('faculty')
democourse = Course.create_course(
name = 'Demo Course',
name_as_title = 'Demo<br>Course',
path = 'demo',
start = '2018-01-01',
copyfrom = False
)
defaultcourse = Course.create_course(
name = 'Default Course',
name_as_title = 'Default<br>Course',
path = 'default_course',
start = '2018-01-01',
copyfrom = False
)
jane = Person.create_person(
username = 'janedoe',
name = 'Jane Q. Doe',
email = 'janedoe@fake.address',
password = 'test' )
john = Person.create_person(
username = 'johnsmith',
name = 'Johnny Smith',
email = 'johnsmith@fake.address',
password = 'test' )
ted = Person.create_person(
username = 'tedteacher',
name = 'Ted Teacher',
email = 'ted@fake.address',
password = 'test' )
tammy = Person.create_person(
username = 'tammytutor',
name = 'Tammy Tutor',
email = 'tammy@fake.address',
password = 'test' )
adam = Person.create_person(
username = 'adamadmin',
name = 'Adam Administrator',
email = 'adam@fake.address',
password = 'test',
is_admin = True )
default_date = '2018-01-02'
democourse.enroll(john, 'student', default_date, create_work=False)
democourse.enroll(jane, 'student', default_date, create_work=False)
democourse.enroll(tammy, 'tutor', default_date, create_work=False)
democourse.enroll(ted, 'faculty', default_date, create_work=False)
# Assignments are set with a dict {nth: {name, due, blurb}.
assignments_data = {
1: {'name': 'week 1',
'due': '2018-01-23',
'blurb': 'Do chap 1 exercises 1 to 10.'},
2: {'name': 'week 2',
'due': 'Jan 28 2018 5pm',
'blurb': 'Write a four part fugue.'}
}
democourse.update_assignments(assignments_data)
assign1 = democourse.get_assignment_by_nth(1)
johns_work = assign1.get_work(john)
johns_work.grade = 'B'
johns_work.submitted = '2018-01-22T18:20:23-05:00' # on time
johns_work.student_seen = johns_work.submitted
johns_work.student_modified = johns_work.submitted
johns_work.faculty_seen = '2018-01-28T16:00:00-05:00'
johns_work.faculty_modified = johns_work.faculty_seen
johns_work.save()
janes_work = assign1.get_work(jane)
janes_work.submitted = '2018-02-04T22:23:24-05:00', # past due
# janes_work.grade = '' # not graded yet
janes_work.student_seen = janes_work.submitted
janes_work.student_modified = janes_work.submitted
janes_work.save()
toggle_debug()
if __name__ == '__main__':
import doctest
doctest.testmod()
| null | null |
6f77c3a1e04eb47c490eb339cf39fc5c925e453c | rudiirawan26/Bank-Saya | /bank_saya.py | 1,114 | 4.15625 | 4 | while True:
if option == "x":
print("============================")
print("Selamat Datang di ATM saya")
print("============================")
print('')
option1 = print("1. Chek Uang saya")
option2 = print("2. Ambil Uang saya")
option3 = print("3. Tabung Uang saya")
print('')
total = 0
option = int(input("Silakan pilih Option: "))
if option == 1:
print("Uang kamu berjumlah: ",total)
elif option == 2:
ngambil_uang = eval(input("Masukan nominal uang yang akan di ambil: "))
rumus = total - ngambil_uang
if ngambil_uang <= total:
print("Selamat anda berhasil ngambil unang")
else:
print("Saldo anda tidak mencukupi")
elif option == 3:
menabung = eval(input("Masukan nominal uang yang kan di tabung: "))
rumus_menabung = menabung + total
print("Proses menabung SUKSES")
else:
print("Masukan tidak di kenali")
else:
print("Anda telah keluar dari program")
| null | null |
9ea0061578d975f5b3480ec73db416db19a5619f | mpernow/eratosthenes | /db_entry.py | 3,832 | 4 | 4 | # Implementation of class for database entry
# Author: Marcus Pernow
# Date: January 2020
import uuid # For random filenames
class DB_Entry():
"""
Definition of a database entry.
Contains the required fields and methods
"""
def set_id(self):
"""
Sets the unique id of the entry, with an increasing counter
"""
# Open file and extract last id
f = open('id_num', 'r')
nums = f.readlines()
num = int(nums[-1][:-1]) + 1
f.close()
# set the id
self.id_num = num
# Append to the fil
f = open('id_num', 'a')
f.write(str(num)+'\n')
f.close()
def set_id_manual(self, id_num):
"""
Manually sets the id
"""
self.id_num = id_num
def set_title(self, title):
"""
Set the title of the entry
"""
self.title = title
def set_authors(self, authors):
"""
Set the authors of the entry
TODO: Put into correct format: "surname, firstname(s)"
separated by semicolon
"""
self.authors = authors
def set_year(self, year):
"""
Set the publication year
"""
if not type(year) == int:
raise ValueError('Year must be an integer')
self.year = year
def set_keywords(self, kw_list):
"""
Sets keywords of entry
"""
# Check that it is a list of strings:
if not all([type(i) == str for i in kw_list]):
raise ValueError('Must be list of strings')
for i in range(len(kw_list)):
kw_list[i] = kw_list[i].lower()
self.kw_list = kw_list
def set_type(self, publication_type):
"""
Set the publication type to book/article/review/other
"""
publication_type = publication_type.lower()
if not (publication_type == 'book' or publication_type == 'article' or publication_type == 'review' or publication_type == 'other'):
raise ValueError('Type must be book/article/review/other')
else:
self.publication_type = publication_type
def set_new_path(self, path = '/mnt/mystorage/pdfs/'):
"""
Sets the path of the entry with random file name
'path' is the directory with default './pdfs/'
TODO: Allow for non-pdf files
"""
f_name = uuid.uuid1().hex
self.path = path + f_name + '.pdf'
def set_path_manual(self, path):
"""
Manually set the path
"""
self.path = path
def get_title(self):
"""
Return the title of self
"""
return self.title
def get_authors(self):
"""
Return the authors of self
"""
return self.authors
def get_year(self):
"""
Returns the year of self
"""
return self.year
def get_keywords(self):
"""
Returns keyowrds of self as list of strings
"""
return self.kw_list
def get_pub_type(self):
"""
Returns the publication type of self
"""
return self.publication_type
def get_path(self):
"""
Returns the path of self
"""
return self.path
def get_id(self):
"""
Return the id of the entry
"""
return self.id_num
def __str__(self):
"""
Prints the entry nicely
"""
return str(self.id_num) + '\t|\t' + self.title + '\t|\t' + self.authors + '\t|\t' + str(self.year)
def make_entry(row):
"""
Takes a row from querying database and creates an entry object
"""
entry = DB_Entry()
entry.set_id_manual(row[0])
entry.set_title(row[1])
entry.set_authors(row[2])
entry.set_year(row[3])
entry.set_type(row[4])
entry.set_keywords(row[5].split(';'))
entry.set_path_manual(row[6])
return entry
if __name__ == "__main__":
print("Testing the code:")
test_entry = DB_Entry()
title = 'Best article ever'
print('Setting title to '+title)
test_entry.set_title(title)
author = 'Marcus Pernow'
print('Setting author to '+author)
test_entry.set_authors('Marcus Pernow')
year = 2020
print('Setting year to '+str(year))
test_entry.set_year(year)
keywords = ['physics','mathematics','truth','philosophy']
print('Setting keywords list to \n\t'+',\n\t'.join(keywords))
pub_type = 'article'
print('Setting type to '+pub_type)
test_entry.set_type(pub_type)
| null | null |
cca327c9bb2b6f5bcaaeaf09b09c80b07fe15e32 | younes-m/Utilitary-Python-Scripts | /spaces_to_under.py | 993 | 3.671875 | 4 | import sys
import os
""" replaces the spaces in file names by underscores ('_')
works with any number of files/folders dragged and dropped on the script"""
def newname(path): #returns the path with spaces in the file name replaced with '_' if spaces in the file name, else false
output = path.split('\\')
output[-1] = output[-1].replace(' ', '_') if ' ' in output[-1] else False
return '\\'.join(output) if output[-1] else False
r = n = 0
i = 1
while True :
try :
if newname(sys.argv[i]) :
os.rename(sys.argv[i], newname(sys.argv[i]))
print ('{0} -> {1}'.format(sys.argv[i].split('\\')[-1], newname(sys.argv[i]).split('\\')[-1]))
r += 1
else :
print('{0} -> Not renamed'.format(sys.argv[i].split('\\')[-1]))
n += 1
i += 1
except IndexError :
break
input('\ndone, {0} file(s) renamed, {1} file(s) ignored, press enter to close program'.format(r,n))
| null | null |
8130b1edf4df29a9ab76784289a22d5fb90863e7 | ridhishguhan/faceattractivenesslearner | /Classify.py | 1,158 | 3.6875 | 4 | import numpy as np
import Utils
class Classifier:
training = None
train_arr = None
classes = None
def __init__(self, training, train_arr, CLASSES = 3):
self.training = training
self.train_arr = train_arr
self.classes = CLASSES
#KNN Classification method
def OneNNClassify(self, test_set, K):
# KNN Method
# for each test sample t
# for each training sample tr
# compute norm |t - tr|
# choose top norm
# class which it belongs to is classification
[tr,tc] = test_set.shape
[trr,trc] = self.train_arr.shape
result = np.array(np.zeros([tc]))
i = 0
#print "KNN : with K = ",K
while i < tc:
x = test_set[:,i]
xmat = np.tile(x,(1,trc))
xmat = xmat - self.train_arr
norms = Utils.ComputeNorm(xmat)
closest_train = np.argmin(norms)
which_train = self.training[closest_train]
attr = which_train.attractiveness
result[i] = attr
#print "Class : ",result[i]
i += 1
return result | null | null |
5d1269355b68717992f38971bedb74877ab668ee | scientific-coder/josephus | /element-recursion/josephus.py | 728 | 3.578125 | 4 | from collections import deque
def find(chainlength = 40, kill = 3):
return findlast(deque(range(1,chainlength+1)),3,1)
def findlast(chain,nth,counter) :
if len(chain) == 1 :
return chain[0]
elif counter == 1 :
#print chain.popleft(), " dies"
chain.popleft()
return findlast(chain,nth,counter+1)
else :
head = chain.popleft()
#print head, " survives"
chain.append(head)
return findlast(chain,nth,1 if counter == nth else counter + 1)
print find()
import time
ITER = 100000
start = time.time()
for i in range(ITER):
find()
end = time.time()
print 'Time per iteration = %s microseconds (element recursive)' % ((end - start) * 1000000 / ITER)
| null | null |
fa0a2e8e0ec8251c6d735b02dfa1d7a94e09c6b2 | paul0920/leetcode | /question_leetcode/1488_2.py | 1,538 | 3.984375 | 4 | import collections
import heapq
rains = [1, 2, 0, 0, 2, 1]
# 0 1 2 3 4 5
rains = [10, 20, 20, 0, 20, 10]
# min heap to track the days when flooding would happen (if lake not dried)
nearest = []
# dict to store all rainy days
# use case: to push the subsequent rainy days into the heap for wet lakes
locs = collections.defaultdict(collections.deque)
# result - assume all days are rainy
res = [-1] * len(rains)
# pre-processing - {K: lake, V: list of rainy days}
for i, lake in enumerate(rains):
locs[lake].append(i)
for i, lake in enumerate(rains):
print "nearest wet day:", nearest
# check whether the day, i, is a flooded day
# the nearest lake got flooded (termination case)
if nearest and nearest[0] == i:
print []
exit()
# lake got wet
if lake != 0:
# pop the wet day. time complexity: O(1)
locs[lake].popleft()
# prioritize the next rainy day of this lake
if locs[lake]:
nxt = locs[lake][0]
heapq.heappush(nearest, nxt)
print "nearest wet day:", nearest
# a dry day
else:
# no wet lake, append an arbitrary value
if not nearest:
res[i] = 1
else:
# dry the lake that has the highest priority
# since that lake will be flooded in nearest future otherwise (greedy property)
next_wet_day = heapq.heappop(nearest)
wet_lake = rains[next_wet_day]
res[i] = wet_lake
print ""
print res
| null | null |
35a0b2ff6bac17344addaf96bc1be0ca15a08161 | AK-1121/code_extraction | /python/python_9812.py | 134 | 3.6875 | 4 | # Find length of 2D array Python
numrows = len(input) # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example
| null | null |
4b873329812e2af982c4c137b52cd5da86dccdeb | update-ankur/Hackerrank_30daysOFcode | /30 days of code( python)/Day 24.py | 682 | 3.703125 | 4 | def removeDuplicates(self,head):
#Write your code here
if head is None:
return
current_node = head
counter = 0
list_data = {}
index = 0
while (current_node is not None):
if (list_data.get(current_node.data) is None):
list_data[current_node.data] = counter
counter += 1
current_node = current_node.next
new_list = Solution()
head = None
for key in sorted(list_data):
head = new_list.insert(head, key)
return head
| null | null |
08c0b696d0bc9a5a584881af22d71378dcc06515 | crazynoodle/Noodle-s-git | /python-code/fib.py | 226 | 3.96875 | 4 | def fib2(n): #return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a,b = 0,1
while a < n:
result.append(a) # see below
a,b = b,a+b
return result
| null | null |
fa9865e06131b5bde1ad368c6d480b4ee5395859 | Andrewlearning/Leetcoding | /leetcode/Array/169. 求超过一半的数字(无序,摩尔投票).py | 1,125 | 3.765625 | 4 | """
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于⌊ n/2 ⌋的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
"""
class Solution(object):
def majorityElement1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums is None and len(nums) == 0:
return 0
res = nums[0]
count = 1
for i in range(1, len(nums)):
if count == 0:
res = nums[i]
count = 1
elif res == nums[i]:
count += 1
else:
count -= 1
return res
"""
https://algocasts.io/episodes/VlWd8W06
摩尔投票法
时间 O(n),空间O(1)
我们用res 来记录当前数量最多的数字
我们用count 来记录当前res记录的数字出现的次数,
遇到相同的数字,count 就加一, 遇到不相同的数字,count就-1
nums[i] == res: count ++
nums[i] != res: count --
if count == 0:
res = nums[i]
count = 1
""" | null | null |
21943f3457560dccdecc3ccc2337176e0ea98173 | WangDongDong1234/python_code | /part2/21.py | 928 | 3.703125 | 4 | # l=["a","b","c"]
# #it=iter(l)
# it=l.__iter__()
# #next=next(it)
# next=it.__next__()
# print(next)
# class Mylist:
# def __init__(self):
# self.list=[1,2,3]
#
# def __len__(self):
# return len(self.list)
#
# l=Mylist()
# print(len(l))
# class Single:
# __ISINCTANCE=None
# def __new__(cls, *args, **kwargs):
# if not cls.__ISINCTANCE:
# cls.__ISINCTANCE=object.__new__(cls)
# print("在new方法里",cls.__ISINCTANCE)
# return cls.__ISINCTANCE
#
# def __init__(self):
# print("在initial方法里",self)
#
# s1=Single()
# print("创建第二个对象")
# s2=Single()
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
print("执行__str__方法")
return "学生的名字是%s,年龄是%s" %(self.name,self.age)
s1=Student("wdd",25)
print("学生:%s" %s1) | null | null |
44cc5b20276024979f97fb31cd221b90ba78e351 | Mahdee14/Python | /2.Kaggle-Functions and Help.py | 2,989 | 4.40625 | 4 | def maximum_difference(a, b, c) : #def stands for define
"""Returns the value with the maximum difference among diff1, diff2 and diff3"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
#If we don't include the 'return' keyword in a function that requires 'return', then we're going to get a special value
#called 'Null'
def least_dif(a ,b, c):
"""Docstring - Finds the minimum value with the least difference between numbers"""
diff1 = a - b
diff2 = b - c
diff3 = a - c
return min(diff1, diff2, diff3)
print(
least_dif(1, 10, 100),
least_dif(1, 2, 3),
least_dif(10, 20, 30)
)
#help(least_dif)
print(1, 2, 3, sep=" < ") #Seperate values in between printed arguments #By default sep is a single space ' '
#help(maximum_difference)^^^
#Adding optional arguments with default values to custom made functions >>>>>>
def greet(who="Mahdee"):
print("Hello ", who)
print(who)
greet()
greet(who="Mahdee")
greet("world")
#Functions applied on functions
def mult_by_five(x, y):
return 5 * x + y
def call(fn, *arg):
"""Call fn on arg"""
return fn(*arg)
print(call(mult_by_five, 1, 1) , "\n\n")
example = call(mult_by_five, 1, 3)
print(example)
def squared_call(fn, a, b, ans):
"""Call fn on the result of calling fn on arg"""
return fn(fn(a, b), ans)
print(
call(mult_by_five, 3, 6),
squared_call(mult_by_five, 1, 1, 1),
sep='\n', # '\n' is the newline character - it starts a new line
)
def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5
print(
'Which number is biggest?',
max(100, 51, 14),
'Which number is the biggest modulo 5?',
max(100, 51, 14, key=mod_5),
sep='\n',
)
def my_function():
print("Hello From My Function!")
my_function()
def function_with_args(name, greeting):
print("Hello, %s, this is an example for function with args, %s" % (name, greeting))
function_with_args("Mahdee", "Good Morning")
def additioner(x, y):
return x + y
print(additioner(1, 3))
def list_benefits():
return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to connect and share code together"
def build_sentence(info):
return "%s , is a benefit of functions" % info
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
name_the_benefits_of_functions()
#Exercise
def to_smash(total_candies, n_friends=3):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
return total_candies % n_friends
print(to_smash(91))
x = -10
y = 5
# # Which of the two variables above has the smallest absolute value?
smallest_abs = min(abs(x), abs(y))
def f(x):
y = abs(x)
return y
print(f(0.00234))
| null | null |
4ffe4db32ef0bfd215f89ae83c1c86a0d20773b7 | mishka245/intellectual-systems | /lib/board.py | 1,942 | 3.953125 | 4 | import random
class Board:
"""
Board class to represent nodes and work with them
"""
def __init__(self, param=None):
if param:
self.from_list(param)
else:
numbers_array = list(range(9))
random.shuffle(numbers_array)
self.from_list(numbers_array)
def __str__(self):
result = ""
for i in range(3):
result = result + str(self.board_array[i]) + '\n'
return result
def __eq__(self, other):
return self.board_array == other.get_board()
def __hash__(self):
result = ""
for i in range(3):
result += "".join(str(x) for x in self.board_array[i])
return int(result)
def get_coords(self):
for i in range(3):
for j in range(3):
if self.board_array[i][j] == 0:
return i, j
def swap(self, coord_first, coord_second):
"""
Swap two number
:param coord_first: first number coordinates
:param coord_second: second number coordinates
:return: returns None
"""
tmp = self.board_array[coord_first[0]][coord_first[1]]
self.board_array[coord_first[0]][coord_first[1]] = self.board_array[coord_second[0]][coord_second[1]]
self.board_array[coord_second[0]][coord_second[1]] = tmp
def get_board(self):
"""
:return: numbers matrix
"""
return self.board_array
def get_board_as_list(self):
"""
:return: board matrix as one dimensional list
"""
return self.board_array[0] + self.board_array[1] + self.board_array[2]
def from_list(self, array):
"""
Make board from array
:param array: array
:return: None
"""
self.board_array = list(range(3))
for i in range(3):
self.board_array[i] = array[i * 3:((i + 1) * 3)]
| null | null |
268040a0b85eb2039026a3bf495bc863fc745bab | dadnotorc/orgrammar | /src/python/_2312_Combine_keys_values_into_new_list/solution.py | 357 | 3.515625 | 4 | def composition(dict_1: dict) -> list:
'''
:param dict_1: Input dictionary
:return: A new list of keys and values in the dictionary
'''
result = []
for k, v in dict_1.items():
result.append(k)
result.append(v)
return result
# return [key if j ^ 1 else value for key, value in dict_1.items() for j in (0, 1)] | null | null |
a3337bde5cf7d0b0712a15f23d2ab63fed289c2f | nickdurbin/iterative-sorting | /src/searching/searching.py | 1,860 | 4.3125 | 4 | def linear_search(arr, target):
# Your code here
# We simply loop over an array
# from 0 to the end or len(arr)
for item in range(0, len(arr)):
# We simply check if the item is equal
# to our target value
# If so, then simply return the item
if arr[item] == target:
return item
# If the target does not exist in our array
# Return -1 which equates to not found
return -1 # not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
# Your code here
# We need the beginning of the array
# So we create a variable and start at zero
start = 0
# Next we need to find the end of the array
# Create a variable use the length - 1
end = len(arr) - 1
# Next we create a loop that runs as long as the start
# and the end are NOT the same and start is LESS THAN
# the value of end
while start <= end:
# Here we create the middle value
# We simply add the start + end and then divide
# By two to find the median value or middle
middle = (start + end) // 2
# If our middle value is the target we are searching for
# simply return the middle value
if arr[middle] == target:
return middle
# Else if the middle value is less than our target value
# We do not need any of the array values before our middle
# So we make the start our middle value + 1
elif arr[middle] < target:
start = middle + 1
# Else if the middle is greater than the target
# we work backwards and make our mid value
# equal to our end value and subtract one
else:
end = middle - 1
# If the target value is not in the array
# return -1, which is not found
return -1 # not found | null | null |
37bcf019ef4658abd5629a3d9cf8ad22cd70cf39 | ioef/PyLinuxTools | /wc.py | 632 | 3.921875 | 4 | #!/usr/bin/env python
'''
Creation of the word count Linux utility in python
'''
import sys
def printStats(filename):
#data = sys.stdin.read()
with open(filename,'r') as data:
data = data.read()
chars = len(data)
words = len(data.split())
lines = len(data.split('\n'))
print "\nThe file includes {0} characters, {1} words and {2} lines".format(chars,words,lines)
def main():
if len(sys.argv) !=2:
print "Wrong number of arguments. Exiting..."
print "usage: wc.py filename"
sys.exit(1)
printStats(sys.argv[1])
if __name__ =='__main__':
main()
| null | null |
0319816ef3a65374eaa7dd895288b6eff0f42f4a | Priyanshuparihar/make-pull-request | /Python/2021/2ndOct_RolloCasanova.py | 1,276 | 4.3125 | 4 | # Function to print given string in the zigzag form in `k` rows
def printZigZag(s, k):
# Creates an len(s) x k matrix
arrays = [[' ' for x in range (len(s))] for y in range (k)]
# Indicates if we are going downside the zigzag
down = True
# Initialize the row and column to zero
col, row = 0, 0
# Iterate over all word's letters
for l in s[:]:
arrays[row][col] = l
# col always increases
col = col + 1
# If going down, increase row
if down:
row = row + 1
# Already at the bottom? let's go up
if row == k:
row = k-2
down = False
# If going up, decrease row
else:
row = row - 1
# Already at top, let's go down
if row == -1:
row = 1
down = True
# Iterate over all k arrays in matrix
for arr in arrays[:]:
# Set str to empty string
str = ""
# Iterate over each letter in array
for l in arr[:]:
# Concatenate letters on array
str = str + l
# Print str
print(str)
# if __name__ == '__main__':
# s = 'THISZIGZAGPROBLEMISAWESOME'
# k = 3
# printZigZag(s, k)
| null | null |
c2f622f51bbddc54b0199c4e0e2982bc2ebfa030 | qdm12/courses | /Fundamental Algorithms/Lesson-03/algorithms.py | 2,479 | 3.875 | 4 | from operator import itemgetter
from math import floor
def radix_sort_alpha(words):
l = len(words[0])
for w in words:
if len(w) != l:
raise Exception("All words should be of same length")
for i in range(l, 0, -1):
words = sorted(words, key=itemgetter(i - 1))
words_str = str([''.join(w) for w in words])
print "PASS "+str(l - i + 1)+": "+words_str
return words_str
def bucket_sort(A):
print "Initial input array A: "+str(A)
n = len(A)
for i in range(n):
assert(A[i] >= 0 and A[i] < 1)
B = [[] for _ in range(n)]
print "Initial output buckets array B: "+str(B)
for i in range(n):
place = int(floor(A[i] * n))
B[place].append(A[i])
print "Output buckets array B with elements in buckets: "+str(B)
for j in range(n):
B[j].sort()
print "Output buckets array B with elements sorted in buckets: "+str(B)
B_final = []
for bucket in B:
B_final += bucket
print "Final output array B: "+str(B_final)
return B_final
class MergeSort(object):
def merge(self, A, l, q, r):
n1 = q - l + 1
n2 = r - q
L = [A[l + i] for i in range(n1)]
R = [A[q + 1 + i] for i in range(n2)]
i = j = 0 # Initial index of first and second subarrays
k = l # Initial index of merged subarray
while i < n1 and j < n2:
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
k += 1
# Copy the remaining elements of L[], if there are any
while i < n1:
A[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there are any
while j < n2:
A[k] = R[j]
j += 1
k += 1
def mergeSort(self, A, l, r):
if l < r:
q = int(floor((l+r)/2))
self.mergeSort(A, l, q)
self.mergeSort(A, q+1, r)
self.merge(A, l, q, r)
def run(self):
A = [54,26,93,17,77,31,44,55,20]
self.mergeSort(A, 0, len(A) - 1)
print A
if __name__ == "__main__":
radix_sort_alpha(["COW", "DOG", "SEA", "RUG", "ROW", "MOB", "BOX", "TAB", "BAR", "EAR", "TAR", "DIG", "BIG", "TEA", "NOW", "FOX"])
bucket_sort([.79,.13,.16,.64,.39,.20,.89,.53,.71,.43])
m = MergeSort()
m.run() | null | null |
c9cb82aef7589e657b85b556a3d33d1fa959b9d7 | ElenaCasado/Python | /18.sumador_digitos.py | 789 | 3.90625 | 4 | def sumador_digitos():
numero=input("Dime un numero de dos digitos:")
decenas=numero/10
unidades=numero - 10*decenas #n%10#
print "La suma de",numero,"vale",decenas+unidades
sumador_digitos()
def sumador_cifras():
suma=0
numero=input("Dime un numero: ")
while numero>10:
suma=suma+numero%10
numero=numero/10
print "La suma de los digitos es ",suma+numero
sumador_cifras()
#programa numero de x cifras, que cuente cuales de esas cifras son pares
def cuales_cifraspares():
suma=0
numero= input("Dime un numero: ")
while numero>1:
aux=numero%10
if aux%2==0:
suma=suma+1
numero=numero/10
print "Hay",suma,"numeros pares"
cuales_cifraspares()
| null | null |
c7b567bde9e143c404c3670793576644a26f6142 | AhmadQasim/Battleships-AI | /gym-battleship/gym_battleship/envs/battleship_env.py | 4,760 | 3.53125 | 4 | import gym
import numpy as np
from abc import ABC
from gym import spaces
from typing import Tuple
from copy import deepcopy
from collections import namedtuple
Ship = namedtuple('Ship', ['min_x', 'max_x', 'min_y', 'max_y'])
Action = namedtuple('Action', ['x', 'y'])
# Extension: Add info for when the ship is sunk
class BattleshipEnv(gym.Env, ABC):
def __init__(self, board_size: Tuple = None, ship_sizes: dict = None, episode_steps: int = 100):
self.ship_sizes = ship_sizes or {5: 1, 4: 1, 3: 2, 2: 1}
self.board_size = board_size or (10, 10)
self.board = None
self.board_generated = None
self.observation = None
self.done = None
self.step_count = None
self.episode_steps = episode_steps
self.action_space = spaces.Discrete(self.board_size[0] * self.board_size[1])
# MultiBinary is a binary space array
self.observation_space = spaces.MultiBinary([2, self.board_size[0], self.board_size[1]])
# dict to save all the ship objects
self.ship_dict = {}
def step(self, raw_action: int) -> Tuple[np.ndarray, int, bool, dict]:
assert (raw_action < self.board_size[0]*self.board_size[1]),\
"Invalid action (Superior than size_board[0]*size_board[1])"
action = Action(x=raw_action // self.board_size[0], y=raw_action % self.board_size[1])
self.step_count += 1
if self.step_count >= self.episode_steps:
self.done = True
# it looks if there is a ship on the current cell
# if there is a ship then the cell is 1 and 0 otherwise
if self.board[action.x, action.y] != 0:
# if the cell that we just hit is the last one from the respective ship
# then add this info to the observation
if self.board[self.board == self.board[action.x, action.y]].shape[0] == 1:
ship = self.ship_dict[self.board[action.x, action.y]]
self.observation[1, ship.min_x:ship.max_x, ship.min_y:ship.max_y] = 1
self.board[action.x, action.y] = 0
self.observation[0, action.x, action.y] = 1
# if the whole board is already filled, no ships
if not self.board.any():
self.done = True
return self.observation, 100, self.done, {}
return self.observation, 1, self.done, {}
# we end up here if we hit a cell that we had hit before already
elif self.observation[0, action.x, action.y] == 1 or self.observation[1, action.x, action.y] == 1:
return self.observation, -1, self.done, {}
# we end up here if we hit a cell that has not been hit before and doesn't contain a ship
else:
self.observation[1, action.x, action.y] = 1
return self.observation, 0, self.done, {}
def reset(self):
self.set_board()
# maintain an original copy of the board generated in the start
self.board_generated = deepcopy(self.board)
self.observation = np.zeros((2, *self.board_size), dtype=np.float32)
self.step_count = 0
return self.observation
def set_board(self):
self.board = np.zeros(self.board_size, dtype=np.float32)
k = 1
for i, (ship_size, ship_count) in enumerate(self.ship_sizes.items()):
for j in range(ship_count):
self.place_ship(ship_size, k)
k += 1
def place_ship(self, ship_size, ship_index):
can_place_ship = False
while not can_place_ship:
ship = self.get_ship(ship_size, self.board_size)
can_place_ship = self.is_place_empty(ship)
# set the ship cells to one
self.board[ship.min_x:ship.max_x, ship.min_y:ship.max_y] = ship_index
self.ship_dict.update({ship_index: ship})
@staticmethod
def get_ship(ship_size, board_size) -> Ship:
if np.random.choice(('Horizontal', 'Vertical')) == 'Horizontal':
# find the ship coordinates randomly
min_x = np.random.randint(0, board_size[0] - 1 - ship_size)
min_y = np.random.randint(0, board_size[1] - 1)
return Ship(min_x=min_x, max_x=min_x + ship_size, min_y=min_y, max_y=min_y + 1)
else:
min_x = np.random.randint(0, board_size[0] - 1)
min_y = np.random.randint(0, board_size[1] - 1 - ship_size)
return Ship(min_x=min_x, max_x=min_x + 1, min_y=min_y, max_y=min_y + ship_size)
def is_place_empty(self, ship):
# make sure that there are no ships by simply summing the cell values
return np.count_nonzero(self.board[ship.min_x:ship.max_x, ship.min_y:ship.max_y]) == 0
def get_board(self):
return self.board
| null | null |
b3a6e632568dd13f128eda2cba96293e2bd0d3cd | sniperswang/dev | /leetcode/L265/test.py | 1,452 | 3.640625 | 4 | """
There are a row of n houses, each house can be painted with one of the k colors.
The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by a n x k cost matrix.
For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
Follow up:
Could you solve it in O(nk) runtime?
"""
class Solution(object):
def minCostII(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if len(costs) == 0:
return 0
m = len(costs)
n = len(costs[0])
for i in range (1, m):
preMin = {}
preMin[0] = min(costs[i-1][1:])
costs[i][0] = costs[i][0] + preMin[0]
if ( n > 1):
preMin[n-1] = min(costs[i-1][:n-1])
costs[i][n-1] = costs[i][n-1] + preMin[n-1]
for j in range (1, n-1):
preMin[j] = min( min(costs[i-1][:j]), min(costs[i-1][j+1:]) )
costs[i][j] = costs[i][j] + preMin[j]
return min(costs[len(costs)-1])
costa = [1,2,4]
costb = [3,1,0]
costc = [1,2,1]
costs = []
costs.append(costa)
costs.append(costb)
costs.append(costc)
s = Solution()
print s.minCostII(costs)
| null | null |
1ad2cd819e2b9ca0e38435955fdea7a29211eb75 | chaerui7967/K_Digital_Training | /Python_KD_basic/List/list_3.py | 277 | 4.3125 | 4 | #리스트 내용 일치
list1 = [1,2,3]
list2 = [1,2,3]
# == , !=, <, >
print(list1 == list2)
# 2차원 리스트
list3 = [[1,2,3],[4,5,6],[7,8,9]]
#행렬 형식으로 출력
for i in list3:
print(i)
for i in list3:
for j in i:
print(j, end="")
print() | null | null |
77d79a10d558f871153a02d7386db26c5a37da9d | patelp456/Project-Euler | /lattice_points.py | 571 | 3.84375 | 4 | #!/usr/bin/env python
# ========= Import required modules =====================
# question is not clear
# for using system commands
import sys
# for using os commands like list directeries etc
import os
# for mathematical functions specially matriices
import numpy as np
# for general maths
from math import *
m,n = input("enter comman separated - number of rows and columns in the grid : ")
arr = np.zeros((m+1,n+1),dtype=int)
arr[0,:] = 1
arr[:,0] = 1
for i in range(1,m+1):
for j in range(1,n+1):
arr[i,j] = arr[i-1,j] + arr[i,j-1]
print arr[m,n] | null | null |
0d0892bf443e39c3c5ef078f2cb846370b7852e9 | JakobLybarger/Graph-Pathfinding-Algorithms | /dijkstras.py | 1,297 | 4.15625 | 4 | import math
import heapq
def dijkstras(graph, start):
distances = {} # Dictionary to keep track of the shortest distance to each vertex in the graph
# The distance to each vertex is not known so we will just assume each vertex is infinitely far away
for vertex in graph:
distances[vertex] = math.inf
distances[start] = 0 # Distance from the first point to the first point is 0
vertices_to_explore = [(0, start)]
# Continue while heap is not empty
while vertices_to_explore:
distance, vertex = heapq.heappop(vertices_to_explore) # Pop the minimum distance vertex off of the heap
for neighbor, e_weight in graph[vertex]:
new_distance = distance + e_weight
# If the new distance is less than the current distance set the current distance as new distance
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
heapq.heappush(vertices_to_explore, (new_distance, neighbor))
return distances # The dictionary of minimum distances from start to each vertex
graph = {
'A': [('B', 10), ('C', 3)],
'C': [('D', 2)],
'D': [('E', 10)],
'E': [('A', 7)],
'B': [('C', 3), ('D', 2)]
}
print(dijkstras(graph, "A")) | null | null |
00ead084fe729599aeedba61cc88fc277e7726ad | menezesluiz/MITx_-_edX | /week1/exercise/exercise-for.py | 442 | 4.34375 | 4 | """
Exercise: for
Finger Exercises due Aug 5, 2020 20:30 -03
Completed
Bookmark this page
Exercise: for exercise 1
5.0/5.0 points (graded)
ESTIMATED TIME TO COMPLETE: 5 minutes
In this problem you'll be given a chance to practice writing some for loops.
1. Convert the following code into code that uses a for loop.
prints 2
prints 4
prints 6
prints 8
prints 10
prints Goodbye!
"""
for i in range(2, 12, 2):
print(i)
print("Goodbye!") | null | null |
f24199e1370b17f6ba250e31db0c817228f1e33d | marysom/stepik | /adaptive python/2_159.py | 169 | 3.78125 | 4 | '''
Write a program: input of this program has a single line with integers. The program must output the sum of these numbers.
'''
print(sum(map(int, input().split())))
| null | null |
8a71c83758318114c1ba91c8ff7ea461bc0f9933 | workready/pythonbasic | /sources/t10/t10ej11.py | 235 | 3.546875 | 4 | import numpy as np
A = np.array([[1, 2], [3, 4]])
A
"""
array([[1, 2],
[3, 4]])
"""
# Esto sería un puntero: si cambiamos B, A también cambia
B = A
# Esto sería una copia: si cambiamos B, A no cambia
B = np.copy(A) | null | null |
47553ba19892329d2a81aa710376ab378aee5a20 | JoaoPauloPereirax/Python-Study | /Mundo2/WHILE/while007.py | 304 | 4.09375 | 4 | '''Escreva um programa que leia um número n inteiro qualquer e mostre na tela os n primeiros termos de uma sequência de fibonacci.'''
n=int(input('Digite um número: '))
anterior=1
atual = 0
cont=1
while cont!=n:
print(atual)
atual+=anterior
anterior=atual-anterior
cont+=1
print(atual) | null | null |
a1b41adcda2d3b3522744e954cf8ae2f901c6b01 | drunkwater/leetcode | /medium/python3/c0099_209_minimum-size-subarray-sum/00_leetcode_0099.py | 798 | 3.546875 | 4 | # DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#209. Minimum Size Subarray Sum
#Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
#For example, given the array [2,3,1,2,4,3] and s = 7,
#the subarray [4,3] has the minimal length under the problem constraint.
#click to show more practice.
#Credits:
#Special thanks to @Freezen for adding this problem and creating all test cases.
#class Solution:
# def minSubArrayLen(self, s, nums):
# """
# :type s: int
# :type nums: List[int]
# :rtype: int
# """
# Time Is Money | null | null |
5f69620a7ce1c8a4b3a7cb32abe697fa4ef522da | danhagg/python_bits | /CrashCourseInPython/kafah.py | 261 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 27 16:22:26 2017
@author: danielhaggerty
"""
answer = "Kafah tells lies"
question = input("Does Kafah prefer Dan or crappy Persian TV: ")
if 'Dan':
print(answer)
else:
print(answer) | null | null |
b97c79695318d3e6ded18a4fa35edcaf5db213c7 | FredC94/MOOC-Python3 | /UpyLab/UpyLaB 5.16 - Compréhension Listes.py | 1,195 | 3.984375 | 4 | """ Auteur = Frédéric Castel
Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Écrire une fonction my_pow qui prend comme paramètres un nombre entier m et un nombre flottant b,
et qui renvoie une liste contenant les m premières puissances de b, c’est-à-dire une liste contenant
les nombres allant de b^0 à b^{m - 1}.
Si le type des paramètres n’est pas celui attendu, la fonction retournera la valeur None.
Exemples:
my_pow(3, 5.0) doit retourner: [1.0, 5.0, 25.0]
my_pow(3.0, 5.0) doit retourner: None
my_pow('a', 'b') doit retourner: None
Consignes:
Dans cet exercice, il vous est demandé d’écrire seulement la fonction my_pow.
Le code que vous soumettez à UpyLaB doit donc comporter uniquement la définition de cette fonction,
et ne fait en particulier aucun appel à input ou à print.
"""
def my_pow(m, b): # ou m est un entier et b est un float
if (type(m) != int or type(b) == str) or (m == 1 and type(b) == int):
return None
res = [b ** exp for exp in range(0, m)]
return res
# OK
my_pow(0, 1.9)
# None
my_pow(1, 4)
my_pow('a', 'b')
my_pow(3.0, 5.0)
my_pow(1.0, 5.0)
| null | null |
fb1795c96050d29340251a3dc328b14e70f3b7bf | jiazekun/Py | /ds_using_dict.py | 403 | 3.625 | 4 | ab={
'Swaroop':'swaroop@swaroopch.com',
'Larry':'larry@wall.com',
'Mali':'mali@qq.com',
'Spa':'spa@hotmail.com'
}
print('Swaroop \'s address is ',ab['Swaroop'])
del ab['Spa']
print('\nThere are{}contents in the address-book\n'.format(len(ab)))
for name,address in ab.items():
print('Contact {} at {}'.format(name,address))
ab['Guido']='guido@python.org'
if 'Guido' in ab:
print('\nGuido\'s address is',ab['Guido']) | null | null |
1fcd14f968db19cc71a7409145afa61c6031d728 | gaylonalfano/Python-3-Bootcamp | /__name__variable.py | 1,067 | 3.546875 | 4 | '''
A "dunder" variable. Special properties represented by __name__ variable.
When run, every Python file/module has its own __name__ variable. If the file is
the main file being run, its value is "__main__". Otherwise, its value is the file name.
***check out say_hi.py and say_sup.py for example***
Basically, the __name__ variable is set to __main__ in the main/executed file.
But, if you
Here's what happens you import something:
1. Tries to find the module (if it doesn't find it, it throws an error).
2. But if found, it runs the code inside of the module being imported
So, in the example with say_hi and say_sup, when you import say_sup into the say_hi file,
it will run the code in the say_sup module FIRST, which has a say_sup() function call.
If you want to prevent this code from running, then here's the trick to ignore code
on import:
if __name__ == "__main__":
# this code will only run
# if the file is the main file!
Ex. Modify the say_sup.py file and add this code to call the function:
if __name__ == "__main__":
say_sup()
''' | null | null |
6aff153c967e821b61c8e5a29facee8663794522 | Zioq/Algorithms-and-Data-Structures-With-Python | /15.Binary Search/binarySearch_recursive.py | 715 | 3.828125 | 4 | # Bisection search - recursive implementation
def bisection_recur(n, arr, start, stop):
# Set the base case first
if start > stop:
return (f"{n} not found in list")
else:
mid = (start + stop) // 2
if n == arr[mid]:
return (f"{n} found at index: {mid}")
elif n > arr[mid]:
start = mid + 1
return bisection_recur(n, arr, start, stop)
else:
stop = mid - 1
return bisection_recur(n, arr, start, stop)
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# #ind 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
n = 8
print(bisection_recur(8, l, 0, len(l)-1))
print("\n")
for num in range(16):
print(bisection_recur(num, l, 0, len(l)-1))
| null | null |
End of preview.