blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e68dea6c5620f5fdcb0b46f916f2fb5b9ca72540 | MrNullPointer/AlgoandDS | /Udacity_NanoDegree/Recursion_revisited/Intro.py | 637 | 3.921875 | 4 | def power_of_2(input):
if input <= 0:
return 1
output = power_of_2(input - 1)
return 2 * output
def sum_of_integers(input):
if input <= 0:
return 0
return input + sum_of_integers(input - 1)
def sum_array(array):
if len(array) <= 0:
return 0
first_elem = array[0]
return first_elem + sum_array(array[1:])
def sum_array_1(array):
return sum_array_idx(array,0)
def sum_array_idx(array,idx):
if len(array) == idx:
return 0
return array[idx] + sum_array_idx(array,idx + 1)
print(sum_array_1([1, 2, 3, 4]))
# print(sum_of_integers(30))
# print(power_of_2(10))
|
0f4ac3d796e581f45a53da2b9a217ea22f2b3ca5 | Gauri69Gupta/python | /file.py | 1,042 | 3.71875 | 4 | print("Question1")
n=int(input("Enter the number of lines: "))
with open("1.txt", "r") as text_file:
contents = text_file.readlines()[-n:]
for line in contents:
print(line)
print('*'*10)
print('\n')
print("Question2")
file=open("1.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print(k, v)
print('*'*10)
print('\n')
print("Question3")
with open('1.txt','r') as ff:
x=ff.read()
with open('2.txt','w') as zz:
a=zz.write(x)
print('*'*10)
print('\n')
print("Question4")
with open('3.txt') as fh1, open('4.txt') as fh2:
for line1, line2 in zip(fh1, fh2):
print(line1+line2)
print('*'*10)
print('\n')
print("Question5")
data = []
with open('5.txt','r') as myfile:
for line in myfile:
data.extend(map(int, line.split(',')))
var=sorted(data)
print(var)
with open('6.txt','w') as myfile2:
for ele in var:
myfile2.write(str(ele))
print('*'*10)
|
0c017617ba8c27d9a7848d376ba17e0005d8e08c | Fuddlebob/CGAAPIMM | /transform/mirror.py | 1,047 | 3.5625 | 4 | from . import abstractTransform
from helper import *
import cv2
import numpy as np
import random
class mirrorTransform(abstractTransform.abstractTransformClass):
def name():
#short form name for the transform
return "Mirror"
def description():
#return a brief description of what the transform does
return "Mirrors the image vertically or horizontally."
def transform(image):
#take in an openCV image and transform it, returning the new image
flip = random.randint(0, 1)
mirror = random.randint(0, 1)
flipimg = cv2.flip(image, flip)
h, w = img_size(image)
if(flip):
#horizontal flip
m = int(w/2)
if(mirror):
#mirror left to right
image[0:h, m:w] = flipimg[0:h, m:w]
else:
#mirror right to left
image[0:h, 0:m] = flipimg[0:h, 0:m]
else:
#vertical flip
m = int(h/2)
if(mirror):
#mirror top to bottom
image[m:h, 0:w] = flipimg[m:h, 0:w]
else:
#mirror bottom to top
image[0:m, 0:w] = flipimg[0:m, 0:w]
return image |
29fa4d91b9e3c4def2e17f0927f0c32b5ffc5929 | vain01/pythonlearning | /grammar/continue_7_7.py | 288 | 3.984375 | 4 | running = True
while running:
s = input('输入字符串:')
if s == 'exit':
running = False
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('输入的长度足够')
else:
print('循环结束')
print('结束')
|
7d31bc9626ef38efc837f3d97cae423213abe7fe | RubeusH/Python_Learning | /Chapter-02/Programming-Exercises/programming-exercise-2-08.py | 309 | 3.78125 | 4 | TIP = 0.18
TAX = 0.07
total_amount = float(input("How much is the total: "))
tip = TIP * total_amount
tax = TAX * total_amount
print("GRAND TOTAL = $" + format(total_amount+tip+tax,'.2f'), "\n\tPURCHASE = $" + format(total_amount, '.2f'), "\n\tTIP = $" + format(tip,'.2f'), "\n\tTAX = $" + format(tax,'.2f'))
|
874d55111c478dbdef223547238e8300e1590848 | harshit3012/AI_Lab | /Lab 1/ticTacToe.py | 4,242 | 3.515625 | 4 | import random
import colorama
from colorama import Fore, Style
board = [' ' for _ in range(10)]
user_char = ''
comp_char = ''
def printBoard(board):
global user_char, comp_char
print("\033c", end="")
print(Fore.GREEN + 'Tic Tac Toe! \n')
print(Fore.WHITE + f'Your player : {user_char}')
print(f'Computer player : {comp_char}', end="\n\n")
print(Fore.BLUE + ' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print('-----------')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print('-----------')
print(' ' + board[7] + ' | ' + board[8] + ' | ' +
board[9] + Style.RESET_ALL, end='\n\n')
def spaceIsFree(pos):
return board[pos] == ' '
def isWinner(bo, le):
return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or (bo[1] == le and bo[2] == le and bo[3] == le) or (bo[1] == le and bo[4] == le and bo[7] == le) or (bo[2] == le and bo[5] == le and bo[8] == le) or (bo[3] == le and bo[6] == le and bo[9] == le) or (bo[1] == le and bo[5] == le and bo[9] == le) or (bo[3] == le and bo[5] == le and bo[7] == le)
def insertLetter(letter, pos):
board[pos] = letter
def selectRandom(li):
r = random.randrange(0, len(li))
return li[r]
def isBoardFull(board):
if board.count(' ') > 1:
return False
return True
def playerMove():
run = True
while run:
move = input(f'\nSelect a position to place an {user_char}: ')
try:
move = int(move)
if move > 0 and move < 10:
if spaceIsFree(move):
run = False
insertLetter(user_char, move)
else:
print('Sorry, this space is occupied!')
else:
print('Please type a number within the range!')
except:
print('Please type a number!')
def compMove():
possibleMoves = [x for x, letter in enumerate(
board) if letter == ' ' and x != 0]
move = 0
for let in [comp_char, user_char]:
for i in possibleMoves:
boardCopy = board.copy()
boardCopy[i] = let
if isWinner(boardCopy, let):
move = i
return move
if 5 in possibleMoves:
move = 5
return move
cornersOpen = []
for i in possibleMoves:
if i in [1, 3, 7, 9]:
cornersOpen.append(i)
if len(cornersOpen) > 0:
move = selectRandom(cornersOpen)
return move
edgesOpen = []
for i in possibleMoves:
if i in [2, 4, 6, 8]:
edgesOpen.append(i)
if len(edgesOpen) > 0:
move = selectRandom(edgesOpen)
return move
def playerChoose():
global user_char, comp_char
print('\nTic Tac Toe! \n')
user_input = input('Enter your player (O / X): ')
while(user_input not in ['o', 'O', '0', 'x', 'X']):
print("Sorry. That's invalid")
user_input = input('Enter your player (O / X): ')
if user_input in ['o', 'O', '0']:
user_char = 'O'
comp_char = 'X'
else:
user_char = 'X'
comp_char = 'O'
def main():
global board, user_char, comp_char
playerChoose()
play = True
while play:
while not(isBoardFull(board)):
if not(isWinner(board, comp_char)):
printBoard(board)
playerMove()
else:
print('Computer won this time.. Hehe!')
break
if not(isWinner(board, user_char)):
move = compMove()
if move == 0:
print('Tie Game!')
else:
insertLetter(comp_char, move)
print(
f'Computer placed an {comp_char} in position', move, ':')
printBoard(board)
else:
print('You won this time! Good Job!')
break
if input('Do you want to play again? (Y/N) ').lower() in ['y', 'yes']:
board = [' ' for _ in range(10)]
print('-----------------------------------')
else:
play = False
if __name__ == "__main__":
main()
|
06207118a538a9fdaa5042bee37639d741d1a777 | preetkd/Mile7 | /Package4Image.py | 1,697 | 3.59375 | 4 |
# Downloading Zip file from URL
from urllib.request import urlopen
from zipfile import ZipFile
import re
# Function to Unzipfile defining upload path
def FileDwnLdFun(path):
zipurl = path
# Download the file from the URL
zipresp = urlopen(zipurl)
# Create a new file on the hard drive
tempzip = open('tempfile.zip', "wb")
# Write the contents of the downloaded file into the new file
tempzip.write(zipresp.read())
# Close the newly-created file
tempzip.close()
# Re-open the newly-created file with ZipFile()
zf = ZipFile("tempfile.zip")
# Extract its contents into <extraction_path>
# note that extractall will automatically create the path
zf.extractall(path = 'Images')
# close the ZipFile instance
zf.close()
filname = path
fup = re.split('/', filname)
filenm = (re.split('\.', fup[5]))
fileup = filenm[0]+'.csv'
upath = fileup
return upath
# Zipping done , Image folder created in ImageExtraction1.py
#----------------------------------------------------------------------------------
# #your path
# col_dir = 'Mile1Images/*.jpg'
#
# #creating a collection with the available images
# images = imread_collection(col_dir)
# assert isinstance(images, object)
#
# print("single Image" )
# print(images[0])
# i=1
# for img in images:
# print("image -------------------")
# if i is 1:
# break
# print(img)
#
#
#
# def load_images(folder):
# images = []
# for filename in folder:
# print(filename)
# img = cv2.imread(filename)
# if img is not None:
# images.append(img)
# return images
#
#
# #images1 = load_images(col) |
265e7b26d9866f09b8da9342e0683841100d7e0a | jiyiyun/programing | /python3/follow_laoqi/part4_Classes/class_Inheritance.py | 389 | 3.875 | 4 | __metaclass__ = type
class Person:
def speak(self):
print "This speak is in class not inheritance"
def setHeight(self):
print "old calss 216 cm"
def weight(self):
print "weight is old class 60 kg"
class man(Person):
def setHeight(self):
print "The height is new 199,not father_class"
if __name__ == "__main__":
jack = man()
jack.setHeight()
jack.speak()
jack.weight()
|
36c583032a301779b7a8f71bd2ef9c7727c51130 | feverrro/Python | /sorting.py | 976 | 3.53125 | 4 | # li = [9,1,8,2,7,3,6,4,5]
# s_li = sorted(li, reverse=True)
# print('Sorted Variable:\t', s_li)
# li.sort(reverse=True)
# print('Original Variable:\t', li)
# tup = (9,1,8,2,7,3,6,4,5)
# s_tup = sorted(tup)
# print('Tuple\t',s_tup)
# di = {'name': 'Corey', 'job': 'programming', 'age': 'None', 'os': 'Mac'}
# s_di = sorted(di)
# print('Dic\t',di)
# print('Sorted Dic\t',s_di)
# li = [-6,-5,-4,1,2,3]
# s_li = sorted(li, key=abs)
# print(s_li)
class Employee():
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def __repr__(self):
return '({},{},${})'.format(self.name, self.age, self.salary)
from operator import attrgetter
e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)
Employees = [e1,e2,e3]
# def e_sort(emp):
# return emp.salary
# lambda e:e.name
s_Employees = sorted(Employees, key=attrgetter('age'))
print(s_Employees)
|
6ac3da8f43f1900e3393fb0a6f8e8edd4b3c7c93 | Nzadrozna/main | /labs/04_conditionals_loops/03_06_while.py | 185 | 4.0625 | 4 | '''
Use a "while" loop to print out every fifth number counting from 1 to 1000.
w
'''
# start at one then go up by 5 till 1000
#
n = 0
while n < 1000:
n = n + 5
print (n)
|
10c7208d814939c47c571e3f2ef6d6782f526484 | chrisglencross/advent-of-code | /aoc2021/day2/day2.py | 866 | 3.796875 | 4 | #!/usr/bin/python3
# Advent of code 2021 day 2
# See https://adventofcode.com/2021/day/2
import re
with open("input.txt") as f:
lines = f.readlines()
def follow_commands(lines, forward, depth):
p, d, aim = 0, 0, 0
for line in lines:
match re.search("^([a-z]+) ([0-9]+)$", line.strip()).groups():
case ["forward", x]:
p, d, aim = forward(p, d, aim, int(x))
case ["up", x]:
p, d, aim = depth(p, d, aim, -int(x))
case ["down", x]:
p, d, aim = depth(p, d, aim, int(x))
print(p * d)
follow_commands(lines,
lambda p, d, aim, x: (p + x, d, aim),
lambda p, d, aim, x: (p, d + x, aim))
follow_commands(lines,
lambda p, d, aim, x: (p + x, d + (x * aim), aim),
lambda p, d, aim, x: (p, d, aim + x))
|
ee26fd79baf700f7cf201916352f41c9874eb835 | mdjukic/repos | /q_python_scripts/return2.py | 1,148 | 4.09375 | 4 | # Returning values
# like python's built-in str() function, which returns a string
# representation of the value specified as its argument by the caller
# custom functions
from __future__ import print_function
import os
import sys
from datetime import datetime
def main(args):
num = str(raw_input('Enter an Intger:') )
result = squared(num)
print('result-->', result)
def squared(num):
if not num.isdigit():
return('Invalid entry')
num = int(num)
return(num*num)
if __name__ == '__main__':
print ('Start of return.py at.....', format(str(datetime.now())))
main(sys.argv[1:])
print ('End of return.py at.....', format(str(datetime.now())))
##############
# typically a 'return' statement will appear at the end of a
# function block to return the final result of executing all statement s
# contained in that function
####
#Enter an Intger:g
#Traceback (most recent call last):
# File "return2.py", line 29, in <module>
# main(sys.argv[1:])
# File "return2.py", line 12, in main
# num = str(input('Enter an Intger:') )
# File "<string>", line 1, in <module>
#NameError: name 'g' is not defined
#
#***Repl Closed***
|
870b8f2dbe5a2803e2e61fa49aa5bd8b7384dfc3 | AdarshRazor/Cracking_Coding_Interview | /Codes and Implementation/Chapter 2 - Linked Lists/2.KthtoLast.py | 1,285 | 4.0625 | 4 | import os
os.system('cls')
class Node:
def __init__(self,data):
self.data=data
self.next=None
'''
find the kth to last element of a singly linked list.
'''
class LinkedList:
def __init__(self):
self.head=None
def appendnode(self,data):
New_Node = Node(data)
if self.head==None:
self.head=New_Node
return
last_node=self.head
while last_node.next!=None:
last_node=last_node.next
last_node.next=New_Node
def printnode(self):
Curr_Node=self.head
while Curr_Node!=None:
print("(",Curr_Node.data,end=" ) --> ")
Curr_Node=Curr_Node.next
print("\n")
def kth_element(self,num):
if num == 0: return None
Curr_Node=self.head
for num in range(0,num-1):
Curr_Node=Curr_Node.next
while Curr_Node is not None:
print("(",Curr_Node.data,end=" ) --> ")
Curr_Node=Curr_Node.next
print("\n")
ll=LinkedList()
ll.appendnode(1)
ll.appendnode(2)
ll.appendnode(3)
ll.appendnode(4)
ll.appendnode(5)
ll.printnode()
print("Priting from 2 to last element . . .")
ll.kth_element(2)
print("Priting from 4 to last element . . .")
ll.kth_element(4) |
a789d39572bbd832bfb9e9a7caa545f245cf1322 | maxoyed/CQU_2021_Spring_Python018 | /题库/第六章练习(分支、循环)/编程题/18.加密数据.py | 173 | 3.578125 | 4 | raw_number = [int(i) for i in list(input())]
password = [(i + 5) % 10 for i in raw_number]
password.reverse()
password = [str(i) for i in password]
print(''.join(password))
|
e8d0f7b265e5966e4d495f63f269d7dc53cef6d3 | zcg741/leetcode | /python-leetcode/src/string/titleToNumber.py | 718 | 3.515625 | 4 | # 给定一个Excel表格中的列名称,返回其相应的列序号。
#
# 例如,
#
# A -> 1
# B -> 2
# C -> 3
# ...
# Z -> 26
# AA -> 27
# AB -> 28
# ...
#
#
# 示例 1:
#
# 输入: "A"
# 输出: 1
#
#
# 示例 2:
#
# 输入: "AB"
# 输出: 28
#
#
# 示例 3:
#
# 输入: "ZY"
# 输出: 701
#
# 致谢:
# 特别感谢 @ts 添加此问题并创建所有测试用例。
#
class Solution:
def titleToNumber(self, s: str) -> int:
numA = ord("A")
ans = 0;
for i in s:
num = (ord(i) - numA) + 1
ans = ans * 26 + num
return ans
s = Solution()
print(s.titleToNumber("A"))
print(s.titleToNumber("AB"))
print(s.titleToNumber("ZY"))
|
051972eda0f011b6344b0accd76bc4baa79f455e | tr0ublye/strukturnoe | /lab3/5.py | 119 | 3.59375 | 4 | import math
n=int(input("vvedi n: "))
m=int(input("vvedi m: "))
s=sum(i*i for i in range(n, m+1))
print (s)
|
627a4dd615278850dee1f2052907ae5072aee276 | Myles-Trump/ICS3U-Unit4-03 | /main.py | 930 | 4.5 | 4 | #!/usr/bin/env python3
# Created by: Myles Trump
# Created on: May 2021
# This program uses a while loop to solve the power of ever number
# up to the inputted number
def main():
# this function uses a while loop to solve the power of ever number
# up to the inputted number
# this is to keep track of how many times you go through the loop
loop_counter = 0
# input
print("\n", end="")
positive = input("Enter an integer to power: ")
# process & output
try:
positive_int = int(positive)
print("\n", end="")
while loop_counter <= positive_int:
powered_number = loop_counter ** 2
print("{0}² = {1}".format(loop_counter, powered_number))
loop_counter = loop_counter + 1
except Exception:
print("\nYou have entered an invalid integer.")
finally:
print("\nDone.")
if __name__ == "__main__":
main()
|
044c8140323d0dcc1fe8190c0beccb2e68823c3a | maxwell-carmichael/chess_ai | /MinimaxAI.py | 4,537 | 3.625 | 4 | # Maxwell Carmichael, 10/10/2020, Modified from CS76 Material
import chess
import math
import random
class MinimaxAI():
def __init__(self):
self.depth = 3 # Constant
self.nodes_visited = 0 # will reset after each move.
self.random_factor = 0.1 # the percent chance that an as-good move overrides some other move to prevent cycles.
random.seed(17) # for replicability. i like the number 17.
# choose best move given a board
def choose_move(self, board):
# if it's white's turn, call max. if it's black's turn, call min.
if board.turn:
util_action = self.max_value(board, 0)
else:
util_action = self.min_value(board, 0)
move = util_action[1] # action
print("Move Utility: " + str(util_action[0])) # utility
print("Maximum Depth: " + str(self.depth))
print("Nodes visited: " + str(self.nodes_visited))
self.nodes_visited = 0 # reset
print("MinimaxAI recommending move " + str(move))
return move
# white move. returns a (utility, move) pair
def max_value(self, board, depth):
self.nodes_visited += 1 # increment
if self.cutoff_test(board, depth):
return (self.material_value_heuristic(board), None)
v = -math.inf
util_action = None # the (utility, move) pair to return
for move in board.legal_moves:
board.push(move) # make the move
move_util_action = self.min_value(board, depth + 1)
if move_util_action[0] > v: # finding maximum utility we can get...
v = move_util_action[0]
util_action = (v, move)
# to prevent loops (always choosing same move), make there be an override possibility for our v
elif move_util_action[0] == v and random.choices([True, False], cum_weights = [self.random_factor, 1]):
util_action = (v, move)
board.pop() # unmake the move
return util_action
# black to move. returns a (utility, move) pair
def min_value(self, board, depth):
self.nodes_visited += 1
if self.cutoff_test(board, depth):
return (self.material_value_heuristic(board), None)
v = math.inf
util_action = None # the (utility, move) pair to return
for move in board.legal_moves:
board.push(move) # make the move
move_util_action = self.max_value(board, depth + 1)
if move_util_action[0] < v: # finding minimum utility we can get...
v = move_util_action[0]
util_action = (v, move)
# to prevent loops (always choosing same move), make there be an override possibility for our v
elif move_util_action[0] == v and random.choices([True, False], cum_weights = [self.random_factor, 1]):
util_action = (v, move)
board.pop() # unmake the move
return util_action
# stop iterating if the game is over or if depth limit is reached
def cutoff_test(self, board, depth):
return board.is_game_over() or self.depth == depth
def material_value_heuristic(self, board):
# win
if board.is_checkmate():
# white's turn, so black just checkmated
if board.turn:
return -10000
# black's turn, so white just checkmated
else:
return 10000
# stalemate, insufficient material, etc.
if board.is_game_over():
return 0
# heuristic at depth limit
map = board.piece_map()
heuristic = 0 # this heuristic will be for white player
# loops through all the pieces and adds them to the heuristic
for square in map:
piece = map[square]
val = 0
if piece.piece_type == 1: # pawn
val = 1
elif piece.piece_type == 2 or piece.piece_type == 3: # knight, bishop
val = 3
elif piece.piece_type == 4: # rook
val = 5
elif piece.piece_type == 5: # queen
val = 9
if piece.color: # white
heuristic += val
else:
heuristic -= val
# considers whether a player puts the other in check
if board.is_check():
if board.turn: # white in check
heuristic -= 0.5
else:
heuristic += 0.5
return heuristic
|
7e1bf8ced55312d987b87c316ff68d3647457e8f | Nehanavgurukul/list | /palindrome1.py | 227 | 4.03125 | 4 | first_list=[1,2,3,4,5,4,3,2,1]
last_list=[]
i=len(first_list)-1
while(i>=0):
last_list.append(first_list[i])
i=i-1
if(first_list==last_list):
print("it is palindrome")
else:
print("it is not palindrome")
|
a5f98a800bd485f463f73f9259bb42eba217fd8c | PriyanSiva/pong-game | /pong.py | 1,410 | 3.796875 | 4 | import turtle
wn = turtle.Screen()
wn.title("pong")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.color('white')
paddle_a.shape('square')
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.color('white')
paddle_b.shape('square')
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.color('white')
ball.shape('square')
ball.penup()
ball.goto(0, 0)
ball.dx = 1
ball.dy = 1
# Functions
def paddle_a_up():
y = paddle_a.ycor();
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor();
y -= 20
paddle_a.sety(y)
def paddle_b_up():
y = paddle_b.ycor();
y += 20
paddle_b.sety(y)
def paddle_b_down():
y = paddle_b.ycor();
y -= 20
paddle_b.sety(y)
# Keyboard Binding
wn.listen()
wn.onkey(paddle_a_up, 'w')
wn.onkey(paddle_a_down, 's')
wn.onkey(paddle_b_up, 'Up')
wn.onkey(paddle_b_down, 'Down')
# Main Game Loop
while True:
wn.update()
# Move the Ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
if ball.ycor() < 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() > -290:
ball.sety(-290)
ball.dy *= -1 |
043b958842f998dbfa9dfb5efe5a634923a29058 | tutuba13/Python-Summary | /Map, Filter, Zip and Reduce/Zip(put together two iterables for example two lists).py | 513 | 4.5625 | 5 | print("Zip Function")
print("Put together two iterables, for examples: link two lists together")
first_list = [1, 2, 3]
second_list = (9, 6, 3) # It can put lists, tuples, sets together
third_list = [7, 10, 8]
print(list(zip(first_list, second_list, third_list)))
print("Sorting with the second element")
a=[(0,2),(9,9),(10,-1),(4,3)]
b=a[:] #Copying list A keeping it intact
a.sort(key=lambda x:x[1]) #Sorting by the second member of the List
b.sort() #Sorting by the first member of the list
print(a)
print(b) |
971a83f9a8277f35199c048fcdf7ec3b0da5cec6 | wererLinC/Python-Learning | /python基础/06_sort.py | 416 | 3.78125 | 4 | # sort
cars = ['bmw', 'audi', 'toyota', 'qiaoke']
print(cars)
cars.sort()
print(cars)
# reverse = True
cars = ['bmw', 'audi', 'toyota', 'qiaoke']
print(cars)
cars.sort(reverse = True)
print(cars)
# sorted
cars = ['bmw', 'audi', 'toyota', 'qiaoke']
print(cars)
print(sorted(cars))
# reverse
cars = ['bmw', 'audi', 'toyota', 'qiaoke']
print(cars)
cars.reverse()
print(cars)
# len
lens = len(cars)
print(lens)
|
c0895a46cc272b0a44ad45b627c8fbc4465f9eaa | GingerWWW/python | /多态.py | 658 | 3.609375 | 4 | class Vehicle:
def __init__(self, number='12345', admin='Xiaoming'):
self.number=number
self.admin=admin
def load(self,origin, destination):
print(origin)
class Track(Vehicle):
def load(self, weight, origin, destination):
print('载货重量:%s,出发地:%s,目标地:%s'%(weight,origin,destination))
class Bus(Vehicle):
def load(self, linenum, origin, destination):
print('线路:%s,出发地:%s,目标地:%s'%(linenum,origin,destination))
if __name__=='__main__':
track=Track()
bus=Bus()
track.load(50,'北京','上海')
bus.load(84,'新宫','西红门')
|
db88287e1c5352afc2d6d5cc68dba9fdef8a3c29 | sivakumargsk/python-programs | /sorting algorthims functions.py | 1,924 | 4.28125 | 4 |
def selection_sort (a):
for i in range (len (a)):
mini = i
for j in range (i, len(a)):
if (a[j] < a[mini]):
mini = j
temp = a[i]
a[i] = a[mini]
a[mini]= temp
return a
def insertion_sort (a):
for i in range (len (a)):
if (a[i] < a[i-1]):
for j in range(i,0,-1):
if ((j > 0) and (a[j] < a[j-1])):
temp = a[j]
a[j] = a[j-1]
a[j-1] = temp
return a
def insertion_sort1 (a):
for i in range (len(a)):
j = i
while ((j > 0) and (a[j] < a[j-1])):
temp = a[j]
a[j] = a[j-1]
a[j-1] = temp
j -= 1
return a
def shell_sort (a):
h = 1
while (h < len(a)/3):
h = (3 * h) + 1
while (h >= 1):
for i in range (h , len(a)):
j = i
while ((j >= h) and (a[j] < a[j-h])):
temp = a[j]
a[j] = a[j-h]
a[j-h] = temp
j -= h
h = h/3
return a
def main() :
coll = [6,5,7,2,9,8,3,4,1]
print selection_sort (coll)
print insertion_sort (coll)
print insertion_sort1 (coll)
print shell_sort (coll)
if __name__=='__main__' :
main()
"""
Note:(N means list length)
worst-case for insertion sort is :
if the list requires ~(N^2/2) comparisions and ~(N^2/2) exchanges for sorting a list.
example: Reverse ordered list.
Best-case for insertion sort is:
if the list requires (N-1) camparisions and 0 exchanges for sorting a list.
example: 1.Sorted list
2.Partially sorted list
3.if list is having less no.of inversion paires
4.small list
when compared to selection sort the insertion sort take less time to sort a list.
shell sort takes very less time when compared to insertion sort depends upon type of list.
|
594701cce3d2c2e7f5586eb058522f993c95d3d2 | Zichuanyun/go-shuati | /chunlin/98.py | 1,149 | 3.8125 | 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
(isValid, _, _) = self.helper(root)
return isValid
def helper(self, root):
"""
:rtype: (bool, int, int) # isValid, max, min
"""
if not root:
return (True, -sys.maxint-1, sys.maxint)
left = self.helper(root.left)
right = self.helper(root.right)
if not left[0] or not right[0]:
return (False, 0, 0)
if (root.left and left[1] >= root.val) or (root.right and right[2] <= root.val): # > < -> >= <=
return (False, 0, 0)
return (True, max(root.val, right[1]), min(root.val, left[2])) # add min/max to update values from leaf nodes
# if left[0] and right[0] and root.val > left[1] and root.val < right[2]:
# return (True, right[1], left[2])
# else:
# return (False, 0, 0)
|
eda8434966532cc89b6c679c35424fd6e6455fbf | sanchit-ahuja/cppcode | /PythonCode/blank.py | 862 | 4.0625 | 4 | #Create a sequence from 100 to 999
three_dig_seq = range(999, 99)
# and an empty list for the palindromes
list_palindromes = []
# loop twice over the number sequence
for n1 in three_dig_seq:
for n2 in three_dig_seq:
# Get the product
number = n1 * n2
# Transform it in string
number = str(number)
length_number = int(len(number)/2)
# Compare each 'letter' to check if
# it's a palindrome
for i in range(length_number):
if number[i] != number[-i - 1]:
number_is_palindrom = False
break
else:
number_is_palindrom = True
# Add the number if it's indeed
# a palindrome
if number_is_palindrom:
list_palindromes.append(int(number))
print max(list_palindromes)
if __name__ == "__main__":
pass
|
d3cc9d16f82db744ffbae2c7085035e743c00bde | pbskumar/GraphSearches_py | /uninformedSearches.py | 14,534 | 4.125 | 4 | import pprint
from copy import deepcopy
class Graph:
"""
Graph Class represents all variations of the Graph Data Structure in the form of a dictionary
Weighted/Uniform paths, Directed/Bi-directional Graphs
Ex: Directed path from node 'A' to 'B' with path cost 'c' is represented as follows:
Graph = {
'A' : [('B', c)]
}
"""
def __init__(self, graph_dict={}):
"""
Initializes the dictionary
:param graph_dict: A predefined dictionary mapping can be provided as an input.
In default case an empty dictionary is initialized.
"""
self.__graph_dict = graph_dict
def create_node(self, nodeID):
"""
To create a new node on the graph.
Inserts the new node as a key to the graph and initializes it to an empty list.
:param nodeID: Identifier of the new node.
"""
if nodeID.title() not in self.__graph_dict.keys():
self.__graph_dict[nodeID.title()] = []
def create_arc(self, origin, destination, cost=1):
"""
Inserts a directed(uni-directional) path from origin to destination to the graph.
:param origin: Identifier of the origin node
:param destination: Identifier of the origin node
:param cost: Cost of the path. By default the cost is initialized to 1.
"""
if origin.title() not in self.__graph_dict:
self.create_node(origin.title())
if destination.title() not in self.__graph_dict[origin.title()]:
self.__graph_dict[origin.title()].append((destination.title(), int(cost)))
def create_edge(self, origin, destination, cost=1):
"""
Inserts a bi-directional path from origin to destination to the graph.
:param origin: Identifier of one node.
:param destination: Identifier of the other node.
:param cost: Cost of the path. By default the cost is initialized to 1.
"""
if origin not in self.__graph_dict:
self.create_node(origin)
if destination not in self.__graph_dict:
self.create_node(destination)
self.create_arc(origin, destination, cost)
self.create_arc(destination, origin, cost)
def get_graph_nodes(self):
"""
:return: Returns a list of all the nodes in the Graph
"""
return deepcopy(list(self.__graph_dict.keys()))
def get_graph_dict(self):
"""
:return: Returns the entire Graph as a dictionary
"""
return deepcopy(self.__graph_dict)
class Node:
"""
Node class is the atomic part of a tree.
"""
def __init__(self, node_identifier, parent=None, edge_cost=0):
"""
self.__total_path_cost is cost from the root node to the current node.
:param node_identifier: Identifier of the node
:param parent: Reference to the parent node.
:param edge_cost: Is the path cost from parent to current node.
"""
self.__node_identifier = node_identifier
self.__parent = parent
try:
self.__total_path_cost = int(parent.get_total_cost()) + edge_cost
except AttributeError:
self.__total_path_cost = int(edge_cost)
def get_node_identifier(self):
"""
:return: Returns the node identifier
"""
return self.__node_identifier
def get_parent(self):
"""
:return: Returns reference to the parent of the current node
"""
return self.__parent
def add_child_node(self, child_node_identifier, cost_to_reach_child_node):
"""
:param child_node_identifier: Identifier of the child node
:param cost_to_reach_child_node: Path cost from parent to child node
:return: Returns the reference of the child node generated
"""
child_node = Node(child_node_identifier, self, cost_to_reach_child_node)
return child_node
def get_total_cost(self):
"""
:return: Returns the total path cost from root node to current node.
"""
return self.__total_path_cost
def read_file_data(file_name):
"""
Reads path data from text. Each path is present line after line in the input file.
A sample route is represented as follows: Arad,Zerind,75
:param file_name:
:return: Returns a list of routes. Each route is returned as a list of 3 items.
route: ['city1', 'city2', 'path cost']
"""
file_reference = open(file_name, 'r')
file_data = []
while True:
edge = file_reference.readline()
if edge:
file_data.append(edge.strip().split(','))
else:
file_reference.close()
break
return file_data
def retrace_path(dest_node):
"""
Retraces path from current node to the root node.
:param dest_node: THe node from which the path has to be retraced
:return: returns a string of all cities travelled, along with the total path.
"""
traced_route = []
current_node = dest_node
while current_node:
traced_route.insert(0, current_node.get_node_identifier())
current_node = current_node.get_parent()
if traced_route:
return str(', '.join(traced_route)) + '\nTotal Path cost: ' + str(dest_node.get_total_cost())
else:
return "Path could not be retraced."
def breadth_first_search(graph, origin, destination):
"""
:param graph: A dictionary representing the graph of interest
:param origin:
:param destination:
:return: Returns the path traversed from the origin to destination along with the cost of total path covered.
"""
origin = origin.title()
destination = destination.title()
if origin == destination:
return "Source and Destination cannot be same."
graph_dict = graph.get_graph_dict()
graph_nodes = graph.get_graph_nodes()
if origin not in graph_nodes:
return "Unable to find 'Source City' in the map."
if destination not in graph_nodes:
return "Unable to find 'Destination City' in the map."
root = Node(origin)
# print root.get_node_identifier(), root.get_parent()
visited_nodes = dict(zip(graph_nodes, [False] * len(graph_nodes)))
queue = [root]
while queue:
current_node = queue.pop(0)
# print(current_node.get_node_identifier())
# print(current_node.get_total_cost())
if visited_nodes[current_node.get_node_identifier()]:
continue
else:
visited_nodes[current_node.get_node_identifier()] = True
if graph_dict[current_node.get_node_identifier()]:
for child_id in graph_dict[current_node.get_node_identifier()]:
child = current_node.add_child_node(*child_id)
# print(child.get_node_identifier())
# print(child.get_total_cost())
# print('------------')
# goal test when child is created
if child.get_node_identifier() == destination:
return retrace_path(child)
else:
# print([city.get_node_identifier() for city in queue])
if child not in [city.get_node_identifier() for city in queue] \
and not visited_nodes[child.get_node_identifier()]:
queue.append(child)
return "Path not found"
def depth_first_search(graph, origin, destination):
"""
:param graph: A dictionary representing the graph of interest
:param origin:
:param destination:
:return: Returns the path traversed from the origin to destination along with the cost of total path covered.
"""
origin = origin.title()
destination = destination.title()
if origin == destination:
return "Source and Destination cannot be same."
graph_dict = graph.get_graph_dict()
graph_nodes = graph.get_graph_nodes()
if origin not in graph_nodes:
return "Unable to find 'Source City' in the map."
if destination not in graph_nodes:
return "Unable to find 'Destination City' in the map."
root = Node(origin)
# print root.get_node_identifier(), root.get_parent()
visited_nodes = dict(zip(graph_nodes, [False] * len(graph_nodes)))
stack = [root]
while stack:
current_node = stack.pop()
# print(current_node.get_node_identifier())
if visited_nodes[current_node.get_node_identifier()]:
continue
else:
visited_nodes[current_node.get_node_identifier()] = True
# print(current_node.get_node_identifier())
# print(current_node.get_total_cost())
if graph_dict[current_node.get_node_identifier()]:
for child_id in graph_dict[current_node.get_node_identifier()]:
child = current_node.add_child_node(*child_id)
# print(child.get_node_identifier())
# print(child.get_total_cost())
# print('------------')
# goal test when child is created
if child.get_node_identifier() == destination:
return retrace_path(child)
else:
if child not in [city.get_node_identifier() for city in stack] \
and not visited_nodes[child.get_node_identifier()]:
# if child not in [city.get_node_identifier() for city in stack]:
stack.append(child)
return "Path not found"
def recursive_dls(graph, current_node, destination, depth_limit):
# print current_node.get_node_identifier(), depth_limit
if current_node.get_node_identifier() == destination:
return retrace_path(current_node)
elif depth_limit == 0:
return False
else:
graph_dict = graph.get_graph_dict()
cutoff_occurred = False
for child_id in graph_dict[current_node.get_node_identifier()]:
child_node = current_node.add_child_node(*child_id)
result = recursive_dls(graph, child_node, destination, depth_limit - 1)
if not result:
cutoff_occurred = True
else:
return result
if cutoff_occurred:
return False
def depth_limited_search(graph, origin, destination, depth_limit):
"""
:param graph: A dictionary representing the graph of interest
:param origin:
:param destination:
:param depth_limit: Maximum depth till which the tree can expand
:return: Returns the path traversed from the origin to destination along with the cost of total path covered.
"""
origin = origin.title()
destination = destination.title()
if origin == destination:
return "Source and Destination cannot be same."
graph_dict = graph.get_graph_dict()
graph_nodes = graph.get_graph_nodes()
if origin not in graph_nodes:
return "Unable to find 'Source City' in the map."
if destination not in graph_nodes:
return "Unable to find 'Destination City' in the map."
return recursive_dls(graph, Node(origin), destination, depth_limit)
def iterative_deepening_search(graph, origin, destination, step_size=1):
"""
:param graph: A dictionary representing the graph of interest
:param origin:
:param destination:
:param step_size: Size of the step to be taken.
:return: Returns the path traversed from the origin to destination along with the cost of total path covered.
"""
origin = origin.title()
destination = destination.title()
if destination == origin:
return "Source and Destination cannot be same."
graph_dict = graph.get_graph_dict()
graph_nodes = graph.get_graph_nodes()
if origin not in graph_nodes:
return "Unable to find 'Source City' in the map."
if destination not in graph_nodes:
return "Unable to find 'Destination City' in the map."
depth_limit = 0
while True:
path = depth_limited_search(graph, origin, destination, depth_limit)
if path:
return path
else:
# print "-------------------------"
depth_limit += step_size
# Main program
if __name__ == "__main__":
input_file_name = 'route.csv' #Available in the repository
input_data = read_file_data(input_file_name)
# print(input_data)
city_map = Graph()
for route in input_data:
city_map.create_edge(*route)
# pprint.pprint(city_map.get_graph_dict())
# pprint.pprint(city_map.get_graph_nodes())
# bfs_route = breadth_first_search(city_map, 'Neamt', "Oradea")
while True:
print("\n\n-------------------------------------------------\n")
origin_city = raw_input('Enter name of the city of origin: ')
destination_city = raw_input('Enter name of the destination city: ')
selected_search_algorithm = raw_input('Select an algorithm. (Enter option number)\n\
1. Breadth First Search\n2. Depth First Search\n3. Iterative Deepening Search\nEnter your choice:\t ')
if int(selected_search_algorithm) == 1:
bfs_route = breadth_first_search(city_map, origin_city.strip().title(), destination_city.strip().title())
print "\nBFS Route:\t" + bfs_route + "\n"
elif int(selected_search_algorithm) == 2:
dfs_route = depth_first_search(city_map, origin_city.strip().title(), destination_city.strip().title())
print "\nDFS Route: \t" + dfs_route + "\n"
elif int(selected_search_algorithm) == 3:
step_size = raw_input('Enter step size for iterative deepening: ')
ids_route = iterative_deepening_search(city_map, origin_city.strip().title(), destination_city.strip().title(), int(step_size))
print "\nIterative Deep Search Route: \t" + ids_route + "\n"
else:
print "Select valid options\n"
exit_key = raw_input("Do you want to continue (y/n): ")
if exit_key.lower() != 'y':
break
|
91d6de231249af2f23d696ce983df04476ceb273 | SlaviSotirov/HackBulgaria | /week_0/day_1/sum_dig.py | 213 | 3.921875 | 4 | def sum_of_digits(n):
sum = 0
n = abs(n)
while n:
sum += int(n) % 10
n = int(n) / 10
return sum
def main():
print (sum_of_digits(12))
if __name__ == '__main__':
main()
|
d86353a283122471c0d22ec6abeb79e375eb69d9 | Sen2k9/Algorithm-and-Problem-Solving | /leetcode_problems/207_Course_Schedule.py | 2,279 | 4.09375 | 4 | """
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
Constraints:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
1 <= numCourses <= 10^5
"""
class Graph:
def __init__(self):
self.indegre = 0
self.outedge = []
class Solution:
def canFinish(self, numCourses, prerequisites):
from collections import defaultdict, deque
graph = defaultdict(Graph)
total_edge = 0
for each in prerequisites:
nextcourse = each[0]
prevcourse = each[1]
graph[prevcourse].outedge.append(nextcourse)
graph[nextcourse].indegre += 1
total_edge += 1
nodepvertex = deque()
for vertex, _ in graph.items():
if graph[vertex].indegre == 0:
nodepvertex.append(vertex)
removeEdge = 0
while nodepvertex:
course = nodepvertex.popleft()
for nextcourse in graph[course].outedge:
graph[nextcourse].indegre -= 1
removeEdge += 1
if graph[nextcourse].indegre == 0:
nodepvertex.append(nextcourse)
if removeEdge == total_edge:
return True
else:
False
sol = Solution()
n = 3
pre = [[1, 0], [2, 0]]
print(sol.canFinish(n, pre))
|
baed068c4294cab0942444b6d3df70dff2ed3228 | aerialboundaries/python_practice | /automate/7-Project3-Strip.py | 393 | 3.859375 | 4 | #!/usr/bin/env python
# Project 7-3 Strong Regex Version of the strip() Method
import re
testWord = 'aabbcc-abc-aabbcc'
def spritRegex(word, remove=' '):
stripRegexL = re.compile(r'(^[' + remove + ']*)')
stripRegexR = re.compile(r'([' + remove + ']*$)')
result = stripRegexL.sub('', word)
result = stripRegexR.sub('', result)
print(result)
spritRegex(testWord, 'ab')
|
52e03e7e317d293e03a3f2156bf1487431132bfa | green-fox-academy/sara2585 | /week02/day-2/copy_file.py | 631 | 3.734375 | 4 |
# Write a function that copies the contents of a file into another
# It should take the filenames as parameters
# It should return a boolean that shows if the copy was successful
def copy_file(copyfromfile,copytofile):
try:
f1 = open(copyfromfile, "r")
f2 = open(copytofile, "w")
contents = f1.readlines()
for content in contents:
f2.writelines(content + "\n")
f1.close()
f2.close()
return True
except FileNotFoundError:
return False
except PermissionError:
return False
print(copy_file("sara test.txt", "write.txt"))
|
1caa0140a669e118b24fe7cf4b6ad4e0a5a15ceb | alinedsoares/api-biblioteca | /clientes.py | 464 | 3.5 | 4 | import encargos
class Cliente:
def __init__(self, id_cliente, id_livro_emprestado):
self.id_cliente = id_cliente
self.id_livro_emprestado = id_livro_emprestado
clientes = Cliente(0, 22)
if clientes.id_livro_emprestado is not None: #TODO: O RETORNO ESTÁ CONFLITANDO COM A ESTRUTURA CONDICIONAL
encargos.encargos_emprestimo(10, 10, 22)
print(clientes.id_livro_emprestado)
else:
print('Cliente sem empréstimos')
|
98c05f524f363ba2ae850eef7e0d7c76f1c559f3 | lcxstar/Hello-World | /1.tkinter基础学习/1.1设置窗口大小及位置.py | 812 | 3.921875 | 4 | # GUI(Graphical User Interface)意为图形用户界面,tkinter 提供的该功能
# Tk的功能是设置主窗口
from tkinter import Tk
# 显示窗口
my_window = Tk()
# 标题
my_window.title('我的窗口')
# 设置窗口居中
# (1)获取当前屏幕大小
screen_width, screen_height = my_window.maxsize()
# (2)设置窗口的大小
width = 480
height = 480
# (3)geometry函数只能识别字符串,所以对数据进行封装
align_str = '%dx%d+%d+%d'%(width,height,(screen_width-width)/2,(screen_height-height)/2)
# (4)设置窗口的宽,高及位置
my_window.geometry(align_str)
# 设置窗口是否可以缩放 True表示可以缩放,False表示不能缩放,默认为True
my_window.resizable(width=False,height=False)
# 显示设置好的窗口
my_window.mainloop()
|
98cb595b32ef616efe03b08e69ba316aaed0e3db | shinkai-tester/python_beginner | /Lesson6/tic_tac_toe2.py | 777 | 3.546875 | 4 | FieldSize = 3
field = [['*' for i in range(FieldSize + 1)] for k in range(FieldSize + 1)]
command = input()
while command != 'Stop':
x, y = [int(i) for i in input().split()]
if x > len(field) - 1 or y > len(field) - 1:
print('Такой координаты не существует!')
else:
if field[x][y] == '*':
if command == 'Крестик':
field[x][y] = 'X'
if command == 'Нолик':
field[x][y] = '0'
else:
print('На этом поле уже стоит символ!')
command = input()
for x in range(1, FieldSize + 1):
for y in range(1, FieldSize + 1):
print(field[x][y], end=' ')
print() |
d8fa6fc536ed8bfe88a9375f48d387116134969a | pradyumnakr/Python_code | /newtonraphson.py | 350 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 26 22:59:53 2018
@author: pradyumna
"""
epsilon=0.01
y=30
guess=y/2.0
numGuesses=0
while abs(guess*guess -y)>=epsilon:
numGuesses+=1
guess=guess-(((guess**2)-y)/(2*guess))
print("numGuesses= "+str(numGuesses))
print('square root of ' +str(y) + ' is about '+ str(guess)) |
5fe69a19cdc598650bdbf922afc0b43f76482e36 | KDiaCodes/ict2018 | /primenumber.py | 453 | 3.6875 | 4 | import os
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
input("Press enter to close")
os.system(r'start C:\Windows\System32\cmd.exe /c C:\Users\KENRICSA\Desktop\start.bat')
|
afa7db62ad284d15173bbf293a95310d9fefe408 | anilkohli98/My-Assignments | /Data_stru/rotatingLinkedList.py | 1,475 | 3.875 | 4 | class node:
def __init__(self,data):
self.data=data
self.next=None
class DoublyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def CountLenRecur(self,temp):
if temp is None:
return 0
else:
return 1+self.CountLenRecur(temp.next)
def InsertAtEnd(self,data):
newnode=node(data)
if self.head is None:
self.head=newnode
self.tail=newnode
return
self.tail.next=newnode
newnode.prev=self.tail
self.tail=newnode
def LeftRotate(self,N):
temp=self.head
count=1
while(temp is not None and count<N+1):
temp=temp.next
count+=1
temp2=temp.next
if (temp2 is None):#this is for the cases like when len ==k
return
temp.next=None
temp2.prev=None
temp.tail.next=self.head
self.head.prev=self.tail
self.head=temp2
self.tail=temp
def PrintingLinkedList(self):
temp=self.head
while(temp is not None):
print(temp.data,end=" ")
temp=temp.next
print()
def main():
List=DoublyLinkedList()
N,K=map(int,input().split())
arr=list(map(int,input().split()))
for i in range(len(arr)):
List.InsertAtEnd(arr[i])
# List.InsertAtBeginning(arr[i])
List.LeftRotate(K)
List.PrintingLinkedList()
if __name__=="__main__":
main() |
d9615cdcc7a75a401e8ed36f6e162f2f6f48067b | BearachB/Hello_World | /Week 2/Lab 5/lab5_q1.py | 133 | 3.765625 | 4 | mark = int(input("Please enter your grade:"))
if mark >= 40:
print("This is a pass")
elif mark <40:
print("This is a fail")
|
9ed94697edab9d58f8f7da5a8a27de21b244fb5d | AlexNedyalkov/Python-OOP-2020 | /attributes_and_methods_03/exercises/gym_04/project/trainer.py | 753 | 3.859375 | 4 | """
Class Trainer
Upon initialization the class will receive the following parameters: name:str.
The class should also have an id (autoincremented starting from 1).
Implement the __repr__ method so it returns the info about the trainer in the following format:
"Trainer <{self.id}> {self.name}"
Create a static method called get_next_id which returns the id that will be given to the next trainer
"""
class Trainer:
autoincremental_id = 1
def __init__(self, name: str):
self.name: str = name
self.id = Trainer.autoincremental_id
Trainer.autoincremental_id += 1
def __repr__(self):
return f"Trainer <{self.id}> {self.name}"
@staticmethod
def get_next_id():
return Trainer.autoincremental_id |
5dc13b3e122461e9514506ba03bc6fa880078e98 | ivan-filonov/online-challenges | /codeeval/moderate/lowest-common-ancestor.py | 903 | 3.59375 | 4 | #"""Sample code to read in test cases:
tree = [30, 8, 52, 3, 20, -1, -1, -1, -1, 10, 29]
def p(x):
res, i = [x], tree.index(x)
while i > 0:
i = (i-1)>>1
res.append(tree[i])
return res
def lca(s):
v1,v2=[int(ss) for ss in s.split()]
# print(v1,v2)
p1,p2=p(v1),p(v2)
# print(p1,p2)
p1,p2=list(reversed(p1)), list(reversed(p2))
i = 0
while i < len(p1) and i < len(p2):
if p1[i] == p2[i]:
i+=1
else:
break
print(p1[i-1])
def t():
for x,y in zip(('8 52', '3 29'), ('30','8')):
lca(x)
print(y)
#t()
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
# ignore test if it is an empty line
# 'test' represents the test case, do something with it
# ...
# ...
test=test.strip()
if len(test)==0:
continue
lca(test)
test_cases.close()
#"""
|
73804fa20ff1108e54c6cc6504053e4b5bf48a71 | sujin1561/fiveneck | /ㅠ핑퐁.py | 3,634 | 3.734375 | 4 | import pygame # 1. pygame 선언
pygame.init() # 2. pygame 초기화
# 3. pygame에 사용되는 전역변수 선언
WHITE = (255,255,255)
BLACK = (0, 0, 0)
size = [400, 300]
screen = pygame.display.set_mode(size)
done = False
clock = pygame.time.Clock()
# 4. pygame 무한루프
def runGame():
global done
## 게임판 크기
screen_width = size[0]
screen_height = size[1]
## 탁구채 크기 (width, height)
bar_width = 9
bar_height = 50
## 탁구채의 시작점 (x,y), 좌측 맨끝 중앙
bar_x = bar_start_x = 0
bar_y = bar_start_y = (screen_height - bar_height) / 2
## 탁구공 크기 (반지름)
circle_radius = 9
circle_diameter = circle_radius * 2
## 탁구공 시작점 (x, y), 우측 맨끝 중앙
circle_x = circle_start_x = screen_width - circle_diameter ## 원의 지름 만큼 빼기
circle_y = circle_start_y = (screen_width - circle_diameter) / 2
bar_move = 0
speed_x, speed_y, speed_bar = -screen_width / 1.28, screen_height / 1.92, screen_height * 1.2
while not done:
time_passed = clock.tick(30)
time_sec = time_passed / 1000.0
screen.fill(BLACK)
circle_x += speed_x * time_sec
circle_y += speed_y * time_sec
ai_speed = speed_bar * time_sec
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
break
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
bar_move = -ai_speed
elif event.key == pygame.K_DOWN:
bar_move = ai_speed
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
bar_move = 0
elif event.key == pygame.K_DOWN:
bar_move = 0
## 탁구채 이동
bar_y += bar_move
## 탁구채 범위 확인
if bar_y >= screen_height:
bar_y = screen_height
elif bar_y <= 0:
bar_y = 0
## 탁구공 범위 확인
## 1) 진행 방향을 바꾸는 행위
## 2) 게임이 종료되는 행위
if circle_x < bar_width: ## bar에 닿았을 때
if circle_y >= bar_y - circle_radius and circle_y <= bar_y + bar_height + circle_radius:
circle_x = bar_width
speed_x = -speed_x
if circle_x < -circle_radius: ## bar에 닿지 않고 좌측 벽면에 닿았을 때, 게임 종료 및 초기화
circle_x, circle_y = circle_start_x, circle_start_y
bar_x, bar_y = bar_start_x, bar_start_y
elif circle_x > screen_width - circle_diameter: ## 우측 벽면에 닿았을 때
speed_x = -speed_x
if circle_y <= 0: ## 위측 벽면에 닿았을때
speed_y = -speed_y
circle_y = 0
elif circle_y >= screen_height - circle_diameter: ## 아래 벽면에 닿았을때
speed_y = -speed_y
circle_y = screen_height - circle_diameter
## 탁구채
pygame.draw.rect(screen,
WHITE,
(bar_x, bar_y, int(bar_width), int(bar_height)))
## 탁구공
pygame.draw.circle(screen,
WHITE,
(int(circle_x), int(circle_y)),
int(circle_radius))
pygame.display.update()
runGame()
pygame.quit()
|
421370cff155d13ff74a9ba3513c0836aa4c4e87 | RomanLopatin/Python | /Algorithms/HW_3/task_3_6.py | 939 | 3.984375 | 4 | """coding=utf-8
3.6.
В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.
Сами минимальный и максимальный элементы в сумму не включать.
"""
import random
arr_size = 10
range_min = 0
range_max = 100
ind_max = 0
ind_min = 0
arr = [random.randint(range_min, range_max) for _ in range(arr_size)]
print(f'old: {arr}')
el_max = arr[0]
el_min = arr[0]
for i in range(1, arr_size):
if arr[i] > el_max:
el_max = arr[i]
ind_max = i
if arr[i] < el_min:
el_min = arr[i]
ind_min = i
print(f'Мин: {el_min} / Max: {el_max}')
sum = 0
if ind_min>ind_max:
ind_min, ind_max = ind_max, ind_min
for i in range(ind_min + 1, ind_max):
sum += arr[i]
print(f'Сумму искомых элементов: {sum}')
|
847c2801c5cfb4bc839c7bd59ec0cd364979440c | cerebnix/Projects | /__init__.py | 414 | 3.640625 | 4 | '''
l= list(range (1,31))
l = input("Enter text")
print (l * 2)
for line in open ('test.txt'):
print (line)
f = open ("test.txt")
for line in f.readlines():
print(line)
import sys
print(sys.copyright, '\n\n', '\n sys.platform', sys.platform, '\n sys.path', sys.path, '\n sys.modules', sys.modules)
'''
stringus = "This {} text locate {} in {} right place".format('<10', '>10', '^10')
print (stringus) |
cee102724632f5cec1f82e77fac37e82296e57b9 | Sunhick/hacker-rank | /Algorithms/Implementation/python/ExtraLongFactorials.py | 184 | 3.859375 | 4 | #!/bin/python
import sys
n = int(raw_input().strip())
def factorial(n):
if ( n == 1 ):
return 1
else:
return ( n * factorial ( n - 1 ))
print factorial(n)
|
72859f810a0ed02079e1f47c35e2db93738f3870 | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/289/81958/submittedfiles/testes.py | 96 | 3.984375 | 4 | n = int(input("Digite um número: "))
while(x<=100):
if n%2==0:
print(x)
x += 1
|
a5f741a9697e8580b24ba6dd0b18537ef80dc548 | gabriellaec/desoft-analise-exercicios | /backup/user_066/ch149_2020_04_13_19_19_50_853685.py | 925 | 3.984375 | 4 | dependentes = int(input('Insira o número de dependentes '))
salario_bruto = int(input('Insira a salario bruto '))
if salario_bruto<=1045.00:
contribuicaoINSS=0.075*salario_bruto
elif salario_bruto<=2089.60:
contribuicaoINSS=0.09*salario_bruto
elif salario_bruto<=3134.40:
contribuicaoINSS=0.12*salario_bruto
elif salario_bruto<=6101.06:
contribuicaoINSS=0.14*salario_bruto
else:
contribuicaoINSS=671.12
print(contribuicaoINSS)
print(salario_bruto)
base_calculo = salario_bruto - contribuicaoINSS - dependentes*189.59
print(base_calculo)
if base_calculo <= 1903.98:
aliquota = 0
deducao = 0
elif base_calculo<=2826.65:
aliquota = 0.075
deducao = 142.80
elif base_calculo <=3751.05:
aliquota = 0.15
deducao = 354.80
elif base_calculo<=4664.68:
aliquota = 0.225
deducao = 636.13
else:
aliquota = 0.275
deducao = 869.36
IRRF = base_calculo*aliquota-deducao
print(IRRF) |
9c174c95d938d98cb6887b7e0fdeb6290ce86ae8 | kamilczerwinski22/Advent-of-Code | /main_files/year_2015/day_9/year2015_day9_part2.py | 1,902 | 3.953125 | 4 | # --- Part Two ---
# The next year, just to show off, Santa decides to take the route with the longest distance instead.
#
# He can still start and end at any two (different) locations he wants, and he still must visit each location exactly
# once.
#
# For example, given the distances above, the longest route would be 982 via (for example) Dublin -> London -> Belfast.
#
# What is the distance of the longest route?
from collections import defaultdict
from itertools import permutations
# Function to build the graph
def find_shortest_route() -> int:
# read file
with open('year2015_day9_challenge_input.txt', 'r', encoding='UTF-8') as f:
routes = f.read().splitlines()
# main logic
possible_places = set()
distances_graph = defaultdict(dict) # create undirected graph with all the routes
for route in routes:
source, _, destination, _, distance = route.split(' ')
possible_places.add(source)
possible_places.add(destination)
# add route distance to the graph (dictionary) from both sides. If connection doesn't exist make it
distances_graph[source][destination] = int(distance)
distances_graph[destination][source] = int(distance)
# create all possible routes using available nodes. Create a list with the sum of the distances between these points
# e.g. permutation: ('Straylight', 'AlphaCentauri', 'Norrath', 'Arbre', 'Tristram', 'Faerun', 'Snowdin', 'Tambi')
# Is the total distance between 'Straylight' and 'Tambi' going through the nodes in order:
# Straylight -> AlphaCentauri -> Norrath -> ... -> Tambi
distances = []
for permutation in permutations(possible_places):
distances.append(sum(map(lambda x, y: distances_graph[x][y], permutation[:-1], permutation[1:])))
return max(distances)
if __name__ == "__main__":
graph = find_shortest_route()
print(graph)
|
6a4e7eb5f53c3fab66cc5cca0cf58ebc90e015e6 | troyleak/RPGMaker | /app/character_gen/skills.py | 1,857 | 3.765625 | 4 | class Skills():
def __init__(self):
self.skills = {
'acrobatics': 0,
'appraise': 0,
'bluff': 0,
'climb': 0,
'craft_a': 0,
'craft_b': 0,
'craft_c': 0,
'diplomacy': 0,
'disable_device': 0,
'disguise': 0,
'escape_artist': 0,
'fly': 0,
'handle_animal': 0,
'heal': 0,
'intimidate': 0,
'knowledge_arcana': 0,
'knowledge_dungeoneering': 0,
'knowledge_engineering': 0,
'knowledge_geography': 0,
'knowledge_history': 0,
'knowledge_local': 0,
'knowledge_nature': 0,
'knowledge_nobility': 0,
'knowledge_planes': 0,
'knowledge_religion': 0,
'linguistics': 0,
'perception': 0,
'perform_a': 0,
'perform_b': 0,
'profession_a': 0,
'profession_b': 0,
'ride': 0,
'sense_motive': 0,
'sleight_of_hand': 0,
'spellcraft': 0,
'stealth': 0,
'survival': 0,
'swim': 0,
'use_magic_device': 0}
def set_skill(self, skill, points):
# Takes the skill and the value as arguments.
# Updates the value, not adding to it
# If it can't find the skill displays a warning message
if skill in self.skills:
self.skills[skill] = points
print("Updated skill" + skill + " with the value")
else:
print("Error updating skill value")
print("test skills.Skills.update()")
def get_skill(self, skill):
if skill in self.skills:
return skill
else:
print("Unable to update " + skill + " skill")
|
728363b1ea914d06af349336f0630c984614db43 | chengchaoyang/my-leetcode-record | /linked-list/0024-swap-nodes-in-pairs.py | 842 | 4.03125 | 4 | """
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
nextNode = head.next
head.next = self.swapPairs(nextNode.next)
nextNode.next = head
return nextNode
|
66113d7bc3597a332c8628d99927e638ce58b368 | Lee-Park-Bae-Project/Algorithm | /problems/boj/2644/bbumjun.py | 810 | 3.5 | 4 | from collections import deque
n = int(input())
a, b = map(int, input().split())
m = int(input())
relation = {}
for i in range(m):
parent, child = map(int, input().split())
relation.setdefault(parent, {})
relation.setdefault(child, {})
relation[parent].setdefault(child, {})
relation[child].setdefault(parent, {})
ans = -1
def bfs(x, y):
global relation, ans
isVisit = [False for _ in range(n+1)]
queue = deque([(x, 0)])
while len(queue) != 0:
cur, cost = queue.popleft()
if cur == y:
ans = cost
return
for child in relation[cur]:
if isVisit[child] == True or relation.get(child, 0) == 0:
continue
isVisit[child] = True
queue.append((child, cost+1))
bfs(a, b)
print(ans)
|
d982bf6dd6845b93159e6aed6a599103a59774a8 | getstock/GETSTOCK | /getstock/accounts/register.py | 2,901 | 3.78125 | 4 | import csv
data = []
t = "!@#$%^&*()_-=+-"
with open('accounts.csv') as file:
csv_reader = csv.reader(file, delimiter = ',')
for row in csv_reader:
data.append(row)
def lower_letter(s):
have = 0
for ch in s:
if ('a' <= ch and ch <= 'z'):
have += 1
return have
def upper_letter(s):
have = 0
for ch in s:
if ('A' <= ch and ch <= 'Z'):
have += 1
return have
def digits(s):
have = 0
for ch in s:
if ('0' <= ch and ch <= '9'):
have += 1
return have
def special_ch(s):
have = 0
for ch in s:
if (ch in t):
have += 1
return have
def main(login, password, repeated_password):
error = error2 = 0
#login = input("Your login: ")
exist = 0
for logins in data:
if (logins[0] == login):
exist = 1
bad = 0
if (exist):
print('!!!!FAILURE!!!!')
print('This login is already registered')
bad = 1
#login:
#length from 5 to 20
#minimum 1 letter and 1 digit
#password
#length from 8 to 20
#minimum 1 letter and 1 digit
U = upper_letter(login)
L = lower_letter(login)
D = digits(login)
S = special_ch(login)
o = 0
if L + U + D + S < len(login):
o = 1
if o != 0 or D == 0 or L + U == 0 or len(login) < 5 or len(login) > 20:
error2 = 1
if (error2 == 1 and bad == 0):
print("!!!!FAILURE!!!!")
bad = 1
if (len(login) < 5 or len(login) > 20):
if len(login) < 5:
print("Login's length is less than 5")
else:
print("Login's length is more than 20")
if (o != 0):
print("Login has other languages or symbols instead of english or special symbols")
if (D == 0):
print("Login has not any digit")
L = lower_letter(password)
U = upper_letter(password)
D = digits(password)
S = special_ch(password)
o = 1
if L + U + D + S < len(password):
o = 1
error = 0
if (L + U == 0 or D == 0 or o == 1 or len(password) < 8 or len(password) > 20):
error = 1
if (error and bad == 0):
print("!!!!FAILURE!!!!")
if (L + U == 0):
print("Password has not any letter")
if (D == 0):
print("Password has not any digit")
if o != 0:
print("Password has other languages or symbols instead of english or special symbols")
if (len(password) < 8 or len(password) > 20):
if (len(password) < 8):
print("Password's length is less than 8")
else:
print("Password's length is more than 20")
if (password != repeated_password):
if (bad == 0):
print('!!!!FAILURE!!!!')
bad = 1
print("Passwords are not same")
return [login, password, 1]
return [login, password, bad]
if __name__ == '__main__':
main()
|
419d27a4647704eeb7b4d24aad082d1a0ebf796e | ryancarmes/findchar-python | /findchar.py | 211 | 3.75 | 4 | list_one = ["Hello", "Lamp", "Moto", "Nurse", "Dolly"]
x = 0
char = "ll"
newlist = []
for x in range(0, len(list_one)):
if list_one[x].find(char) != -1:
newlist.append(list_one[x])
print newlist
|
3a5c3c4c66888688f157b115ea5ae48dcf3385d4 | Liu-Zhijuan-0313/pythonAdvance | /lianxi/day0216/queue03.py | 626 | 3.6875 | 4 | # 进程通信,两个进程同时操作队列,有读有写
# 进程池下共享Queue,使用Manager创建队列
from multiprocessing import Pool
from multiprocessing import Manager
import time
# 向队列里放数据
def writep(q1):
while True:
q1.put(0)
time.sleep(2)
# 一直等待队列里有数据
def readp(q1):
while True:
r = q1.get()
print(r)
if __name__ == '__main__':
q = Manager().Queue(5)
q.put(-2)
q.put(-1)
pool = Pool(5)
pool.apply_async(writep, (q,))
pool.apply_async(readp, (q,))
pool.close()
pool.join()
print("finish")
|
a0df8246243dca4e382355f4e18f349c81422be5 | DennisCkw/Python-Coursera | /10.Tuple.py | 588 | 4.4375 | 4 | #Tuples are like list but are immutable(cannot be changed).
# - cannot sort, append, add in tuples.
# - tuple is a reduction of list.
# But they are more efficient, less processing time and less memory.
# Tuples are preferred when making 'temporary variables' over lists.
#Multi assign
x, y = (3, 4)
print(x, y)
#Tuples are comparable
z = (1, 2 ,3) < (2, 0 , 4)
print(z)
#Sorting Lists of Tuples
# Use sorted function to sort it into a list
d = {'a':10, 'b':1, 'c':22}
l = d.items()
print(sorted(l))
#shortcut
c = {'a':10, 'b':1, 'c':2}
print(sorted([(v,k) for k,v in c.items()]))
|
629eb51d134daba1140ac1a1bd810c709af0c514 | ninepillars/trunk | /example/pythonexample/bookexample/lession_3/lession_3_4.py | 936 | 3.875 | 4 | # coding: utf-8
'''
Created on 2011-12-2
@author: Lv9
'''
import copy;
a = [1, 2, 3, 4, [5, 6]];
b = a;
b[0] = '1';
print(a, a is b);#当a和b引用指向同样的对象的时候 更改a同时也会更改b
b = list(a);
b[0] = 1;
print(a, a is b);#执行浅copy后 重新创建了一个对象 但是仅仅是对第一层进行了简单的copy 保存了a列表中元素的引用
b[4][0] = '5';
print(a, a is b);#a和b中的特定类型的元素的引用指向的依旧是同一个对象
b = copy.deepcopy(a);#执行深copy 创建一个新对象并且递归的复制它包含的所有对象 没有内置操作可以创建对象的深拷贝 但是可以使用标准库的copy.deepcopy()函数完成该工作 如下例所示:
b[4][0] = 5;
print(a, a is b);#a和b中的列表元素都被重新创建了 虽然b中列表元素的值在更改之前与a相同 但是深拷贝是全部重新创建一次
|
47e506eb4997480026d2635e19c020423328935d | AlessyJay/Python-practice-2021 | /practice25.py | 94 | 3.578125 | 4 | list1 = ['ant','bird','cat','dog','eagle']
list1[0] = 'ape'
list1.append('fish')
print(list1) |
16b8804e5b85e8b92893d49a8c8e2f929e9fed84 | UmutKoca/azimuth | /azimuth.py | 2,003 | 4.4375 | 4 | print("""
Convert grads to degrees, find zone and calculate azimuth angle
""")
import math
X1 = float(input("Please enter X1 coordinate: "))
Y1 = float(input("Please enter Y1 coordinate: "))
X2 = float(input("Please enter X2 coordinate: "))
Y2 = float(input("Please enter Y2 coordinate: "))
def check_zone(X1,X2,Y1,Y2):
deltaX = X2 - X1
deltaY = Y2 - Y1
if(deltaX != 0):
delta = deltaY / deltaX
azimuth_grad = math.atan(delta)*200 / math.pi
azimuth_degree = azimuth_grad * 180 / 200
distance = math.sqrt(deltaY**2 + deltaX**2)
if(deltaY > 0 and deltaX > 0):
print("Distance between points: " + str(distance))
print("Angle is in First Zone")
print("Azimuth angle in degree: " + str(azimuth_degree))
print("Azimuth angle in grad: " + str(azimuth_grad))
print("\n")
if(deltaY > 0 and deltaX < 0):
print("Distance between points: " + str(distance))
print("Angle is in Second Zone")
print("Azimuth angle in degree: "+ str(azimuth_degree + 180))
print("Azimuth angle in grad: " + str(azimuth_grad + 200))
print("\n")
if(deltaY < 0 and deltaX < 0):
print("Distance between points: " + str(distance))
print("Angle is in Third Zone")
print("Azimuth angle in degree: " + str(azimuth_degree + 180))
print("Azimuth angle in grad: " + str(azimuth_grad + 200))
print("\n")
if(deltaY < 0 and deltaX > 0):
print("Distance between points: " + str(distance))
print("Angle is in Fourth Zone")
print("Azimuth angle in degree: " + str(azimuth_degree + 360))
print("Azimuht angle in grad: " + str(azimuth_grad + 400))
print("\n")
else:
print("something wrong happened, please check the coordinates.")
print("Results for points: \n")
check_zone(X1,X2,Y1,Y2)
|
c46623ee5d065470bb630733d0c585f3887a87b2 | codesigned4/AdvancedPython | /4) Usage of Github API/githubAPI.py | 1,530 | 3.5 | 4 | import requests
class Github:
def __init__(self):
self.apiURL="https://api.github.com"
self.token="dkljfPOEOkjdjfmcmaqwekd956"
def getUser(self,username):
response=requests.get(self.apiURL+"/users/"+username)
return response.json()#json import edip json.loads() methodunu kullanmakla aynı şey
def getRepositories(self,username):
result=requests.get(self.apiURL+"/users/"+username+"/repos")
return result.json()
def creteRepository(self,name):
response=requests.post(self.apiURL+"/user/repos?access_token="+self.token,json={
"name":name,
"private":True,
})
return response.json()
github=Github()
while True:
secim=input("1- Find User\n2- Get Repositories\n3- Create Repositories\n4- Exit\nSeçim: ")
if secim=="4":
break
else:
if secim=="1":
username=input("Username: ")
result=github.getUser(username)
print(f"name: {result['name']} public repos: {result['public_repos']} followers: {result['followers']}")
elif secim=="2":
username=input("Username: ")
result=github.getRepositories(username)
for repo in result:
print(repo["name"])
elif secim=="3":
name=input("Repository Name: ")
result=github.creteRepository(name)
print(result)
else:
print("Geçerli bir seçim yapınız!") |
3d0cfce32961d3c13f2331db9e00c8e4edb9fcdf | haoknowah/OldPythonAssignments | /Gaston_Noah_NKN328_Hwk18/Ch06_005_permutation.py | 1,590 | 4.03125 | 4 | try:
from itertools import permutations
except ImportError as exc:
print(exc)
def permutation(word):
'''
permutation()=finds permutations of an input word
returns a list of the permutations
'''
try:
return ["".join(char) for char in permutations(word)]
except:
print("Unhandled exception.")
if __name__ == "__main__":
def test_permutation():
'''
test_permutation()=tests the permutation() method
@param cont=boolean that determines if program repeats
@param word=input word
@param good=boolean that shows if word is a valid input
prints permutations of input word
flair=makes sure that there are no repeat letters in word
'''
try:
cont=True
while cont==True:
while True:
word=str(input("Enter a word with no repeated letters: "))
good=True
if word.isalpha()==False:
good=False
else:
for char in word:
if word.count(char) > 1:
good=False
break
if good==True:
break
else:
print("Not a proper word or repeats letters.")
print(permutation(word))
end=input("Reset? y or n ")
if end.lower()=="n":
cont=False
except:
print("Something unexpected happenned.")
test_permutation()
|
09bd05740d57ea01694e0db75ac5228e4c777b43 | testdemo11/test2_pratice | /pratice_lesson5_selenium/test_wait.py | 1,210 | 3.640625 | 4 | #直接等待
#time.sleep(2)
#隐式等待,轮询查找(default 0.5s),全局等待
#self.driver.implicitly_wait(2)
#显式等待 WebDriverWait 配合until,until_not(),判断进行等待
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
class TestWait:
def setup(self):
self.driver = webdriver.Chrome()
self.driver.get("https://home.testing-studio.com/")
self.driver.implicitly_wait(3)
def test_wait(self):
self.driver.find_element(By.XPATH,"//*[@title='所有分类']").click()
sleep(3)
# self.driver.find_element(By.XPATH,"//*[@title='测试答疑']").click()
# sleep(3)
# def wait(x):
# return len(self.driver.find_elements(By.XPATH,"//*[@class='table-heading']")) > 1
WebDriverWait(self.driver,10).until(expected_conditions.visibility_of_element_located((By.XPATH,"//*[@class='table-heading']")))
# sleep(3)
self.driver.find_element(By.XPATH, "//*[@title='招聘内推']").click()
sleep(3)
self.driver.quit()
|
6f67128f5afe61ef495661dc3d3194796bcf9288 | NHopewell/coding-practice-problems | /Algorithms/leetcode/strings/repeatedSubstringPattern.py | 1,471 | 3.734375 | 4 | """
Problem:
given a string, check if it can be constructed using
substring appended multiple times
Examples:
Input: "abab"
Output" True
-------------
Input: "aba"
Output: False
-------------
Inputer: "abcabcabcabc"
Output: True
"""
import pytest
def is_repeated_substring_pattern(s: str) -> bool:
return s in (s + s)[1: -1]
"""
smallest_window: int = 1
current_window: int = 1
#pointer: int = 0
#left_bountry: int = len(s)
for i, letter in enumerate(s):
for next_letter in s[i+1:]:
if letter != next_letter:
current_window += 1
if smallest_window > 1:
smallest_window = min(smallest_window, current_window)
else:
smallest_window = current_window
current_window = 1
divided = [s[i: i+smallest_window] for i in range(0, len(s), smallest_window)]
print(divided)
return divided.count(divided[0]) == len(divided)
"""
##### TESTS #####
def test_is_repeated_substring_pattern_true():
expected = True
actual = is_repeated_substring_pattern("abcabcabcabc")
assert(actual == expected)
def test_is_repeated_substring_pattern_false():
expected = False
actual = is_repeated_substring_pattern("aba")
assert(actual == expected)
if __name__ == "__main__":
pytest.main() |
92eb5468109689e8227fe97abf8acf3c97a7323f | donhwi94/NomadCoders_WebScrapper_with_Python | /Code_Challenge/Day Four Blueprint/main.py | 883 | 3.90625 | 4 | import os
import requests
start = True
def answer():
while True:
a = input("Do you want to start over? y/n ")
if a == "n" or a == "N":
print("K bye!")
return False
elif a == "y" or a =="Y":
os.system('clear')
return True
else:
print("That's not a valid answer.")
while start:
print("Welcome to IsItDown.py!")
print("Please write a URL or URLs you want to check. (separated by comma")
urls = input().split(",")
for url in urls:
url = url.strip()
if "." not in url:
print(f"{url} is not a valid URL.")
else:
if "http" not in url:
url = "http://" + url
try:
response = requests.get(url)
if response.status_code == 200:
print(f"{url} is up!")
else:
print(f"{url} is down!")
except:
print(f"{url} is down!")
start = answer() |
746366ad91cb782b4bed8c4cee17e0d92d75f486 | zeraien/advent_of_code_2020 | /dimo/day3.py | 772 | 3.703125 | 4 | import math
def load_file(name="day3.txt"):
map_list = []
with open(name,'r') as f:
map_list = f.readlines()
return [l.strip() for l in map_list]
def traverse(map_list, x_step=0, y_step=1):
counter, x=0,0
wrap_point = len(map_list[0])
for idx in range(0, len(map_list), y_step):
line = map_list[idx]
if line[x]=="#":
counter+=1
x+=x_step
x = x%wrap_point
return counter
def traverse_alt(map_list):
paths = [
[1,1],
[3,1],
[5,1],
[7,1],
[1,2]
]
values = []
for x,y in paths:
values.append(traverse(map_list, x_step=x,y_step=y))
return values, math.prod(values)
def run():
print("Part 1: Hit %s trees" % traverse(load_file()))
print("Part 2: Hit %s trees (product %s)" % traverse_alt(load_file()))
if __name__=="__main__":
run()
|
2961a6913819dcfb6f430f9cf3ed7d90c82857f5 | AnubodhKarki/Nim | /Nim.py | 6,231 | 3.984375 | 4 | #Nim
import random
import math
def Menu():
quit = False
bad_choice = True
while bad_choice == True:
print('\nNIP MENU:')
print('~~~~~~~~~~~~')
print('1 : play against an AI')
print('2 : rules')
print('3 : quit')
Choice = raw_input("What would you like to do? (1/2/3) ")
if (Choice[0] != '1' and Choice[0] != '2' and Choice[0] != '3'):
print('The input was not a 1,2 or 3')
else:
bad_choice = False
if Choice[0] == '1':
play()
elif Choice[0] == '2':
rules()
else:
quit = True
print 'Goodbye!'
return quit
def InitializeHeaps():
Heap_A = random.randint(1,12)
Heap_B = random.randint(1,12)
Heap_C = random.randint(1,12)
return (Heap_A,Heap_B,Heap_C)
def rules():
Rules_Input = -1
print('\nNIP RULES:')
print('~~~~~~~~~~~~')
print ('Basic Rules:\n - There are 3 heaps with a random amount of items in each heap\n' \
' - You are allowed to take any amount from 1 heap per turn.' \
'\n - The win conditions differ, dependent on which mode you are playing')
print 'Normal: you win if you take the last item remaining'
print('Misere: you win if you force the other player to take the last item remaining')
print('Enter 0 when you are ready to go back to the main menu')
while Rules_Input != 0:
Rules_Input = raw_input('Please enter \'0\' to quit: ')
try:
Rules_Input = int(Rules_Input)
except:
pass
Menu()
def ChooseMode():
bad_choice = True
while bad_choice == True:
print('\nWhice mode would you like to play?')
print('1 : Normal')
print('2 : Misere')
Mode_Choice = raw_input('Choose a mode (1/2): ')
if (Mode_Choice != '1' and Mode_Choice != '2'):
print('The input was not a 1 or 2')
else:
bad_choice = False
#1 is Normal
#2 is Misere
return int(Mode_Choice)
def PrintHeap(Item_Group):
print('\nA | B | C')
print Item_Group['a'],' ',Item_Group['b'],' ',Item_Group['c']
def CheckWin(Mode,Last_Player,Before_Player,Item_Group):
win = False
if Item_Group['a'] + Item_Group['b'] + Item_Group['c'] == 0:
win = True
if Mode == 1:
PrintHeap(Item_Group)
print '\nThe winner is:', Last_Player,'!'
else:
PrintHeap(Item_Group)
print '\nThe winner is:', Before_Player,'!'
return win
def PlayerMove(Item_Group):
print('\ntype \'q\' at any time to quit')
print('\nIt is your turn')
bad_heap = True
x = 0
while bad_heap == True:
Heap_Choice = raw_input('What amount would you like to remove (ex. a2 \ b4 \ a1)')
if Heap_Choice.lower() == 'q':
quit = True
break
else:
quit = False
if Heap_Choice[0].lower() != 'a' and Heap_Choice[0].lower() != 'b' and Heap_Choice[0].lower() != 'c':
bad_heap = True
else:
bad_heap = False
try:
x = int(Heap_Choice[1:3])
except:
try:
x = int(Heap_Choice[1])
except:
bad_heap = True
pass
if x <= 0:
bad_heap = True
if bad_heap == False:
if Item_Group[Heap_Choice[0]] - int(Heap_Choice[1]) >= 0:
if x >= 10:
Item_Group[Heap_Choice[0]] = Item_Group[Heap_Choice[0]] - int(Heap_Choice[1:3])
else:
Item_Group[Heap_Choice[0]] = Item_Group[Heap_Choice[0]] - int(Heap_Choice[1])
else:
bad_heap = True
if bad_heap == True:
print('The input did not work, please try again')
return quit
def AiPlay(Item_Group,Mode):
print('\nIt is the AI\'s turn')
Nim_Sum = Item_Group['a']^Item_Group['b']^Item_Group['c']
if Nim_Sum == 0:
#There are no winnable moves unless the player makes a mistake
for i in Item_Group:
#remove 1 from a random heap
if Item_Group[i] > 0:
Item_Group[i] = (Item_Group[i] - random.randint(1,Item_Group[i]))
break
else:
Temp = [Item_Group['a'],Item_Group['b'],Item_Group['c']]
for i in range(0,Temp[0]):
if (i^Item_Group['b']^Item_Group['c'] == 0):
Temp[0] = i
break
for i in range(0,Temp[1]):
if (Item_Group['a']^i^Item_Group['c'] == 0):
Temp[1] = i
break
for i in range(0,Temp[2]):
if (Item_Group['a']^Item_Group['b']^i == 0):
Temp[2] = i
break
if max(Temp) <= 2:
#Misere
if Mode == 2:
if (sum(Temp)%2) == 0:
if max(Temp) > 0:
Temp[Temp.index(max(Temp))] -= 1
else:
if (sum(Temp)%2) == 1:
Temp[Temp.index(max(Temp))] -= 1
Item_Group['a'] = Temp[0]
Item_Group['b'] = Temp[1]
Item_Group['c'] = Temp[2]
def play():
win = False
Mode = ChooseMode()
(Heap_A,Heap_B,Heap_C) = InitializeHeaps()
Item_Group = {'a':Heap_A , 'b':Heap_B , 'c':Heap_C}
quit = False
while (win == False and quit == False):
PrintHeap(Item_Group)
quit = PlayerMove(Item_Group)
win = CheckWin(Mode,'you','the AI',Item_Group)
if (win == False and quit == False):
PrintHeap(Item_Group)
AiPlay(Item_Group,Mode)
win = CheckWin(Mode,'the AI','you',Item_Group)
if quit == True:
print('GoodBye!')
if __name__ == '__main__':
PlayAgain = True
while PlayAgain == True:
quit = Menu()
if quit == False:
PlayAgain = raw_input('Would you like to play again?\n' \
' (type \'y\' to play again, anything else will exit) ')
if PlayAgain.lower() == 'y':
PlayAgain = True
else:
PlayAgain = False
else:
PlayAgain = False
|
3f09efbf3c305a9fbb41dd09cd4d4a94b998ee9e | louisbemberg/python_notes | /py4e/2-conditionals.py | 568 | 4.03125 | 4 | if 2 + 2 == 4 :
print("quick mafs")
if type("Loulou") == type("Bemberg") :
print("Both of these are strings!")
if 6 < 9 : print("One line if statement woohoo!")
if 10 < 5 :
print("inside the if block")
print("not inside the if block")
age = 17
if age < 18 :
print("You cannot drink alcohol, here's a coke!")
else :
print("Cold fresh beer! Cheers mate!")
print('santé!')
if age < 16 :
print("You cannot drink alcohol, here's a coke!")
elif age < 18 :
print("You can drink beer in switzerland")
else :
print("Cold fresh Vodka! Cheers mate!")
|
9fd606cd0bf82bd2df096e0ad467273cc848b810 | Brom-nn/PythonCourse | /Practice/EvgeniySyatoykin/2.1.py | 154 | 3.640625 | 4 | inta=0;
print("Введите ")
input(a)
def fun(a, b):
if a > b:
print(f"max number={a}")
else:
print(f"max number{b}")
|
0116fa0608352979c9a7667fb4f0abda4573f812 | viniciusmartins1/python-exercises | /ex013.py | 209 | 3.65625 | 4 | salario = float(input('Qual é o salário do funcionário: R$ '))
reajuste = salario * 1.15
print('Um funcionário que ganhava R$ {}, com 15% de aumento, passa a receber R$ {:.2f}!'.format(salario, reajuste))
|
2ef24b19bd050ee4c6d8be772ea0b9685507cab8 | jhonfa94/python | /8_Encasulamiento/1_encapsulamiento.py | 1,467 | 3.96875 | 4 | ''' El encapsuplamiento es practicamente el no permitir que se pueda acceder a los atributos de forma directa,
sino que se pueda acceder a traves de metodos,
Para definir un atributo de forma privada para que no sea accedido desde cualquier lugar, se hace a través del doble guion bajo(__)
Para ellos se crea los metodos de get y set, en donde:
get se utiliza para acceder publicamente al valor que se tiene establecido
set se utiliza para establecer el valor del atributo
'''
class Persona:
# Con el doble guion bajo (__) se indica que es un atributo de tipo privado
def __init__(self,nombre,edad):
self.__nombre = nombre
self.__edad = edad
# Metodo de get para acceder
def get_nombre(self):
return self.__nombre
# Metodo para set, el cual se le asigna
def set_nombre(self,nombre):
self.__nombre = nombre
# Metodo get de edad
def get_edad(self):
return self.__edad
# Metodo set de edad
def set_edad(self,edad):
self.__edad = edad
# Creando un objeto
# se genera error porque ya no se accede de forma directa
''' p1 = Persona("Juan")
print(p1.nombre) '''
# Creando el objeto, con pametros iniciales
p1 = Persona("Jhon",26)
print(p1.get_nombre())
print(p1.get_edad())
print("--------------------")
# Modificando los parametros iniciales
p1.set_nombre('Karla')
p1.set_edad(22)
print(p1.get_nombre())
print(p1.get_edad())
|
5e8a776b0e7713f7eec1307281a628cd1b631bc6 | shalgrim/advent_of_code_2020 | /python/day13_1.py | 591 | 3.53125 | 4 | from math import prod
ARRIVAL_TIME = 1003681
LINE_TWO = '23,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,37,x,x,x,x,x,431,x,x,x,x,x,x,x,x,x,x,x,x,13,17,x,x,x,x,19,x,x,x,x,x,x,x,x,x,x,x,409,x,x,x,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,29'
BUSES_IN_SERVICE = [int(bus) for bus in LINE_TWO.split(',') if bus != 'x']
if __name__ == '__main__':
wait_times = {}
for bus in BUSES_IN_SERVICE:
wait_times[bus] = bus - (ARRIVAL_TIME % bus)
shortest_tuple = sorted(
[tuple(item) for item in wait_times.items()], key=lambda x: x[1]
)[0]
print(prod(shortest_tuple))
|
1dd4547e8e5d1250bbf4514a25236b40aacf7853 | Hschan2/Opentutorials | /Python/Python/python/func.py | 618 | 4.03125 | 4 | #!python
print("Content-Type: text/html; charset-utf-8\n")
'''
a = 1
b = 2
c = 3
s = a+b+c
r = s/3
print(r)
'''
'''
#average 함수 코드
def average() :
a = 1
b = 2
c = 3
s = a+b+c
r = s/3
print(r)
average()
'''
'''
#average 함수 코드 응용, 괄호에 변수를 넣어 더 쉽게 사용 (매개변수, parameter)
def average(a,b,c) :
s = a+b+c
r = s/3
print(r)
#안에 값들은 인자라고 부른다. argument
average(10,20,30)
'''
def average(a,b,c) :
s = a+b+c
r = s/3
return r
#안에 값들은 인자라고 부른다. argument
print(average(10,20,30))
def a() :
return 'haha'
print(a())
|
aafcf34641e0be7cb6f67176ea8d487405f4a772 | ntsdwkr/Python | /ncr.py | 231 | 3.640625 | 4 | # ncr using function
def fact(n):
ans = 1
for i in range(1, n+1):
ans = ans * i
return ans
def ncr(n, r):
return fact(n)//(fact(r)*fact(n-r))
n = int(input())
r = int(input())
ans = ncr(n, r)
print(ans)
|
a5f8cf2de38a252d3e9c9510368419e5a763cf74 | TheFibonacciEffect/interviewer-hell | /squares/odds.py | 1,215 | 4.28125 | 4 | """
Determines whether a given integer is a perfect square, without using
sqrt() or multiplication.
This works because the square of a natural number, n, is the sum of
the first n consecutive odd natural numbers. Various itertools
functions are used to generate a lazy iterable of odd numbers and a
running sum of them, until either the given input is found as a sum
or the sum has exceeded n.
"""
from itertools import accumulate, count, takewhile
import sys
import unittest
is_square = lambda n: n > 0 and n in takewhile(lambda x: x <= n, accumulate(filter(lambda n: n & 1, count())))
class SquareTests(unittest.TestCase):
def test_squares(self):
for i in range(1, 101):
if i in (1, 4, 9, 16, 25, 36, 49, 64, 81, 100):
assert is_square(i)
else:
assert not is_square(i)
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit(unittest.main())
value = None
try:
value = int(sys.argv[1])
except TypeError:
sys.exit("Please provide a numeric argument.")
if is_square(value):
print("{} is a square.".format(value))
else:
print("{} is not a square.".format(value))
|
a6b4a196de4ccf74fcbed58c3c69bc7bac34bf2c | amosniu/Python_CRMDSJ | /第二章.py | 3,137 | 3.609375 | 4 | #coding=gbk
#2-1
message = 'Ұ̣Ұpython'
print(message)
#2-2
message = 'pythonϲıԣѧǿ'
print(message)
#2.3ַ
#2.3.1ʹ÷ַСд
#ĸΪд
name = 'ada lovelace'
print(name.title())
#ĸȫΪд
name = 'Ada Lovelace'
print(name.upper())
#ĸΪСд
print(name.lower())
#2.3.2ϲ(ƴ)ַ
first_name = 'amos'
last_name = 'niu'
full_name = first_name + ' ' + last_name
print(full_name)
print('Hello,' + full_name.title() + '!')
message = 'Hello,' + full_name.title() + '!'
print(message)
#2.3.3ʹƱзӿհ
#Ʊ\t
print('Python')
print('\tPython')
#з\n
print('ϲ̣ʹҿ֣Python')
print('ϲ̣\nʹҿ֣\nPython')
print('ϲ̣\n\tʹҿ֣\n\tPython')
#2.3.4ɾհ
country = 'й '
print(country)
print(country.rstrip())
country = ' й'
print(country.lstrip())
country = ' й '
print(country.strip())
#2.3.5ʹַʱ
#ȷʹõź˫
message = "I'am Amos Niu."
print(message)
#message = 'I'am Amos Niu.'дᱨ
#˫меţмַеŻᱨ
#2.3.6Python2еprint
# print"Hello, Python World!"
#2-3
user_name = 'Amos Niu'
print('Hello' + ' ' + user_name + ',' + 'would you like to learn some Python today?')
#2-4
user_name = 'Amos Niu'
print(user_name.lower())
print(user_name.upper())
print(user_name.title())
#2-5
print('˵䡷˵' + '\n\tDZҪȱڡ')
#2-6
famous_person = 'Amos Niu'
message = 'Hello' + ' ' + famous_person + ',' + 'would you like to learn some Python today?'
print(message)
#2-7
user_name = ' Amos Niu '
print(user_name.strip())
print('\n\t' + user_name.strip())
#2.4
#2.4.1
print(1 + 2)
print(3 - 2)
print(2 * 3)
print(3 / 2)
#˺Ŵ˷
print(3 ** 2)
print(10 ** 6)
print((2+3) * 4)
#2.4.2
print(0.1 + 0.1)
#СλDzȷģ£
print(0.2 + 0.1)
print(3 * 0.1)
#2.4.3ʹústr()ʹ
age = 23
message = 'Happy ' + str(age) + 'rd Birthday!'
print(message)
#2.4.4 Python2е
#Python2УĵĽвͬ磺3 / 2 = 1
#ֻ֣Сֻᱻֱɾ
#Python2ҪҪȷһΪ3.0 / 2 = 1.5
#3 / 2.0 = 1.5
#2-8
a = 3 + 5
b = 11 - 3
c = 2 * 4
d = 16 / 2
print(a)
print(b)
print(c)
print(d)
#2-9
favorite_number = 188
message = 'ϲǣ' + str(favorite_number)
print(message)
#2.5ע
#2.5.1αдע
#"#"ݻᱻPython
#2.5.2ñдʲôע
|
0ddf8389cb42e7d18641a5b4d74ebb594d6edff7 | zv2051/Study | /MIT_600/fibonacciRecursion.py | 433 | 4.09375 | 4 | #!/usr/bin/python3
####################################################################
#
# proc fibonacci by recursion
#
####################################################################
var = int(input("Enter a Number:"))
def fibonacciRe(var):
assert type(var) == int and var >=0
if var == 0 or var == 1:
return 1
else:
return fibonacciRe(var - 1) + fibonacciRe(var - 2)
print(fibonacciRe(var))
|
011af88a76fc4c0bc12a4c900d46f84d1ceb6df0 | jammy-bot/atom-test | /2-py.py | 674 | 3.796875 | 4 | #-------------------------------------------------------------------------------
# Name: 2-py
# Purpose: test file for atom-plus
#
# Author: jbot
#
# Created: 12/04/2019
# Copyright: (c) jammy-bot 2019
#-------------------------------------------------------------------------------
length_list = []
# initalize the list with i, followed by i plus i^2 for the number of
# iterations in test_length
def runnit(test_length):
i=1
while len(length_list) < test_length:
length_list.append(i)
i += i*2
#print the list as it iterates
print(length_list)
# print the final list
# print(length_list)
runnit(6)
|
272c357360c8070dd5a383ad9d1e9197454ba401 | caylavgonzales/ITMGT-25.03-Submissions-Cayla-Gonzales-Section-A- | /202386_GONZALES_CAYLA_HANDLINGFILES.py | 1,776 | 3.859375 | 4 | products = {
"americano":{"name":"Americano","price":150.00},
"brewedcoffee":{"name":"Brewed Coffee","price":110.00},
"cappuccino":{"name":"Cappuccino","price":170.00},
"dalgona":{"name":"Dalgona","price":170.00},
"espresso":{"name":"Espresso","price":140.00},
"frappuccino":{"name":"Frappuccino","price":170.00},
}
def get_product(code):
return products[code]
def get_property(code, property):
return products[code][property]
def main():
inp = ""
orders = {}
total = 0
while inp != "/":
subtotal = 0
order = input("Enter your order: {code}, {quantity} ")
if order != "/":
code, quantity = order.split(", ")
product = get_product(code)
else:
break
quantity = int(quantity)
price = product["price"]
subtotal = price * quantity
if code in orders.keys():
orders[code]["quantity"] += quantity
orders[code]["subtotal"] += subtotal
else:
orders[code] = {
"quantity" : quantity,
"subtotal" : subtotal
}
total += subtotal
orders = dict(sorted(orders.items()))
output = []
output.append('==')
output.append('CODE\t\t\tNAME\t\t\tQUANTITY\t\t\tSUBTOTAL')
for code, order in orders.items():
name = get_property(code, "name")
quantity = order["quantity"]
subtotal = order["subtotal"]
output.append(f'{code}\t\t{name}\t\t{quantity}\t\t\t\t{subtotal}')
output.append("")
output.append(f'Total:\t\t\t\t\t\t\t\t\t\t{total}')
output.append('==')
output = "\n".join(output)
print(output)
with open("receipt.txt", "w") as f:
f.write(output)
main()
|
cbb789854cfcee1aa9f31347c505a8c582b304e7 | VakinduPhilliam/Python_Time_Machine | /Python_Datetime_Time_Delta.py | 1,777 | 4.125 | 4 | # Python Datetime
# datetime Basic date and time types.
# The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the
# focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
# There are two kinds of date and time objects: naive and aware.
# An aware object has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information,
# to locate itself relative to other aware objects. An aware object is used to represent a specific moment in time that is not open to interpretation.
# A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents
# Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it is up to the program whether a
# particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of
# reality.
#
# 'timedelta' Objects:
#
# A timedelta object represents a duration, the difference between two dates or times.
# class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0).
# All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.
#
# Note that normalization of negative values may be surprising at first.
#
# For example,
#
from datetime import timedelta
d = timedelta(microseconds=-1)
(d.days, d.seconds, d.microseconds)
#
# OUTPUT: '(-1, 86399, 999999)'
# |
b2227b0448249064574b1c4fda4bf1514a2bf375 | limiyou/Pyproject | /1python基础/class4 list and dict/demo07_tuple.py | 333 | 4.0625 | 4 | """
元组
元组和列表相似
元组是不可变的,只能获取;列表是可变的(增加,修改)
元组表示:()
列表表示:[]
"""
tp=(3,4,5)
print(tp)
print(type(tp))
#空元组
tp=()
print(tp)
#TODO: 一个元素的元组,在元素后面一定要加,
tp=(1,)
print(tp)
#查找
print(tp[0]) |
17a7805435ebdad80573f3ab8cb4628ae48d23f7 | abhiram11/NLP-and-Multi-Layered-Neural | /tensorflow/deepnet.py | 3,762 | 3.6875 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
#one element is hot (ON), rest all are cold (OFF)
n_nodes_hl1 = 500
n_nodes_hl2 = 500 # number of nodes for hiddden layers
n_nodes_hl3 = 500 # the numbers can be random, not necessarily 500
n_classes = 10 #already defined in MNIST but still defined here
batch_size = 100
# matrix = height x width, here 28x28 pixel image converted to one line of 28x28 = 784 pixels(?) ki array
x = tf.placeholder('float', [None, 784]) #always good to describe its input type
y = tf.placeholder('float') # x is data y is label
def neural_network_model(data):
hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784,n_nodes_hl1])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))} #tensorflow variable which is tf random normal whose shape is defined
hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1 ,n_nodes_hl2])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
output_1_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes]))}
#neurons work as : (input data ^ weights) + biases cuz if input data = 0 then neuron won't fire
l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']) , hidden_1_layer['biases'])
l1 = tf.nn.relu(l1) #rectify linear/threshold function that takes the l1 as input value in its bracket
l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']) , hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)
l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']) , hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)
output = tf.matmul(l3,output_1_layer['weights']) + output_1_layer['biases']
return output
#specify how to run data thru that model
def train_neural_network(x):
prediction = neural_network_model(x) #taking input data passing thr nnmodel, thru its layers, returns the output in prediciton;
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
#will calculate the cost difference between the calculated prediction and the ACTUAL pre-present y value
#time to minimize the cost difference
optimizer = tf.train.AdamOptimizer().minimize(cost)
#has parameter learning_rate=0.001 that can be defined too
hm_epochs = 10 #how many epochs we want, less for lower performace CPU
#epochs = cycles of feed forwads + backpropagations
#epoch = seen all of training data once
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(hm_epochs):
epoch_loss = 0
for _ in range(int(mnist.train.num_examples/batch_size)): # _ represents a variable that we dont care about
# implies how many times we wanna run the cycles depending on the dynamic entry of batch_size
epoch_x,epoch_y= mnist.train.next_batch(batch_size) #input and labels as x and y
_, c = sess.run([optimizer,cost], feed_dict={x:epoch_x,y:epoch_y}) # c represents cost
epoch_loss+=c # for each c we resett epochloss but we need to keep count
print(" Epoch ",epoch," completed out of ", hm_epochs, " loss : ", epoch_loss)
#data training completed
#now run them thru the model
#try to make % completed
correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1)) #first will return index of max value and matches with the other, i.e prediction = y
accuracy = tf.reduce_mean(tf.cast(correct,'float')) #type cassting
print('Accuracy: ',accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))
train_neural_network(x)
|
614f942da599ff50d2b8608b07f4f8a5a1cb218e | RaviMudgal/AlgoAndDataStructures | /recursion/SumList.py | 338 | 3.875 | 4 | def listSum(numList):
sum = 0
for i in numList:
sum += i
return sum
print (listSum([1,2,3,4,]))
# listSum using recursion
def listSumRecursion(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listSumRecursion(numList[1:])
print(listSumRecursion([3,4,5,6,7,7,8]))
|
6d18b7343951327484d14f41c920fc6de550d572 | Darlley/Python | /LIVRO_CursoIntensivoPython/Capitulo_3/ex07.py | 1,387 | 3.78125 | 4 | #3.7 – Reduzindo a lista de convidados: Você acabou de descobrir que sua nova
#mesa de jantar não chegará a tempo para o jantar e tem espaço para somente
#dois convidados.
#• Comece com seu programa do Exercício 3.6. Acrescente uma nova linha que
#mostre uma mensagem informando que você pode convidar apenas duas pessoas
#para o jantar.
#• Utilize pop() para remover os convidados de sua lista, um de cada vez, até que
#apenas dois nomes permaneçam em sua lista. Sempre que remover um nome de
#sua lista, mostre uma mensagem a essa pessoa, permitindo que ela saiba que
#você sente muito por não poder convidá-la para o jantar.
#• Apresente uma mensagem para cada uma das duas pessoas que continuam na
#lista, permitindo que elas saibam que ainda estão convidadas.
#• Utilize del para remover os dois últimos nomes de sua lista, de modo que você
#tenha uma lista vazia. Mostre sua lista para garantir que você realmente tem uma
#lista vazia no final de seu programa.
convidados = ['John Walton', 'Alvin Plantinga', 'Bertrand Russell', 'William Lane Craig', 'Francis Collins', 'Leibniz']
del convidados[0]
del convidados[2]
print("\nInfelizmente a mesa do jantar não chegará a tempo, então graças a este exercicio terei que desfazer o convite dos maires pensadores filosofos e cientistas.")
convidados.pop(4)
convidados.pop(5)
print("Mas o convite ainda esta de pé para vocês:")
print(convidados)
|
b5c40939b75e212648e3f19d0adbc03cd688c490 | Taoge123/OptimizedLeetcode | /LeetcodeNew/DynamicProgramming/LC_361_Bomb_Enemy.py | 5,061 | 3.90625 | 4 |
"""
Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0'
(the number zero), return the maximum enemies you can kill using one bomb.
The bomb kills all the enemies in the same row and column from the planted point
until it hits the wall since the wall is too strong to be destroyed.
Note: You can only put the bomb at an empty cell.
Example:
Input: [["0","E","0","0"],["E","0","W","E"],["0","E","0","0"]]
Output: 3
Explanation: For the given grid,
0 E 0 0
E 0 W E
0 E 0 0
Placing a bomb at (1,1) kills 3 enemies.
"""
class Solution:
def maxKilledEnemies(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if grid is None or len(grid) == 0 or len(grid[0]) == 0:
return 0
dp = [[[0, 0] for j in range(len(grid[0]))] for i in range(len(grid))]
for i in range(0, len(grid)):
for j in range(0, len(grid[0])):
if grid[i][j] == "E":
dp[i][j] = [dp[i - 1][j][0] + 1, + dp[i][j - 1][1] + 1]
elif grid[i][j] == "0":
dp[i][j] = [dp[i - 1][j][0], dp[i][j - 1][1]]
maxKilled = 0
for i in reversed(range(0, len(grid))):
for j in reversed(range(0, len(grid[0]))):
if j != len(grid[0]) - 1:
if grid[i][j + 1] != "W":
dp[i][j][1] = dp[i][j + 1][1]
if i != len(grid) - 1:
if grid[i + 1][j] != "W":
dp[i][j][0] = dp[i + 1][j][0]
if grid[i][j] == "0":
curKilled = dp[i][j][0] + dp[i][j][1]
if curKilled > maxKilled:
maxKilled = curKilled
return maxKilled
class Solution2:
def maxKilledEnemies(self, grid):
maxEnemy = 0
tgrid = [list(i) for i in zip(*grid)]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '0':
maxEnemy = max(maxEnemy, self.countEInRow(j, grid[i]) + self.countEInRow(i, tgrid[j]))
return maxEnemy
def countEInRow(self, i, row):
if len(row) == 1:
return 0
tempE = 0
# move right
for j in range(i + 1, len(row)):
if row[j] == 'E':
tempE += 1
if row[j] == 'W':
break
# move left
for j in range(i - 1, -1, -1):
if row[j] == 'E':
tempE += 1
if row[j] == 'W':
break
return tempE
class Solution3:
def maxKilledEnemies(self, grid):
if not grid or not grid[0]: return 0
top = [[0] * len(grid[0]) for i in range(len(grid))]
bot = [[0] * len(grid[0]) for i in range(len(grid))]
left = [[0] * len(grid[0]) for i in range(len(grid))]
right = [[0] * len(grid[0]) for i in range(len(grid))]
for i in range(1, len(grid)):
for j in range(len(grid[0])):
top[i][j] = top[i - 1][j] + (grid[i - 1][j] == 'E')
if grid[i - 1][j] == 'W':
top[i][j] = 0
for i in range(len(grid)):
for j in range(1, len(grid[0])):
left[i][j] = left[i][j - 1] + (grid[i][j - 1] == 'E')
if grid[i][j - 1] == 'W':
left[i][j] = 0
for i in range(len(grid) - 1)[::-1]:
for j in range(len(grid[0])):
bot[i][j] = bot[i + 1][j] + (grid[i + 1][j] == 'E')
if grid[i + 1][j] == 'W':
bot[i][j] = 0
for i in range(len(grid)):
for j in range(len(grid[0]) - 1)[::-1]:
right[i][j] = right[i][j + 1] + (grid[i][j + 1] == 'E')
if grid[i][j + 1] == 'W':
right[i][j] = 0
return max([left[i][j] + right[i][j] + top[i][j] + bot[i][j]
for i in range(len(grid)) for j in range(len(grid[0])) if grid[i][j] == '0'], default=0)
class Solution4:
def maxKilledEnemies(self, grid):
# Write your code here
m, n = len(grid), 0
if m:
n = len(grid[0])
result, rows = 0, 0
cols = [0 for i in range(n)]
for i in range(m):
for j in range(n):
if j == 0 or grid[i][j-1] == 'W':
rows = 0
for k in range(j, n):
if grid[i][k] == 'W':
break
if grid[i][k] == 'E':
rows += 1
if i == 0 or grid[i-1][j] == 'W':
cols[j] = 0
for k in range(i, m):
if grid[k][j] == 'W':
break
if grid[k][j] == 'E':
cols[j] += 1
if grid[i][j] == '0' and rows + cols[j] > result:
result = rows + cols[j]
return result
|
103f2674ed5700000edda2737a2f6df0a801e4b0 | d391/UBB--Formal-Languages-and-Compiler-Design | /lab6/Grammar.py | 2,243 | 3.59375 | 4 | class Grammar:
def __init__(self, _nonterminal_symbols, _terminal_symbols, _productions, _start_terminal):
self.nonterminal_symbols = _nonterminal_symbols
self.terminal_symbols = _terminal_symbols
self.productions = _productions
self.start_terminal = _start_terminal
@staticmethod
def read_from_file(filename):
with open(filename) as file:
nonterminal_symbols = Grammar.parse_line(file.readline())
terminal_symbols = Grammar.parse_line(file.readline())
start_terminal = Grammar.parse_line(file.readline())
productions = Grammar.parse_productions(Grammar.parse_line(''.join([line for line in file])))
return Grammar(nonterminal_symbols, terminal_symbols, productions, start_terminal)
@staticmethod
def parse_line(line):
return [element.strip() for element in line.strip().split('=')[1].strip()[1:-1].split(',')]
@staticmethod
def parse_productions(productions):
result = []
for rule in productions:
[lhs, rhs] = rule.strip().split('->')
results = rhs.strip().split('|')
for res in results:
result.append((lhs.strip(), res.split()))
return result
def find_production(self, symbol):
result = []
for production in self.productions:
if production[0] == symbol:
result.append(production[1])
return result
def menu(self):
print("0 - Exit")
print("1 - Productions")
print("2 - Nonterminal symbols")
print("3 - Terminal symbols")
print("4 - Productions for a given nonterminal")
def printMenu(self):
while True:
self.menu()
choice = int(input("> "))
if choice == 0:
return
if choice == 1:
print(self.productions)
if choice == 2:
print(self.nonterminal_symbols)
if choice == 3:
print(self.terminal_symbols)
if choice == 4:
nt = input("Give nonterminal: ")
print(self.find_production(nt))
|
e5862f062f63daa9d44276bcfe9172a6e46b3077 | jtsit/checklists | /excel-json-converter.py | 3,317 | 3.6875 | 4 | #this is the concept in python.
import csv # to read csv file
import xlsxwriter # to write xlxs file
import ast
# you can change this names according to your local ones
csv_file = 'data.csv'
xlsx_file = 'data.xlsx'
# read the csv file and get all the JSON values into data list
data = []
with open(csv_file, 'r') as csvFile:
# read line by line in csv file
reader = csv.reader(csvFile)
# convert every line into list and select the JSON values
for row in list(reader)[1:]:
# csv are comma separated, so combine all the necessary
# part of the json with comma
json_to_str = ','.join(row[1:])
# convert it to python dictionary
str_to_dict = ast.literal_eval(json_to_str)
# append those completed JSON into the data list
data.append(str_to_dict)
# define the excel file
workbook = xlsxwriter.Workbook(xlsx_file)
# create a sheet for our work
worksheet = workbook.add_worksheet()
# cell format for merge fields with bold and align center
# letters and design border
merge_format = workbook.add_format({
'bold': 1,
'border': 1,
'align': 'center',
'valign': 'vcenter'})
# other cell format to design the border
cell_format = workbook.add_format({
'border': 1,
})
# create the header section dynamically
first_col = 0
last_col = 0
for index, value in enumerate(data[0].items()):
if isinstance(value[1], dict):
# this if mean the JSON key has something else
# other than the single value like dict or list
last_col += len(value[1].keys())
worksheet.merge_range(first_row=0,
first_col=first_col,
last_row=0,
last_col=last_col,
data=value[0],
cell_format=merge_format)
for k, v in value[1].items():
# this is for go in deep the value if exist
worksheet.write(1, first_col, k, merge_format)
first_col += 1
first_col = last_col + 1
else:
# 'age' has only one value, so this else section
# is for create normal headers like 'age'
worksheet.write(1, first_col, value[0], merge_format)
first_col += 1
# now we know how many columns exist in the
# excel, and set the width to 20
worksheet.set_column(first_col=0, last_col=last_col, width=20)
# filling values to excel file
for index, value in enumerate(data):
last_col = 0
for k, v in value.items():
if isinstance(v, dict):
# this is for handle values with dictionary
for k1, v1 in v.items():
if isinstance(v1, list):
# this will capture last 'type' list (['Grass', 'Hardball'])
# in the 'conditions'
worksheet.write(index + 2, last_col, ', '.join(v1), cell_format)
else:
# just filling other values other than list
worksheet.write(index + 2, last_col, v1, cell_format)
last_col += 1
else:
# this is handle single value other than dict or list
worksheet.write(index + 2, last_col, v, cell_format)
last_col += 1
# finally close to create the excel file
workbook.close()
|
2dbf6f8e09c0c5e3056a8407953b198db446348a | utksezgin/GTU-Homeworks | /Daily Coding Problems/Stack.py | 1,245 | 4.28125 | 4 | # This problem was asked by Amazon.
# Implement a stack that has the following methods:
# • push(val), which pushes an element onto the stack
# • pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null.
# • max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null.
# Each method should run in constant time.
class Stack:
def __init__(self):
self.maxInStack = None
self.stack = []
def push(self, val):
self.stack.append(val)
if self.maxInStack == None:
self.maxInStack = val
elif val > self.maxInStack:
self.maxInStack = val
def pop(self):
if len(self.stack) == 0:
return None
item = self.stack[len(self.stack)-1]
self.stack = self.stack[:-1]
return item
def max(self):
if len(self.stack) == 0:
return None
else:
return self.maxInStack
# Test Driver
s = Stack()
s.push(2)
print("2 pushed to stack")
s.push(5)
print("5 pushed to stack")
print("Current Max %d" % s.max())
s.push(7)
print("7 pushed to stack")
print("Current Max %d" % s.max())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop()) |
bc7cfe416b5b89b9428923c9f577a47126dafdf7 | ErmanoClaude/Algorithms | /SymmetricDifference.py | 782 | 4.28125 | 4 | """ A function that takes two or more arrays and returns an array of the symmetric difference (△ or ⊕). """
def sym(*args):
"""Return Unique Values between Arrays into one array """
sym = [];
value = args[0][0]
for array in args:
#iterate over tuple of arrays
for value in array:
#iterate over values in each arrays in tuple
count = 0
for array2 in args:
#iterate each array in tuple
#check if value is in other arrays
try:
index = array2.index(value)
except ValueError:
count = count + 1
if(count == len(args) - 1):
#count one less then number of arrays means
#Value is unique add it to sym
sym.append(value)
return list(dict.fromkeys(sym))
SymDif = sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])
print(SymDif)
|
7dc777a03f0b40171a7e4b423e77c534fa603df0 | webstorage119/Iris_pattern_classification | /CNNModels/GoogLeNet/util/dataloader.py | 4,396 | 3.59375 | 4 | '''
(x_train, x_test)
: uint8 array of RGB image data with shape (num_samples, 3, 32, 32) or (num_samples, 32, 32, 3)
based on the image_data_format backend setting of either channels_first or channels_last respectively.
(y_train, y_test)
: uint8 array of category labels (integers in range 0-9) with shape (num_samples,)
'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'
'''
from keras.utils import np_utils
from keras.datasets import cifar10
from .constants import *
import numpy as np
class DataLoader:
@staticmethod
def load_data():
# 훈련셋 시험셋 로딩: train, test
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_data = np.concatenate((x_train, x_test), axis=0)
y_data = np.concatenate((y_train, y_test), axis=0)
# 3600 1800 600 train test val
# 훈련셋 검증셋 분리
x_val = x_data[54000:]
y_val = y_data[54000:]
x_test = x_data[36000:54000]
y_test = y_data[36000:54000]
x_train = x_data[0:36000]
y_train = y_data[0:36000]
# 3072 = 32 * 32 * 3
x_train = x_train.reshape(36000, FLG.WIDTH, FLG.HEIGHT, FLG.DEPTH).astype('float32') / 255.0
x_test = x_test.reshape(18000, FLG.WIDTH, FLG.HEIGHT, FLG.DEPTH).astype('float32') / 255.0
x_val = x_val.reshape(6000, FLG.WIDTH, FLG.HEIGHT, FLG.DEPTH).astype('float32') / 255.0
# # 훈련셋, 검증셋 고르기
# train_rand_idxs = np.random.choice(50000, 700)
# val_rand_idxs = np.random.choice(10000, 300)
# x_train = x_train[train_rand_idxs]
# y_train = y_train[train_rand_idxs]
# x_val = x_val[val_rand_idxs]
# y_val = y_val[val_rand_idxs]
print('X_train shape:', x_train.shape)
print('x_val shape:', x_val.shape)
print('x_test shape:', x_test.shape)
print(x_train.shape[0], 'train samples / ', x_val.shape[0], 'val samples / ', x_test.shape[0], 'test samples')
from sklearn.preprocessing import LabelBinarizer
# 라벨링 전환 : 다중분류 모델일 때 -> one-hot encoding 처리
# nb_classes = 10
# y_train = np_utils.to_categorical(y_train, nb_classes)
# y_val = np_utils.to_categorical(y_val, nb_classes)
# y_test = np_utils.to_categorical(y_test, nb_classes)
# 라벨링 전환
''' ['panda' 'dogs' 'cats' 'dogs' .....] -> [ [0 1 0]\n [1 0 0 ]\n [0 0 1 ]\n .... ] '''
lb = LabelBinarizer()
y_train = lb.fit_transform(y_train)
y_val= lb.transform(y_val)
y_test= lb.transform(y_test)
''' lb.classes_ : ['cats' 'cogs' 'panda'] ndarray 형식 '''
return x_train, y_train, x_val, y_val, x_test, y_test, lb
#
#
# def test_data(self):
# # 훈련셋 시험셋 로딩: train, test
# (x_train, y_train), (x_test, y_test) = cifar10.load_data()
#
# # 훈련셋 검증셋 분리: train -> train, val
# x_val = x_train[40000:]
# y_val = y_train[40000:]
# x_train = x_train[0:40000]
# y_train = y_train[0:40000]
#
# x_train = x_train.reshape(40000, 3072).astype('float32') / 255.0
# x_val = x_val.reshape(10000, 3072).astype('float32') / 255.0
# x_test = x_test.reshape(10000, 3072).astype('float32') / 255.0
#
# # # 훈련셋, 검증셋 고르기
# # train_rand_idxs = np.random.choice(50000, 700)
# # val_rand_idxs = np.random.choice(10000, 300)
# #
# # x_train = x_train[train_rand_idxs]
# # y_train = y_train[train_rand_idxs]
# # x_val = x_val[val_rand_idxs]
# # y_val = y_val[val_rand_idxs]
#
# print('X_train shape:', x_train.shape)
# print('x_val shape:', x_val.shape)
# print('x_test shape:', x_test.shape)
# print(x_train.shape[0], 'train samples')
# print(x_val.shape[0], 'test samples')
# print(x_test.shape[0], 'test samples')
#
# # 라벨링 전환 : 원핫인코딩 (one-hot encoding) 처리
# nb_classes = 10
# y_train = np_utils.to_categorical(y_train, nb_classes)
# y_val = np_utils.to_categorical(y_val, nb_classes)
# y_test = np_utils.to_categorical(y_test, nb_classes)
#
# return x_train, y_train, x_val, y_val, x_test, y_test
#
|
9d0230ccdfed81a0b5a617e6abc84f333e7246ca | Ruturaj4/leetcode-python | /easy/to-lower-case.py | 376 | 3.84375 | 4 | #Implement function ToLowerCase() that has a string parameter str,
#and returns the same string in lowercase.
class Solution:
def toLowerCase(self, str: str) -> str:
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower = "abcdefghijklmnopqrstuvwxyz"
temp = dict(zip(upper, lower))
return "".join([temp[x] if x in temp else x for x in str])
|
a79fdd3b6be3765e0266986b7d72bebade4fb65a | iamanogre/capitalone_OSCARS | /capitalone.py | 4,304 | 3.625 | 4 | """
CapitalOne Challenge
Due 3/10/2015
Author: Gary Hoang
"""
import csv
import string
import operator
from states import states_to_letters, letters_to_states
# nominees
MAP = {'birdman': "Birdman", 'whiplash': "Whiplash",
'sniper': "American Sniper",
'budapest': "The Grand Budapest Hotel",
'imitation': "The Imitation Game", 'selma':"Selma",
'theory': "The Theory of Everything",
'boyhood': "Boyhood"}
# empty dictionaries
nominees = {} # nominee counters
counters = {} # so we don't count a movie twice in one line
birdman_times = {} # dictionary to hold all of the times Birdman was tweeted about
states = {} # dictionary to hold the number of times a state tweeted through out the Oscars
def keywithmaxval(dic):
"""
input is a dictionary and returns the key with the
greatest value.
"""
vals = list(dic.values())
keys = list(dic.keys())
return keys[vals.index(max(vals))]
def dictreset(dic):
"""
input is dictionary and resets all values in dictionary.
preserves keys.
"""
for elem in dic.keys():
dic[elem] = 0
def printmaxtomin(dic, string, conver_dic, text):
"""
input is dictionary and prints out
all keys from key with biggest value to key with smallest value
"""
print(string, file=text)
# get dictionary values, get rid of duplicates, turn to list
# use sorted to sort from biggest to smallest
values = sorted(list(set(dic.values())), reverse=True)
keys = []
for v in values:
for key,value in dic.items():
if v == value:
keys.append(key)
counter = 1
for k in keys:
print(str(counter) + ": " + conver_dic[k], file=text)
counter += 1
# Used to strip each message of all characters except for letters
elim = ''.join(chr(c) if chr(c).isupper() or chr(c).islower() else ' ' for c in range(256))
def main():
print("Program Started. Please wait a while.")
for nominee in MAP:
nominees[nominee] = 0
counters[nominee] = 0
for state in letters_to_states.keys():
states[state] = 0
reader = csv.reader(open('oscar_tweets.csv', "rt", encoding="utf8", newline=''), dialect="excel")
data = [line for line in reader]
for line in data[1:]:
# look at what each user wrote in their tweet
string = line[2]
string = string.translate(elim).lower().split()
for key in nominees.keys():
for word in string:
# checking on the go
if len(word) <= 4:
continue
if counters[key] == 0:
if key in word:
nominees[key] += 1
counters[key] += 1
if key == 'birdman':
time = line[0].split()[3].split(':')
hour = time[0]
minute = time[1]
tup = (hour, minute)
if tup in birdman_times:
birdman_times[tup] += 1
else:
birdman_times[tup] = 1
# looking for states now!
location = line[8]
location_counter = 0
if location: # so not an empty string!!
location = location.translate(elim).lower()
# to test states like "New York" and "North Dakota"
for state in states_to_letters.keys():
if state.lower() in location:
states[states_to_letters[state]] += 1
location_counter = 1
# now testing by two letter intials
if not location_counter:
for word in location:
if location_counter:
break
if len(word) == 2:
if word.upper() in letters_to_states.keys():
states[word.upper()] += 1
location_counter = 1
break;
# reset our counter dictionaries
dictreset(counters)
# write our results to RESULTS.txt
with open("RESULTS.txt", "w") as text_file:
print("RESULTS:", file=text_file)
print("==================", file=text_file)
printmaxtomin(nominees, "Part 1: Popularity Ranking of Oscar Nominees 2015\n From most popular to least", MAP, text_file)
print("==================", file=text_file)
print("Part 2: Time Birdman was most tweeted about", file=text_file)
time = keywithmaxval(birdman_times)
print("Most Tweeted about moment: " + str(int(time[0])) + ":" + time[1] + "PM or " + str(int(time[0])+4) + ":" + time[1] + "PM PST", file=text_file)
print("==================", file=text_file)
# not including Washington DC.
printmaxtomin(states, "Part 3: State Activity\n From Twitter Storm to Desert", letters_to_states, text_file)
print("Finished Computuations. Gathered Results and wrote them to RESULTS.txt")
main() |
d5becd9c56bb2ab8fd73ebacc7d1d8f494ab50ee | dtliao/Starting-Out-With-Python | /chap.4/08 p.162 ex5. hard.py | 593 | 4.375 | 4 | years=int(input('Enter number of years:'))
year=0
total_months=0
total_rainfall=0
average_rainfall=0
month_rainfall=0
for years in range(years):
print('For year', years+1, ':' )
for month in range(12):
month_rainfall=float(input('Enter the inches of rainfall for the month:'))
total_months+=1
total_rainfall+=month_rainfall
average_rainfall= total_rainfall/total_months
print('The number of months is', total_months)
print('The total inches of rainfall is', total_rainfall)
print('The average rainfall per month is', format(average_rainfall, '.2f')) |
28e0eaa23ab1ab3484ef394601ffbf1b07fe1d84 | mackowia/bootcamp | /basic/zjazd I/while.py | 450 | 3.921875 | 4 | a = 0
while a < 10:
print ( 2 ** a )
a += 1
a = 0
b = 0
while b < 10000:
print ( b )
a += 1
b = 2 ** a
a = 1
while a < 10:
print ( 2 ** a)
a += 1
a = 0
while a < 100:
print(f"{a}^2 = {a ** 2}")
a+=1
suma_temperatur = 0
dzien = 1
while dzien < 8 :
suma_temperatur += float (input(f"Podaj temperaturę dla dnia {dzien}: "))
dzien += 1
print (f"Średnia temperatur to { suma_temperatur / 7 :.2f}")
|
b92ce495aa97e6715b9d19385e8f24e81566f13e | ShangruZhong/leetcode | /Linearlist/36.py | 992 | 3.71875 | 4 | """
36. Valid Sudoku
@author: Shangru
@date: 2015/09/30
"""
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
def isValid(x, y, tmp):
for i in range(9):
if board[i][y] == tmp:
return False
for i in range(9):
if board[x][i] == tmp:
return False
for i in range(3):
for j in range(3):
if board[(x/3)*3+i][(y/3)*3+j] == tmp:
return False
return True
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
tmp = board[i][j]
board[i][j] = 'F'
if isValid(i,j,tmp) == False:
return False
else:
board[i][j] = tmp
return True
|
29e26446572fbca3cf3bf3969c78d21b11447514 | ThalesLeal/python | /URI/URI 1006.py | 250 | 3.890625 | 4 | # -*- coding: utf-8 -*-
def media (A,B,C):
return (A * 0.2)+(B * 0.3)+(C * 0.5)
def main():
A = float(input(""))
B = float(input(""))
C = float(input(""))
print("MEDIA = %2.1f" % media(A,B,C))
if __name__ == '__main__':
main() |
05da8da042444d88e1134d70eb85a68082e4dac6 | Antilos/llgram | /llgram/rule.py | 954 | 3.546875 | 4 | class Rule:
def __init__(self):
"""
"""
self.left = ""
self.right = list()
self.first = set()
self.action = None
def __repr__(self):
return f"{self.left} -> {' '.join(self.right)}"
def __str__(self):
return f"{self.left} -> {' '.join(self.right)}"
def __eq__(self, other):
return str(self) == str(other)
def __hash__(self):
return hash(self.__str__())
def getLeft(self):
return self.left
def setLeft(self, val):
self.left = val
def getRight(self):
return self.right
def appendRight(self, val):
self.right.append(val)
def getFirst(self):
return self.first
def addFirst(self, val):
self.first.add(val)
def setFirst(self, val):
self.first = val
def getAction(self):
return self.action
def setAction(self, val):
self.action = val |
8782c17f9c8740cc744594b888ce740f1ae57ec5 | Nutner/mod02acelera | /func1rnivel.py | 320 | 3.546875 | 4 | def normal(x):
return x
def cuadrado(y):
return y*y
def cubo(x):
return x**3
def sumaTodos(limitTo,f):
resultado = 0
for i in range(limitTo + 1):
resultado += f(i)
return resultado
if __name__ == "__main__":
print (sumaTodos(100,normal))
print (sumaTodos(3,cuadrado))
|
d8fbc755a27a42c631663891970d67a5ccf2a3b2 | iturricf/clusteris | /clusteris/timer.py | 679 | 3.5625 | 4 | # -*- coding: utf-8 -*-
from timeit import default_timer as timer
class Timer(object):
def __init__(self):
self.times = []
self.start = 0
self.end = 0
def AddTime(self, description):
t = timer()
self.times.append((description, t))
if (description.lower() == "start"):
self.start = t
if (description.lower() == "end"):
self.end = t
def PrintTimes(self):
for t in range(len(self.times) - 1):
time = self.times[t+1][1] - self.times[t][1]
print("Time for %s: %s" % (self.times[t+1][0], time))
print("Total time: %s" % (self.end - self.start))
|
7381c75df418ec000814aed230ba6ba7f06334a5 | anks321/numpy | /numpy.py | 424 | 4 | 4 | import numpy as np
#Accessing / Chnaging
a=np.array([[1,2,3,4,5,6],[7,8,9,10,11,12]])
print(a)
#getting specific element (r,c)
print(a[1,5])
#Getting a spcefic row
print(a[0,:])
#Getting a specefi column
print(a[:,3])
# Getting every other element of first row
print(a[0,1:6:2])
#Changing element
a[1,5]=14
a[:,3]=[1,2]
print(a)
#3d element
b=np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
print(b)
print(b[:,:,0]) |
c49786a218257cbb4d24eb5bcecb0ea59c0037c4 | q759729997/qyt_nlp_collections | /文本相似度/jaccard_distance.py | 738 | 3.890625 | 4 | def calculate_jaccard_distance(words1, words2):
"""计算jaccard距离"""
# 转换为set集合
words_set1 = set(words1)
words_set2 = set(words2)
# 计算交集与并集
union_len = len(words_set1.union(words_set2)) # 两个集合的并集
intersection_len = len(words_set1.intersection(words_set2)) # 两个集合的交集
return 1 - intersection_len / union_len
if __name__ == "__main__":
"""
jaccard距离
"""
words1 = ['I', 'like', 'apple']
words2 = ['I', 'do', 'not', 'like', 'apple']
print(calculate_jaccard_distance(words1, words2)) # 0.4
words1 = '123'
words2 = '12345'
print(calculate_jaccard_distance(set(words1), set(words2))) # 0.4
|
9d50c5d6c6c40e6d8d46bc9ded80c13774bc985a | latata666/newcoder | /leecode/lec_322_coinChange.py | 1,114 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/6/15 10:56
# @Author : Mamamooo
# @Site :
# @File : lec_322_coinChange.py
# @Software: PyCharm
"""
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。
如果没有任何一种硬币组合能组成总金额,返回 -1
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
"""
import functools
class Solution:
def coinChange(self,coins,amount):
print(coins,amount)
@functools.lru_cache(amount)
def dp(rem):
if rem < 0:
return -1
if rem == 0:
return 0
mini = int(1e9)
for coin in self.coins:
res = dp(rem -coin)
if res >= 0 and res < mini:
mini = res + 1
return mini if mini < int(1e9) else -1
self.coins = coins
if amount < 1 :
return 0
return dp(amount)
s = Solution()
coins = [1, 2, 5]
amount = 11
result = s.coinChange(coins,amount)
print(result) |
7c4f99a4575011edc4bdb9340f35694d3a1061eb | Babkock/python | /6 - Functions/Module6/validate_input/validate_input_in_functions.py | 1,010 | 4.25 | 4 | #!/usr/bin/python3
"""
Tanner Babcock
October 1, 2019
Module 6, topic 4: Functions with variable parameter lists
"""
"""
This function prints the test name and test score. It asks for
user input if the score is not in the valid range.
:param test_name: The name of the test taker
:param test_score: The score of the test, should be in the 0-100 range
:param invalid_message: The message to print if test_score is invalid
:raises ValueError: If test_score is not an integer type
"""
def score_input(test_name, test_score=0, invalid_message="Invalid test score, try again!"):
if (isinstance(test_score, int) != True):
raise ValueError
if test_score in range(0, 100):
print("{}: {}".format(test_name, test_score))
else:
print(invalid_message)
while not 0 <= test_score <= 100:
get_score = int(input("Please enter a valid score: "))
test_score = get_score
print("{}: {}".format(test_name, test_score))
# return { test_name : test_score }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.