blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
72bf293798f3a21d789c8e63c79e4d0df37b1323 | neilhan/reinforcement_learning_python | /python/tic_tac_toe/play.py | 4,063 | 3.765625 | 4 | #! python3
import numpy as np
import matplotlib.pyplot as plt
from tic_tac_toe import BOARD_LENGTH
from tic_tac_toe.game_env import Environment
from tic_tac_toe.agent import Agent
from tic_tac_toe.human import Human
def play_game(p1, p2, env: Environment, draw=False) -> None:
# loops until game over
current_player = None
while not env.is_game_over():
# alternate between players
# p1 first
if current_player == p1:
current_player = p2
else:
current_player = p1
# draw, for user to see
if draw:
if draw == 1 and current_player == p1:
env.draw_board()
if draw == 2 and current_player == p2:
env.draw_board()
# current_player move
current_player.take_action(env)
# update state_history
state = env.get_state()
p1.update_state_history(state)
p2.update_state_history(state)
# after one game play, see who won?
if draw:
env.draw_board()
# value function update
p1.update_V_after_episode(env)
p2.update_V_after_episode(env)
def get_state_hash_and_winner(
env, i=0, j=0, board_width=BOARD_LENGTH, board_height=BOARD_LENGTH):
"""
Return all states(as ints) and who is winner for those states if any.
(i,j) refers to the next cell on the board to permute(need to try -1,0,1)
impossible games are ignored. ie 3x and 3o in a row in one game,
since that will never happen in real game.
:param env: the env
:param i: loop i start with
:param j: loop j start with
:return: [(state, winner, ended)]
"""
results = []
for v in (0, env.x, env.o):
env.board[i, j] = v
if j >= (board_width - 1):
if i >= (board_height - 1):
state = env.get_state()
ended = env.is_game_over(force_recalc=True)
winner = env.winner
# only append to result when all 9 cells are filled
results.append((state, winner, ended))
else: # reset j, go to next row
results += get_state_hash_and_winner(env, i + 1, 0)
else:
results += get_state_hash_and_winner(env, i, j + 1)
return results
def _build_V_for(player, env, state_winner_triples):
"""
returns the V lookup table: state->v as numpy array
if player_x wins, V(s) = 1
if x loses or draw, V(s) = 0
otherwise, V(s) = 0.5
:param env: Environment
:param state_winner_triples: [(state, winner, ended), (..), ..]
:return: V funciton as lookup table: state->v
"""
V = np.zeros(env.num_states)
for state, winner, ended in state_winner_triples:
if ended:
if winner == player: # either player_x, or player_o
v = 1
else:
v = 0
else:
v = 0.5
V[state] = v
return V
def build_init_V_for_player_x(env, state_winner_triples):
return _build_V_for(env.x, env, state_winner_triples)
def build_init_V_for_player_o(env, state_winner_triples):
return _build_V_for(env.o, env, state_winner_triples)
def main():
env = Environment()
state_winner_triples = get_state_hash_and_winner(env)
player_x = Agent()
V_x = build_init_V_for_player_x(env, state_winner_triples)
player_x.set_V(V_x)
player_x.set_player(env.x)
player_o = Agent()
V_o = build_init_V_for_player_o(env, state_winner_triples)
player_o.set_V(V_o)
player_o.set_player(env.o)
# play games
T = 10000
for t in range(T):
if t % 200 == 0:
print('Played game:', t)
play_game(player_x, player_o, Environment())
# human vs ai
human = Human()
human.set_player(env.o)
while True:
player_x.set_verbose(True)
play_game(player_x, human, Environment(), draw=2)
answer = input('Play again? Y/n: ')
if answer and answer.lower()[0] == 'n':
break
if __name__ == '__main__':
main()
|
a18df08e864b6e31a5fd6c0909f64f40c76d1feb | pikeszfish/LeetCode | /leetcode.py/LengthofLastWord.py | 232 | 3.609375 | 4 | class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
s = s.strip().split(' ')[-1].strip(',')
return len(s)
a = Solution()
print a.lengthOfLastWord("Hello World") |
159d615b1862a59ba7d4f66938971ae965ec69f9 | hongjl/Python-network-program | /checkStrongPassword.py | 895 | 3.53125 | 4 | #! python3
'''
强口令: 长度不少于8个字符,同时包含大写和小写字符,至少有一个数字
'''
import re
text = ['SLKJDFSLDKF','laksfdlksd','8378373849999','asdf','sdfkjSDLFK','aslkdfj89899','SLKDFJSLDKF89687','asdfkSDKF78799'] # 测试,只有一个符合条件
def checkStrongPassword(pwList):
# castAndNum = re.compile(r'\w*?[0-9A-Z]*[a-z]+\w*')
lowCast = re.compile(r'[^a-z]*[a-z]+[^a-z]*') # 包含小写字母
uppCast = re.compile(r'[^A-Z]*[A-Z]+[^A-Z]*') # 包含大写字母
num = re.compile(r'\D*\d+\D*') # 包含至少一个数字
beyond8 = re.compile(r'\w{8,}') # 至少8个字符
for pw in pwList:
if(lowCast.search(pw) != None and uppCast.search(pw) != None
and num.search(pw) != None and beyond8.search(pw) != None):
print(pw)
checkStrongPassword(text)
|
1307d3e6241c40f19b8f9c9901147a474e9e3e80 | AllanBastos/Atividades-Python | /ESTATÍSTICA APLICADA/Listas/Exercicio 5.py | 103 | 3.640625 | 4 | def is_sorted(t):
return t == sorted(t)
print(is_sorted([1, 2, 2]))
print(is_sorted(['b', 'a'])) |
8f0502272e6f2eb623c2b09a4af1b852978ab318 | K-Vaid/Python | /Basics/pallindromic.py | 633 | 4.25 | 4 | """
Code Challenge
Name:
Pallindromic Integer
Filename:
pallindromic.py
Problem Statement:
You are given a space separated list of integers.
If all the integers are positive and if any integer is a palindromic integer, then you need to print True else print False.
(Take Input from User)
Hint: What is pallindromic Integer
Input:
12 9 61 5 14
Output:
True
"""
# give list of inputs from user
user_input = input("Enter space seperated values :").split()
if all([int(i)>0 for i in user_input]) and any([i==i[::-1] for i in user_input]):
print ("True")
else:
print ("False")
|
c693f3d36bbb296bae46c9b3b7ecb34128232f97 | VTrifanov/Quadratic-equation | /grafic.py | 2,337 | 3.546875 | 4 | import tkinter as tk
canvas_h = 650
canvas_w = 800
#x_left = -4
#x_right = 4
#y_top = 4
#y_bottom = -4
#dx = canvas_w / (x_right-x_left) #цена пикселя по х
#dy = canvas_h / (y_top-y_bottom) #цена пикселя по y
def main(a=1, b=0, c=0, x_left=-4, x_right=4, y_bottom=-4, y_top=4):
global canvas, list_x_old, list_y_old
dx = canvas_w / (x_right - x_left) # цена пикселя по х
dy = canvas_h / (y_top - y_bottom) # цена пикселя по y
window2 = tk.Tk()
canvas = tk.Canvas(window2, width=canvas_w, height=canvas_h, bg='#012')
canvas.pack()
window2.title('холст')
window2.geometry(f'{canvas_w}x{canvas_h}+200+10')
oxes(x_left, x_right, y_top, y_bottom, dx, dy)
list_x_old = list_x(x_left, x_right) #список координат х в обычной системе координат (не canvas)
list_y_old = list_y(a, b, c, x_left, x_right)
draw_graf(x_left, y_top, dx, dy)
window2.mainloop()
def oxes(x_left, x_right, y_top, y_bottom, dx, dy):
cx = -x_left*dx
cy = y_top*dy
canvas.create_line(0, cy, canvas_w, cy, fill="white")
canvas.create_line(cx, 0, cx, canvas_h, fill="white")
x_step = (x_right - x_left) / 8
x = x_left + x_step
while x < x_right:
x_canvas = (x-x_left)*dx
canvas.create_line(x_canvas, cy-5, x_canvas, cy+5, fill="white")
canvas.create_text(x_canvas, cy+15, text=str(round(x, 1)), fill='white')
x += x_step
y_step = (y_top - y_bottom) / 8
y = y_top - y_step
while y > y_bottom:
y_canvas = (y-y_top)*dy
canvas.create_line(cx-5, -y_canvas, cx+5, -y_canvas, fill="white")
canvas.create_text(cx+15, -y_canvas, text=str(round(y, 1)), fill='white')
y -= y_step
def list_x(x_left, x_right):
list1=[]
x=x_left
step=(x_right-x_left) / canvas_w
while x<=x_right:
list1.append(x)
x+=step
return list1
def list_y(a,b,c, x_left, x_right):
list2=[]
for x in list_x(x_left, x_right):
y=a*x**2+b*x+c
list2.append(y)
return list2
def draw_graf(x_left, y_top, dx, dy):
i=0
for x in list_x_old:
x=(x-x_left)*dx
y=(list_y_old[i]-y_top)*dy
canvas.create_line(x,-y,x+1,-y, fill='yellow')
i+=1
|
5a8da87ee3ed9b3d7ee966935bcd14eb8e31ef65 | y43560681/y43560681-270201054 | /lab9/example4.py | 169 | 3.96875 | 4 | t = input("Please enter second : ")
def sleep(t, k = t):
k = int(k)
if k == -1:
return
else:
print(k)
return sleep(t, k - 1)
sleep(t) |
b582f4291e063f51bcdec69fbf8feac08b89bf3b | erdi54/Data_Structure_Algorithm_Python | /Array Sequences/unique_characters.py | 665 | 4 | 4 | """
Bir dize verildiğinde, tüm benzersiz karakterlerin karşılaştırıldığından emin olun.
Örneğin, 'abcde' dizgisi tüm benzersiz karakterlere sahiptir ve True döndürmelidir.
'Aabcde' dizgisi yinelenen karakterler içeriyor ve false döndürmeli.
"""
def uni_char(st):
if len(st) > 256:
return False
char_set = [False]*128
for i in range(0, len(st)):
val = ord(st[i])
if char_set[val]:
return False
char_set[val] = True
return True
if __name__ == '__main__':
st = "abcde"
st1 = "Aabcdee"
print(uni_char(st))
print(uni_char(st1))
|
9f0306ca8dfaf280e846685652a23853116d212f | julielaursen/Homework | /Julie_Laursen_Lab8b.py | 1,539 | 4.25 | 4 |
#define main function
def main():
#create empty list called students
students = []
#call modify_students
modify_students(students)
#define modify_students and pass students to it
def modify_students(students):
counter = 0
while counter < 12:
#take input for 12 students and append them to student list
name = input("Please input the student's name: ")
counter += 1
students.append(name)
#print(students, '\n')
#sort list in alphabetical order
students.sort()
print('Sorted order:', students, '\n')
#sort list in reverse order
students.sort(reverse=True)
print('Reverse sorted order', students, '\n')
#append instructor's name onto the list
students.append('Rene Polanco')
print('Students and instructor,', students, '\n')
#insert your own name at the beginning of the list
students.insert(0, 'Julie Laursen')
print('Students, instructor and name:', students, '\n')
#output the list to a file named names.txt
outfile = open('names.txt', 'w')
for item in students:
outfile.write(str(item) + '\n')
outfile.close()
#display the contents of names.txt
infile = open('names.txt', 'r')
file_contents = infile.read()
infile.close()
print(file_contents)
#convert list to tuple
file_tuple = tuple(students)
#call main function
main()
|
ffb5f7ee32419362d014ea123c9b70f47283abdf | chandni-s/NewsFlash | /src/response.py | 2,555 | 3.65625 | 4 | from model import Model
import json
class ClassEncoder(json.JSONEncoder):
"""A custom JSON encoder that defaults to using the __dict__ method for
database Model classes and subclasses. This allows for automatic
conversion to JSON.
"""
def default(self, o):
"""(ClassEncoder, Object) -> Object
Returns a dict if the object is Model class or subclass, or the
default serializable object otherwise.
"""
if isinstance(o, Model):
return o.__dict__
return json.JSONEncoder.default(self, o)
class Response:
"""A response to an AJAX request. Contains the data for the response,
extra parameters for the response, the result indicating operation
success or failure, and a message describing operation success or
failure.
"""
def __init__(self, result=False, msg='', data=None, params=None):
"""(Response, Bool, str, obj, dict) -> None
Creates a response using the given data.
"""
self.response = {'data': data, 'result': result, 'msg': msg}
if params:
self.update_params(params)
def get_data(self):
"""(Response) -> obj
Returns the data for the response.
"""
return self.response['data']
def get_params(self):
"""(Response) -> dict
Returns the parameters for the response.
"""
return self.response
def to_json(self):
"""(Response) -> str
Converts the response to JSON for sending over the internet. The
custom encoder defined above is used for the conversion.
"""
return json.dumps(self.response, cls=ClassEncoder)
def update_params(self, params):
"""(Response, dict) -> None
Updates the parameters for the response with the given dict.
"""
self.response.update(params)
def __str__(self):
"""(Response) -> str
Converts the response to a printable string.
"""
return str(self.response)
def __len__(self):
"""(Response) -> int
Returns the number of elements in the response data.
"""
return len(self.get_data())
def __eq__(self, other):
"""(Response, Response) -> bool
Returns True if the response data is the same.
"""
return self.get_data() == other.get_data()
def __nonzero__(self):
"""(Response) -> bool
Returns True if the result was true, and False otherwise.
"""
return self.response['result']
|
f30fd06a8c1b6e2c994148ef0ad7a3415ac8493b | pvanh80/intro-to-programming | /round11/Numerical_integration.py | 1,111 | 3.953125 | 4 | # Intro to programming
# Numerical integration
# Phan Viet Anh
# 256296
# http://mathworld.wolfram.com/RiemannSum.html
def math_function(x):
return -pow(x,2) + 2*x + 4
def approximate_area(math_function, lower_bound_area, upper_bound_area, number_rec):
step = (upper_bound_area-lower_bound_area)/number_rec
area = 0
index = 1
for index in range(0,number_rec):
area += min(math_function(lower_bound_area + (index * step)),
math_function(lower_bound_area + ((index + 1) * step))) * step
return area
# Riemann Sum with additional parameter sample_type: lower, upper, middle point,
# def approximate_area(math_function, lower_bound_area, upper_bound_area, number_rec, sample_type):
# step = (upper_bound_area-lower_bound_area)/number_rec
# area = 0
# index = 1
# for index in range(0,number_rec):
# area += min(math_function(lower_bound_area + (index * step)),
# math_function(lower_bound_area + ((index + 1) * step))) * step
#
# return area
def main():
print(approximate_area(math_function, -1, 3, 4))
main()
|
f5f4dc58e04991b23e384689db7fff3741d7c1e9 | GeorgeJopson/OCR-A-Level-Coding-Challenges | /15-Pangrams/Pangrams.py | 459 | 4.1875 | 4 | def isPangram(string):
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for letter in string:
try:
del alphabet[alphabet.index(letter.lower())]
except:
pass
if(len(alphabet)==0):
return True
else:
return False
if(isPangram(input("Input a string: "))):
print("It is a pangram")
else:
print("It is not a pangram")
|
d4f81a35ec2dd689f47680667a248bfbb9065bfd | magezil/magezil.github.io | /battleship.py | 3,115 | 4.375 | 4 | from random import randint
''' Battleship implementation - does not have to be a square board '''
board = [] # displayed board
ships = [] # board with ships are located
types = {} # types of ships and size
nrows = 10 # number of rows on board
ncols = 10 # number of columns on board
# Create board for other player and for ships
for x in range(nrows):
board.append(["O"] * ncols)
ships.append(["O"] * ncols)
# Define type of ships : sizes and position them
types = {
"carrier": 5,
"battleship": 4,
"cruiser": 3,
"submarine": 3,
"destroyer": 2
}
def print_board(board):
col = 0
temp = []
print " ",
for i in range(nrows):
print i,
print ""
for row in board:
print col, " ".join(row)
col += 1
# gives random position based on ship size
def random_pos(size):
return randint(0, nrows-size-1)
# check if position is valid
def isValid(row, col, size, orientation):
valid = True
if orientation:
for i in range(size):
valid = valid and (row+i) in range(0, nrows) and col in range(0, ncols) and ships[row+i][col] == "O"
else:
for i in range(size):
valid = valid and row in range(0, nrows) and (col+i) in range(0, ncols) and ships[row][col+i] == "O"
return valid;
# place ship
def place(ship):
size = types[ship]
# assign dummy values for isValid()
x = y = orientation = -1
while not isValid(x, y, size, orientation):
orientation = randint(0,1)
if orientation:
x = random_pos(size)
y = random_pos(1)
else:
x = random_pos(1)
y = random_pos(size)
for i in range(size):
if orientation:
ships[x+i][y] = "X"
else:
ships[x][y+i] = "X"
# Test
# print ship, size, x, y
for type in types:
place(type)
#print_board(ships)
# Game implementation
print "Let's play Battleship!"
print_board(board)
win = False # Cannot win at the beginning of the game.
#nturns = 20 # If want to limit game to a certain number of turns
#for turn in range(nturns):
turn = 0
# Play until you win
while not win:
print "Turn ", turn+1
while True:
try:
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))
except ValueError:
print "Please enter a number"
continue
else:
break
if (guess_row not in range(nrows)) or (guess_col not in range(ncols)):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] != "O"):
print "You guessed that one already."
elif ships[guess_row][guess_col] == "X":
print "Hit!"
ships[guess_row][guess_col] = "H"
board[guess_row][guess_col] = "H"
win = True # Assume it was the last hit, but check if there are any other x's
for i in range(len(ships)):
win = win and not ('X' in ships[i])
if win:
print "Congratulations! You sunk my battleship!"
print_board(ships)
else:
print "You missed!"
board[guess_row][guess_col] = "X"
print_board(board)
turn += 1
|
66e60bf7b0d5ef02153b9ba4bb0b99e405758a45 | Latas2001/python-program | /birthday reminder.py | 721 | 4.375 | 4 | dict={}
while True:
print("_______________Birthday App________________")
print("1.Show Birthday")
print("2.Add to Birthday List")
print("3.Exit")
choice = int(input("Enter the choice: "))
if choice==1:
if len(dict.keys())==0:
print("nothing to show....")
else:
name=input("Enter the name look for birthday....")
birthday=dict.get(name,"No data found")
print(birthday)
elif choice==2:
name=input("Enter your friend's name: ")
date=input("Enter the birthday: ")
dict[name]=date
print("Birthday added successfully")
elif choice==3:
break
else:
print("Choose a valid option")
|
d5ed44cdcaecaaff976e5abbb838f20f50e75347 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sieve/953f80d71f8840e596e6db2a119b9425.py | 215 | 3.765625 | 4 | def sieve(n):
multiples = set()
sieved = []
for i in range(2, n + 1):
if i not in multiples:
sieved.append(i)
multiples.update(range(i * i, n + 1, i))
return sieved
|
8eb1f4859bc9b3bc6e459026bd2634cfb0c52058 | wesenbergg/hy-data-analysis-with-python-2020 | /part01/part01-e06_triple_square/src/triple_square.py | 340 | 3.953125 | 4 | #!/usr/bin/env python3
def triple(num):
return num*3
def square(num):
return num**2
def main():
for i in range(1, 11):
t=triple(i)
s=square(i)
if t < s:
break
print("triple({:.0f})=={:.0f} square({:.0f})=={:.0f}".format(i, t, i, s))
if __name__ == "__main__":
main()
|
c89309952ac1544725ffb382cdedc72f879f4719 | riya-kostha/PyhtonAssignment | /largest.py | 211 | 4 | 4 | list=[1,2,45,67,89,90,170]
for i in range(len(list)):
list.sort()
print("list is",list)
print("second largest number",list.__getitem__(len(list)-2))
print("second smallest number",list.__getitem__(1)) |
8a89548f36d60ec9efd878b46e99388b004d2917 | juniorsmartins/Aulas-Python | /Aula24.py | 490 | 3.921875 | 4 | # coding: latin-1
for contador in range (5, 0, -1):
print(contador)
print("\n")
for cont in range (1, 6):
print(cont)
print("\n")
lista = {1, 4, 7, 9}
for itens in lista:
print(itens)
print("\n")
arquivo = {1: "Mário", 2: "Pedro", 3: "Alberto", 4: "Francisco"}
for itens in arquivo:
print(itens, arquivo[itens])
print("\n")
ferramentas = {1: "Martelo", 2: "Prego", 3: "Alicate", 4: "Serrote"}
for itens, valor in ferramentas.items():
print(itens, " -> ", valor)
print("\n")
|
3c1caed099d9f6096f2625604cae2d6491694474 | jiinmoon/Algorithms_Review | /Archives/Leet_Code/Old-Attempts/0142_Linked_List_Cycle_II.py | 579 | 3.5 | 4 | """ 142. Linked List Cycle II
Question:
Given a linked list with a cycle, return the node where cycle begins.
"""
class Solution:
def detectCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
# cycle found. restart from head until fast is none.
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return fast
return none
|
1e791a16dc783d149d0fd4eaa314d4902db53f43 | jvnabais/Test-Python | /PythonFile.py | 682 | 3.640625 | 4 | correct_answer = "Corret!"
wrong_answer = "Wrong!"
a = 100
b = -100
total = a + b
if total == 0:
print(correct_answer)
else:
print(wrong_answer)
d = 20
s = -20
total1 = d + s
if total1 == 0:
print(correct_answer)
else:
print(wrong_answer)
g = 10
j = 20000
total2 = g + j
if total2 == 1000:
print(correct_answer)
else:
print(wrong_answer)
n = 50
m = 50
total3 = n + m
if total3 == 0:
print(correct_answer)
else:
print(wrong_answer)
y = 80
z = -80
total4 = y + z
if total4 == 0:
print(correct_answer)
else:
print(wrong_answer)
o = 20
p = -20
total5 = o + p
if total5 == 0:
print(correct_answer)
else:
print(wrong_answer) |
a4cc4ce100623548acfb4a4b07c610199e5b65b2 | robobyn/code-challenges | /fin-nth-fibonacci.py | 961 | 4.34375 | 4 | """Write a function fib() that a takes an integer n and returns the nth
Fibonacci number."""
def find_nth_fibonacci(n):
"""Finds and returns nth Fibonacci number.
Input: Positive integer
Returns: nth number in Fibonacci sequence - assumes series is 0-indexed."""
if n < 0:
raise ValueError("Negative index not allowed.")
if n == 0 or n == 1:
return n
# start counter at n of 2 because need at least 2 prev ints for loop
counter = 2
# if n is 2 current will be 1 (result of adding 0 and 1)
current = 1
# previous number starts at 1
prev = 1
# second previous number starts at 0
prev_prev = 0
while counter < n:
counter += 1
prev_prev = prev
prev = current
current = prev_prev + prev
return current
print find_nth_fibonacci(10)
print find_nth_fibonacci(0)
print find_nth_fibonacci(86)
print find_nth_fibonacci(6)
print find_nth_fibonacci(-5)
|
88e32db0dda55d4eb11c3e03c57e1b9be6e813f5 | acarmonag/ST0245-008 | /Talleres/Recursividad/punto5.py | 261 | 3.6875 | 4 | igual, aux = 0, 0
texto = input("Ingrese la palabra: ")
for i in reversed(range(0, len(texto))):
if texto[i] == texto[aux]:
igual += 1
aux += 1
if len(texto) == igual:
print("El texto es palindromo")
else:
print("El texto NO es palindromo") |
2724d9e711f853cf578ad7104c663eea64c367a6 | Vasilic-Maxim/LeetCode-Problems | /problems/1013. Partition Array Into Three Parts With Equal Sum/1 - Accumulate.py | 622 | 3.8125 | 4 | from itertools import accumulate
from typing import List
class Solution:
"""
Time: O(2n) => O(n)
Space: O(n)
"""
def canThreePartsEqualSum(self, nums: List[int]) -> bool:
# do not need to check if 'nums' is empty because
# of the condition [3 <= A.length <= 50000]
nums_sums = list(accumulate(nums))
step, reminder = divmod(nums_sums[-1], 3)
# if the total sum is not divisible by 3 then the
# list cannot be divided
if reminder:
return False
it = iter(nums_sums)
return all(step * i in it for i in range(1, 4))
|
58dfb6132acf6bd75b83feffebd471faf85e5f5b | Hahn9/MyPython | /join.py | 10,701 | 3.734375 | 4 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s = """line1\nline2\nline3\n"""
print s
SyntaxError: multiple statements found while compiling a single statement
>>> s='hello,world'
>>> print s
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(s)?
>>> s='hello,world'
>>> print(s)
hello,world
>>> s='abcdefg'
>>> s[0:]
'abcdefg'
>>> s[-1]
'g'
>>> s[0;-1]
SyntaxError: invalid syntax
>>> s[0:-1]
'abcdef'
>>> s[-1:-1]
''
>>> s = """line1\nline2\nline3\n"""
>>> print(s)
line1
line2
line3
>>> s = "line1\nline2\nline3\n"
>>> print(s)
line1
line2
line3
>>> int(input("enter a real number"))
enter a real number
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
int(input("enter a real number"))
ValueError: invalid literal for int() with base 10: ''
>>> a = int (input("enter a real number"))
enter a real number
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
a = int (input("enter a real number"))
ValueError: invalid literal for int() with base 10: ''
>>> s="0123456"
>>> s[0:]
'0123456'
>>> s[0]
'0'
>>> s[2]
'2'
>>> s[s[0]:s[2]]
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
s[s[0]:s[2]]
TypeError: slice indices must be integers or None or have an __index__ method
>>> s[int(s[0]):int(s[2])]
'01'
>>> s="abcdefg"
>>> x=2
>>> s[x]
'c'
>>> s[x,x+1]
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
s[x,x+1]
TypeError: string indices must be integers
>>> s[x]
'c'
>>> s[x,x+1]
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
s[x,x+1]
TypeError: string indices must be integers
>>> s[x]
'c'
>>> s[2,3]
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
s[2,3]
TypeError: string indices must be integers
>>> s[x,abs(x-2)]
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
s[x,abs(x-2)]
TypeError: string indices must be integers
>>> abs(-1)
1
>>> s="abcdefg"
>>> s[0]
'a'
>>> s="bcdefg"
>>> s[0]
'b'
>>> s[0]="a"
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
s[0]="a"
TypeError: 'str' object does not support item assignment
>>> s[0]
'b'
>>> s="a"+s[0:]
>>> s[0]
'a'
>>> "ac" in s
False
>>> "abc" in s
True
>>> stringname.
SyntaxError: invalid syntax
>>> s.upper()
'ABCDEFG'
>>> s.isupper
<built-in method isupper of str object at 0x0000000002D84998>
>>> s.find()
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
s.find()
TypeError: find() takes at least 1 argument (0 given)
>>> s.lower()
'abcdefg'
>>> s.isupper()
False
>>> s.islower()
True
>>> s.find()
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
s.find()
TypeError: find() takes at least 1 argument (0 given)
>>> s=" abc def"
>>> s.strip('')
' abc def'
>>> s.strip(" ")
'abc def'
>>> s.strip("")
' abc def'
>>> s="xxxabc xxxdef"
>>> s.strip("x")
'abc xxxdef'
>>> s="abcde"
>>> s.find("b")
1
>>> s.find("ec")
-1
>>> s.find("da")
-1
>>> s="abcdef"
>>> s.find("da")
-1
>>> print "This string has a %d in it" % 4
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("This string has a %d in it" % 4)?
>>> print "This string has a %d in it"%4
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("This string has a %d in it"%4)?
>>> print ("This string has a %d in it" % 4)
This string has a 4 in it
>>> s="abcd"
>>> "a" in s
True
>>> "cd\n" in s
False
>>> "cd" in s
True
>>> s="abc"
>>> upper(s)
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
upper(s)
NameError: name 'upper' is not defined
>>> s.upper(s)
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
s.upper(s)
TypeError: upper() takes no arguments (1 given)
>>> s.upper()
'ABC'
>>> s="ABC"
>>> upper(s)
Traceback (most recent call last):
File "<pyshell#75>", line 1, in <module>
upper(s)
NameError: name 'upper' is not defined
>>> s.isupper
<built-in method isupper of str object at 0x0000000001D6DE68>
>>> s.isupper()
True
>>> upper(s)
Traceback (most recent call last):
File "<pyshell#78>", line 1, in <module>
upper(s)
NameError: name 'upper' is not defined
>>> s.isupper()
True
>>> upper(s)
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
upper(s)
NameError: name 'upper' is not defined
>>> print "你好,世界"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("你好,世界")?
>>> "你好,世界"
KeyboardInterrupt
>>> s="你好,世界"
>>> print (s)
你好,世界
>>> print("你好,世界")
你好,世界
>>>
KeyboardInterrupt
>>> print("hello");print("world")
hello
world
>>> days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
>>> print (days)
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
>>> s="abcd"
>>> s[0]
'a'
>>> s[-0]
'a'
>>> s[-0]
'a'
>>> s="hello,world"
>>> s[4,7]
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
s[4,7]
TypeError: string indices must be integers
>>> s[4:7]
'o,w'
>>> s[2]
'l'
>>> s[1,2]
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
s[1,2]
TypeError: string indices must be integers
>>> s="abcdef"
>>> x=2
>>> s[x]
'c'
>>> s[x,x+1]
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
s[x,x+1]
TypeError: string indices must be integers
>>> len([1,2,3,4,5])
5
>>> [1,2]+[5,6,8]
[1, 2, 5, 6, 8]
>>> ["HI!"]*8
['HI!', 'HI!', 'HI!', 'HI!', 'HI!', 'HI!', 'HI!', 'HI!']
>>> L=[1,2,3,4,5]
>>> L[2]
3
>>> max(L)
5
>>> min(L)
1
>>> list.append(10)
Traceback (most recent call last):
File "<pyshell#109>", line 1, in <module>
list.append(10)
TypeError: descriptor 'append' requires a 'list' object but received a 'int'
>>> list.append("10")
Traceback (most recent call last):
File "<pyshell#110>", line 1, in <module>
list.append("10")
TypeError: descriptor 'append' requires a 'list' object but received a 'str'
>>> list.append(list[10,11])
Traceback (most recent call last):
File "<pyshell#111>", line 1, in <module>
list.append(list[10,11])
TypeError: 'type' object is not subscriptable
>>> tup(1,2,3,4,5)
Traceback (most recent call last):
File "<pyshell#112>", line 1, in <module>
tup(1,2,3,4,5)
NameError: name 'tup' is not defined
>>> tup=(1,2,3,4,5)
>>> tup[0]
1
>>> tup=(0,3,6,7,9,4)
>>> min(tup)
0
>>> max(tup)
9
>>> mid(tup)
Traceback (most recent call last):
File "<pyshell#118>", line 1, in <module>
mid(tup)
NameError: name 'mid' is not defined
>>> cmp(tup2,tup4)
Traceback (most recent call last):
File "<pyshell#119>", line 1, in <module>
cmp(tup2,tup4)
NameError: name 'cmp' is not defined
>>> len(tup)
6
>>> tuple(seq)
Traceback (most recent call last):
File "<pyshell#121>", line 1, in <module>
tuple(seq)
NameError: name 'seq' is not defined
>>> x=[1,2,3,4]
>>> x.reverse()
>>> print(x)
[4, 3, 2, 1]
>>> x.pop()
1
>>> x
[4, 3, 2]
>>> x=[1,2,3,4,5]
>>> x
[1, 2, 3, 4, 5]
>>> x.insert(1,5)
>>> x
[1, 5, 2, 3, 4, 5]
>>> x.insert(1,5)
>>> x
[1, 5, 5, 2, 3, 4, 5]
>>> x.insert(5,9)
>>> x
[1, 5, 5, 2, 3, 9, 4, 5]
>>> x.append(6)
>>> x
[1, 5, 5, 2, 3, 9, 4, 5, 6]
>>> x.count(5)
3
>>> x.reverse()
>>>
>>> x
[6, 5, 4, 9, 3, 2, 5, 5, 1]
>>> x
[6, 5, 4, 9, 3, 2, 5, 5, 1]
>>> x.remove(5)
>>> x
[6, 4, 9, 3, 2, 5, 5, 1]
>>> x.remove(5)
>>> x
[6, 4, 9, 3, 2, 5, 1]
>>> x=[a,b,c,d]
Traceback (most recent call last):
File "<pyshell#146>", line 1, in <module>
x=[a,b,c,d]
NameError: name 'a' is not defined
>>> a=1
>>> b=2
>>> c=3
>>> d=4
>>> x=[a,b,c,d]
>>> x
[1, 2, 3, 4]
>>> x=[]
>>> x
[]
>>> x.append(5)
>>> x
[5]
>>> x=[]
>>> x
[]
>>> x.count()
Traceback (most recent call last):
File "<pyshell#159>", line 1, in <module>
x.count()
TypeError: count() takes exactly one argument (0 given)
>>> x.count(1)
0
>>> if '':
print "False"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("False")?
>>> if '':
print ("False")
else:
SyntaxError: unindent does not match any outer indentation level
>>> if '':
print"True"
SyntaxError: invalid syntax
>>> if '' :
print "false"
else:
print "true“
SyntaxError: expected an indented block
>>> if '' :
print "false"
else:
print "true“
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("false")?
>>> if '' :
print (false)
else:
print (true)
Traceback (most recent call last):
File "<pyshell#171>", line 4, in <module>
print (true)
NameError: name 'true' is not defined
>>> if '' :
print ("false")
else:
print ("true“)
SyntaxError: EOL while scanning string literal
>>> x=[1,2,3,4,5]
>>> x[4]=9
>>> x
[1, 2, 3, 4, 9]
>>> x[2]=8
>>> x
[1, 2, 8, 4, 9]
>>>
KeyboardInterrupt
>>>
>>> s=[1,2,3,4,5]
>>> s
[1, 2, 3, 4, 5]
>>> s.join(list)
Traceback (most recent call last):
File "<pyshell#181>", line 1, in <module>
s.join(list)
AttributeError: 'list' object has no attribute 'join'
>>> L=[1,2,3,4,5]
>>> L
[1, 2, 3, 4, 5]
>>> s.join(L)
Traceback (most recent call last):
File "<pyshell#184>", line 1, in <module>
s.join(L)
AttributeError: 'list' object has no attribute 'join'
>>> l=["one","two","three"]
>>> l
['one', 'two', 'three']
>>> ",",join
Traceback (most recent call last):
File "<pyshell#187>", line 1, in <module>
",",join
NameError: name 'join' is not defined
>>> ",",join(l)
Traceback (most recent call last):
File "<pyshell#188>", line 1, in <module>
",",join(l)
NameError: name 'join' is not defined
>>> ",",join(l)
Traceback (most recent call last):
File "<pyshell#189>", line 1, in <module>
",",join(l)
NameError: name 'join' is not defined
>>> l=["one","two","three"]
>>> l
['one', 'two', 'three']
>>> ",,,",join(l)
Traceback (most recent call last):
File "<pyshell#192>", line 1, in <module>
",,,",join(l)
NameError: name 'join' is not defined
>>>
|
bf22fc065590d309dd2242c26be3585ca16b3c46 | googlewaitme/oneloveonventi | /bd.py | 2,639 | 3.59375 | 4 | """
Вся работа с БД будет тут
"""
import sqlite3
class BD:
def __init__(self, name_bd="mybd.sqlite"):
""" инитиализация курсора и бд"""
self.conn = sqlite3.connect(name_bd)
self.cursor = self.conn.cursor()
def create_tables(self):
""" Creating new base of date"""
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS details
(id, name_detail, type)
""")
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS drons
(id, name_dron, cost)
""")
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS dron_map
(id, name, detail, count_detail)
""")
self.conn.commit()
return True
def insert_in_tables(self, details_table=[], drons_table=[], dron_map=[]):
details_table = self.filter_details_table(details_table)
self.cursor.executemany("INSERT INTO details VALUES (?,?,?)", details_table)
self.conn.commit()
self.cursor.executemany("INSERT INTO drons VALUES (?,?,?)", drons_table)
self.conn.commit()
self.cursor.executemany("INSERT INTO dron_map VALUES (?,?,?,?)", dron_map)
self.conn.commit()
def filter_details_table(self, details_table):
"""
фильтрует детали для бд
:param details_table:
:return: ([list for table], [лист ошибок почему вида : строка 23 не записана в бд,
так как содержится буква в числе])
"""
index_line = 1
for detail in details_table:
detail[0]
def filter_drons_table(self, drons_table):
"""
фильтрует drons для бд
:param drons_table:
:return: ([list for table], [лист ошибок почему вида : строка 23 не записана в бд,
так как содержится буква в числе])
"""
pass
def filter_dron_map(self, dron_map):
"""
фильтрует детали для бд
:param dron_map:
:return: ([list for table], [лист ошибок почему вида : строка 23 не записана в бд,
так как содержится буква в числе])
"""
pass
def test_bd():
# Тестовые данные
details_table = [
(1, 'detail1', 'batter'),
(2, 'detail2', 'batter'),
(3, 'dateil3', 'other')
]
drons_table = [
(1, 'dron1', 100),
(2, 'dron2', 300)
]
dron_map = [
(1, 'dron1', 'detail1', 23),
(1, 'dron1', 'detail2', 2),
(2, 'dron2', 'detail1', 1),
(2, 'dron2', 'detail2', 345)
]
bd = BD()
bd.create_tables()
bd.insert_in_tables(drons_table=drons_table,
dron_map=dron_map,
details_table=details_table)
|
f9842fc629fd79343b70d8d7ba8fc555d7119cbf | as-segaf/python | /OOP/class-object.py | 1,136 | 4.21875 | 4 | #!/usr/bin/python3
class employee:
'common base class for all employees'
empCount = 0
def __init__(self, name, salary): # read about 'self' in w3schools.com, it's easier to understand
self.nama = name
self.gaji = salary
employee.empCount += 1
def displayCount(tes):
print("Total employee:", tes.empCount)
def displayEmployee(var):
print('name:',var.nama, ', salary:', var.gaji)
emp1 = employee('bambang', 10000) # This would create first object of employee class
emp2 = employee('agus', 20000) # This would create second object of employee class
print(emp1.empCount)
print(emp1.gaji)
print(emp1.nama)
emp1.displayCount()
emp2.displayEmployee()
emp1.gaji = 5000 # Modify 'gaji' attribute
emp1.umur = 20 # Add 'umur' attribute
del emp1.gaji # Delete 'gaji' attribute in emp1
hasattr(emp1, 'salary') # Returns true if 'salary' attribute exists
getattr(emp1, 'salary') # Returns value of 'salary' attribute
setattr(emp1, 'salary', 7000) # Set attribute 'salary' at 7000
delattr(emp1, 'salary') # Delete attribute 'salary'
|
244d3cb9086eee028ea0b2281362d16a849f7024 | AckersonC/CPython | /Elif.py | 357 | 3.875 | 4 | deposit = float(input("Please enter the ammount of your deposit >>> "))
if deposit < 50 :
print ("Hooray, you get a free gift card!")
elif deposit < 100 :
print ("Hooray, you get a free toaster!")
elif deposit < 200 :
print ("Hooray, you get a free TV")
elif deposit > 200 :
print ("Hooray, you get a free TV!")
print ("Have a nice day!") |
93c8cf8204c919afccca1f1fc44d78d5fab0cdcc | niteesh2268/coding-prepation | /leetcode/Problems/36--Valid-Sudoku-Medium.py | 1,103 | 3.546875 | 4 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = collections.defaultdict(list)
columns = collections.defaultdict(list)
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
else:
rows[i].append(board[i][j])
columns[j].append(board[i][j])
values = []
for i in (0, 3, 6):
for j in (0, 3, 6):
entry = []
for k in range(i, i+3):
for l in range(j, j+3):
if board[k][l] != '.':
entry.append(board[k][l])
values.append(entry)
for entry in rows.values():
if len(set(entry)) != len(entry):
return False
for entry in columns.values():
if len(set(entry)) != len(entry):
return False
for entry in values:
if len(set(entry)) != len(entry):
return False
return True |
0abff1690f093027f7bb8cc9c72b5af324444a1b | Abhi4899/data-structures-and-algorithms | /python practice/factorial.py | 143 | 3.9375 | 4 | def fact(x):
if x==1:
return x
return x*fact(x-1)
n=int(input('Enter a number\n'))
print('{}! = {}'.format(n,fact(n)))
|
a60513be6c7f4ca9c7c450fc0cfaf79e47e7e7fb | Jeandcc/CS50 | /pset6/Credit/credit.py | 786 | 3.6875 | 4 | import cs50
cCardStr = str(cs50.get_int("Number: "))
def checksum(string):
digits = list(map(int, string))
odd_sum = sum(digits[-1::-2])
even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])
return (odd_sum + even_sum) % 10
def verify(string):
return (checksum(string) == 0)
if not verify(cCardStr):
print("INVALID")
exit()
isAmex = False
isMastercard = False
isVisa = False
first2Digits = int(cCardStr[:2])
if first2Digits == 34 or first2Digits == 37:
isAmex = True
if first2Digits >= 51 and first2Digits <= 55:
isMastercard = True
if first2Digits >= 40 and first2Digits <= 49:
isVisa = True
if (isAmex):
print("AMEX")
if (isMastercard):
print("MASTERCARD")
if (isVisa):
print("VISA")
else:
print("INVALID")
|
8f85990e6548c2c520aae2c24be958cee5907a46 | Sam-G-23/Python-class2020 | /string_functions.py | 650 | 4.25 | 4 | """
program: string_functions.py
Sam Goode
sgoode1@dmacc.edu
6/13/2020
The purpose of this program to to calculate a users input so that they can determine their hourly wage
"""
def multiply_string():
"""
:param string_multiplier: represents the string used to multiply as 'message'
:param n: represents the number 3
:return: the mathematical operation as multi
"""
n = int(input("Please input an integer: "))
string_multiplier = 'message'
multi = n * string_multiplier
return multi
if __name__ == '__main__':
print(multiply_string())
# Everything seems to be working perfectly with no issues
|
5fa10bd2d0fd5feeac017c3379b9bb529862427f | obemauricio/Algoritmos_python | /aprox_soluciones.py | 328 | 4.125 | 4 | target = int(input('Choose a number: '))
epsilon = 0.01
step = epsilon**2
answer = 0.0
while abs(answer**2 - target) >= epsilon and answer <= target:
print(answer)
answer += step
if abs(answer**2 - target) >= epsilon:
print(f'{target} square root not found')
else:
print(f'Square root of {target} is {answer}') |
c59e148abaf79dee76e2c0eef5fc989d1a1db44e | gidandm/checkio | /Median.py | 520 | 3.703125 | 4 | # -*- coding: utf-8 -*-
def checkio(data):
data.sort()
length = len(data)
half = length//2
if (length % 2) != 0:
mediana = data[half]
else:
mediana = (data[(half)-1] + data[(half)])/2
return mediana
# BEST
# off = len(data) // 2
# data.sort()
# med = data[off] + data[-(off + 1)]
# return med / 2
if __name__ == '__main__':
print(checkio([1, 2, 3, 4, 5]))
print(checkio([3, 1, 2, 5, 3]))
print(checkio([1, 300, 2, 200, 1]))
print(checkio([3, 6, 20, 99, 10, 15]))
|
b325f39b89b421e5edeb1472b494f471081d1327 | danilocamus/curso-em-video-python | /aula 16/desafio 074.py | 428 | 3.84375 | 4 | from random import randint
num = randint(1, 10), randint(1, 10), randint(1,10), randint(1, 10), randint(1, 10)
print('Os valores spteados foram: ')
for n in num:
print(f'{n} ', end='')
maior = sorted(num)
menor = sorted(num)
print(f'\nO maior número sorteado é {maior[4]}\nO menor número sorteado é {menor[0]}')
#print(f'O maior valor sorteado foi {max(num)}')
#print(f'O menor valor sorteado foi {min(num)}') |
d91936546e575c5b3daa3c20061d2541d379dc3b | AMJefford/Simulation-and-Chemistry-System | /Student File.py | 25,676 | 3.5625 | 4 | from tkinter import *
import tkinter.messagebox as tm
import sqlite3
import array
import string
import DatabaseKey
from cryptography.fernet import Fernet
from Simulation import *
import random
import time
class Login:
def __init__(self, root):
self.__UsernameE = Entry(root)
self.__PasswordE = Entry(root,show = "*")
self.CreateDisplay()
def CreateDisplay(self):
UsernameL = Label(root,text = "Username").grid(row = 0, padx = 5)
PasswordL = Label(root,text = "Password").grid(row = 1, padx = 5)
self.__UsernameE.grid(row = 0, column = 1)
self.__PasswordE.grid(row = 1, column = 1)
root.minsize(width = 250,height = 80)
Button(text = "Login", command = self.ButtonClicked).grid(column = 2, pady = 5)
def ButtonClicked(self):
Username = self.__UsernameE.get()
Password = self.__PasswordE.get()
Database.CheckCreds(Username,Password)
class Main(object):
def __init__(self, StudentSetClass, StudentFN, Username):
self.__StudentSN = Username[1:]
self.__Class = StudentSetClass
self.__StudentFN = StudentFN
print(self.__StudentFN)
Main.MainWindow(self)
def MainWindow(self):
Window = Toplevel(root)
OnlineHomework = Label(Window, text = "Online Homework", font = ("Georgia", 20),bg = "#E59866", fg = "white").grid(sticky = N+S+E+W)
Description = Label(Window, bg = "white", text = '''Hello! Welcome to the self marking homework system! This program will allow your
homework to be automatically marked upon completion. \nMeaning you wont have to wait for a result or feedback!''').grid(padx = 20, pady = 5)
Window["bg"] = "white"
Window.title("Home")
Window.resizable(height = False, width = False)
GoToHomework = Button(Window, text = "Check To-Do Homework", command = lambda: ToCompleteClass(self.__Class, self.__StudentSN, self.__StudentFN))
GoToHomework.grid(padx = 300, pady = 5, sticky = N+E+S+W)
PreviousHomework = Button(Window, text = "Check Previous Homework", command = lambda: PreviousHomeworkClass(self.__Class, self.__StudentSN, self.__StudentFN))
PreviousHomework.grid(padx = 300, pady = 5, sticky = N+E+S+W)
SimulationButton = Button(Window, text = "Go To Simulation", command = lambda: Simulation.RunSimulation())
SimulationButton.grid(padx = 300, pady = 5, sticky = N+E+S+W)
menuBar = Menu(Window)
Window.winfo_toplevel()['menu'] = menuBar
file = Menu(menuBar)
file.add_command(label = 'Log Out', command = Window.destroy)
file.add_command(label = 'Help', command = Main.Help)
menuBar.add_cascade(label = "File", menu = file)
def Help():
Window = Toplevel(root)
Info = Text(Window, height = 30, width = 100)
Info.pack()
Info.insert(END,'''HELP:
This program is intended for acedemic purposes. In the main menu you will find three options:
Check To-Do Homework
Check Previous Homework
Go To Simulation
Check To-Do Homework:
Here you will be presented with any live homework set by your teachers that you have yet to
complete. Upon selection, you will be presented with a series of questions that have been set for
you where you can either type of select your answer. Once the series of questions have been
completed, you will be presented with a new page displaying your score, and the questions you got
correct/incorrect, along with the correct answer. Your scores and answers will then be available to
view by your teachers.
Check Previous Homework:
Selecting this option will allow you to view any homework that you have completed before. A list of your previous homework will be shown where you can then select an option to view the questions
and answers to the homework, along with your score.
Go To Simulation:
The simulation is a classic PV=nRT simulation whereby you can alter the conditions to view the
effects. You have three conditions to change: temperature, volume, and number of moles. To gradually
change a condition, click either the green (increase) or red (decrease) button. To view the effect
more quickly, hold down the chosen button.
If there is any further help required, please email:
help@system.co.uk ''')
class ToCompleteClass(object):
def __init__(self, StudentSetClass, StudentSN, StudentFN):
self.__Class = StudentSetClass
self.__StudentFN = StudentFN
self.__StudentSN = StudentSN
self.__ListofButtons = []
self.__HomeworkData = []
self.SelectHomework()
def SelectHomework(self):
Window = Toplevel(root)
Window.title("Select a homework to complete.")
ListOfHomeworks = []
try:
HomeworkFile = open("Live Homework.txt","r")
except FileNotFoundError:
tm.showinfo("File Error.", "Can Not Find File.")
Window.withdraw()
return
for line in HomeworkFile:
line = (line.strip("\n")).split(",")
self.__HomeworkData.append(line)
HomeworkFile.close()
Info1 = Label(Window, text = "You have no homework to complete!")
Info = Label(Window, text = "Select one of the following homework to complete:")
if len(self.__HomeworkData) == 0:
Info1.grid()
else:
Info.grid()
def DetermineSelection(button):
ButtonText = button['text']
CompletedList = []
QuestionData = []
Text = ButtonText.split("-")
self.__HomeworkSelection = Text[0].strip(" ")
Window.destroy()
print(self.__HomeworkSelection)
self.LiveHomework(0, 0, CompletedList, QuestionData)
def PrintOptions():
try:
CompletedHomework = open("Completed Homework.txt", "r")
except FileNotFoundError:
tm.showinfo("File Error.", "Completed Homework File Not Found.")
Window.withdraw()
return
CompletedHomework = CompletedHomework.readlines()
StudentsCompletedHomework = []
for X in range(len(CompletedHomework)):
StudentsCompleted = str(CompletedHomework[X]).split(",")
StudentCompletedHWID = str(StudentsCompleted[1]).strip("\n")
if StudentsCompleted[0] == (self.__StudentFN + " " + self.__StudentSN):
StudentsCompletedHomework.append(StudentCompletedHWID)
for Y in range(len(self.__HomeworkData)):
if self.__HomeworkData[Y][8] == self.__Class and self.__HomeworkData[Y][9] not in ListOfHomeworks and self.__HomeworkData[Y][9] not in StudentsCompletedHomework:
HomeworkInfo = str(self.__HomeworkData[Y][9]) + " - " + str(self.__HomeworkData[Y][2]) + " -" + str(self.__HomeworkData[Y][3])
Button1 = Button(Window, text = HomeworkInfo)
Button1.configure(command = lambda button = Button1: DetermineSelection(button))
Button1.grid(sticky = N+E+W+S)
self.__ListofButtons.append(Button1)
ListOfHomeworks.append(self.__HomeworkData[Y][9])
if not ListOfHomeworks:
Info1.grid()
Info.destroy()
PrintOptions()
def LiveHomework(self, Y, Score, CompletedList, QuestionData):
self.__HomeworkData = []
try:
HomeworkFile = open("Live Homework.txt","r")
except FileNotFoundError:
tm.showinfo("File Error.","Live Homework File Not Found.")
return
for line in HomeworkFile:
line = (line.strip("\n")).split(",")
self.__HomeworkData.append(line)
HomeworkFile.close()
if Y+1 <= len(self.__HomeworkData):
QuestionText = self.__HomeworkData[Y][0]
self.__MCAnswers = []
if self.__HomeworkData[Y][4] == "MC":
self.__MCAnswers.append(self.__HomeworkData[Y][5])
self.__MCAnswers.append(self.__HomeworkData[Y][6])
self.__MCAnswers.append(self.__HomeworkData[Y][7])
self.__MCAnswers.append(self.__HomeworkData[Y][1])
self.__CorrectAnswer = self.__HomeworkData[Y][1]
random.shuffle(self.__MCAnswers)
else:
self.WriteScoretoFile(Score, CompletedList, QuestionData, Y)
return
if self.__HomeworkData[Y][8] == self.__Class and self.__HomeworkData[Y][9] == self.__HomeworkSelection:
self.__Unit = self.__HomeworkData[Y][2]
self.__Topic = self.__HomeworkData[Y][3]
print(self.__Topic)
print(self.__Unit)
NewWindow = Toplevel(root)
NewWindow.title("Homework.")
NewWindow.geometry("+200+200")
NewWindow["bg"] = "#ffffff"
NewWindow.resizable(width = False, height = False)
QuestionData.append(self.__HomeworkData[Y])
NewWindow.title("Get Homework")
var = StringVar()
var.set("Label")
label = Label(NewWindow, text = QuestionText, bg = "#ffffff").grid(columnspan = 2, pady = 5, row = 0, column = 0, sticky = N+E+S+W)
self.v = IntVar()
self.v.set(0)
if self.__MCAnswers:
for val in range(len(self.__MCAnswers)):
UserChoiceMC = Radiobutton(NewWindow,
indicatoron = False,
text = self.__MCAnswers[val],
tristatevalue = "x",
padx = 20,
variable = self.v, value = val).grid(sticky = N+E+S+W, columnspan = 2)
else:
self.AnswerBox = Entry(NewWindow)
self.AnswerBox.grid(columnspan = 2, sticky = N+E+S+W)
NextButton = Button(NewWindow, text = "Confirm Answer",command = lambda: self.Confirm(NewWindow, Y, Score,
CompletedList, QuestionData)).grid(padx = 20, pady = 20, row = 10, column = 1, sticky = E)
else:
self.LiveHomework(Y+1, Score, CompletedList, QuestionData)
def Confirm(self, NewWindow, Y, Score, CompletedList, QuestionData):
Correct = False
KeyAnswer = ""
KeyWords = []
print(self.__HomeworkData[Y][4])
if self.__HomeworkData[Y][4] == 'MC':
UserAnswer = self.v.get()
UserAns = (self.__MCAnswers[UserAnswer])
CompletedUsersAnswer = UserAns
if UserAns == self.__CorrectAnswer:
Score += 1
Correct = True
elif self.__HomeworkData[Y][4] == 'Not MC':
UserAnswer = self.AnswerBox.get()
WordsIn = 0
if "/" in self.__HomeworkData[Y][1]:
KeyWords = ((self.__HomeworkData[Y][1]).lower()).split("/")
elif " " in self.__HomeworkData[Y][1]:
KeyWords = ((self.__HomeworkData[Y][1]).lower()).split(" ")
else:
KeyAnswer = (self.__HomeworkData[Y][1]).lower()
UserAnswer = UserAnswer.split(" ")
CompletedUsersAnswer = self.AnswerBox.get()
for x in range(len(UserAnswer)):
if UserAnswer[x].lower() in KeyWords:
WordsIn += 1
if WordsIn >= 3 or UserAnswer[x] == KeyAnswer:
Score += 1
Correct = True
Answer = [CompletedUsersAnswer, str(Correct) ,self.__HomeworkData[Y][4] , self.__HomeworkData[Y][0], self.__HomeworkData[Y][1]]
CompletedList.append(Answer)
NewWindow.destroy()
self.LiveHomework(Y+1, Score, CompletedList, QuestionData)
def WriteScoretoFile(self, Score, CompletedList, QuestionData, Y):
try:
StudentScoreFile = open("Student Scores File.txt", "a")
except FileNotFoundError:
tm.showinfo("File Error.", "Can Not Save Score.")
return
StudentScoreFile.write(self.__StudentFN + " " + self.__StudentSN + "," + str(Score) +"," + self.__Class + "," + self.__HomeworkSelection + "\n")
StudentScoreFile.close()
try:
CompletedHomework = open("Completed Homework.txt","a")
except FileNotFoundError:
tm.showinfo("File Error.","Can Not Save Progress.")
return
CompletedHomework.write(self.__StudentFN + " " + self.__StudentSN + "," + self.__HomeworkSelection + "\n")
CompletedHomework.close()
try:
PreviousHomework = open("Previous Homework.txt", "a")
except FileNotFoundError:
tm.showinfo("File Error.","Previous Homework File Not Found.")
return
CrucialInfo = "," + self.__StudentFN + " " + self.__StudentSN + "," + self.__HomeworkSelection + "," + str(Score) + "," + self.__Unit + "," + self.__Topic
for X in range(len(CompletedList)):
NoExcess = str.maketrans("", "", "[]''")
print(CompletedList[X])
Pure = ((str(CompletedList[X])).translate(NoExcess))
PreviousHomework.write(Pure)
PreviousHomework.write(CrucialInfo)
PreviousHomework.write("\n")
PreviousHomework.close()
self.CompletedScreen(CompletedList, QuestionData, Score)
def CompletedScreen(self, CompletedList, QuestionData, Score):
Window = Toplevel(root)
Window.geometry("600x600")#mass e, prot mg, lig, similar?
Window.title("Results.")#ligand complex
def Data(CompletedList, QuestionData, Score):
Congratulations = str("Your score: ") + str(Score)
Label(frame, text = Congratulations).grid()
for x in range(len(CompletedList)):
Label(frame, text = (CompletedList[x][3]).capitalize()).grid()
if CompletedList[x][1] == 'True':
Label(frame, text = "Your answer was correct: ").grid()
Label(frame, text = CompletedList[x][0]).grid()
else:
Label(frame, text = "Your answer was: ").grid()
Label(frame, text = CompletedList[x][0]).grid()
if CompletedList[x][2] == "MC":
Label(frame, text = "Correct answer: ").grid()
Label(frame, text = CompletedList[x][4]).grid()
else:
Label(frame, text = "Your answer must include at least 3 of the below key words: ").grid()
Label(frame, text = CompletedList[x][4]).grid()
Label(frame, text = "\n").grid()
def ChangeScroll(event):
self.Canvas.configure(scrollregion = self.Canvas.bbox("all"), width = 550, height = 550)
MyFrame=Frame(Window, relief = GROOVE, width = 550, height = 550, bd = 1)
MyFrame.place(x = 10,y = 10)
self.Canvas = Canvas(MyFrame)
frame = Frame(self.Canvas)
myscrollbar = Scrollbar(MyFrame, orient = "vertical",command = self.Canvas.yview)
self.Canvas.configure(yscrollcommand = myscrollbar.set)
myscrollbar.pack(side = "right",fill = "y")
self.Canvas.pack(side = "left")
self.Canvas.create_window((200,200), window = frame, anchor = 'nw')
frame.bind("<Configure>",ChangeScroll)
Data(CompletedList, QuestionData, Score)
class PreviousHomeworkClass(object):
def __init__(self, Class, StudentSurname, StudentFN):
self.__Class = Class
self.__StudentSN = StudentSurname
self.__StudentFN = StudentFN
self.PresentData()
def PresentData(self):
try:
PreviousHwResults = open("Previous Homework.txt", "r")
except FileNotFoundError:
tm.showinfo("File Error","Previous Homework File Not Found.")
return
PreviousHwResults = PreviousHwResults.readlines()
if not PreviousHwResults:
tm.showinfo("None.", "There are no completed homeworks.")
return
Window = Toplevel(root)
Window.geometry("650x270")
Window.title("Previous Homework.")
def ChangeScroll(event):
self.Canvas.configure(scrollregion = self.Canvas.bbox("all"))
MyFrame = Frame(Window, relief = GROOVE, bd = 1)
MyFrame.place(x = 10,y = 10)
self.Canvas = Canvas(MyFrame)
self.__Frame = Frame(self.Canvas)
myscrollbar = Scrollbar(MyFrame, orient = "vertical", command = self.Canvas.yview)
hscrollbar = Scrollbar(MyFrame, orient = "horizontal", command = self.Canvas.xview)
self.Canvas.configure(yscrollcommand = myscrollbar.set)
self.Canvas.configure(xscrollcommand = hscrollbar.set)
hscrollbar.pack(fill = "x")
myscrollbar.pack(side = "right",fill = "y")
self.Canvas.pack(side = "left")
IDS = []
self.__StudentData = []
if len(PreviousHwResults) == 0:
Label(self.__Frame, text = "There are no completed homeworks yet!").grid()
else:
def ViewPreAnswers(button):
def ChangeScroll2(event):
self.Canvas2.configure(scrollregion = self.Canvas2.bbox("all"))
Window = Toplevel(root)
Window.title("Previous Homework.")
Window.geometry("530x230")
MyFrame2 = Frame(Window,relief = GROOVE,bd = 1)
MyFrame2.place(x = 10,y = 10)
self.Canvas2 = Canvas(MyFrame2, width = 500, height = 200)
self.__Frame = Frame(self.Canvas2)
myscrollbar = Scrollbar(MyFrame2,orient = "vertical",command = self.Canvas2.yview)
hscrollbar = Scrollbar(MyFrame2, orient = "horizontal", command = self.Canvas2.xview)
self.Canvas2.configure(xscrollcommand = hscrollbar.set)
self.Canvas2.configure(yscrollcommand = myscrollbar.set)
hscrollbar.pack(fill = "x")
myscrollbar.pack(side = "right",fill = "y")
self.Canvas2.pack(side = "left")
self.Canvas2.create_window((0,0),window = self.__Frame,anchor = 'nw')
ButtonText = button['text']
Text = ButtonText.split(":")
HomeworkID = Text[1]
Label(self.__Frame, text = "Question").grid(row = 0, sticky = W, padx = 5, pady = 5)
Label(self.__Frame, text = "Answer/Key Words").grid(row = 0, column = 1, sticky = W, padx = 5, pady = 5)
Label(self.__Frame, text = "Your answer").grid(row = 0, column = 2, sticky = W, padx = 5, pady = 5)
for x in range(len(self.__StudentData)):
if self.__StudentData[x][6] == HomeworkID:#0 = user ans, 1 = if correct, 2 = mc, 3 = question, 4 = acc answer, 5 = name, 6 = id, 7 = score
Label(self.__Frame, text = self.__StudentData[x][3]).grid(row = x + 2, sticky = W, padx = 5, pady = 5)#question
Label(self.__Frame, text = self.__StudentData[x][4]).grid(row = x + 2, sticky = W, column = 1, padx = 5, pady = 5)#acc answer
Label(self.__Frame, text = self.__StudentData[x][0]).grid(row = x + 2, column = 2, sticky = W, padx = 5, pady = 5)
self.__Frame.bind("<Configure>", ChangeScroll2)
def PrintOptions():
Label(self.Canvas, text = "HomeworkID").grid(row = 0, sticky = W, padx = 5, pady = 5)
Label(self.Canvas, text = "Score").grid(column = 1, row = 0, sticky = W, padx = 5, pady = 5)
Label(self.Canvas, text = "Unit").grid(column = 2, row = 0, sticky = W, padx = 5, pady = 5)
Label(self.Canvas, text = "Topic").grid(column = 3, row = 0, sticky = W, padx = 5, pady = 5)
for line in range(len(PreviousHwResults)):
p = (PreviousHwResults[line])
l = p.split(",")
ID = l[6]
if l[5] == self.__StudentFN + " " + self.__StudentSN:
self.__StudentData.append(l)
if ID not in IDS:
Label(self.Canvas, text = l[8]).grid(row = line + 1, sticky = W, column = 2, pady = 5)
IDS.append(ID)
Label(self.Canvas, text = l[6]).grid(row = line + 1, column = 0, sticky = W, padx = 5, pady = 5)#id
Label(self.Canvas, text = l[7]).grid(row = line + 1, column = 1, sticky = W, padx = 5, pady = 5)#score[8][9]
Label(self.Canvas, text = l[9].strip("\n")).grid(row = line + 1, column = 3, sticky = W, pady = 5, padx = 5)
Info = "View Answers to ID:" + str(ID)
ButtonID = Button(self.Canvas, text = Info)
ButtonID.configure(command = lambda button = ButtonID: ViewPreAnswers(button))
ButtonID.grid(sticky = W, column = 4, row = line + 1, padx = 5, pady = 5)
print(self.__StudentData)
print("here")
if not self.__StudentData:
Label(self.Canvas, text = "You have no completed homework yet.").grid()
PrintOptions()
self.__Frame.bind("<Configure>", ChangeScroll)
class Database:
def CheckCreds(Username,Password):
conn=sqlite3.connect('OnlineHomework.db', timeout = 1)
c=conn.cursor()
Cipher_Suite = Fernet(DatabaseKey.key)
StudentUsername = []
StudentPassword = []
StudentFN = []
StudentClass = []
c.execute("SELECT * FROM StudentLogin;")
for column in c:
StudentClass.append(column[4])
StudentFN.append(column[0])
c.execute("SELECT Username FROM StudentLogin;")
for column in c:
StudentUsername.append(column[0])
c.execute("SELECT Password FROM StudentLogin;")
for column in c:
UncipheredText = Cipher_Suite.decrypt(column[-1])
PlainText = (bytes(UncipheredText).decode("utf-8"))
StudentPassword.append(PlainText)
if Username in StudentUsername:
Correct = int(StudentUsername.index(Username))
StudentFN = StudentFN[(StudentUsername.index(Username))]
if str(Password) == StudentPassword[Correct]:
tm.showinfo("Login info", "Welcome " + Username)
StudentSetClass = StudentClass[(StudentUsername.index(Username))]
root.withdraw()
Main(StudentSetClass, StudentFN, Username)
else:
tm.showerror("Login error", "Incorrect Username or Password. Please try again.")
else:
tm.showerror("Login error", "Incorrect Username or Password. Please try again.")
print(StudentUsername)
print(StudentClass)
print(StudentFN)
print(StudentPassword)
conn.commit()
conn.close()
root = Tk()
root.resizable(width=False,height=False)
root.wm_title("Please login.")
root.minsize(width=300,height=300)
Login(root)
root.mainloop()
|
8f6abfe85a2253d0599fb519ad21ab0c36cfa5f7 | bsakers/Introduction_to_Python | /hashes.py | 1,424 | 4.71875 | 5 | #hashes are referred to as dictionaries
example_hash = {'key1' : 1, 'key2' : 2, 'key3' : 3}
print example_hash["key1"]
print example_hash["key2"]
print example_hash["key3"]
#dictionaries are mutable, meaning they can be changed (mutated) after being created. Here is adding to it
food_cart = {}
food_cart["chicken and rice"]= 5.50
food_cart["gyro"]=6.00
food_cart["cheesesteak"]= 7.00
print food_cart
menu_count= len(food_cart)
print "There are " + str(menu_count) + " items to choose from at the food cart"
#we can delete from a dictionary as well by 'del dictionary[key]'
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
del zoo_animals["Sloth"]
del zoo_animals["Bengal Tiger"]
#similar to an array, we can overwrite a key-value pair through 'dictionary['key']= new_value'
zoo_animals["Unicorn"] = "On Top of a Mountain"
print zoo_animals
#arrays and hashes can exist within one another, as expected
my_dictionary= {
"dota_heros": ["luna", "axe", "juggernaut"],
"money": 2484,
"day": "Friday"
}
#to find "juggernaut"
print my_dictionary["dota_heros"][2]
#to find 'friday'
print my_dictionary["day"]
#to find f in Friday
print my_dictionary["day"][0]
#to add 50 to money
my_dictionary['money']+= 50
#to remove axe
my_dictionary['dota_heros'].remove('axe')
|
08cbf8cc5b485e299bbc656eafd5c8da792189a6 | CristianGastonUrbina/Curso_Python | /Clase02/diccionario_geringoso.py | 782 | 4.03125 | 4 | #2.14
"""Construí una función que, a partir de una lista de palabras, devuelva un diccionario geringoso.
Las claves del diccionario deben ser las palabras de la lista y los valores deben ser sus traducciones al geringoso
(como en el Ejercicio 1.18). Probá tu función para la lista ['banana', 'manzana', 'mandarina'].
Guardá este ejercicio en un archivo diccionario_geringoso.py para entregar al final de la clase."""
def geringoso (palabra):
palabrapa = ""
for c in palabra:
palabrapa = palabrapa + c
if c == "a" or c == "e" or c == "i" or c == "o" or c == "u":
palabrapa = palabrapa + "p" + c
return palabrapa
def geringosLista(lista):
dic = {}
for i in lista:
dic[i]= geringoso(i)
return dic
print(geringosLista(['banana', 'manzana', 'mandarina']))
|
04f0807018faa05e702de4e8e3f96f7245416c72 | akshayparakh25/wikipediaInfoboxExtractorForInformationExtraction | /dump.py | 408 | 3.65625 | 4 | import csv
import pickle
def dump_dictionary(fileName, dictionaryName):
print("dumping "+fileName)
with open(fileName, 'wb') as handle:
pickle.dump(dictionaryName, handle, protocol=pickle.HIGHEST_PROTOCOL)
def dump_dictionary_csv(fileName, dictionaryName):
with open(fileName, "w+") as csv_file:
writer = csv.writer(csv_file)
for key, val in dictionaryName.items():
writer.writerow([key, val]) |
c5fbc22eca1b354b09c8f454fb7444be0f7746b2 | HarshGarg1201/Tkinter | /R-L-M_ click.py | 472 | 3.9375 | 4 | import tkinter
window = tkinter.Tk()
window.title("right-left-middle-click")
def left_click(event):
tkinter.Label(window, text = "left ckick").pack()
def middle_click(event):
tkinter.Label(window, text = "middle click").pack()
def right_click(event):
tkinter.Label(window, text = "right click").pack()
window.bind("<Button-1>", left_click)
window.bind("<Button-2>", middle_click)
window.bind("<Button-3>", right_click)
window.mainloop() |
e92a7a601620cddecd70c10faf18edafa0a0e1a0 | aksharjoshi/practice_problem | /leetcode_top100/twoSum.py | 443 | 3.5 | 4 | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for index, value in enumerate(nums):
remaining = target - value
if(remaining in map):
return [index, map[remaining]]
map.update({value:index})
raise Exception("No solution found") |
acd52b8aec0dd6ee42229729d03836adc61e9e54 | belozi/Python-Programs | /MITx 6.00.1x/problem_set_2/problem_3b.py | 1,074 | 3.609375 | 4 | balance = 999999
annualInterestRate = .18
lowerBound = balance / 12
upperBound = (balance * ( 1 + .18)) / 12
payment = (upperBound + lowerBound) / 2
def guessPayment(l, u):
lower = l
upper = u
return (lower + upper) / 2
def monthlyStatement(x, y, z):
balance = x
annualInterestRate = y
payment = z
count = 0
total = 0
while count < 12:
ub = (balance - payment) + ((balance - payment) * (annualInterestRate / 12))
balance = ub
total += payment
count += 1
return balance
check = monthlyStatement(balance, annualInterestRate, payment)
counter = 0
while counter < 25:
check = monthlyStatement(balance, annualInterestRate, payment)
if check >= 0 and check < .01:
print ("Lowest Payment: " + "%.02f" %payment)
break
elif check > 0:
counter += 1
lowerBound = payment
payment = guessPayment(lowerBound, upperBound)
else:
counter += 1
upperBound = payment
payment = guessPayment(lowerBound, upperBound)
|
96283335dd4499a8f0043f49b066d0063ed9cdd6 | scottstewart1234/Scripts-For-the-M100-ROS-DJI-OSDK | /FlyPath.py | 5,466 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 11:09:03 2019
@author: scottstewart
"""
import math
import os
class flight_path: #lets us make a flight path ealsiy
def __init__(self): #initialize a set of latitudes and longitudes
self.lat = list()
self.lon = list()
def calculatePath(self, sLat, sLon, eLat, eLon): #calcualte the squarewave of flight paths
assert (len(self.lon)==0)
assert (len(self.lat)==0)
meter_in_gps= 0.0000090909 #to convert things to meters later
SquareWave_width = 5 #meters
dif_lat = eLat-sLat;
dif_lon = eLon-sLon;
if (dif_lat>dif_lon):
steps= dif_lon/(SquareWave_width*meter_in_gps)
for i in range(0, math.floor(steps)): #Appends two at a time to get both sides of the squarewave
if (i%2==0):
self.lat.append(sLon+i*meter_in_gps*SquareWave_width)
self.lon.append(sLat)
self.lat.append(sLon+i*meter_in_gps*SquareWave_width)
self.lon.append(eLat)
else:
self.lat.append(sLon+i*meter_in_gps*SquareWave_width)
self.lon.append(eLat)
self.lat.append(sLon+i*meter_in_gps*SquareWave_width)
self.lon.append(sLat)
else:
steps= dif_lat/(SquareWave_width*meter_in_gps)
for i in range(0, math.floor(steps)): #Appends two at a time to get both sides of the squarewave
if (i%2==0):
self.lon.append(sLat+i*meter_in_gps*SquareWave_width)
self.lat.append(sLon)
self.lon.append(sLat+i*meter_in_gps*SquareWave_width)
self.lat.append(eLon)
else:
self.lon.append(sLat+i*meter_in_gps*SquareWave_width)
self.lat.append(eLon)
self.lon.append(sLat+i*meter_in_gps*SquareWave_width)
self.lat.append(sLon)
#done
#done
#done
assert (len(self.lon)==len(self.lat))
def runBash(self):
assert (len(self.lon)==len(self.lat))
velocity = "10.0"
idle_velocity ="0.5"
action_on_finish = "0"
mission_exec_times = "1"
yaw_mode = "0"
trace_mode = "0"
action_on_rc_lost="1"
gimbal_pitch_mode = "1"
altitude = "10.0"
damping_distance= "1.0"
target_yaw= "0"
target_gimbal_pitch= "-90"
turn_mode= "0"
has_action= "0"
action_time_limit= "100"
action_repeat = "0"
command_list = "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"
command_parameter = "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"
string = "\"waypoint_task:\n velocity_range: "+velocity \
+"\n idle_velocity: "+idle_velocity+"\n action_on_finish: "+action_on_finish\
+"\n mission_exec_times: "+mission_exec_times+"\n yaw_mode: "+yaw_mode\
+"\n trace_mode: "+trace_mode+"\n action_on_rc_lost: "+action_on_rc_lost\
+"\n gimbal_pitch_mode: "+gimbal_pitch_mode+"\n mission_waypoint:"
#print(len(self.lon))
for i, j in zip(self.lon, self.lat):
tempString = "\n - latitude: "+str(j)\
+"\n longitude: "+str(i)\
+"\n altitude: "+altitude\
+"\n damping_distance: "+damping_distance\
+"\n target_yaw: "+target_yaw\
+"\n target_gimbal_pitch: "+target_gimbal_pitch\
+"\n turn_mode: "+turn_mode\
+"\n has_action: "+has_action\
+"\n action_time_limit: "+action_time_limit\
+"\n waypoint_action:"\
+"\n action_repeat: "+action_repeat\
+"\n command_list: "+command_list\
+"\n command_parameter: "+command_parameter
string = string +tempString
string = string+"\""
tempString = "#!/bin/bash\n"\
+"# Automatically launch ROS for the DJI M100 on The Desktop Scott Stewart uses in the lab room 450 for the USDA project\n"\
+"#Import the bash files necessary to run ROS\n"\
+"source /opt/ros/melodic/setup.bash\n"\
+"source /home/scottstewart/catkin_ws/devel/setup.bash\n"\
+"#CreateMission\n"\
+"roscd dji_sdk\n"\
+"#Take Control Of the Drone\n"\
+"rosservice call /dji_sdk/sdk_control_authority \"1\"\n"\
+"#Upload the mission\n"\
+"rosservice call /dji_sdk/mission_waypoint_upload "
string = tempString+string
tempString="\n#Takeoff\n"\
+"rosservice call /dji_sdk/drone_task_control \"task: 4\"\n"\
+"#Fly Mission\n"\
+"rosservice call /dji_sdk/mission_waypoint_action \"action: 0\""
string = string+tempString
#print(string)\
file = open("VariableWaypoint.bash","w") #overwrite existing file if it exists
file.write(string)
file.close();
output = os.popen('bash VariableWaypoint.bash').read()#call and exectute the bash function
print(output)
fp = flight_path()
fp.calculatePath(10,10,10.0005,10.0005) #start latitude, start longitude, end latitude, end logitude. Makes a squarewave pattern between these points
fp.runBash();
|
6f96d7627f70b6c71bfe685fb77a0daf958acf3e | mkhira2/automate-the-boring-stuff | /python-basics/hello.py | 852 | 4.125 | 4 | # This program says hello and asks for my name
# print('Hello world!')
# print('What is your name?') # ask for their name
# myName = input()
# print('It is good to meet you, ' + myName)
# print('The length of your name is: ' )
# print(len(myName))
# print('What is your age?') # ask for their age
# myAge = input()
# print('You will be ' + str(int(myAge) + 1) + ' in a year.')
print('Hello world!')
def getAge():
print('What is your age?') # ask for their age
myAge = input()
if myAge.isnumeric():
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
else:
print('Please enter an integer.')
getAge()
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName.title() + '.')
print('You have ' + str(len(myName)) + ' characters in your name.')
getAge() |
8b8777580c054cf56c15d702ac8db3889a72be24 | henkmollema/spInDP | /spInDP/LegThread.py | 1,804 | 3.5 | 4 | import time
import threading
class LegThread(threading.Thread):
"""Provides a thread for handling leg movements."""
def __init__(self, legId, sequenceController, group=None, target=None, args=(), kwargs=None, verbose=None):
"""Initializes a new instance of the LegThread class."""
super(LegThread, self).__init__()
self.target = target
self.name = 'LegThread' + str(legId)
self.deamon = True
self._legId = legId
self._sequenceController = sequenceController
self.cCoordinates = [0, 0, 0]
def run(self):
queue = self._sequenceController.legQueue[self._legId]
while not self._sequenceController.stopped:
try:
legMovement = queue.get()
if (legMovement.empty is False):
self._sequenceController.servoController.move(
(self._legId - 1) * 3 + 1, legMovement.coxa, legMovement.coxaSpeed)
self._sequenceController.servoController.move(
(self._legId - 1) * 3 + 2, legMovement.femur, legMovement.femurSpeed)
self._sequenceController.servoController.move(
(self._legId - 1) * 3 + 3, legMovement.tibia, legMovement.tibiaSpeed)
# Sleep this thread for maxexectime seconds (until the move has been completed)
time.sleep(legMovement.maxExecTime if legMovement.maxExecTime > 0 else 0.005)
self.cCoordinates = legMovement.IKCoordinates
# except:
# print ("error on leg " + str(self.legId))
finally:
# Mark the task as done in the queue.
queue.task_done()
print ("While loop of " + self.name + " stopped.")
|
d3a89dd33f3192def08d13da606dfb5c05ffd4b6 | chenhh/Uva | /uva_11369.py | 544 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Authors: Hung-Hsin Chen <chenhh@par.cse.nsysu.edu.tw>
License: GPL v2
status: AC
difficulty: 1
http://luckycat.kshs.kh.edu.tw/homework/q11369.htm
"""
import math
def main():
T = int(input())
for _ in range(T):
n = int(input())
# sort prices in descending order
prices = sorted(list(map(int, input().split())))[::-1]
# number of check which can save money
n_check = n//3
save = sum(prices[cdx*3+2] for cdx in range(n_check))
print (save)
if __name__ == '__main__':
main()
|
e4f76f72072250379d6ca80d35ca0f0565786084 | RevanthR/AI_Assignments | /assignment.py | 2,400 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 21:13:06 2019
@author: DELL
"""
#assignment 1
dict={'keys':['shanghai','intanbul','hyderabad'],'value':[17,18,19]}
dict
#assignment 2
answer = 20
guess = int(input('enter the number you have guessed\n'))
difference = answer-guess
if difference < -30:
print("too hight")
if difference<0 and difference >- 30:
print("just high")
if difference < 20 and difference >0 :
print("just low")
if difference>0 and difference > 30:
print("too low")
#assignment 2 2nd problem
for i in range(0,30+1):
if(i%5==0):
print(i)
#assignment2 3rd problem
interlimit = int(input("enter the number for which you want to find the nearest square"))
i=1
while(i*i<interlimit):
i=i+1
i=i-1
print(i)
#assignment 3 part 1
x=np.array([1,2,3,4])
y=np.array([5.5,6.5,7.5,8.5])
print(np.add(x,y))
print(np.subtract(x,y))
print(np.multiply(x,y))
print(np.divide(x,y))
#assignment 3 part 2
x=np.array([[1,2],[3,4]])
print(np.sqrt(x[:,:1]),"\n")
print(np.sqrt(x[1:,:]))
print(np.max(x, axis=0))
print(x.max(axis=0))
print(np.max(x, axis=1))
print(np.min(x, axis=0))
print(np.min(x, axis=1))
print(np.median(x))
print(np.std(x))
print(np.mean(x))
print(np.exp(x))
#assignment 4
data=[
{
'year': 1990, 'name' : 'Alice', 'department' : 'HR','Age':25, 'Salary':50000
},
{
'year': 1990, 'name' : 'Bob', 'department' : 'RD','Age':30, 'Salary':48000
},
{
'year': 1990, 'name' : 'Charlie', 'department' : 'Admin','Age':45, 'Salary':55000
},
{
'year': 1991, 'name' : 'Alice', 'department' : 'HR','Age':26, 'Salary':52000
},
{
'year': 1991, 'name' : 'Bob', 'department' : 'RD','Age':31, 'Salary':50000
},
{
'year':1991, 'name' : 'Charlie', 'department' : 'Admin','Age':46, 'Salary':60000
},
{
'year': 1992, 'name' : 'Alice', 'department' : 'HR','Age':27, 'Salary':60000
},
{
'year':1992, 'name' : 'Bob', 'department' : 'RD','Age':32, 'Salary':52000
},
{
'year':1992, 'name' : 'Charlie', 'department' : 'Admin','Age':28, 'Salary':62000
}
]
data_series=pd.DataFrame(data,index=[0,1,2,3,4,5,6,7,8])
data_series
print(data_series.groupby(['year'])['Salary'].sum())
print(data_series.groupby(['name'])['Salary'].sum())
print(data_series.groupby(['department','year'])['Salary'].sum()) |
d7955d98d231d53b62a821defade3236e23bd990 | Niloy28/Python-programming-exercises | /Solutions/Q78.py | 155 | 3.875 | 4 | # Please write a program to randomly print a integer number between 7 and 15 inclusive.
import random
random.seed()
print(random.randint(7, 15))
|
7f21f2a0314ae83149986c2140b10c1c2e5f670b | skyleh/Data_Visualization | /code/chapter17/test1.py | 389 | 3.96875 | 4 | def hanoi(n,a,b,c):
if n==1:
print(a,'-->',c)
else:
# 将前n-1个盘子从a移动到b上
hanoi(n-1,a,c,b)
# 将最底下的最后一个盘子从a移动到c上
hanoi(1,a,b,c)
# 将b上的n-1个盘子移动到c上
hanoi(n-1,b,a,c)
n=int(input('请输入汉诺塔的层数:'))
print("移动路径为:")
hanoi(n,'a','b','c') |
7790064eb041efbacf849c21ede726fe34db51e5 | jwds123/offer | /二叉搜索树与双向链表36.py | 1,999 | 3.546875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
'''
定义两个辅助节点listHead(链表头节点)、listNode(链表尾节点)。事实上,二叉树只是换了种形式的链表;
listHead用于记录链表的头节点,用于最后算法的返回;listNode用于定位当前需要更改指向的节点。
'''
def __init__(self):
self.listHead = None
self.listNode = None
def Convert(self, pRootOfTree):
if not pRootOfTree:
return
self.Convert(pRootOfTree.left)
if not self.listHead:
self.listHead=self.listNode=pRootOfTree
else:#二叉树改成双向的链条
self.listNode.right=pRootOfTree
pRootOfTree.left=self.listNode
self.listNode=pRootOfTree
self.Convert(pRootOfTree.right)
return self.listHead
# 给定二叉树的前序遍历和中序遍历,获得该二叉树
def reConstructBinaryTree(self, pre, tin):
if not pre and not tin:
return
if set(pre)!=set(tin):
return
root = TreeNode(pre[0])
i = tin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:i + 1], tin[:i])
root.right = self.reConstructBinaryTree(pre[i + 1:], tin[i + 1:])
return root
#打印双向链条
def print_node(self,head):
#先向右打印
while head.right:
print(head.val, end=" ")
head = head.right
print(head.val)
#再向左打印
while head:
print(head.val, end=" ")
head = head.left
def main():
solution = Solution()
preorder_seq = [4, 2, 1, 3, 6, 5, 7]
middleorder_seq = [1, 2, 3, 4, 5, 6, 7]
Treeroot=solution.reConstructBinaryTree(preorder_seq,middleorder_seq)
head=solution.Convert(Treeroot)
solution.print_node(head)
if __name__ == '__main__':
main()
|
7b8dbc3e5e4358a04ef75c73b3c1e112c96c9138 | Hariharansingaram/training-session | /மாட்டுப் பொங்கல்.py | 967 | 3.703125 | 4 | #question
Sivasamy is a farmer living in the southern part of Tamilnadu. He has ‘N’ bulls on his farm, which he uses to plough his fields. Hence “Mattu Pongal” is a special occasion to celebrate the hard work of all those bulls. So, for every Mattu Pongal, the bulls will be decorated, the horns of the bull are painted. Each bull is painted with different colors so it looks visually appealing. But seeing the cost-effectiveness part, it is difficult to buy ‘N’ different colors of paints. So Sivasamy usually mixes two or more colors to make a newer color. Paintbox costs 225 rs each. So what will be the minimum expenditure of Sivasamy to color all his ‘N’ bulls with different colors?
Input Format
One single integer input N – Number of bulls
Constraints
1<=N<=10^9
Output Format
One single integer output denoting the minimum expenditure of Sivasamy.
Sample Input 0
7430427
Sample Output 0
5175
#answer
n=int(input())
print(n.bit_length()*225)
|
f10fa62a92ee35cd6dbe266c1d8c052d33ac1da0 | ai-se/ActiveConfig_codebase | /PerformanceMetrics/Spread/Spread.py | 3,519 | 3.53125 | 4 | from __future__ import division
def spread_calculator(obtained_front, extreme_point1, extreme_point2):
"""Given a Pareto front `first_front` and the two extreme points of the
optimal Pareto front, this function returns a metric of the diversity
of the front as explained in the original NSGA-II article by K. Deb.
The smaller the value is, the better the front is.
"""
def euclidean_distance(list1, list2):
assert(len(list1) == len(list2)), "The points don't have the same dimension"
distance = sum([(i - j) ** 2 for i, j in zip(list1, list2)]) ** 0.5
assert(distance >= 0), "Distance can't be less than 0"
return distance
def closest(obtained_front, point, distance=euclidean_distance):
"""Returns the point from obtained_front which is closed to point"""
closest_point = None
min_distance = 1e100
for opoint in obtained_front:
temp_distance = distance(opoint, point)
if temp_distance <= min_distance:
min_distance = temp_distance
closest_point = opoint
assert(closest_point is not None), "closest_point cannot be None"
return closest_point, min_distance
_, df = closest(obtained_front, extreme_point1)
_, dl = closest(obtained_front, extreme_point2)
distances = [euclidean_distance(obtained_front[i], obtained_front[i+1]) for i in xrange(len(obtained_front) -1)]
try:
distances_mean = sum(distances)/len(distances)
except:
pass
d_variance = sum([abs(di - distances_mean) for di in distances])
N = len(obtained_front)
return (df + dl + d_variance)/(df + dl + (N -1) * distances_mean)
def file_reader(filepath, separator=" "):
from os.path import isfile
assert(isfile(filepath) == True), "file doesn't exist"
content = []
for line in open(filepath, "r"):
content.append([float(element) for element in line.split(separator) if element != "\n"])
return content
def sort_list_of_list(list_of_list):
""" This function is to extract the extreme points"""
def sorting_def(list):
number_of_objectives = len(list)
weights = reversed([10 ** i for i in xrange(number_of_objectives)])
return sum([element * weight for element, weight in zip(list, weights)])
return sorted(list_of_list, key=sorting_def)
def spread_calculator_wrapper():
true_pf_folder = "./True_PF/"
obtained_pf_folder = "./Obtained_PF/"
from os import listdir
true_pf_files = [true_pf_folder + name for name in listdir(true_pf_folder)]
obtained_pf_files = [obtained_pf_folder + name for name in listdir(obtained_pf_folder)]
assert(len(true_pf_files) == len(obtained_pf_files)), "Number of files in both folders should be equal"
for true_pf_file, obtained_pf_file in zip(true_pf_files, obtained_pf_files):
true_pf_content = file_reader(true_pf_file)
obtained_pf_content = file_reader(obtained_pf_file)
sorted_true_pf_content = sort_list_of_list(true_pf_content)
sorted_obtained_pf_content = sort_list_of_list(obtained_pf_content)
first_extreme_solution = sorted_true_pf_content[0]
second_extreme_solution = sorted_true_pf_content[-1]
spread = spread_calculator(sorted_obtained_pf_content, first_extreme_solution, second_extreme_solution)
print "Name: ", true_pf_file, " Spread: ", round(spread, 3)
return None
if __name__ == "__main__":
spread_calculator_wrapper()
|
207b607a416365a704d0d99b15e57d37a61b4f54 | Avani1992/database_pytest | /database/key_test.py | 2,357 | 3.59375 | 4 | """create a DB in which orders and customers tables are there. Using the concept of Primary Key and Foreign Key.
cu_id is a Primary key of table customers and foreignkey of table orders. Fetch data from customers table according to the ordername of orders table.
and compare the fetched data with json file in which inserted data stored.If data matched then testcase passed else failed using pytest concept.
Two file ctreated key_test.py, key_test2.py and customer_data.json"""
import mysql.connector
import json
class key_test:
def create_table(self):
self.con = mysql.connector.connect(host="localhost", username="root", password="user123", database="key_test")
self.cursor=self.con.cursor()
# self.cursor.execute("create table Customers(cu_id int not null,cu_name varchar(45),roti varchar(45),sabji varchar(45),sweet varchar(45),primary key(cu_id))")
# self.cursor.execute("Create table orders(or_id int not null, o_name varchar(45), cu_id int not null ,primary key(or_id),foreign key(cu_id) references Customers(cu_id))")
self.con.commit()
def fill_data(self):
# self.q1="insert into Customers(cu_id,cu_name,roti,sabji,sweet) values(%s,%s,%s,%s,%s)"
# self.values=[(1001,"Kuman","Plain","brinjal","Gulab-Jamun"),(1003,"Avani","Fulka","Paneer","Rasgulla"),(1002,"Ruchi","Naan","PaneerBhurji","Rasmalai"),
# (1005,"Pooja","Plain","Tomato","Barfi"),(1007,"Neha","Tanduri","Potato","Jamun")]
# self.cursor.executemany(self.q1,self.values)
# self.q2="insert into orders(or_id,o_name,cu_id) values(%s,%s,%s)"
# self.values=[(101,"order1",1001),(102,"order3",1003),(103,"order2",1005),(104,"order4",1003),(105,"order5",1002),(106,"order6",1007)]
# self.cursor.executemany(self.q2,self.values)
# self.con.commit()
self.q3="select * from Customers"
self.cursor.execute(self.q3)
self.data=self.cursor.fetchall()
print(self.data)
with open("customeres_data.json","w") as file1:
self.l2 = list()
self.d1 = dict()
for data in self.data:
self.d1[data[0]]=data
file1.write(json.dumps(self.d1))
print(self.d1)
obj=key_test()
obj.create_table()
obj.fill_data()
|
49139b15072d0797fb0c027ab00fd39ed77743be | Baes14/Python-work | /ordinal_numbers.py | 247 | 3.90625 | 4 | numbers=list(range(1,10))
for number in numbers :
if number == 1 :
print("--> "+str(number)+"st")
elif number == 2 :
print("--> "+str(number)+"nd")
elif number == 3 :
print("--> "+str(number)+"rd")
else :
print("--> "+str(number)+"th") |
3af2c34ad27c921dbc7dafd5e01894a43754a562 | dinkoslav/Python | /Programing0-1/Week1/1-IO-Simple-Problems/n_dice_more.py | 252 | 3.640625 | 4 | N = input("Enter sides: ")
from random import randrange
firstRoll = randrange(1,int(N))
secondRoll = randrange(1,int(N))
print ("First roll:")
print (firstRoll)
print ("Second roll:")
print (secondRoll)
print ("Sum is:")
print (firstRoll + secondRoll)
|
ae19d203bc911c1a26e77dcf54de1fb3869959f1 | quekyufei/rl-tictactoe | /rl_ttt/player.py | 1,059 | 3.703125 | 4 | import random
class Player():
def __init__(self, mark):
self.mark = mark
self.num_wins = 0
self.num_losses = 0
self.num_draws = 0
def get_move(self, board):
# returns move object corresponding to move
pass
def game_ended(self, result):
if result == 'win':
self.num_wins += 1
elif result == 'loss':
self.num_losses += 1
else:
self.num_draws += 1
def all_done(self):
pass
class HumanPlayer(Player):
def __init__(self, mark):
Player.__init__(self, mark)
def get_move(self, board):
while True:
# Get user input (integer from 0 - 8)
user_in = int(input('Enter move: '))
# number is invalid
if user_in not in range(0,9):
print('Enter a number between 0 and 8.')
continue
# square is not blank
if board.is_move_legal(user_in):
return board.get_move_object(user_in, self.mark)
else:
print('Move is not legal.')
class RandomPlayer(Player):
def __init__(self, mark):
Player.__init__(self, mark)
def get_move(self, board):
return random.choice(board.get_legal_moves(self.mark)) |
5048e0ac6f930a54a21d2a22825ce403cbc389da | jason-azze/learning-py | /testing-aug-assignment-ops.py | 143 | 3.875 | 4 | base = int(input ("What is your base salary?"))
base /= 52
print(base, "is your weekly pay.")
print (input ("Press any key to continue."))
|
330d22c3a6e47c69d51c1cdf1095fba47ed27a19 | priyanka-111-droid/100daysofcode | /Day054/intro-backend-web-dev/Theory/first-class-func-and-decorators/dec1.py | 1,218 | 4.90625 | 5 | ####<<<DECORATORS>>>####
# A decorator is a function that takes another function as an argument,adds some functionality and returns another function
#Recap:first class function
def outer_func(message):
def inner_func():
print("Message :",message)
#no () as we don't want this function to execute
return inner_func
greeting=outer_func("Hi!")
greeting()
goodbye=outer_func("Bye!")
goodbye()
#Now modifying above code sample to a decorator:
#instead of passing message,we will pass function called original_function
def decorator_function(original_function):
def wrapper_function():
# print("Message :",message)
#instead of printing message,we will execute original function and return it
print(f"Wrapper executed this before {original_function.__name__}")
return original_function()
return wrapper_function
def display():
print("display function ran")
#FIRST WAY TO DECORATE A FUNCTION AND EXECUTE IT
decorated_display=decorator_function(display)
decorated_display()
#SECOND WAY TO DECORATE A FUNCTION AND EXECUTE IT(using @ symbol)
@decorator_function
def another_display():
print("Another display function ran")
another_display() |
cc0a8388c2d9e807787768ac37186898b1211d86 | winaba/mapScreen | /rotinasDeConfiguracao.py | 2,965 | 3.5625 | 4 | import pyautogui
from arquivoDeConfiguracao import ArquivoDeConfiguracao
class RotinasDeConfiguracao:
def __init__(self):
self.config = ArquivoDeConfiguracao()
self.pos = pyautogui
def configuraArquivoSAT(self):
print("")
print("##################################")
print("Vamos configurar os documentos SAT")
print("##################################")
print("")
print('Coloque o mouse sobre o local que ficará os campos mencionados e precione [Enter]')
print("")
print('Coloque o mouse sobre')
input('- O campo chave de acesso: ')
self.config.addLine('CHAVE_ACESSO_X', str(self.pos.position()[0]) )
self.config.addLine('CHAVE_ACESSO_Y', str(self.pos.position()[1]) )
print('Leitura realizada')
input("- O botão [Salvar Nota]: ")
self.config.addLine('SALVAR_NOTA_SAT_X', str(self.pos.position()[0]) )
self.config.addLine('SALVAR_NOTA_SAT_Y', str(self.pos.position()[1]) )
print('Leitura realizada')
def configuraArquivoCupom(self):
print("")
print("####################################")
print("Vamos configurar os documentos Cupom")
print("####################################")
print("")
print('Coloque o mouse sobre o local que ficará os campos mencionados e precione [Enter]')
print("")
print('Coloque o mouse sobre')
input('- O campo CNPJ do Emissor da Nota: ')
self.config.addLine('CNPJ_EMISSOR_X', str(self.pos.position()[0]) )
self.config.addLine('CNPJ_EMISSOR_Y', str(self.pos.position()[1]) )
print('Leitura realizada')
input("- O botão [Salvar Nota]: ")
self.config.addLine('SALVAR_NOTA_CUPOM_X', str(self.pos.position()[0]) )
self.config.addLine('SALVAR_NOTA_CUPOM_Y', str(self.pos.position()[1]) )
print('Leitura realizada')
def configuraControles(self):
print("")
print("#######################################")
print("Agora vamos configurar outros controles")
print("#######################################")
print("")
self.config.addLine('ERROS_SEGUIDOS', input("- Qual a quantidade de erros seguidos que podem ocorrer? "))
self.config.addLine('SAT_TOTAL_MINUTO', input("- Qual a quantidade de erros seguidos que podem ocorrer? "))
self.config.addLine('CUPOM_TOTAL_MINUTO', input("- Qual a quantidade de erros seguidos que podem ocorrer? "))
def visualizaArquivoDeConfiguracao(self):
print("")
print("##############################")
print("Visualização do arquivo gerado")
print("##############################")
print("")
self.config.content()
def gravaArquivo(self):
import os
print('Local do arquivo gerado: ')
print(os.getcwd() + '\config.ini')
self.config.post()
|
ce8dd9aa2a543cfe1ac3dea225460d37393b1cc0 | Sitiestiya/uin_modularization_using_class_and_package | /main.py | 1,906 | 3.90625 | 4 | nama = 'Siti Estiya Pujiningtiyas'
program = 'Hukum Newton 1'
print(f'Program{program} oleh {nama}')
def hitung_HK1_Newton(massa, percepatan) :
HK1_Newton = massa * percepatan
print(f'massa = {massa/1}kg mengalami sebuah percepatan = {percepatan/1} m/s**')
print(f'Sehingga HK1_Newton = {HK1_Newton} N')
return HK1_Newton
#massa
#percepatan
HK1_Newton = hitung_HK1_Newton(5, 0)
HK1_Newton = hitung_HK1_Newton(50, 0)
keterangan = 'HK 1 Newton menjelaskan tentang kelembaman benda ditandai dengaan tidak adanya perpindahan selama gaya yang diberikan = 0'
print(f'keterangan{keterangan}')
program = 'Hukum Newton 2'
print(f'program{program}')
def hitung_HK2_Newton(massa, percepatan) :
HK2_Newton = massa * percepatan
print(f'massa = {massa/1}kg mengalami sebuah percepatan = {percepatan/1} m/s**')
print(f'Sehingga HK2_Newton = {HK2_Newton} N')
return HK2_Newton
#massa
#percepatan
HK2_Newton = hitung_HK2_Newton(5, 3)
HK2_Newton = hitung_HK2_Newton(50, 2)
keterangan = "Hukum 2 Newton menjelaskan bahwa apabila sebuah benda bermassa dikenai sebuah Gaya sebesar N maka akan mengalami sebuah percepatan dimana percepatannya tidak sama dengan 0"
print(f'keterangan{keterangan}')
program = 'Hukum 3 Newton'
print(f'program{program}')
def hitung_HK3_Newton(Gaya1, Gaya2) :
HK3_Newton = Gaya1
HK3_Newton = -Gaya2
print(f'Gaya1 = {Gaya1/1}N akan mengalami sebuah gaya yang berlawanan arah = {-Gaya2/1}N')
print(f'Sehingga HK3_Newton = {HK3_Newton} N')
return HK3_Newton
#aksi
#reaksi
HK3_Newton = hitung_HK3_Newton(5, 5)
HK3_Newton = hitung_HK3_Newton(15, 15)
keterangan = 'Hukum 3 Newton menjelaskan tentang sebuah aksi = -reaksi, sehingga apabila sebuah benda bermassa m mengalami sebuah Gaya maka benda tersebut juga akan mengalami akan mengalami reaksi Gaya sebelumnya yang ditandai dengan tanda (-) sebagai tanda berlawanan'
print(f'keterangan{keterangan}')
|
850755819618cc51a51ed5716c06db48826ad1bb | john-mcgonigle/random_scripts | /whiteboard/code_exercises/guess_the_number.py | 1,129 | 4.15625 | 4 | from random import randint
def main():
print('Let\'s play a guessing game. I\'ll choose a number between 1 and 10 and you try and guess the correct number!')
number = randint(1,10)
game(number)
def game(number):
game_over = False
guess = input('OK. I\'ve chosen my number. What do you think it is?\n')
while game_over != True:
try:
guess= int(guess)
except:
guess = input('Please enter a valid number.\n')
continue
print('OK. So you guessed: {guess}.'.format(guess=guess))
if guess == number:
print('Well done. You guessed correctly, the number was {guess}'.format(guess=guess))
game_over = True
else:
decision(guess, number)
if game_over == False:
guess = input('Try again. Pick a number.\n')
def decision(guess, number):
if guess < number:
message = 'lower'
else:
message = 'higher'
print('Oh no!. Your guess of {guess} was {message} than the number I chose.'.format(guess=guess, message=message))
if __name__ == '__main__':
main() |
ccc5f80ca14477cf28910efcca3d018aa2ecb003 | fl4kee/homework-repository | /homework1/task5.py | 960 | 4.09375 | 4 | """
Given a list of integers numbers "nums".
You need to find a sub-array with length less equal to "k", with maximal sum.
The written function should return the sum of this sub-array.
Examples:
nums = [1, 3, -1, -3, 5, 3, 6, 7], subarray_len = 3
result = 16
"""
from typing import List
def find_maximal_subarray_sum(nums: List[int], subarray_len: int) -> int:
array_len = len(nums)
# Array's length greater than 1, subarray's length greater than 1 but less then array's length
if array_len > 1 and 1 < subarray_len <= array_len:
# Initial max value
max_sum = sum(nums[0:subarray_len - 1])
# i - start index
for i in range(0, array_len - subarray_len + 1):
# j - subarray's length
for j in range(2, subarray_len + 1):
subarray_sum = sum(nums[i:i + j])
max_sum = subarray_sum if subarray_sum > max_sum else max_sum
return max_sum
return 0
|
1462a4ef2588709b6e9a02bb1d0d50951ca095f3 | nidhiatwork/Python_Coding_Practice | /Lists/FindMaxIdxDiff.py | 1,070 | 3.5 | 4 | # Given an array arr[], find the maximum j – i such that arr[j] > arr[i].
# Examples :
# Input: {34, 8, 10, 3, 2, 80, 30, 33, 1}
# Output: 6 (j = 7, i = 1)
import collections
def FindMaxIdxDiff(arr):
n = len(arr)
result = 0
maxFromEnd = collections.deque()
val = -float("inf")
for num in reversed(arr):
val = max(num, val)
maxFromEnd.appendleft(val)
for i in range(0, n):
low = i + 1
high = n - 1
ans = i
while (low <= high):
mid = int((low + high) / 2)
if (arr[i] <= maxFromEnd[mid]):
# We store this as current
# answer and look for further
# larger number to the right side
ans = max(ans, mid)
low = mid + 1
else:
high = mid - 1
# Keeping a track of the
# maximum difference in indices
result = max(result, ans - i)
print(result)
arr = [34, 8, 10, 3, 2, 80, 30, 33, 1]
FindMaxIdxDiff(arr) |
5a8e7c0f527e794b9e93c220e2f76202f74abbed | bzd111/PythonLearn | /decorator_use/decorator_def_without_args.py | 649 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from functools import wraps
def decorate_test(func):
@wraps(func)
def wrap(*args, **kwargs):
print('This is a decorate')
print('func name {}'.format(func.__name__))
return func(*args, **kwargs)
return wrap
@decorate_test
def say_hello():
return 'say hello'
def say_hello_none():
return 'say hello'
class TestSay(object):
@decorate_test
def say_hello(self):
return 'say hello'
if __name__ == "__main__":
print(say_hello())
print("-"*30)
print(decorate_test(say_hello_none)())
print("-"*30)
test = TestSay()
print(test.say_hello())
|
9a4780f29a49ec8845c3a50567879f4c111cc349 | aakashmathuri/Python | /ex_03_02/ex_03_03.py | 255 | 3.9375 | 4 | score = input("Enter Score: ")
xf = float(score)
if xf >=1:
print("please enter correct score!")
elif xf >= 0.9:
print("A")
elif xf >= 0.8:
print("B")
elif xf >= 0.7:
print("C")
elif xf >= 0.6:
print("D")
elif xf < 0.6:
print("F")
|
32e10602a8582d637224a58e8ebc73243dd07503 | AlexMaraio/CMBBispectrumCalc | /lib/Visualisation.py | 2,854 | 3.515625 | 4 | # Created by Alessandro Maraio on 02/02/2020.
# Copyright (c) 2020 University of Sussex.
# contributor: Alessandro Maraio <am963@sussex.ac.uk>
"""
This file will be where our visualisation tools will be put so that way
we can present the results for the two- and three-point function integrals
in a nice and coherent way.
This will be especially true for the three-point function because it is a function
of 3 variables, we will need to plot on a 3D grid and so some work will need to get this right.
"""
import matplotlib.pyplot as plt
def twopf_visualisation(ell, c_ell, use_seaborn=True, use_LaTeX=False):
"""
Function for creating a default power spectrum plot for C_ell vs ell, in standard plotting units.
Takes ell and c_ell, which are lists that corresponds to the integration data, and optional bool switches
on or off using the seaborn plotting style, and using LaTeX labels.
"""
# If using seaborn, import it and set plot options given function inputs
if use_seaborn:
import seaborn as sns
sns.set(font_scale=1.75, rc={'text.usetex': True}) if use_LaTeX else sns.set(font_scale=1.5)
# Create a matplotlib figure and plot the power spectrum on it.
plt.figure(figsize=(16, 9))
plt.loglog(ell, c_ell, lw=2.5)
plt.xlabel(r'$\ell$')
# Change the y-label depending on if we're using LaTeX labels or not
if use_LaTeX:
plt.ylabel(r'$C_\ell \,\, \ell(\ell + 1) / 2 \pi \,\, [\mu \textrm{K}^2]$')
else:
plt.ylabel(r'$C_\ell \,\, \ell(\ell + 1) / 2 \pi \,\, [\mu K^2]$')
plt.title(r'CMB TT power spectrum $C_\ell$ plot')
plt.tight_layout()
plt.show()
def equal_ell_bispectrum_plot(ell, bispec, use_seaborn=True, use_LaTeX=False, save_folder=None):
"""
Function that creates a default plot of the equal ell CMB bispectrum.
Takes arguments of the ell and bispec, which are lists that corresponds to the integration data,
two bool switches that determine plot styling options,
and an optional string save_folder, which if provided saves the figure into the folder given.
"""
# Import seaborn if we are using it and initialise with plot settings determined by function inputs
if use_seaborn:
import seaborn as sns
sns.set(font_scale=1.75, rc={'text.usetex': True}) if use_LaTeX else sns.set(font_scale=1.5)
# Create a matplotlib figure and plot the bispectrum on it
plt.figure(figsize=(16, 9))
plt.semilogx(ell, bispec, lw=2.5)
plt.xlabel(r'$\ell$')
plt.ylabel(r'Bispectrum $b_{\ell \, \ell \, \ell}$')
plt.title(r'CMB TTT bispectrum plot for $\ell_1 = \ell_2 = \ell_3 \equiv \ell$')
plt.tight_layout()
# If a save folder is provided, save the figure to that folder.
if save_folder is not None:
plt.savefig(str(save_folder) + '/bispectrum_equal_ell.png', dpi=500)
plt.show()
|
0adfb30c50baaaa22ca8fa18ef7ff65ed9cf8989 | Igglyboo/Project-Euler | /1-99/30-39/Problem31.py | 690 | 3.53125 | 4 | from time import clock
def timer(function):
def wrapper(*args, **kwargs):
start = clock()
print(function(*args, **kwargs))
print("Solution took: %f seconds." % (clock() - start))
return wrapper
@timer
def find_answer():
total = 0
for a in range(200, -1, -200):
for b in range(a, -1, -100):
for c in range(b, -1, -50):
for d in range(c, -1, -20):
for e in range(d, -1, -10):
for f in range(e, -1, -5):
for g in range(f, -1, -2):
total += 1
return total
if __name__ == "__main__":
find_answer()
|
a6e08f63e78cba25bdfcd901704391277a63e1d5 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2176/60641/250740.py | 476 | 3.671875 | 4 | def main():
string = list(input())
new_string = sorted(set(string))
result = []
for i in new_string:
result = result + find_index(string, i, 0)
print(" ".join(map(str, result)))
def find_index(string, s, start):
result = []
num = string.index(s, start) + 1
try:
result = find_index(string, s, num) + result
except ValueError:
pass
result.append(num)
return result
if __name__ == "__main__":
main()
|
fbe185684b2dd1375f1b800a5daf5b9a7f34d6b8 | martinusso/code_practice | /codingbat/python/warmup_1/front_back.py | 365 | 4 | 4 | #!/usr/bin/python
# coding: utf-8
'''
Given a string, return a new string where the first and last chars have been exchanged.
front_back('code') -> 'eodc'
front_back('a') -> 'a'
front_back('ab') -> 'ba'
'''
def front_back(str):
if not len(str) > 1:
return str
first = str[0]
last = str[-1:]
mid = str[1:-1]
return last + mid + first
|
7b2306235f97967fd505cba3b567e71ce7064a5e | luliyucoordinate/Leetcode | /src/0129-Sum-Root-to-Leaf-Numbers/0129.py | 1,048 | 3.609375 | 4 | class Solution:
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = 0
if not root:
return result
path = [(0, root)]
while path:
pre, node = path.pop()
if node:
if not node.left and not node.right :
result += pre*10 + node.val
path += [(pre*10 + node.val, node.right), (pre*10 + node.val, node.left)]
return result
# class Solution:
# def _sumNumbers(self, root, value):
# if root:
# self._sumNumbers(root.left, value*10+root.val)
# self._sumNumbers(root.right, value*10+root.val)
# if not root.left and not root.right:
# self.result += value*10 + root.val
# def sumNumbers(self, root):
# """
# :type root: TreeNode
# :rtype: int
# """
# self.result = 0
# self._sumNumbers(root, 0)
# return self.result |
4b557e715d52d155d33a4702e9a124e75e0ca4b3 | paulykp/python_practice | /tip_counting_new.py | 949 | 3.96875 | 4 | #imports for currency values
from money.money import Money
from money.currency import Currency
#defines the way that one inputs the currency value 'i.e. no period as it's valued in cents not dollars¢s
def USD(cents):
return Money.from_sub_units(cents, Currency.USD)
#Combines Names list with totals in the records.py file for output in console
def shifts(names, totals):
return list(zip(names, totals))
#weekday & Saturday tip counting
def weekdays(tip1, tip2, tip3, tip4, tip5):
open_one = USD(tip1) + USD(tip2) + USD(tip3)
open_three = open_one + USD(tip4)
ten_close = USD(tip2) + USD(tip3) + USD(tip4) + USD(tip5)
noon_close = ten_close - USD(tip2)
return (open_one, open_three, ten_close, noon_close)
#Sunday tip counting
def sunday(tip1, tip2, tip3):
all_day = USD(tip1) + USD(tip2) + USD(tip3)
open_one = USD(tip1) + USD(tip2)
ten_close = all_day - USD(tip1)
return (all_day, open_one, ten_close)
|
425f002af31ae0ae4dc4592191cc3819018edff1 | RuizhenMai/academic-blog | /leetcode/akuna/3_palindrome_dates.py | 1,170 | 3.984375 | 4 | from calendar import monthrange
def generate_palindrome_date(year):
'''
param:
year (string)
return:
number of palindrome date of the century the year is in(int)
'''
century_start = year // 100 * 100 + 1 # 2001 is the start of 21st century
century_end = century_start + 99
count = 0
for yyyy in range(century_start, century_end):
for mm in range(1,13):
num_days = monthrange(yyyy,mm)[1] # 28 days or 30 days etc
for dd in range(1,num_days+1):
if dd < 10:
dd = "0" + str(dd)
else:
dd = str(dd)
date = str(mm) + dd + str(yyyy)
# check if 7 digits palindrome
if date == date[::-1]:
count+=1
# check if 8 digits palindrome
if mm < 10:
date_prime = "0" + str(mm) + dd + str(yyyy)
if date_prime == date_prime[::-1]:
count += 1
return count
print(generate_palindrome_date(2016)) # output 38 |
0ba262e62d69b2b1e43517673148c79bd3759abd | karunaswamy1/Function | /qu2.py | 122 | 3.796875 | 4 | # numbers = [3, 5, 7, 34, 2, 89, 2, 5]
# a=max(numbers)
# print(a)
list = [8, 6, 4, 8, 4, 50, 2, 7]
a=min(list)
print(a)
|
9f373d564388d51b8e870b72808066901a4eff1c | parfeniukir/parfeniuk | /Lesson 6/loop_v5.py | 110 | 3.84375 | 4 | for i in range(5):
print(i)
else:
print('Else block i = ', i)
for i in range("Hello"):
print(i) |
cc62cf27be15a5c13817784790a235c04b6b0b5b | aknkrstozkn/ceng3511 | /p3/knapsack_ga.py | 2,548 | 3.78125 | 4 | # starter code for solving knapsack problem using genetic algorithm
import random
fc = open('./c.txt', 'r')
fw = open('./w.txt', 'r')
fv = open('./v.txt', 'r')
fout = open('./out.txt', 'w')
c = int(fc.readline())
w = []
v = []
for line in fw:
w.append(int(line))
for line in fv:
v.append(int(line))
print('Capacity :', c)
print('Weight :', w)
print('Value : ', v)
popSize = int(input('Size of population : '))
genNumber = int(input('Max number of generation : '))
print('\nParent Selection\n---------------------------')
print('(1) Roulette-wheel Selection')
print('(2) K-Tournament Selection')
parentSelection = int(input('Which one? '))
k = 0
if parentSelection == 2:
k = int(input('k=? (between 1 and ' + str(len(w)) + ') '))
print('\nN-point Crossover\n---------------------------')
n = int(input('n=? (between 1 and ' + str(len(w) - 1) + ') '))
print('\nMutation Probability\n---------------------------')
mutProb = float(input('prob=? (between 0 and 1) '))
print('\nSurvival Selection\n---------------------------')
print('(1) Age-based Selection')
print('(2) Fitness-based Selection')
survivalSelection = int(input('Which one? '))
elitism = bool(input('Elitism? (Y or N) '))
print('\n----------------------------------------------------------')
print('initalizing population...')
old_population = []
for i in range(popSize):
temp = []
for j in range(len(w)):
temp.append(random.randint(0, 1))
old_population.append(temp)
print('evaluating fitnesses...')
ft = 0
wt = 0
population = {}
for i, chrom in enumerate(old_population):
ft = 0
wt = 0
for j, gene in enumerate(chrom):
ft += gene * int(v[j])
wt += gene * int(w[j])
population[chrom] = ft
print(i + 1, chrom, ft, wt)
##################################################################
####---Selection---#####
def roulette_wheel_selection():
max = sum([int(population[chrom]) for chrom in population])
pick = random.uniform(0, max)
current = 0
for chromosome in population:
current += population[chromosome]
if current > pick:
return chromosome
def k_tournament_selection():
best_c = []
best_ft = 0
for i in range(0, k):
initial_c = random.choice(list(population.keys()))
random_ft = population[initial_c]
if random_ft > best_ft:
best_ft = random_ft
best_c = initial_c
return best_c
fout.write('chromosome: 101010111000011\n')
fout.write('weight: 749\n')
fout.write('value: 1458')
fout.close()
|
76136aa0005ddbfd37cf3082c4fecccee02bb4da | Sloomey/DigitalNum_RPi | /src/digits.py | 1,802 | 4.375 | 4 | import LEDarea as area
""" This file is used to have each number be displayed through LEDs (every
number 0-9) using a function. The function's parameter takes a number which
is the number that gets displayed with LEDs. """
def digit(num):
if num == 0:
area.MIDDLE_TOP()
area.RIGHT_TOP()
area.LEFT_TOP()
area.LEFT_BOTTOM()
area.RIGHT_BOTTOM()
area.MIDDLE_BOTTOM()
elif num == 1:
area.RIGHT_TOP()
area.RIGHT_BOTTOM()
elif num == 2:
area.MIDDLE_TOP()
area.RIGHT_TOP()
area.MIDDLE_MIDDLE()
area.LEFT_BOTTOM()
area.MIDDLE_BOTTOM()
elif num == 3:
area.MIDDLE_TOP()
area.RIGHT_TOP()
area.MIDDLE_MIDDLE()
area.RIGHT_BOTTOM()
area.MIDDLE_BOTTOM()
elif num == 4:
area.LEFT_TOP()
area.RIGHT_TOP()
area.MIDDLE_MIDDLE()
area.RIGHT_BOTTOM()
elif num == 5:
area.MIDDLE_TOP()
area.LEFT_TOP()
area.MIDDLE_MIDDLE()
area.RIGHT_BOTTOM()
area.MIDDLE_BOTTOM()
elif num == 6:
area.MIDDLE_TOP()
area.LEFT_TOP()
area.MIDDLE_MIDDLE()
area.LEFT_BOTTOM()
area.RIGHT_BOTTOM()
area.MIDDLE_BOTTOM()
elif num == 7:
area.MIDDLE_TOP()
area.RIGHT_TOP()
area.RIGHT_BOTTOM()
elif num == 8:
area.MIDDLE_TOP()
area.LEFT_TOP()
area.RIGHT_TOP()
area.MIDDLE_MIDDLE()
area.LEFT_BOTTOM()
area.RIGHT_BOTTOM()
area.MIDDLE_BOTTOM()
elif num == 9:
area.MIDDLE_TOP()
area.LEFT_TOP()
area.RIGHT_TOP()
area.MIDDLE_MIDDLE()
area.RIGHT_BOTTOM()
area.MIDDLE_BOTTOM()
else:
print("Not a valid option.")
|
95277ade6069e1fd5b265e749ee18e4314406252 | zarozombie/music-tool | /Theory/chord.py | 994 | 3.84375 | 4 | import notes
# start = input("Enter Starting Note: \n")
# s = start.upper()
# root = notes.con_note(s)
# # print(root)
# root = int(root)
# first = root
# third = root + 4
# fifth = root + 7
# # print(first, third, fifth)
# print (notes.num_to_note(first), notes.num_to_note(third), notes.num_to_note(fifth))
def majchord(note):
root = notes.con_note(note.upper())
first = root
third = root + 4
fifth = root + 7
print(notes.num_to_note(first), notes.num_to_note(third), notes.num_to_note(fifth))
def minchord(note):
root = notes.con_note(note.upper())
first = root
third = root + 3
fifth = root + 7
print(notes.num_to_note(first), notes.num_to_note(third), notes.num_to_note(fifth))
def seventh(note):
root = notes.con_note(note.upper())
first = root
third = root + 4
fifth = root + 7
seventh = root + 11
print (notes.num_to_note(first), notes.num_to_note(third), notes.num_to_note(fifth), notes.num_to_note(seventh))
|
da995afe233213d8c4ecfb1eb891b6111a9351b4 | hs06146/Python | /1차원 배열/BJ_2562.py | 143 | 3.515625 | 4 | num = 0
index = 0
for i in range(9):
a = int(input())
if(a > num):
num = a
index = i + 1
print('%d\n%d'%(num, index)) |
25bd6cb192d98de533c89d7fe47cd0191f81f1fc | GMwang550146647/network | /3.爬虫/1.request/1.html_text.py | 695 | 3.578125 | 4 | """
1.反爬机制
1.反爬文件:
url/robots.txt
2.UA检查
"""
import os
import requests
urls = {
'sogou': {
'url': 'https://www.sogou.com/web',
'params': {
'query': 'gmwang'
},
'headers': {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15'
}
}
}
for namei, args in urls.items():
response = requests.get(args['url'], params=args['params'],headers=args['headers'])
content = response.text
save_file = os.path.join('download', f'{namei}.html')
with open(save_file, 'w') as f:
f.write(content)
|
d9afc2fbf4be2f42b30bc60cc590a63a21343a12 | shoaibrayeen/Programmers-Community | /Data Structure/Array Or Vector/Counting Sort/SolutionByVaishnavi.py | 904 | 3.578125 | 4 | def count_sort(arr):
max_element = int(max(arr))
min_element = int(min(arr))
range_of_elements = max_element - min_element + 1
count_arr = [0 for _ in range(range_of_elements)]
output_arr = [0 for _ in range(len(arr))]
for i in range(0, len(arr)):
count_arr[arr[i]-min_element] += 1
for i in range(1, len(count_arr)):
count_arr[i] += count_arr[i-1]
for i in range(len(arr)-1, -1, -1):
output_arr[count_arr[arr[i] - min_element] - 1] = arr[i]
count_arr[arr[i] - min_element] -= 1
for i in range(0, len(arr)):
arr[i] = output_arr[i]
return arr
#taking inputs
arrSize=int(input("Enter your array size:"))
arr=[]
print("Enter your array elements: ")
for i in range(arrSize):
arr.append(int(input()))
ans = count_sort(arr)
print("Sorted character array is " + str(ans))
|
04e6f673030f0b48b68580b10fd2d595001cbccf | emapco/Python-Code-Challenges | /count_unique_words.py | 1,486 | 3.796875 | 4 | from collections import Counter
import re
import string
# counts the number of unique words and how often each occurs
def count_unique_words(file_path):
with open(file_path, 'r', encoding='utf8') as file:
# regex matches all characters that are not alphanumeric, ', or -
forbidden_characters = ''.join([re.match("[^0-9a-zA-Z'-]+", char).string
for char in string.printable
if re.match("[^0-9a-zA-Z'-]+", char)])
word_counts = Counter()
for lines in file.readlines():
for word in lines.lower().split():
word_counts[word.strip(forbidden_characters)] += 1
total = sum(word_counts[key] for key in word_counts.keys())
print(f"Total Words: {total}\n")
print("Top 20 Words:")
for item in word_counts.most_common(20):
print("{:<20} {}".format(item[0], item[1]))
return word_counts
# does not properly parse "ALL'S"
def solution(path):
with open(path, encoding='utf8') as file:
all_words = re.findall(r"[0-9a-zA-Z-']+", file.read())
all_words = [word.upper() for word in all_words]
print("\nTotal Words:", len(all_words))
word_counts = Counter()
for word in all_words:
word_counts[word] += 1
print('\nTop 20 Words:')
for word in word_counts.most_common(20):
print(word[0], '\t', word[1])
return word_counts
|
957c78e36975520f3fdd24371916c5eb0ebbbb1d | AhlemKaabi/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 891 | 3.765625 | 4 | #!/usr/bin/python3
'''script that lists all cities from the
database hbtn_0e_4_usa
'''
if __name__ == "__main__":
import MySQLdb
from sys import argv
# Open database connection
db = MySQLdb.connect(
host="localhost",
user=argv[1],
password=argv[2],
database=argv[3],
)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# sql query string to be executed on the database
sql = """SELECT cities.id, cities.name, states.name
FROM cities
JOIN states
ON states.id = cities.state_id
ORDER BY cities.id
"""
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
# Now print fetched result
for row in results:
print(row)
cursor.close()
db.close()
|
32edac452bca0b5b977a91084f71d6699fdcd44e | arathym/sentimentprediction | /merge_test_files.py | 885 | 3.609375 | 4 | #----- combining all the text files into the csv and also removing the punctuations------
# This program should be run inside the test folder since we are taking all the global .text files from that folder
import glob
import string
fw = open('test_set.csv','wb') # file to which we are writing all the text files to
punc = string.punctuation # has all the punctuations
for files in glob.glob("DATA/test/test/*.txt"): # this searches all the pathnames(like .csv,.txt) provided in the folder
fr = open(files,'rb') # opening the file
data = fr.readline().translate(None, punc).lower() # removing the punctuations and converting all words to lower letters
fw.writelines(data + '\n') # writing the translated data to the csv file and adding new line at the end
fw.close() # closing the file to which we wrote
|
e78afcf31ab5c1038b4e15826dc2833412551d0c | JackoDev/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 325 | 4.15625 | 4 | #!/usr/bin/python3
"""a new moduke to count the number of lines of a file"""
def number_of_lines(filename=""):
"""function that returns the number of lines of a text file:"""
num_line = 0
with open(filename, encoding='utf-8') as a_file:
for line in a_file:
num_line += 1
return num_line
|
29260e64cd500d42ec06a7de941bca45658b3d03 | zhangyanan3/python-Artificial-Intelligence | /代码/第5章深度学习与神经网络/3-激活函数.py | 897 | 4.0625 | 4 |
# 3-激活函数python实现
def sigmoid(z):
""" Reutrns the element wise sigmoid function. """
return 1./(1 + np.exp(-z))
def sigmoid_prime(z):
""" Returns the derivative of the sigmoid function. """
return sigmoid(z)*(1-sigmoid(z))
def ReLU(z):
""" Reutrns the element wise ReLU function. """
return (z*(z > 0))
def ReLU_prime(z):
""" Returns the derivative of the ReLU function. """
return 1*(z >= 0)
def lReLU(z):
""" Reutrns the element wise leaky ReLU function. """
return np.maximum(z/100, z)
def lReLU_prime(z):
""" Returns the derivative of the leaky ReLU function. """
z = 1*(z >= 0)
z[z == 0] = 1/100
return z
def tanh(z):
""" Reutrns the element wise hyperbolic tangent function. """
return np.tanh(z)
def tanh_prime(z):
""" Returns the derivative of the tanh function. """
return (1-tanh(z)**2)
|
8654a979f5b006a59c05d8304560f5897ec00365 | PhillipLeeHub/python-algorithm-and-data-structure | /leetcode/230_Kth_Smallest_Element_in_a_BST_Medium.py | 547 | 3.5625 | 4 | 230. Kth Smallest Element in a BST Medium
Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Constraints:
The number of nodes in the tree is n.
1 <= k <= n <= 104
0 <= Node.val <= 104
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
|
9fd5230e59016a9677bc146446fe073bea12ae1b | eanyanwu/mirthful-rcis | /mirthful_rcis/dal/datastore.py | 1,479 | 3.9375 | 4 | from mirthful_rcis import get_db
import sqlite3
import os.path
class DbTransaction:
"""
Simplifies creating a database transaction
A transaction in this sense is any sequence of commands that are executed
before calling `commit`
This is done by using a python context manager to place all the boiler
plate code in one location.
When the context manager is used, it returns a cursor object.
When the context manager is exited, it executes the commit() method
"""
connection = None
def __init__(self):
pass
def __enter__(self):
self.connection = get_db()
cursor = self.connection.cursor()
return cursor
def __exit__(self, *args):
self.connection.commit()
def query(sql, args=None, one=False):
"""
Execute a single SQL command returns the results.
"""
with DbTransaction() as conn:
if args is None:
args = ()
conn.execute(sql, args)
results = conn.fetchall()
if one:
return next(iter(results), None)
else:
return results
def executemany(*args, **kwargs):
"""
Simple wrapper around the sqlite executemany method
"""
with DbTransaction() as conn:
conn.executemany(*args, **kwargs)
def execute_script(sql_script):
"""
Execute multiple sql statments at once
"""
with DbTransaction() as conn:
return conn.executescript(sql_script)
|
7fc28902c844db88132dad93ac04ca1e7e209d71 | terrifyzhao/leetcode | /other/max_path_sum.py | 774 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.max_path = float("-inf")
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.max_gain(root)
return self.max_path
def max_gain(self, node):
if not node:
return 0
left = max(self.max_gain(node.left), 0)
right = max(self.max_gain(node.right), 0)
new_path = node.val + left + right
self.max_path = max(self.max_path, new_path)
# 返回的是一条路径的值
return node.val + max(left, right)
|
b3e729e006026c40d1d834c916a8ab36f8030640 | CodeEMP/DCpython | /week2/tues/turtles/shapes.py | 1,968 | 3.75 | 4 | from turtle import *
def circle(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
circle(size)
def square(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
forward(size)
right(90)
forward(size)
right(90)
forward(size)
right(90)
forward(size)
def star(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
forward(size)
left(160)
forward(size)
left(160)
forward(size)
left(160)
forward(size)
left(160)
forward(size)
left(160)
forward(size)
left(160)
forward(size)
left(160)
forward(size)
left(160)
forward(size)
def hexagon(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
forward(size)
left(60)
forward(size)
left(60)
forward(size)
left(60)
forward(size)
left(60)
forward(size)
left(60)
forward(size)
def octogon(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
forward(size)
left(45)
forward(size)
left(45)
forward(size)
left(45)
forward(size)
left(45)
forward(size)
left(45)
forward(size)
left(45)
forward(size)
left(45)
forward(size)
def pentagon(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
forward(size)
left(72)
forward(size)
left(72)
forward(size)
left(72)
forward(size)
left(72)
forward(size)
def triangle(size, fill, color):
boo = fill
if boo is True:
fill(True)
fillcolor(color)
color(color)
forward(size)
left(120)
forward(size)
left(120)
forward(size) |
88dd626d84459c738bcb6918596b6dce66971e9f | rafin007/Machine-Learning | /Assignment - 1/Perceptron.py | 4,102 | 3.90625 | 4 | import numpy as np
from matplotlib import pyplot as plt
#Class for creating a Perceptron
class Perceptron:
#initialize perceptron
def __init__(self, neurons, bias, epochs, data, eta, dimensionality, num_training, num_testing):
self.neurons = neurons #number of input neurons
self.bias = bias #bias
self.epochs = epochs #number of epochs
self.data = data #training data
self.eta = eta #learning rate
self.dimensionality = dimensionality #dimensionality of the matrix
self.ee = np.zeros(num_training) #error difference between predicted value and generated value
self.mse = np.zeros(self.epochs) #mean squared error for plotting the graph
self.weight = np.zeros(neurons) #initial weight
self.num_training = num_training #number of training samples
self.num_testing = num_testing #number of testing samples
self.error_points = 0 #to keep track of the total testing error
#returns the shuffled dataset
def get_shuffled_dataset(self, sample):
shuffle_sequence = np.random.choice(self.data.shape[0], sample)
shuffled_data = self.data[shuffle_sequence]
return shuffled_data
#return the output of activation function
def activation_func(self, x):
y = np.sign(self.weight.dot(x) + self.bias)
return y
def fit(self): #learn through the number of traing samples
for e in range(self.epochs):
#shuffle the dataset for each epoch
shuffled_data = self.get_shuffled_dataset(self.num_training)
for i in range(self.num_training):
#fetch data
x = shuffled_data[i, 0:self.neurons]
#fetch desired output from dataset
d = shuffled_data[i, self.dimensionality]
#activation function
y = self.activation_func(x)
#calculate difference
self.ee[i] = d - y
#new weight
new_weight = self.weight + x.dot(self.ee[i] * self.eta)
#at any point if the weights are similar, then skip to the next epoch
if new_weight.any() == self.weight.any():
break
#otherwise set the new weight as current weight
self.weight = new_weight
#calculate mean squared error for each epoch
self.mse[e] = np.square(self.ee).mean()
print('End of training.')
print(f'Total points trained: {self.num_training}')
print(f'Total epochs: {self.epochs}')
print('____________________________________')
#show graph of learning curve against mean squared error
def plot_fit(self):
plt.xlabel('Epochs')
plt.ylabel('Mean squared error (mse)')
plt.title('Training accuracy')
plt.plot(self.mse)
plt.show()
def predict(self): #predict and calulate testing accuracy
shuffled_data = self.get_shuffled_dataset(self.num_testing)
for i in range(self.num_testing):
#fetch data
x = shuffled_data[i, 0:self.neurons]
# activation function
y = self.activation_func(x)
#plot x based on the result of activation function
if y == 1:
plt.plot(x[0], x[1], 'rx')
elif y == -1:
plt.plot(x[0], x[1], 'k+')
#calculate error points
if abs(y - shuffled_data[i, self.dimensionality]) > 0.0000001:
self.error_points += 1
#calculate testing accuracy
testing_accuracy = 100 - ((self.error_points/self.num_testing) * 100)
print('End of testing.')
print(f'Total points tested: {self.num_testing}')
print(f'Total errror points: {self.error_points}')
print(f'Testing accuracy: {testing_accuracy:.2f}%')
#plot testing graph
def plot_predict(self):
plt.title('Testing accuracy')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.show()
|
822b46685f0016d191c8d8116a50004915e74b40 | ArmandoBerlanga/python_playground | /src/python_tutorial/dictionaries.py | 711 | 3.875 | 4 | # Diccionarios, son lo mismo que los HashMaps en Java
digits = {
1 : "uno",
2 : "dos",
3 : "tres",
4 : "cuatro",
5 : "cinco",
6 : "seis",
7 : "siete",
8 : "ocho",
9 : "nueve",
0 : "cero"
}
value = int (input ("Inserte un valor numertico: "))
concat = ""
for c in str(value):
concat += (digits [int(c)]) + " "
print (concat)
'''
Puedes usar el metodo get en lugar del [key] para añadir parametros y/o que no se genere error
No se ocupan metodos especficios par asignar solo usa el [] y dale nuevos valores
'''
emojis = {
":)" : "😀",
":(" : "💩"
}
message = input("> ")
for s in message.split(" "):
print (emojis.get(s, s) + " ", end = " ")
|
f6f425c706bad902a44e85d3cc61b1bf7b805286 | tomreddle/vip3test | /第二次上课练习.py | 6,150 | 4.40625 | 4 | # 1、打印小猫爱吃鱼,小猫要喝水
class Cat:
def eat(self, food):
print('小猫爱吃{}'.format(food))
def drink(self):
print('小猫要喝水')
catty = Cat()
catty.eat('鱼')
catty.drink()
# 2、小明爱跑步,爱吃东西。——有吃、跑步两种方法
# 1)小明体重75.0公斤 ——人的属性
# 2)每次跑步会减肥0.5公斤 ——跑步的方法,每次减肥0.5公斤
# 3)每次吃东西体重会增加1公斤——吃的方法,每次吃增加1公斤
# 4)小美的体重是45.0公斤—— 小美的属性
class Person:
def __init__(self, weight, name):
self.weight = weight
self.name = name
def run(self):
self.weight -= 0.5
def eat(self):
self.weight += 1.0
xiaoming = Person(75.0, '小明')
xiaomei = Person(45.0, '小美')
xiaoming.run()
xiaomei.eat()
xiaomei.run()
print('{}现在的体重是{}'.format(xiaoming.name, xiaoming.weight))
print('{}现在的体重是{}'.format(xiaomei.name, xiaomei.weight))
# 3、摆放家具
# 需求:
# 1).房子有户型,总面积和家具名称列表(用字典更直接一点?)
# 新房子没有任何的家具
# 2).家具有名字和占地面积,其中
# 床:占4平米
# 衣柜:占2平面
# 餐桌:占1.5平米
# 3).将以上三件家具添加到房子中
# 4).打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表
class Room:
def __init__(self, room_type, area, furniture):
self.room_type = room_type
self.area = area
self.furniture = furniture
def room(self):
sum = 0
for i in list(self.furniture.values()):
sum += i
print('户型是{},总面积{},剩余面积有{},家具有{}'
.format(self.room_type, self.area, self.area - sum, list(self.furniture.keys())))
dic = {}
dic1 = {'床': 4, '衣柜': 2, '餐桌': 1.5}
new_room = Room('三室一厅', 90.26, dic)
new_room.room()
room = Room('三室一厅', 90.26, dic1)
room.room()
# 定义Room1 和 Furniture 两个类来实现
# Room 有户型,总面积和家具名称属性
# Furniture 有名字和占地面积 属性
# Room1类中调用Furniture中的属性进行打印
class Furniture:
def __init__(self, name, furniture_area):
self.name = name
self.furniture_area = furniture_area
class Room1:
def __init__(self, room_type1, area_total, furniture_name=[]):
self.room_type1 = room_type1
self.area_total = area_total
self.furniture_name = furniture_name
self.area_left = area_total
def add_furniture(self, jiaju):
self.furniture_name.append(jiaju.name)
# area_left = self.area_total
self.area_left -= jiaju.furniture_area
def room_print(self):
print('户型{}总面积{}家具有{}剩余面积{}'.format(self.room_type1, self.area_total, self.furniture_name, self.area_left))
bed = Furniture('床', 4)
closet = Furniture('衣柜', 2)
table = Furniture('餐桌', 1.5)
room1 = Room1('三室一厅', 30)
room1.add_furniture(bed)
room1.add_furniture(closet)
room1.add_furniture(table)
room1.room_print()
# 4.士兵开枪
# 需求:
# 1).士兵瑞恩有一把AK47
# 2).士兵可以开火(士兵开火扣动的是扳机)
# 3).枪 能够 发射子弹(把子弹发射出去)
# 4).枪 能够 装填子弹 --增加子弹的数量
# 士兵:姓名 枪 开火(使用枪)
# 枪:型号 子弹数量 发射动作 装填子弹
class Gun:
def __init__(self, gun_name, bullet_count=30):
self.gun_name = gun_name
self.bullet_count = bullet_count
def fire(self):
if self.bullet_count > 0:
print('发射一发子弹')
self.bullet_count -= 1
print('子弹还剩{}'.format(self.bullet_count))
else:
print('重新装弹')
self.reload()
def reload(self):
self.bullet_count += 30
print('子弹重新装填,{}发'.format(self.bullet_count))
class Soldier:
def __init__(self, soldier_name, gun_soldier):
self.soldier_name = soldier_name
self.gun_soldier = gun_soldier
print('士兵{}有一把{}'.format(self.soldier_name, self.gun_soldier))
def shoot(self, bullet_carry):
Gun(self.gun_soldier, bullet_carry).fire()
ryen = Soldier('瑞恩', 'AK47')
ryen.shoot(10)
# 读取文件内容
with open(r'E:\code\test.txt', 'r') as test:
# 定义列表存放L开头的姓名
l = []
# 定义列表存放出生日期
age = []
# 定义列表存放女性信息
female = []
s = test.readlines()
print(s)
for i in s:
print(i)
if i.find('L') != -1:
l.append(i.split('|')[0])
age.append(i.split('|')[-1].strip())
if i.find('女') != -1:
female.append(i.strip())
# for line in test:
# # line.strip()
# str3 = line.strip().split('|')
# if line.find('l') != -1:
# l.append(str3[0])
# age.append(age.append(str3[-1]))
print(l)
print(sorted(age))
print(female)
# for line in test:
# # line.strip()
# str3 = line.strip().split('|')
# if line.find('l') != -1:
# l.append(str3[0])
# age.append(age.append(str3[-1]))
# print(L)
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
# 任务1-找出所有L开头的人名
# 任务2-按照年龄进行排序
# 任务3-找出所有女性用户的信息
f = open(r'E:\code\data1.txt', 'r')
s = f.readlines()
# print(s)
f.close()
s1 = []
for i in s:
s1.append(i.strip().split('|'))
for j in range(len(s1) - 1):
for i in range(len(s1) - 1):
if s1[i][-1] > s1[i + 1][-1]:
c = s1[i]
s1[i] = s1[i + 1]
s1[i + 1] = c
s2 = []
for i in s1:
s2.append('|'.join(i))
print('按年龄从大到小排列{}'.format(s2))
s3 = []
s4 = []
for i in s:
if '女' in i:
s3.append(i.strip())
if i.startswith('L'):
s4.append(i.strip())
print('女性信息{}'.format(s3))
print('姓名中带L人员信息{}'.format(s4))
|
8442e5c6d85955ac9db619036f14ac6dea5d9d42 | hakusama1024/Practice | /Big_Integer.py | 1,493 | 3.71875 | 4 | class BigInteger:
def __init__(self, num):
self.bigInteger = []
self.sign = False
if num < 0:
self.sign = True
num = abs(num)
while num:
self.bigInteger.insert(0, num%10)
num /= 10
if self.sign:
self.bigInteger.insert(0, '-')
def add(self, n):
sign = False
if n < 0:
sign = True
n = -n
nlist = []
while n:
nlist.insert(0, n%10)
n/=10
if self.bigInteger[0] == '-' and sign:
self.bigInteger = self.addTwoList(self.bigInteger[1:], nlist)
self.bigInteger.insert(0, '-')
elif self.bigInteger[0] == '-' and not sign:
self.bigInteger = self.minusTwoList(nlist, self.bigInteger[1:])
elif self.bigInteger[0] != '-' and sign:
self.bigInteger = self.minusTwoList(self.bigInteger[1:], nlist)
elif self.bigInteger[0] != '-' and not sign:
self.bigInteger = self.addTwoList(self.bigInteger, nlist)
return self.bigInteger
def addTwoList(self, list1, list2):
print list1
print list2
list1 = list1[::-1]
list2 = list2[::-1]
l = []
s = []
if len(list1) < len(list2):
l = list2
s = list1
else:
l = list1
s = list2
acc = 0
for i in range(len(s)):
tmp = (l[i] + acc + s[i])/10
l[i] = (l[i]+s[i]+acc)%10
acc = tmp
print l
if acc:
for i in range(len(s), len(l)):
tmp = (l[i]+acc)/10
l[i] = (l[i]+acc)%10
acc = tmp
if acc:
l.append(1)
return l[::-1]
def minusTwoList(self, list1, list2):
return list1
a = BigInteger(9999999)
print a.add(21341)
|
dede3764d57eb9909477a8bd1caa35b77e856178 | hamdi3/Python-Practice | /Generators.py | 2,315 | 4.375 | 4 | #Generators are used when dealing with very long lists since theyre are mem. efficent (Lazy object)
def genraum(n):
for num in range(n):
yield num**3 #using yield instead of return is by generators since the generators only run once and does'nt sotore anything in the memory meaning its significantly efficent and faster
#for x in genraum (10): #gen. are to be called lke this
# print(x)
def genfib(n):
a = 1
b = 1
output = []
for i in range(n):
output.append(a)
yield a
a,b = b, a+b
def fib(n): #the same code without yield would be (this is a normal func)
a = 1
b = 1
output = []
for i in range(n):
output.append(a)
a,b = b, a+b
return output
for num in genfib(3):#there are no upper limit since this is only calculated when called and not saved in the memory
print("this was done by gen",num)
print("done by func",fib(10))# we dont need a for loop here but since it's not a generator this would lead to an exception later on when using bigger number
def simple_gen():
for x in range(3):
yield x
g = simple_gen()
print(g) # this would only say that g is refering to a gen. also an object
print("the first elim in simple_gen is",next(g)) #generator can be used with next(), p.s the first next would only give us the first elim
print("the sec elim in simple_gen is",next(g))#calling it again will give the second elim since generator are only used once
print("the 3d elim in simple_gen is",next(g))#third elim
#print("the first elim in simple_gen is",next(g)) calling it a fourth time would lead to an error since it only give the first 3 values (in range(3))
#iterators
s ="hello"
s_iter = iter(s) #thats how to make an iterator (to use next with) like genrator
print(next(s_iter))
#Assessments
#Generator 1 for quadrates number
def genquadrate(N):
for i in range(N):
yield i*i
for i in genquadrate(10):
print("genquadrate",i)
#Generator 2 for random numbers between to nums
import random
def zuf_zahl(unten,oben,N):
for i in range(N):
yield random.randint(unten,oben)
for num in zuf_zahl(1,10,3):
print("random number",num)
#another way to build gen
l = [1,2,3,4,5,6,7]
gen = (item for item in l if item > 4) #this uses a yield automaticly
for i in gen:
print(i)
|
dd4160faf7592705626f7e9dee95fa6f55d10a13 | claudey/zoo-assignment | /zoo_class.py | 3,386 | 3.890625 | 4 | class Zoo:
def __init__(self,name,gender,age):
self.name = name
self.gender = gender
self.age = age
def get_injured(self):
pass
##
####class for animals
####and all of its sub classes
##
class Animals(Zoo):
def __init__(self,name,gender,age):
Zoo.__init__(self,name,gender,age)
def feed(self):
pass
def reproduce(self):
pass
def gestation_period(self):
pass
def defense_mechanism(self,defense_mechanism):
pass
## class for the mode of movement
## inheriting from animals
class Mode_of_movement(Animals):
def __init__(self,name,gender,age,mode_of_movement):
Animals.__init__(self,name,gender,age)
self.mode_of_movement = mode_of_movement
def get_mode_of_movement(self):
return self.mode_of_movement
## class for Type of animals
## inheriting from animals
class Type (Animals):
def __init__(self,name,gender,age,Type):
Animals.__init__(self,name,gender,age)
self.type = Type
def get_type(self):
return self.type
##this is the class for people
##and all of its subclasses
class People(Zoo):
def __init__(self,name,gender,age,arrival,departure):
Zoo.__init__(self,name,gender,age)
self.phoneNo = ''
self.address = ''
self.email = ''
self.arrival = arrival
self.departure = departure
def __str__(self):
print "this is the people"
def set_phoneNo(self, phoneNo):
self.phoneNo= phoneNo
def set_address(self, address):
self.address = address
def set_email(self, email):
self.email = email
def get_phoneNo(self):
return self.phoneNo
def get_address(self):
return self.address
def get_arrival(self):
return self.arrival
def get_departure(self):
return self.departure
def get_email(self):
return self.email
## This is the class for workers
## inheriting from people
class workers(People):
def __init__(self,name,gender,age,arrival,departure,year_of_emp):
People.__init__(self,name,gender,age,arrival,departure)
self.department = ''
self.speciality = ''
self.position = ''
self.year_of_emp = year_of_emp
def set_department(self, department):
self.department = department
def set_position(self, position):
self.position = position
def set_speciality(self, speciality):
self.speciality = speciality
def get_position(self):
return self.position
def get_department(self):
return self.department
def get_specialty(self):
return self.specialty
def get_year_of_emp(self):
return self.year_of_emp
def no_of_vistors_being_guided(self):
pass
class Visitors(People):
def __init__(self,name,gender,age,date,arrival_time,purpose):
People.__init__(self,name,gender,age,arrival,departure)
self.purpose = purpose
self.depart_time = ''
def set_depart_time(self,depart_time):
self.depart_time = depart_time
def set_purpose(self, purpose):
self.purpose = purpose
def get_purpose(self):
return self.purpose
def add_visitor(self):
pass
def rem_visitor(self):
pass
|
325f782db869edeb8ba40308a8c01002984d00d8 | Asha-Billava/django-rest-calendar | /core/utils.py | 745 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import pytz
# Assume the calendar is for Europeans only (as it currently has only Polish language).
TIMEZONE_CONTINENT = "Europe"
# Assume the application is for Poles mostly (as it currently has only Polish language).
DEFAULT_TIMEZONE = "Europe/Warsaw"
SYSTEM_TIMEZONE = "Europe/Warsaw"
def get_timezones():
"""
Return timezones. Only one continent will suffice for the scope of the exercise.
"""
return tuple([(x, x) for x in pytz.all_timezones if TIMEZONE_CONTINENT in x])
def normalize_to_utc(time, timezone):
"""
Convert naive time into given timezone, then UTC
"""
utct = pytz.timezone(u'UTC')
tzt = pytz.timezone(timezone)
return tzt.localize(time).astimezone(utct)
|
fd7abfc15d0b61465243e3092042ff03e7288dd4 | husnejahan/MyLeetcode-practice | /Algorithms and data structures implementation/Graph/boggleSearch.py | 3,144 | 4.03125 | 4 | """You're given a 2D Boggle Board which contains an m x n matrix (2D list) of characters, and a string - word. Write a method - boggle_search that searches the Boggle Board for the presence of the input word. Words on the board can be constructed with sequentially adjacent letters, where adjacent letters are horizontal or vertical neighbors (not diagonal). Also, each letter on the Boggle Board must be used only once.
Example:
Input Board :
[
[A, O, L],
[D, E, L],
[G, H, I],
]
Word: "HELLO"
Output: True
"""
#Approach 1
def boggle_search(board, word):
# do dfs
rows = len(board)
cols = len(board[0])
for r in range(rows):
for c in range(cols):
if board[r][c] == word[0]:
# do dfs
if dfs(board, r, c, word) == True:
return True
return False
def dfs(board, r, c, word):
to_visit = [(r, c, 0)]
visited = set()
visited.add((r, c, 0))
while to_visit:
current = to_visit.pop()
r, c, i = current[0], current[1], current[2]
print(r, c, i)
if board[r][c] == word[i]:
# add the next cells to stack
if i == len(word) - 1:
return True
if isValid(r - 1, c, board) and (r - 1, c, i + 1) not in visited:
to_visit.append((r - 1, c, i + 1))
# r + 1, c
if isValid(r + 1, c, board) and (r + 1, c, i + 1) not in visited:
to_visit.append((r + 1, c, i + 1))
# r, c- 1
if isValid(r, c - 1, board) and (r, c - 1, i + 1) not in visited:
to_visit.append((r, c - 1, i + 1))
# r, c + 1
if isValid(r, c + 1, board) and (r, c + 1, i + 1) not in visited:
to_visit.append((r, c + 1, i + 1))
visited.add(current)
return False
def isValid(r, c, aboard):
return 0 <= r < len(aboard) and 0 <= c < len(aboard[0])
#Approach 2
def boggle_search(board,word):
rows = len(board)
cols = len(board[0])
out = False
for i in xrange(rows):
for j in xrange(cols):
out = search(i,j,board,word,"")
if out:
return True
return out
def search(r,c,board,word,predecessor):
rows = len(board)
cols = len(board[0])
# Terminating Conditions
if (r > rows -1 # Out of Bounds
or r < 0 # Out of Bounds
or c > cols-1 # Out of Bounds
or c < 0 # Out of Bounds
or predecessor not in word # Not matching pattern
or board[r][c] == '@'):
return False
ch = board[r][c]
s = predecessor + ch
out = False
if s == word:
return True
else:
board[r][c] = '@' # Mark the board node as visited
# Check up, down, left, right
out = search(r-1,c,board,word,s) or search(r+1,c,board,word,s) or search(r,c-1,board,word,s) or search(r,c+1,board,word,s)
board[r][c] = ch # Unmark the board node
return out |
955291aad2dc60394164db84b47188bad795bbbe | NPozn/Python_Lab_7 | /Task4.py | 368 | 3.71875 | 4 | #Содержит ли согласные буквы
import re
def ContainSymbols(s):
return re.findall(r"[wrtpsdfghjklzxcvbnmцкнтглдшщзхфвпртсчб]", s) != []
exist = ContainSymbols(input("Введите слово"))
if exist == True :
print("Есть согласная буква")
else:
print("Согласной буквы нет") |
773e7ea877e8179e62382ca04408d30eb70c078e | zelanko/MyProjectEulerSolutions | /Project_0005/SmallestMultiple.py | 483 | 3.609375 | 4 | """Smallest multiple
[Problem 5](https://projecteuler.net/problem=5)
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"""
candidate = 2520
found = False
while not found:
for n in range(2, 21):
if candidate % n != 0:
candidate += 1
break
else:
found = True
print(candidate)
|
b8d463232b0521f1c5d729c6428b75a7234b242a | RawitSHIE/Algorithms-Training-Python | /Dote.py | 296 | 3.640625 | 4 | """
60070081
Dot_E
"""
def main():
"""dota"""
per = int(input())
if per%2 == 1:
per += 1
team = fac(per)/(fac(per/2)*fac(per/2))
print(int(team))
def fac(num):
"""fac"""
count = 1
for i in range(1, int(num)+1):
count *= i
return count
main()
|
269b476e19b9f54aead730a204f2bb554e1c7c25 | OneCalledSyn/project-euler | /Python Problems/euler12.py | 1,100 | 3.734375 | 4 | # What is the value of the first triangle number to have over five hundred divisors?
#First try (failure)
import math
n = 5
divisors = 1
number = 6
x = 4
while True:
for i in range(2, math.floor(number/2) + 2):
if number % i == 0:
divisors += 1
if divisors = n:
break
number += x
x += 1
divisors = 1
print(number)
# Second try: What did I learn?
# Tau(n), which gives the number of divisors, is the product of the degree of each prime factor + 1
# How to get program runtime using timeit module
import timeit
start = timeit.default_timer()
def tau(number):
n = number
p = 2
e = 1
if number == 1:
return 1
while (p * p <= n):
counter = 1
while (n % p == 0):
n /= p
counter += 1
p += 1
e *= counter
if (n == number or n > 1):
e *= 1 + 1
return e
def euler12(n):
x = 1
y = 1
while tau(y) < n :
x += 1
y += x
return y
print(euler12(501))
stop = timeit.default_timer()
print('Program Runtime: ', stop - start)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.