blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1ef507d37774d64bc4c6e74b828e9fa679b9ad6f | vsr202vsr/Vijay-Python-java-conversion | /RandomGenerators.py | 906 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 1 16:48:47 2017
@author: Reddy
"""
import time
class RandonGenerator(object):
__A,__B,__M=5,7,1024
def __init__(self,seed=None):
self.seed= int(time.time())*45289647896
if seed != None:
self.seed = seed
print(self.seed)
def getRandom1(self,n):
return int(time.time()) % n
def getRandom2(self,n):
obj = int()
print(id(obj))
return id(obj) %n
def getRandom3(self, n):
tmp =( (RandonGenerator.__A * self.seed)+RandonGenerator.__B) % RandonGenerator.__M
self.seed = tmp
# print(self.seed)
return tmp % n
if __name__ == "__main__" :
print("hello")
rg = RandonGenerator()
for i in range(20):
time.sleep(2)
print(rg.getRandom2(10))
|
5b82cf5d0d8aff7919adc5437add2c7d77dffa43 | saetar/pyEuler | /done/py/euler_038.py | 1,721 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Jesse + Graham Rubin
"""
Pandigital multiples
Problem 38
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576. We will
call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4,
and 5, giving the pandigital, 918273645, which is the concatenated product
of 9 and (1,2,3,4,5).
What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
concatenated product of an integer with (1,2, ... , n) where n > 1?
"""
from itertools import permutations, count
def make_number(l):
return int(''.join(l))
def p038():
lists_of_multipliers = [[j for j in range(1, i)] for i in range(3, 11)]
one_to_nine = ['9', '8', '7', '6', '5', '4', '3', '2', '1']
list_of_perms = set(make_number(perm) for perm in permutations(one_to_nine))
max_pan_digit = max(list_of_perms)
def check_num(n):
for multipliers in lists_of_multipliers:
num = int(''.join([str(i*n) for i in multipliers]))
if num in list_of_perms:
return True
if num > max_pan_digit:
return False
return False
starting_n = max(i for i in range(10000) if check_num(i))
remaining_digs = 9
products = []
for n in count(1):
products.append(starting_n*n)
remaining_digs -= len(str(starting_n*n))
if remaining_digs == 0:
return int("".join([str(num) for num in products]))
if __name__ == '__main__':
ANSWER = p038()
print("ANSWER: {}".format(ANSWER))
|
0128db90e37b8b12910e823f910ece88be698b84 | jasehackman/05_Classes | /employees.py | 2,156 | 4.03125 | 4 | # Create a class that contains information about employees of a company and define methods to get/set employee name, job title, and start date.
import datetime
now = datetime.datetime.now()
class Employee:
def __init__(self, hireDate = now):
self.__startDate = hireDate
@property
def name(self):
try:
return self.__name
except:
print("add a name")
@name.setter
def name(self,name):
self.__name = name
@property
def job_title(self):
try:
return self.__job_title
except:
print("no job title")
@job_title.setter
def job_title(self, title):
self.__job_title = title
@property
def startDate(self):
try:
return self.__startDate
except:
print("no start date")
@startDate.setter
def startDate(self, date):
self.__startDate = date
def __str__(self):
return f"this employee's name is {self.__name}"
bob = Employee()
bob.name = "bob"
bob.job_title = "janitor"
print(bob)
# Copy this Company class into your module.
class Company(object):
"""This represents a company in which people work"""
def __init__(self, company_name, date_founded):
self.company_name = company_name
self.date_founded = date_founded
self.employees = set()
def get_company_name(self):
"""Returns the name of the company"""
return self.company_name
def employeePrint (self):
[print(employee.name) for employee in self.employees]
def __str__(self):
return f"Company's name is {self.company_name} and its employees are {print(customer) for customer in self.employees}"
# # Add the remaining methods to fill the requirements above
# Consider the concept of aggregation, and modify the Company class so that you assign employees to a company.
# Create a company, and three employees, and then assign the employees to the company.
NSS = Company("NSS", "2013")
jim = Employee()
mike = Employee()
jim.name = "jim"
mike.name = "Greg"
NSS.employees.add(jim)
NSS.employees.add(mike)
NSS.employeePrint()
|
e637cf2b0b0e27950bfa887c80c0096b5e10d3e2 | croixsuhy/otherProjects | /connectfour.py | 2,520 | 3.84375 | 4 | from numpy import full
# Create an array filled with blank strings
board = full((6, 7), " ")
# Variable exists to stop main loop when someone wins
win = False
def clear():
# Clears the screen
print("\n" * 100)
def displayBoard():
# Prints the board
print(" " + str(board)[1:-1])
def p1Input():
selection = int(input("P1: Enter a row number between 1-7: "))
# Makes it so the player has to actually put in an input
done = False
while not done:
# Checks each row so the pieces can "stack" on each other
if board[5][selection - 1] == " ":
board[5][selection - 1] = "x"
done = True
elif board[4][selection - 1] == " ":
board[4][selection - 1] = "x"
done = True
elif board[3][selection - 1] == " ":
board[3][selection - 1] = "x"
done = True
elif board[2][selection - 1] == " ":
board[2][selection - 1] = "x"
done = True
elif board[1][selection - 1] == " ":
board[1][selection - 1] = "x"
done = True
elif board[0][selection - 1] == " ":
board[0][selection - 1] = "x"
done = True
else:
print("All spaces on this row are taken!")
p1Input()
done = True
def p2Input():
selection = int(input("P2: Enter a row number between 1-7: "))
# Makes it so the player has to actually put in an input
done = False
while not done:
# Checks each row so the pieces can "stack" on each other
if board[5][selection - 1] == " ":
board[5][selection - 1] = "o"
done = True
elif board[4][selection - 1] == " ":
board[4][selection - 1] = "o"
done = True
elif board[3][selection - 1] == " ":
board[3][selection - 1] = "o"
done = True
elif board[2][selection - 1] == " ":
board[2][selection - 1] = "o"
done = True
elif board[1][selection - 1] == " ":
board[1][selection - 1] = "o"
done = True
elif board[0][selection - 1] == " ":
board[0][selection - 1] = "o"
done = True
else:
print("All spaces on this row are taken!")
def main():
# Temp, might make a better way
while not win:
clear()
displayBoard()
p1Input()
clear()
displayBoard()
p2Input()
main()
|
00db21d32383775d72d81631f6c0a2897f9ec85f | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/mrkpet004/question4.py | 1,041 | 3.96875 | 4 | """program that takes in a list of marks (separated by spaces) and outputs a histogram representation of the marks
peter m muriuki"""
#get the list of marks and add them into an array
marks_str=input("Enter a space-separated list of marks:\n")
marks=marks_str.split(" ")
counter={'w':0,'x':0,'y':0,'z':0,'f':0} #initialise a counter (dictionary)
#sort the marks into different categories and count occurencies of each different category,storing them into the counter
for item in marks:
item=int(item)
if item >=75:
counter['w'] +=1
elif 70<=item<75:
counter['x'] +=1
elif 60<=item<70:
counter['y'] +=1
elif 50<=item<60:
counter['z'] +=1
elif item<50:
counter['f'] +=1
#print out the different counts for each category of marks in a histogram format
print ("1 |","X"*counter['w'],sep="")
print ("2+|","X"*counter['x'],sep="")
print ("2-|","X"*counter['y'],sep="")
print ("3 |","X"*counter['z'],sep="")
print ("F |","X"*counter['f'],sep="")
|
1f07572031b06ef690fd0f9984012f096f0aac60 | c940606/leetcode | /二分搜索.py | 455 | 3.984375 | 4 | def lower_bound(array, first, last, value):
while first < last:
mid = first + (last - first) // 2
if array[mid] < value:
first = mid + 1
else:
last = mid
return first
def upper_bound(array, first, last, value):
while first < last:
mid = first + (last - first) // 2
if array[mid] <= value:
first = mid + 1
else:
last = mid
return first
a = [1, 2, 2, 3, 3, 4, 4]
print(lower_bound(a, 0, 7, 3))
print(upper_bound(a, 0, 7, 3))
|
0206f8cddc1193c074700b2240f73c8eb123e33f | ARtoriouSs/sanya-script-runtime | /sanya_script_runtime/type.py | 1,122 | 3.53125 | 4 | class Type:
def put(self):
pass
def puts(self):
self.put()
print()
def cast(self, type_):
pass
def summation(self, value):
pass
def subtraction(self, value):
pass
def multiplication(self, value):
pass
def division(self, value):
pass
def and_(self, value):
from .logic import Logic
return Logic(self.cast("logic").value and value.cast("logic").value)
def or_(self, value):
from .logic import Logic
return Logic(self.cast("logic").value or value.cast("logic").value)
def not_(self):
from .logic import Logic
return Logic(not self.cast("logic").value)
def equal(self, value):
from .logic import Logic
return Logic(self.value == value.value)
def not_equal(self, value):
from .logic import Logic
return Logic(self.value != value.value)
def greater_or_equal(self, value):
pass
def less_or_equal(self, value):
pass
def greater(self, value):
pass
def less(self, value):
pass
|
5e084a1c28096aef891fe3d3e5ec4e26d5f5c4c2 | ShimsyV/Python-Challenge | /pyBank/main.py | 3,084 | 4.03125 | 4 | # First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
## This os.path.join function is used to concatenate all of the provided arguments
csvpath = os.path.join('.', 'Resources', 'budget_data.csv')
#Setting Variables
total_months = 0
net_amount = 0
monthly_change = 0
total_monthly_change = []
month_count = []
average_monthly_change = 0
greatest_increase = 0
greatest_increase_month = 0
greatest_decrease = 0
greastest_decrease_month = 0
# Improved Reading using CSV module
with open(csvpath, 'r') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Read the header row first
csv_header = next(csvreader)
# row is the next line in the csvreader
row = next(csvreader)
# Setting the variables for row
previous_profit_loss = int(row[1])
total_months += 1
net_amount += int(row[1])
# Read each Row of data
for row in csvreader:
# Calculate the total months
total_months += 1
# Calculate the net amount
net_amount += int(row[1])
# Calculate average change in profit/loss
monthly_change = int(row[1]) - previous_profit_loss
total_monthly_change.append(monthly_change)
previous_profit_loss = int(row[1])
month_count.append(row[0])
# Calculate the greatest increase profit
if int(row[1]) > greatest_increase:
greatest_increase = int(row[1])
greatest_increase_month = row[0]
# Calculate the greatest decrease loss
if int(row[1]) < greatest_decrease:
greatest_decrease = int(row[1])
greastest_decrease_month = row[0]
# Calculate the average change between months
average_monthly_change = sum(total_monthly_change) / len(total_monthly_change)
print(f'Financial Analysis')
print(f'-------------------------------------------------------')
print(f'Total Months: {total_months}')
print(f'Total: ${net_amount}')
print(f'Average Change: $ {average_monthly_change:.2f}')
print(f'Greatest Increase in Profits: {greatest_increase_month} (${max(total_monthly_change)}) ')
print(f'Greatest Decrease in Loss: {greastest_decrease_month} (${min(total_monthly_change)}) ')
# Specify the file to write to
output_path = os.path.join('.', 'analysis', 'analysis.txt')
# Open file and write
with open(output_path, 'w') as analysis_file:
# Write the report
analysis_file.write(f'Financial Analysis\n')
analysis_file.write(f'-------------------------------------------------------\n')
analysis_file.write(f'Total Months: {total_months}\n')
analysis_file.write(f'Total: ${net_amount}\n')
analysis_file.write(f'Average Change: $ {average_monthly_change:.2f}\n')
analysis_file.write(f'Greatest Increase in Profits: {greatest_increase_month} (${max(total_monthly_change)})\n')
analysis_file.write(f'Greatest Decrease in Loss: {greastest_decrease_month} (${min(total_monthly_change)})\n') |
bbafc75a98115d50c4531da34e18a7f01227e228 | shellshock1953/python | /games/battlefield/new_battlefield.py | 3,032 | 3.734375 | 4 | """second try
defs
generate_board
random_ship_placement
check_ships_placement
show_boards
show_messages
shots
hits
bot_logic
bot_hit
"""
import string
import random
# ACT 1. Game field
def generate_board(board_size):
board = []
for sell in range(board_size):
board.append(["."] * board_size)
return board
def show_head():
print(" PLAYER\t\t\t BOT")
def show_boards(player_board, bot_board, board_size):
""" TODO: make tabulate if board size bigger than 10"""
numbers = ' '.join(str(x) for x in range(1, board_size + 1))
print(" %s\t %s") % (str(numbers), str(numbers))
alphabet = string.uppercase
alphabet = alphabet[:board_size]
letter = 0
for row in range(board_size):
player_row = " ".join(player_board[row])
bot_row = " ".join(bot_board[row]).replace("=", ".")
print(" %s %s\t%s %s") % \
(alphabet[letter], player_row,\
alphabet[letter], bot_row)
letter += 1
def manual_ship_placement(board,ship_len):
print ("Select leng: 4")
leng = 4
print ("Use H J K L to move")
print ("Use V to switch to vertical")
print ("User E to select")
x, y = selector(player_board, bot_board)
print x,y
def ships(board):
ships = {
4 : ([0,0,0],),
3 : ([0,0,0],[0,0,0]),
2 : ([0,0,0],[0,0,0],[0,0,0]),
1 : ([1,1,1],[0,0,0],[0,0,0],[0,0,0])
}
for ship_type in range(1,5):
for ship in range(0,5-ship_type):
board, ships[ship_type][ship][0], \
ships[ship_type][ship][1], \
ships[ship_type][ship][2] = ship_placement(board,ship_type)
print(ships)
def selector(board_orig,bot_board):
import copy
x = 4
y = 4
board = copy.deepcopy(board_orig)
board[x-1][y-1] = "+"
board[x-1][y+1] = "+"
board[x+1][y-1] = "+"
board[x+1][y+1] = "+"
while True:
board = copy.deepcopy(board_orig)
arrow = raw_input()
if arrow == "h": y = y - 1
elif arrow == "j": x = x + 1
elif arrow == "k": x = x - 1
elif arrow == "l": y = y + 1
elif arrow == "e":
print coordinated_to_alpha(x,y)
return x,y
board[x-1][y-1] = "+"
board[x-1][y+1] = "+"
board[x+1][y-1] = "+"
board[x+1][y+1] = "+"
show_boards(board,bot_board, 10)
def coordinated_to_alpha(x,y):
alphabet = string.uppercase
alpha_x = alphabet[x]
alpha_y = y + 1
alpha_coordinates = str(alpha_x) + str(alpha_y)
return alpha_coordinates
def coordinated_to_num(alpha_x, alpha_y):
alphabet = string.uppercase
x = str(alphabet).index(alpha_x)
y = int(alpha_y) - 1
return x,y
# FINAL ACT. The Game.
if __name__ == "__main__":
board_size = 10
player_board = generate_board(board_size)
bot_board = generate_board(board_size)
show_boards(player_board, bot_board, board_size)
manual_ship_placement(player_board,4)
|
8109e90252bdd0baeaf88a9851a38a0dcaa9502c | L200180162/praktikum_AlgoproA | /prak8.1.py | 1,739 | 3.546875 | 4 | a = {'NIM':'L200180162','Nama':'Raihan Mazarul Hidayat','Alamat':'Kudus','Panggilan':'Raihan','PT':'UMS','Fak':'FKI','Prodi':'Informatika','K':'Keluar'}
print ("Pilihan yang tersedia:")
print ("N menampilkan Nama")
print ("n menampilkan NIM")
print ("l menampilkan Alamat")
print ("p menampikan Panggilan")
print ("t menampilkan PT")
print ("f menampilkan Fakultas")
print ("i menampilkan Prodi")
print ("K menampilkan Keluar")
def Nama():
"menampilkan data diri masing-masing 1 setiap data"
print ('Nama:' + a['Nama'])
def NIM():
"menampilkan data diri masing-masing 1 setiap data"
print ('NIM:' + a['NIM'])
def Alamat():
"menampilkan data diri masing-masing 1 setiap data"
print ('Alamat:' + a['Alamat'])
def Panggilan():
"menampilkan data diri masing-masing 1 setiap data"
print ('Panggilan:' + a['Panggilan'])
def PT():
"menampilkan data diri masing-masing 1 setiap data"
print ('PT:' + a['PT'])
def Fak():
"menampilkan data diri masing-masing 1 setiap data"
print ('Fak:' + a['Fak'])
def Prodi():
"menampilkan data diri masing-masing 1 setiap data"
print ('Prodi:' + a['Prodi'])
def K():
"menampilakn data diri masing-masing 1 setiap data"
print ('K:' + a['K'])
repeat = True
repeat = True
while repeat :
x = input("Pilihan saudara :")
if x == "N" :
Nama()
elif x == "n" :
NIM()
elif x == "l" :
Alamat()
elif x == "p" :
Panggilan()
elif x == "t" :
PT()
elif x == "f" :
FAK()
elif x == "i" :
Prodi()
elif x == "k" :
print ("Terima Kasih.")
repeat = False
|
14a5667bc248de421a21035c8dd3c3a15c1bc811 | ae0616/math_problems | /PreshTallwalkerLengthProblems/points_on_circumference.py | 561 | 3.609375 | 4 | from Point import Point
from Circle import Circle
from random import seed
def get_rand_distance(c):
p1 = c.random_point_on_circumference()
p2 = c.random_point_on_circumference()
return p1.distance_from_point(p2)
def get_avg_distance(num_samples):
sum = 0.0
for i in range(num_samples):
sum += get_rand_distance(c)
return sum / num_samples
if __name__ == "__main__":
c = Circle(0.0, 0.0, 1.0)
seed()
for i in range(100000, 1000001, 100000):
print('{0} samples, result: {1}'.format(i, get_avg_distance(i))) |
b08c4b9ba34b1de43d4f177e53d80c96a1359dad | ambarish710/python_concepts | /leetcode/easy/543_diameter_of_binary_tree.py | 1,219 | 4.375 | 4 | # Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
#
# Example:
# Given a binary tree
# 1
# / \
# 2 3
# / \
# 4 5
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
#
# Note: The length of path between two nodes is represented by the number of edges between them.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.diameter = 1
# Depth of tree
def depth(node):
if node is None:
return 0
else:
ldepth = depth(node.left)
rdepth = depth(node.right)
self.diameter = max(self.diameter, ldepth + rdepth + 1)
return max(ldepth, rdepth) + 1
# Function Call
depth(root)
# Return
return self.diameter - 1
|
d747594c19026a5a7dfb8739d05587377632f75c | atulkhedkar40/python-final | /Numpy Game of Life Final.py | 3,859 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""Libraries Imported"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
"""Initial SEED for the System"""
Z=np.zeros((80,80)) #The Complete Map
Z[35:65,35:65]=np.random.randint(0,4,(30,30)) #The Random Seed
def neighbours(Z,n):
N = np.zeros(Z.shape, int)
#Add all surounding elements and divide by n
N[1:-1,1:-1] += (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
Z[1:-1,0:-2] + Z[1:-1,2:] +
Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])
N=N/n
return N
"""Function To Iterarte The Game of Life"""
def iterate(Z):
#Z1 is the the initial state of system (Stored for further use)
Z1=np.empty_like(Z)
Z1[:]=Z
"""Count neighbours of Type 3"""
Z[:]=Z1
Z_ = Z.ravel() #ravel opens up an array into a linear list
"""Selecting elements of type 1 and 2 and making them 0"""
S1=np.argwhere((Z_==1)|(Z_==2))
Z_[S1]=0
"""N3 is an array which consists the number of 3s surrounding
any element"""
N3=neighbours(Z,3)
#Return Z to its original State
Z[:]=Z1
Z_ = Z.ravel()
"""Count neighbours of Type 1"""
"""Selecting elements of type 2 and 3 and making them 0"""
S2=np.argwhere((Z_==2)|(Z_==3))
Z_[S2]=0
"""N3 is an array which consists the number of 1s surrounding
any element"""
N1=neighbours(Z,1)
#Return Z to its original State
Z[:]=Z1
Z_ = Z.ravel()
"""Count neighbours of Type 2"""
"""Selecting elements of type 1 and 3 and making them 0"""
S3=np.argwhere((Z_==1)|(Z_==3))
Z_[S3]=0
N2=neighbours(Z,2)
"""Count neighbours of Type 0"""
N0 = np.zeros(Z.shape, int)
N0=8-N1+N2+N3
#Return Z to its original State
Z[:]=Z1
Z_=Z.ravel()
#use ravel to open up arrays for better use
N1_=N1.ravel()
N2_=N2.ravel()
N3_=N3.ravel()
N0_=N0.ravel()
"""Apply rules"""
R1 = np.argwhere( (N1_ >2)) #These arrays consist of those
R2 = np.argwhere( (N2_ >2)) #which satisfy specified rules
R3 = np.argwhere( (N3_ >2))
R4 = np.argwhere((Z_==1) & (N2_ >3))
R5 = np.argwhere((Z_==2) & ((N3_ >3)|(N1_<2)))
R6 = np.argwhere((Z_==3) & (N3_ >3))
R7 = np.argwhere((Z_==1) & ((N2_ >1)))
R8 = np.argwhere((Z_==0) & ((N3_ >2)|(N2_>1)))
R9 = np.argwhere((Z_==0) & ((N2_ >2)|(N1_>1)))
"""As arrays from numpy stay linked we have to make
separate arrays which are not linked"""
C1=np.empty_like(R1)
C1[:]=R1
C2=np.empty_like(R2)
C2[:]=R2
C3=np.empty_like(R3)
C3[:]=R3
C4=np.empty_like(R4)
C4[:]=R4
C5=np.empty_like(R5)
C5[:]=R5
C6=np.empty_like(R6)
C6[:]=R6
C7=np.empty_like(R7)
C7[:]=R7
C8=np.empty_like(R8)
C8[:]=R8
C9=np.empty_like(R9)
C9[:]=R9
"""Set new values (Implement the Rules)"""
Z_[C2] = 2
Z_[C3] = 3
Z_[C4] = 0
Z_[C5] = 0
Z_[C6] = 3
Z_[C7] = 2
Z_[C8] = 3
Z_[C9] = 2
Z_[C1] = 1
"""Make sure borders stay null"""
Z[0,:] = Z[-1,:] = Z[:,0] = Z[:,-1] = 0
"""Making a Colourmap of Required Colours"""
cmap=colors.ListedColormap(['brown','green','blue','red'])
"""To Continuously Iterate our function"""
for gen in range(1000):
iterate (Z)
"""Plotting"""
plt.imshow(Z,interpolation ='nearest',cmap=cmap)
plt.show(block=False)
plt.pause(0.000001)
|
237fe5e35775dd2b23189ea4b1f8175e5c70a07b | IsabelGraciano/Analisis-Numerico | /Entrega 1/NumericMethodsPython/Bisection.py | 1,837 | 3.75 | 4 |
import math
# author Valeria
def f(x):
# function
return ((math.log((math.pow((math.sin(x)), 2)) + 1)) - (0.5))
#bisection method
def bisection(a, b, iterations, tolerance):
x0 = 0
y0 = 0
i = 1
xm = (a + b) / 2
result = f(xm)
#Method data input control
if iterations < 1:
print("Iterations must be greater than 0")
if result == 0:
print(xm + " Its a root")
if f(a) * f(b) > 0:
print("There is no root in this interval")
#First iteration
print("Iter: " , i)
print("a: " , a)
print("xm: " , xm)
print("b: " , b)
print("f(xm): " , f(xm))
print("E: ")
print("")
i += 1
#Loop start
while (result != 0 and i <= iterations and abs(x0 - xm) > tolerance):
print("Iter: " , i)
if (result * f(a) < 0):
a = a
b = xm
else:
b = b
a = xm
x0 = xm
y0 = result
xm = (a + b) / 2
result = f(xm);
i += 1
print("a: " , a)
print("xm: " , xm)
print("b: " , b)
print("f(xm): " , f(xm))
print("E: " , (abs(x0 - xm)))
print("")
#Method data output control
if (result == 0):
print("An approximation of the root was found in " , (xm))
elif (i > iterations):
print("Iteration limit reached")
elif (abs(x0 - xm) < tolerance):
print("The maximum tolerance permitted " , (tolerance) , ". In the iteration " , (i) , " the maximum tolerance was reached " , (abs(x0 - xm)))
print("Data in the last iteration")
print("Iteration " , (i-1))
print("xm= " , (xm))
print("f(xm)= " , f(xm))
print("E= " , (abs(x0 - xm)))
bisection(0, 1, 100, math.pow(10, -7)) |
c0ae2a94b331238dd9f464a29499bcca7f75f619 | vladimirpekarski/python_courses | /7th_lesson/3rd_task.py | 189 | 3.53125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'vladimir.pekarsky'
price_per_kg = 6.6
kilo = 1.2
while kilo < 2.0:
print('Price for {}kg: {}'.format(kilo, price_per_kg * kilo))
kilo += 0.2
|
0829eefa257aaa57f27c5515d87d6b5642da6730 | lvonbank/IT210-Python | /Ch.02/P2_22.py | 359 | 4.03125 | 4 | # Levi VonBank
## Initializes a string variable and prints the first three characters
# followed by three periods
userInput = str(input("Enter a string: "))
last = len(userInput) - 1
firstThree = userInput[0] + userInput[1] + userInput[2]
LastThree = userInput[last-2] + userInput[last-1] + userInput[last]
middle = "..."
print(firstThree + middle + LastThree) |
03254a2f2891d7deb8f2c252e1376f5510ae7682 | JavierCamposCuesta/repoJavierCampos | /1ºDaw/ProgramacionPython/Python/Bucles3-1/ej5.py | 978 | 4.03125 | 4 | '''
5. Design a method called myPower that receives one integer and one integer positive
numbers as parameters and the method calculates the power of the first parameter raised
the second number. You only can use the multiplication. If the parameters are not right
(the second parameter is negative) the method should return -1. Remember that any number
raised 0 is 1
Created on 9 dic. 2020
@author: Javier
'''
def calculaPotencia(base, exponente):
#base=int(input("Introduce la base"))
#exponente=int(input("introduce el exponente"))
resultado=1
if exponente<0:
base=1/base
exponente=-exponente
for i in range (0, exponente): #@UnusedVariable
resultado=resultado*base
print(resultado)
#return resultado
calculaPotencia(base=int(input("base: ")), exponente=int(input("exponente: ")))
#assert(calculaPotencia(2, 10)==1024)
#assert(calculaPotencia(-3, -3)==round(-0.037))
#assert(calculaPotencia(-4, 3)==-64) |
cd13879a493f1bc045686f051817119493d071f4 | dwiprasetyoo/Algoritma-Pemrograman | /Praktikum 3/Modul 3 - Materi.py | 1,039 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
@Materi: Control Structure
@Judul: Praktikum 3 Materi
@Hari/Tanggal: Senin, 20210920
@NIM: 065001900001
@author: Azhar Rizky Zulma
"""
b = float(input("Masukkan berat badan (dalam kilogram): "))
t = float(input("Masukkan tinggi badan (dalam meter): "))
bmi = b/(t*t)
if (bmi < 18.5):
print("kamu termasuk Underweight")
elif (bmi >= 18.5) and (bmi >= 24.9):
print("kamu termasuk Normal")
elif (bmi >= 25) and (bmi <= 29.9):
print("kamu termasuk Overweight")
else:
print("Kamu termasuk Obesitas")
"""
inputBulan = int(input("masukkan inputBulan: "))
inputTahun = int(input("masukkan tahun: "))
if(inputBulan >= 13 or inputBulan <= 0):
print("Masukin bulan yg bener woi")
elif(inputBulan == 1 or inputBulan == 3 or inputBulan == 5 or inputBulan == 7 or inputBulan == 8 or inputBulan == 10 or inputBulan == 12):
print("Ini 31 hari")
elif(inputBulan == 2):
if(inputTahun % 4 == 0 and inputBulan == 2):
print("Ini 29 hari")
else:
print("Ini 28 hari")
else:
print("Ini 30 hari")
"""
|
aa3dbd9bcb17ef456057a1c1991acb8c7f545856 | Humhunter/cookbook | /essays/decorate_study.py | 2,433 | 3.671875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# author: JinSong.xiao(61627515@qq.com)
# time: 2019/12/9 20:45
import time
from functools import wraps
def get_message(message):
print('Got a message: {}'.format(message))
def root_call(func, message):
print(func(message))
def func_example(message):
def get_message_1(message):
print('Got a message_1: {}'.format(message))
return get_message_1(message)
def func_closure():
def get_message_2(message):
print('Got a message_2: {}'.format(message))
return get_message_2
def my_decorator(func):
def wrapper():
print('wrapper of decorator')
func()
return wrapper
def greet():
print('hello world')
def my_decorator_1(func):
@wraps(func)
def wrapper(message):
print('wrapper of decorator')
func(message)
return wrapper
@my_decorator_1
def greet_decorator(message):
print(message)
def repeat(num):
def my_decoretor_define(func):
@wraps(func)
def wrapper(*args, **kwargs):
for i in range(num):
print('wrapper of decorator')
func(*args, **kwargs)
return wrapper
return my_decoretor_define
@repeat(5)
def greet_repeat(message):
print(message)
# study the decorator of class
class Count:
def __init__(self, func):
self.func = func
self.num_calls = 0
def __call__(self, *args, **kwargs):
self.num_calls += 1
print('number of calls is : {}'.format(self.num_calls))
return self.func(*args, **kwargs)
@Count
def example():
print('hello world')
def main():
root_call(get_message, 'Hello World')
func_example('hello world')
send_message = func_closure()
send_message('hello world')
def log_execution_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
res = func(*args, **kwargs)
end = time.perf_counter()
print('{} took {} ms'.format(func.__name__, (end - start) * 1000))
return res
return wrapper
if __name__ == '__main__':
main()
print('=========================')
greet = my_decorator(greet)
greet()
print('=========================')
greet_decorator('hello world 3 thousand')
print('=========================')
greet_repeat('I am the best')
print('=========================')
example()
example()
|
044e440ad59e7c19322e49923e044f7551c7089a | Gdens/Gdens | /MyRepo/Python/phonebook.py | 570 | 4.125 | 4 | question = "y"
while question != "n":
name = input("What is your name? ")
number = input("What is your number? ")
email = input("What is your email? ")
with open("contacts.txt","a") as file:
file.write(f"{name} {number} {email}\n")
while True:
question = input("Add another contact? Y|n: ")
if question == "y" or question == "" or question == "n":
break
else:
print("You did not make a correct selection. Please use a 'y' or 'n'.")
|
b9f58e48bdf7d2a7ac3e6ad9e221219e1c5659e7 | Provinm/leetcode | /dp/63.unique-paths-ii.py | 2,031 | 3.9375 | 4 | #
# @lc app=leetcode id=63 lang=python3
#
# [63] Unique Paths II
#
# https://leetcode.com/problems/unique-paths-ii/description/
#
# algorithms
# Medium (33.22%)
# Total Accepted: 182.3K
# Total Submissions: 548.6K
# Testcase Example: '[[0,0,0],[0,1,0],[0,0,0]]'
#
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in
# the diagram below).
#
# The robot can only move either down or right at any point in time. The robot
# is trying to reach the bottom-right corner of the grid (marked 'Finish' in
# the diagram below).
#
# Now consider if some obstacles are added to the grids. How many unique paths
# would there be?
#
#
#
# An obstacle and empty space is marked as 1 and 0 respectively in the grid.
#
# Note: m and n will be at most 100.
#
# Example 1:
#
#
# Input:
# [
# [0,0,0],
# [0,1,0],
# [0,0,0]
# ]
# Output: 2
# Explanation:
# There is one obstacle in the middle of the 3x3 grid above.
# There are two ways to reach the bottom-right corner:
# 1. Right -> Right -> Down -> Down
# 2. Down -> Down -> Right -> Right
#
#
#
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid) -> int:
for row_idx, row in enumerate(obstacleGrid):
for idx, ele in enumerate(row):
if ele == 1:
obstacleGrid[row_idx][idx] = 0
elif idx == 0 and row_idx == 0:
obstacleGrid[row_idx][idx] = 1
elif row_idx == 0:
obstacleGrid[row_idx][idx] = obstacleGrid[row_idx][idx-1]
elif idx == 0:
obstacleGrid[row_idx][idx] = obstacleGrid[row_idx-1][idx]
else:
obstacleGrid[row_idx][idx] = obstacleGrid[row_idx-1][idx] + obstacleGrid[row_idx][idx-1]
return obstacleGrid[-1][-1]
# grid = [[1,0]]
# grid = [[0,0,0],[0,1,0],[0,0,0]]
# s = Solution()
# print(s.uniquePathsWithObstacles(grid))
'''
✔ Accepted
✔ 43/43 cases passed (40 ms)
[WARN] Failed to get submission beat ratio.
'''
|
858b96b7075249aa2e185edf932e6052f21e80a3 | JenZhen/LC | /lc_ladder/Basic_Algo/data-struture/Nested_List_Weighted_Sum_II.py | 6,240 | 4.25 | 4 | #!/usr/local/bin/python3
# https://leetcode.com/problems/nested-list-weight-sum-ii/
# Example
# Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
#
# Each element is either an integer, or a list -- whose elements may also be integers or other lists.
#
# Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e.,
# the leaf level integers have weight 1, and the root level integers have the largest weight.
#
# Example 1:
#
# Input: [[1,1],2,[1,1]]
# Output: 8
# Explanation: Four 1's at depth 1, one 2 at depth 2.
# Example 2:
#
# Input: [1,[4,[6]]]
# Output: 17
# Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17.
"""
Algo: DFS, BFS
D.S.: queue
Solution1: DFS
和nested-list-weight-sum 解法相同,但是第一步先去找最深的层数,然后倒着算weight
Solution2: BFS
Solution3: BFS not using extra space to save level sum
Corner cases:
"""
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution1:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
maxDepth = self.get_max_depth(nestedList, 1)
print(maxDepth)
return self.get_weighted_sum(nestedList, maxDepth)
def get_max_depth(self, nestedList, depth):
tmp = depth
for ele in nestedList:
if ele.isInteger():
tmp = max(tmp, depth)
else:
tmp = max(tmp, self.get_max_depth(ele.getList(), depth + 1))
return tmp
def get_weighted_sum(self, nestedList, depth):
sum = 0
for ele in nestedList:
if ele.isInteger():
sum += ele.getInteger() * depth
else:
sum += self.get_weighted_sum(ele.getList(), depth - 1)
return sum
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution2:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
from collections import deque
if not nestedList or len(nestedList) == 0:
return 0
sumStack = []
q = deque([])
q.append(nestedList)
print(len(q))
while q:
size = len(q)
curLevelSum = 0
# 遍历每一层,把层内的整数拿出来求和,放在sumStack中
for _ in range(size):
sub_list = q.popleft()
for ele in sub_list:
if ele.isInteger():
curLevelSum += ele.getInteger()
else:
q.append(ele.getList())
sumStack.append(curLevelSum)
sum = 0
maxLevel = len(sumStack)
# sumStack 的元素个数就是层数,第一个数就是第一层的整数和
for level in range(maxLevel):
sum += sumStack[level] * (maxLevel - level)
return sum
class Solution3:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
from collections import deque
if not nestedList or len(nestedList) == 0:
return 0
sumStack = []
q = deque([])
q.append(nestedList)
res = 0
cumres = 0
while q:
size = len(q)
for _ in range(size):
sub_list = q.popleft()
for ele in sub_list:
if ele.isInteger():
cumres += ele.getInteger()
else:
q.append(ele.getList())
res += cumres
return res
# Test Cases
if __name__ == "__main__":
solution = Solution()
|
f27ddd7768139d7a9909d378422ce299214b16ec | lollipopnougat/AlgorithmLearning | /力扣习题/145二叉树的后序遍历/binarytreepostordertraversal.py | 1,147 | 3.75 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def postorderTraversal(self, root: TreeNode) -> list:
self.res = []
self.helper(root)
return self.res
def helper(self, root):
if root:
self.helper(root.left)
self.helper(root.right)
self.res.append(root.val)
class Solution2:
'''
进阶:非递归算法
'''
def postorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
tmp = []
res = []
stack.append(root)
while len(stack) != 0:
node = stack[-1]
if len(tmp) != 0 and tmp[-1] == node:
res.append(node.val)
tmp.pop()
stack.pop()
elif node == None:
stack.pop()
continue
else:
tmp.append(node)
stack.append(node.right)
stack.append(node.left)
return res
|
a375adf16edf2170a006e624ca391ca84a51796e | effgenlyapin29081983/algorithms | /task9_lesson3.py | 858 | 3.765625 | 4 | """
Найти максимальный элемент среди минимальных элементов столбцов матрицы.
"""
from random import randint
COUNT_ROWS = 5
COUNT_COLS = 4
MIN_VALUE = 0
MAX_VALUE = 100_000
DIVISOR = 1000
min_els = []
matrix = []
for i in range(COUNT_ROWS):
matrix.append([])
min_el_col = 0
for j in range(COUNT_COLS):
matrix[i].append(randint(MIN_VALUE, MAX_VALUE)/DIVISOR)
if j == 0:
min_el_col = matrix[i][j]
else:
if matrix[i][j] < min_el_col:
min_el_col = matrix[i][j]
min_els.append(min_el_col)
for i in range(COUNT_COLS):
print([matrix[j][i] for j in range(COUNT_ROWS)])
print(min_els)
max_el = min_els[0]
for i in range(1, len(min_els)):
if min_els[i] > max_el:
max_el = min_els[i]
print(f"{max_el}")
|
50dbc84ce7d6411a38ef2d95e81d71f719e0b042 | timedata-org/expressy | /expressy/value.py | 477 | 3.96875 | 4 | """A `Value` returns a result when called."""
class Value(object):
"""Value returns a fixed value when called."""
def __init__(self, value):
self.value = value
def __call__(self):
return self.value
class Symbol(Value):
"""Symbol refers to a name in a symbol table."""
def __call__(self):
"""Returns itself when evaluated so the result can't accidentally be
used in futher calculations.
"""
return self
|
c954bc7733e02f109ff26de25a12198a845bf90e | yashparmar15/LT-problems | /Word Pattern.py | 491 | 3.53125 | 4 | class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
w = s.split()
if len(w) != len(pattern):
return False
d = {}
for p, w in zip(pattern, w):
if p in d:
if d[p] != w:
return False
elif w in d.values():
return False
else:
d[p] =w
return True
|
f9c622a0fb7c543b25e78b86a33c2636e28912cd | Jackyzzk/Coding-Interviews-2 | /剑指offer-面试题36. 二叉搜索树与双向链表-2.py | 2,649 | 3.734375 | 4 | # Definition for a Node.
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
"""
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。
要求不能创建任何新的节点,只能调整树中节点指针的指向。
为了让您更好地理解问题,以下面的二叉搜索树为例:
4
2 5
1 3
我们希望将这个二叉搜索树转化为双向循环链表。链表中的每个节点都有一个前驱和后继指针。
对于双向循环链表,第一个节点的前驱是最后一个节点,最后一个节点的后继是第一个节点。
下图展示了上面的二叉搜索树转化成的链表。“head” 表示指向链表中有最小元素的节点。
head --|
V
||=> 1 <==> 2 <==> 3 <==> 4 <==> 5 <=||
||===================================||
特别地,我们希望可以就地完成转换操作。当转化完成以后,树中节点的左指针需要指向前驱,
树中节点的右指针需要指向后继。还需要返回链表中的第一个节点的指针。
注意:本题与主站 426 题相同:
https://leetcode-cn.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
注意:此题对比原题有改动。
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof
"""
def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root:
return None
aux = Node(0)
que, p, pre = [], root, aux
while que or p:
while p:
que.append(p)
p = p.left
p = que.pop()
pre.right, p.left, pre = p, pre, p
p = p.right
pre.right = aux.right
aux.right.left = pre
return aux.right
def create(nums):
if not nums:
return None
root = Node(nums.pop(0))
que = [root]
while que:
node = que.pop(0)
left = nums.pop(0) if nums else None
right = nums.pop(0) if nums else None
node.left = Node(left) if left is not None else None
node.right = Node(right) if right is not None else None
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
return root
def main():
nums = [4, 2, 5, 1, 3]
nums = []
test = Solution()
ret = test.treeToDoublyList(create(nums))
print(ret)
if __name__ == '__main__':
main()
|
fabe8017682d87793e400a4141227d3348939868 | Arthurcn96/EasyServer | /server | 1,674 | 3.53125 | 4 | #!/bin/python3
# Programa que cria um servidor http na pasta atual e gera um QR Code para o link na rede.
# Autor: Arthur Novais
#
# server.py
import qrcode_terminal as qr
import netifaces as ni
import argparse
import sys
import os
class Server:
def __init__(self, path, port):
self.path = path
self.ip = ni.ifaddresses('eno1')[ni.AF_INET][0]['addr']
self.server = "http://"+self.ip+":"+str(port)
self.srv = "python3 -m http.server " + str(port)
def run(self):
print('entered here')
try:
command = self.srv + " -d " + str(self.path)
print("A server was opened in ", self.srv)
print("Sharing files from ", self.path)
qr.draw(self.server)
os.system(command)
except Exception as e:
print("Error" + e)
def main():
parser = argparse.ArgumentParser(
description="App developed to open a local server o a designed folder",
usage="%(prog)s [-f] [-p]",
)
parser.add_argument(
"-f",
"--path",
type=str,
metavar="",
help="The path to the folder",
)
parser.add_argument(
"-p",
"--port",
type=str,
metavar="",
help="Set a port to run the server",
)
args = parser.parse_args()
# Saving default values
path = os.path.abspath(os.getcwd())
port = 9000
# Setting command-line options
if (args.path):
path = args.path
if (args.port):
port = args.port
print(path)
localServer = Server(path,port)
localServer.run()
print(path)
if __name__ == "__main__":
main()
|
9d7d4f3297db002248f23cca87f96ae297756264 | EmperorEuler/leetcode | /核心/二分搜索.py | 419 | 3.765625 | 4 | """
一个有序数组的搜索方案,
每次都使用对半分的方式, 如果搜索的目标值大于中位数, 则目标值应该在数组的右半边
如果小于中位数, 则目标值应该在数组的左半边
递归执行
我们假设该数值存在于数组中
"""
# 未完成
def binary_search(nums: [int], target: int) -> int:
mid = len(nums) // 2
if nums[mid] < target:
pass
return 0
|
4d3166d9e9536b3fd77b9271528c43e9f7978bd1 | Zahidsqldba07/competitive-programming-1 | /Leetcode/June Leetcooding Challenge/num_bsts.py | 265 | 3.75 | 4 | # Unique Binary Search Trees
'''
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
'''
class Solution:
def numTrees(self, n: int) -> int:
return factorial(2 * n) // factorial(n) // factorial(n) // (n + 1)
|
b69560e14fb30444a4aaa2a1e6a46d8af16d14ad | youngseok-hwang/Python | /인덱싱과슬라이싱.py | 3,978 | 3.78125 | 4 | shopping_list = ["두부", "양배추", "딸기", "사과", "토마토"]
print(shopping_list[0])
item = shopping_list[1]
print(item)
item = shopping_list[-1] # -1은 제일 마지막, -len(shopping_list) = -5는 제일 처음 요소를 지칭
print(item)
print(shopping_list[-len(shopping_list)])
squares = [0, 1, 4, 9, 16, 25, 36, 48]
a = squares[1:6] # 슬라이싱은 새로운 리스트를 반환한다.
print(a) # 인덱스는 0부터 순서를 센다. 0 1 2 3 4 5 6 7
b = squares[:3] # 끝에 인덱스 2를 부르고 싶으면 해당 인덱스에 +1하여 지정한다.
c = squares[3:]
print(b)
print(c)
d = squares[0:len(squares)] # 처음과 끝의 인덱스는 0과 리스트의 크기와 같다.
print(d)
squares = [0, 1, 4, 9, 16, 25, 36, 48]
e = 7**2
squares[7] = e # 리스트는 언제든지 변경 가능하다.
print(squares)
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters)
letters[2:5] = ['C', 'D', 'E'] # 리스트 일부를 변경
print(letters)
letters[2:5] = [] # 리스트 일부를 삭제
print(letters)
marvel_heroes = ["스파이더맨", "헐크", "아이언맨"]
dc_heroes = ["슈퍼맨", "배트맨", "원더우먼"]
heroes = marvel_heroes+dc_heroes # 두 개의 리스트 합병시 + 연산자 사용
print(heroes)
value = [1, 2, 3] * 3 # 리스트 반복시 * 연산자 사용
print(value)
value = 3 * [1, 2, 3] # 반대로 곱해도 결과값은 같다.
print(value)
letters = ['a', 'b', 'c', 'd'] # 리스트 길이
f = len(letters)
print(f)
shopping_list = [] # 새로운 항목을 끝에 추가
shopping_list.append("두부")
shopping_list.append("양배추")
shopping_list.append("딸기")
print(shopping_list)
shopping_list.insert(1, "생수") # 특정 인덱스 위치에 추가하는 메소드 .insert()
print(shopping_list) # 추가될 때 지정한 인덱스의 뒤에 있던 목록은 뒤로 밀린다.
heroes = ["스파이더맨", "슈퍼맨", "헐크", "아이언맨", "배트맨"]
if "배트맨" in heroes: # 리스트에 요소가 있는지 확인하는 방법 in
print("영웅 중에는 배트맨도 있습니다.")
index = heroes.index("슈퍼맨") # 특정 요소의 인덱스를 알고자 할 때
print(index)
if "배트맨" in heroes: # 특정 요소가 있는지 확인 후 인덱스 번호를 알아낸다.
index = heroes.index("배트맨") # 있는지 없는지 확인하지 않았을 때 만약 없다면 오류가 발생한다.
print(heroes[index])
print(heroes)
heroes.pop(1) # 특정위치의 요소를 삭제한다.
print(heroes)
heroes = ["스파이더맨", "슈퍼맨", "헐크", "아이펀맨", "조커"]
heroes.remove("조커") # pop()은 인덱스로 항목을 정하는 반면, remove()는 직접 항목을 정하는 점에서 다르다.
print(heroes)
list1 = [1, 2, 3]
list2 = [1, 2, 3]
a = list1 == list2 # ==는 같은지 확인하는 연산자이다.
print(a) # 리스트 길이가 다르거나 리스트 항목이 다를 경우 False가 뜬다.
list3 = [4, 5, 6]
b = list1 < list3
print(b) # 각 항목이 큰지 작은지 비교하여 맞는 명제면 True가 뜬다.
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
c = min(values)
d = max(values)
print(c)
print(d)
a = [3, 5, 1, 4, 2]
a.sort()
print(a)
a = [3, 5, 1, 4, 2]
b = sorted(a)
print(a)
print(b)
e = sorted("A picture is worth a thousand words.".split(), key=str.lower) # 대 소문자 가리는 것없이 배열하는 것
print(e)
f = sorted([3, 5, 1, 4, 2], reverse=False) # False는 역순을 부정한다는 뜻으로로 순서대로 나열된다.
g = sorted([3, 5, 1, 4, 2], reverse=True) # True는 역순 그대로 나열한다.
print(f)
print(g)
str = "Where there is a will, there is a way."
h = str.split() # 문자열 쪼개기
print(h)
|
65644db5dbec26f30917e65262096ff3d8ba181e | tdishant/NPTEL-Joy-of-Computing-Using-Python | /Week-6/Week6_1.py | 392 | 3.5 | 4 |
import string
d = {}
data = ""
for i in range(len(string.ascii_letters)):
d[string.ascii_letters[i]] = string.ascii_letters[i-1]
print(d)
with open("trial.txt") as f:
while True:
c = f.read(1)
if not c:
print("End of file")
break
if c in d:
data = d[c]
else:
data = c
print(data, end="") |
50612679990b825f1a6717587f4dc84accd108e1 | franchescaleung/ICS31 | /lab8.py | 6,427 | 3.8125 | 4 | # Franchesca Leung 78831208 and Yujie Wang 33065328. ICS 31 Lab sec 3. Lab asst 8.
#part c
from collections import namedtuple
Dish = namedtuple('Dish', 'name price calories')
#c.1
print("c1")
def read_menu_with_count(f: "filename") -> "list of dishes":
'''takes file, reads file, returns a list of Dish structures created from the data'''
infile = open(f, "r")
dishes = []
count = 0
for i in infile:
if count>=1:
a = i.split("\t")
dish = Dish(a[0], str(a[1]), str(a[2].strip()))
dishes.append(dish)
count+=1
infile.close()
return dishes
##print(read_menu_with_count("menu2.txt"))
#c.2
print()
print("c2")
def read_menu(f: "filename") -> "list of dishes":
'''takes file, reads file, returns a list of Dish structures created from the data'''
infile = open(f, "r")
dishes = []
count = 0
for i in infile:
a = i.split("\t")
dish = Dish(a[0], str(a[1]), str(a[2].strip()))
dishes.append(dish)
count +=1
infile.close()
return dishes
##print(read_menu("menu3.txt"))
#c.3
print()
print("c3")
def write_menu(l: "list of dishes", f: "filename") -> None:
'''write the dish data to the named file'''
outfile = open(f, "w")
outfile.write(str(len(l)))
outfile.write("\n")
for dish in l:
for att in dish:
outfile.write(str(att) + "\t")
outfile.write("\n")
outfile.close()
return
dish1 = Dish("Chicken", "$14.99", "450")
dish2 = Dish("Samosa", "$12.00", "300")
a = [dish1, dish2]
write_menu(a, "b.txt")
#Part D
print()
print("---Part D---")
print()
Course = namedtuple('Course', 'dept num title instr units')
# Each field is a string except the number of units
ics31 = Course('ICS', '31', 'Intro to Programming', 'Kay', 4.0)
ics32 = Course('ICS', '32', 'Programming with Libraries', 'Thornton', 4.0)
wr39a = Course('Writing', '39A', 'Intro Composition', 'Alexander', 4.0)
wr39b = Course('Writing', '39B', 'Intermediate Composition', 'Gross', 4.0)
bio97 = Course('Biology', '97', 'Genetics', 'Smith', 4.0)
mgt1 = Course('Management', '1', 'Intro to Management', 'Jones', 2.0)
Student = namedtuple('Student', 'ID name level major studylist')
# All are strings except studylist, which is a list of Courses.
sW = Student('11223344', 'Anteater, Peter', 'FR', 'PSB', [ics31, wr39a, bio97, mgt1])
sX = Student('21223344', 'Anteater, Andrea', 'SO', 'CS', [ics31, wr39b, bio97, mgt1])
sY = Student('31223344', 'Programmer, Paul', 'FR', 'COG SCI', [ics32, wr39a, bio97])
sZ = Student('41223344', 'Programmer, Patsy', 'SR', 'PSB', [ics32, mgt1])
studentBody = [sW, sX, sY, sZ]
#d.1
print("d1")
def students_at_level(l: "list of students", level: str) -> "list of students":
'''takes list of students and returns students with matching class level'''
matched = []
for student in l:
if student.level == level:
matched.append(student) #all attributes
return matched
print(students_at_level(studentBody, "FR"))
#d.2
print()
print("d2")
def students_in_majors(l: "list of students", s: "list of strings") -> "list of students":
'''takes lists of students and returns students who have a major listed in s'''
matched = []
for student in l:
if student.major in s:
matched.append(student) #all attributes
return matched
print(students_in_majors(studentBody, ["PSB", "CS"]))
#d.3
print()
print("d3")
print()
def course_equals(c1: Course, c2: Course) -> bool:
''' Return True if the department and number of c1 match the department and
number of c2 (and False otherwise)
'''
return c1.dept == c2.dept and c1.num == c2.num
def course_on_studylist(c: Course, SL: 'list of Course') -> bool:
''' Return True if the course c equals any course on the list SL (where equality
means matching department name and course number) and False otherwise.
'''
for course in SL:
if course_equals(course, c):
return True
return False
def student_is_enrolled(S: Student, department: str, coursenum: str) -> bool:
''' Return True if the course (department and course number) is on the student's
studylist (and False otherwise)
'''
cour = Course(department, coursenum, "", "", 0)
return course_on_studylist(cour, S.studylist)
def students_in_class(l: "list of students", dept: str, cour: int) -> "list of students":
'''returns a list of students who are enrolled in specific dept and course'''
enrolled = []
for student in l:
if student_is_enrolled(student, dept, cour):
enrolled.append(student) #all attributes
return enrolled
print(students_in_class(studentBody, "Writing", "39A"))
#d.4
print()
print("d4")
print()
def student_names(l: "list of Students") -> "list of names":
'''takes a list of students and returns a list of just the names of those students'''
names = []
for student in l:
names.append(student.name)
return names
print(student_names(studentBody))
#d.5
print()
print("d5")
print()
print("1")
print(students_in_majors(studentBody, ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS']))
print("2")
print(student_names(students_in_majors(studentBody, ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS'])))
print("3")
print((str(len(students_in_majors(studentBody, ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS'])))) + " student(s) in this major")
print("4")
##fix
print(student_names(students_in_majors(students_at_level(studentBody, "SR"), ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS'])))
print("5")
print(len(students_in_majors(students_at_level(studentBody, "SR"), ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS'])))
print("6")
print((str(len(students_in_majors(students_at_level(studentBody, "SR"), ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS']))/len(students_in_majors(studentBody, ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS'])))) + " %")
print("7")
#number of freshman in ics major
a = students_in_majors(students_at_level(studentBody, "FR"), ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS'])
enroll = 0
for student in a:
if student_is_enrolled(student, "ICS", "31"):
enroll +=1
print(enroll)
print("8")
b = students_at_level(studentBody, "FR")
s = 0
g=0
for student in b:
if student_is_enrolled(student, "ICS", "31"):
g +=1
for c in student.studylist:
s += c.units
print(s/g)
|
c40d7b58d549a8f9c7c66b59090526902d6f0169 | romperstomper/thinkpython | /17.1.py | 363 | 3.9375 | 4 | #!/usr/bin/python
import sys
class Time(object):
def __init__(self, seconds=None, minutes=None, hours=None):
self.seconds = seconds
self.minutes = minutes
self.hours = hours
def time_to_int(self):
"""Converts times to integers. """
minutes = self.hours * 60 + self.minutes
seconds = minutes * 60 + self.seconds
return seconds
|
bac6a5f29a8774ad0e28b8112c079327d6047b42 | emmanavarro/holbertonschool-machine_learning | /math/0x04-convolutions_and_pooling/4-convolve_channels.py | 2,615 | 4.0625 | 4 | #!/usr/bin/env python3
"""
Convolution with Channels
"""
import numpy as np
def convolve_channels(images, kernel, padding='same', stride=(1, 1)):
"""
Performs a convolution on grayscale images
Args:
- images is a numpy.ndarray with shape (m, h, w) containing multiple
grayscale images:
:m: is the number of images
:h: is the height in pixels of the images
:w: is the width in pixels of the images
- kernel is a numpy.ndarray with shape (kh, kw) containing the kernel
for the convolution
:kh: is the height of the kernel
:kw: is the width of the kernel
- padding is a tuple of (ph, pw)
* if ‘same’, performs a same convolution
* if ‘valid’, performs a valid convolution
* if a tuple:
:ph: is the padding for the height of the image
:pw: is the padding for the width of the image
* the image should be padded with 0’s
Notes: You are only allowed to use two for loops; any other loops of any
kind are not allowed
Returns: a numpy.ndarray containing the convolved images
"""
m, h, w = images.shape[0], images.shape[1], images.shape[2]
kh, kw = kernel.shape[0], kernel.shape[1]
sh, sw = stride[0], stride[1]
if padding == 'same':
# Padding for the output
ph = int(((h - 1) * sh + kh - h) / 2) + 1
pw = int(((w - 1) * sw + kw - w) / 2) + 1
if padding == 'valid':
ph, pw = 0, 0
if isinstance(padding, tuple):
# Padding for the output
ph, pw = padding[0], padding[1]
# Creating the pad of zeros around the output matrix
pad_img = np.pad(images,
pad_width=((0, 0),
(ph, ph),
(pw, pw),
(0, 0)), # Channels dimension
mode='constant',
constant_values=0)
# Output matrix height and width
oh = int(np.floor(((h + (2 * ph) - kh) / sh) + 1))
ow = int(np.floor(((w + (2 * pw) - kw) / sw) + 1))
# Creating the output matrix with shape (m, h, w) as the inital input
output = np.zeros((m, oh, ow))
# Loop over every pixel in the output
for x in range(ow):
for y in range(oh):
x0 = x * sw
y0 = y * sh
x1 = x0 + kw
y1 = y0 + kh
output[:, y, x] = np.sum(pad_img[:, y0:y1, x0:x1] * kernel,
axis=(1, 2, 3))
return output
|
bf686eaa630ac7e4143a83128bf7d8bbbb5be570 | pattrinidad/cmsc128-ay2015-16-assign002-c | /programming_assignment001.py | 7,360 | 3.71875 | 4 | #!/usr/bin/env python
#Submitted by: Patricia Ann T. Trinidad AB-3L
###Date created: 02-07-2016
##Date Submitted: 02-14-2016
#Sources: www.quora.com/How-do-I-convert-numbers-to-words-in-python
#http://stackoverflow.com/questions/8982163/how-do-i-tell-python-to-convert-integers-into-words
#declaration of arrays
numToWords1 = {0:'zero',1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6:'six', \
7:'seven', 8:'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve'\
,13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17:'seventeen'\
,18: 'eighteen', 19: 'nineteen',20:'twenty',30:'thirty',40:'forty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety'}
numToWords3 = [' hundred', ' thousand ', ' million ']
wordsToNum1 = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, \
'seven':7, 'eight':8, 'nine':9, 'ten':10, 'eleven':11, 'twelve':12, \
'thirteen':13, 'fourteen':14, 'fifteen':15, 'sixteen':16, 'seventeen':17\
,'eighteen' : 18, 'nineteen':19, 'twenty':20, 'thirty':30, 'forty':40, 'fifty':50, 'sixty':60, 'seventy':70\
,'eighty':80, 'ninety':90}
#formulas derived from stackoverflow
def numToWords(integer): #number to words conversion
current2 = ""
if integer >= 0 and integer <= 19: return ' ' + numToWords1[integer] #1-19
elif integer < 100:
if integer % 10 == 0 : return numToWords1[integer]
else: return numToWords1[integer // 10*10] + ' ' + numToWords1[integer % 10]
elif integer >= 100 and integer <= 999:
if integer % 100 == 0: return numToWords1[integer // 100] + ' ' + 'hundred'
else: return numToWords1[integer//100] + ' hundred ' + numToWords(integer % 100)
elif integer >= 1000 and integer <= 9999:
if integer % 1000 == 0: return numToWords1[integer] + ' ' + 'thousand'
else: return numToWords1[integer//1000] + ' thousand ' + numToWords(integer % 1000)
elif integer % 1000000 == 0: return "One million"
elif integer >= 10000 and integer <= 99999:
if integer % 10000 == 0: return numToWords2[integer//10000] + ' ' + ' thousand '
else: return numToWords(integer //1000) + ' thousand ' + numToWords(integer % 1000)
elif integer >= 100000 and integer <= 999999:
if integer % 10000 == 0: return numToWords1[integer//10000] + ' ' + 'hundred thousand '
else: return numToWords(integer // 1000) + ' thousand ' + numToWords(integer % 1000)
return
#pass the tokenized string array and convert them to str using str() function
#return the concatenated string
def wordsToCurrency(money,currency):
res1 = str(wordsToNum(money.split(" ")))
return currency + res1
def numberDelimited(money,delimiter,jumps): #delimiting the string
res1 = ""
length = len(str(money))
letters = str(money) #converting the integer to a string
string = list(letters) #converting the string to list
i = 0 #i counter
for char in string: #for-loop
if i % jumps == 0 and i is not 0: #if i is divisible to jumps and not 0
res1 += delimiter; res1 += char #concatenate delimiter and string[index] to res1
else: res1 += char #else only concatenate string[index] to res1
i+=1 #increment 1
if i == length: break #if end of list, break loop
return (res1) #return res1
#doesn't work in all cases, only works on basic words
def wordsToNum(stringArray):
#initialization of variables
integer2 = 0
ones = 0 ; tens = 0 ; hundreds = 0; thousands = 0
i = 0
try: #traverses the stringArray list
while stringArray[i]:
if stringArray[i] == "zero":
integer2 = integer2 + 0
elif stringArray[i] == "one":
integer2 = integer2 + 1
elif stringArray[i] == "two":
integer2 = integer2 + 2
elif stringArray[i] == 'three':
integer2 = integer2 + 3
elif stringArray[i] == "four":
integer2 = integer2 + 4
elif stringArray[i] == "five":
integer2 = integer2 + 5
elif stringArray[i] == "six":
integer2 = integer2 + 6
elif stringArray[i] == "seven":
integer2 = integer2 + 7
elif stringArray[i] == "eight":
integer2 = integer2 + 8
elif stringArray[i] == "nine":
integer2 = integer2 + 9
elif stringArray[i] == "ten":
integer2 = integer2 + 10
elif stringArray[i] == "eleven":
integer2 = integer2 + 11
elif stringArray[i] == "twelve":
integer2 = integer2 + 12
elif stringArray[i] == "thirteen":
integer2 = integer2 + 13
elif stringArray[i] == "fourteen":
integer2 = integer2 + 14
elif stringArray[i] == "fifteen":
integer2 = integer2 + 15
elif stringArray[i] == "sixteen":
integer2 = integer2 + 16
elif stringArray[i] == "seventeen":
integer2 = integer2 + 17
elif stringArray[i] == "eighteen":
integer2 = integer2 + 18
elif stringArray[i] == "nineteen":
integer2 = integer2 + 19
elif stringArray[i] == "twenty":
integer2 = integer2 + 20
elif stringArray[i] == "thirty":
integer2 = integer2 + 30
elif stringArray[i] == "forty":
integer2 = integer2 + 40
elif stringArray[i] == 'fifty':
integer2 = integer2 + 50
elif stringArray[i] == "sixty":
integer2 = integer2 + 60
elif stringArray[i] == "seventy":
integer2 = integer2 + 70
elif stringArray[i] == "eighty":
integer2 = integer2 + 80
elif stringArray[i] == "ninety":
integer2 = integer2 + 90
elif stringArray[i] == "hundred" and stringArray[i+1] == "thousand":
thousands = integer2 * 100000
integer2 = 0
i+=2
elif stringArray[i] == "hundred":
hundreds = integer2 * 100
elif stringArray[i] == "thousand":
thousands = integer2 * 1000
integer2 = 0
elif stringArray[i] == "million":
integer2 = integer2 * 1000000
i += 1
except IndexError:
pass
return (thousands+hundreds+integer2) #hard-coded sheezzz
#used for testing the library
print('THIS WAS MADE FOR TESTING PURPOSES ONLY.')
print('[1]Number To Words Converter')
print('[2]Words To Number Converter')
print('[3]Words To Currency Converter')
print('[4]Number Delimiter')
choice = int(input("Choice: "))
#numToWords() testing
if choice == 1:
integer = int(input("Enter the amount(in numbers): ")) #string is stored in integer
current = ""
current = numToWords(integer)
print (current)
#wordsToNum() testing
elif choice == 2:
string2 = raw_input("Enter the amount(in words): ") #stored as a data type string
string3 = string2.split(" ") #tokenize string
result2 = wordsToNum(string3)
print (result2)
#wordsToCurrency() testing
elif choice == 3:
money = raw_input("Enter the amount(in words): ")
currency = raw_input("Enter the currency(min. of 3 letters):")
result = wordsToCurrency(money,currency)
print (result)
#NumberDelimiter() testing
elif choice == 4:
money = int(input("Enter the amount(in numbers): "))
delimiter = raw_input("Enter a delimited(single char ONLY): ")
jumps = int(input("Enter the no. of jumps when the delimiter appears: "))
result = numberDelimited(money,delimiter,jumps)
print (result)
|
9d44360949cc822a2eeae9d7009d828ac2c5d45c | mateuszwyrwa/Sudoku | /solving.py | 936 | 3.875 | 4 | import numpy as np
from Creating import *
all = {1,2,3,4,5,6,7,8,9}
def vertical(x): #creates collection of vertical numbers from point
virt = t[x]
return virt
def horizontal(y):
virt = t[:,y]
return virt
def whichsquare(x,y): #check in which square program is and creates list of numbers
if x <= 2:
if y <= 0:
sqre = [t[:3,0:3]]
if y <= 5 and y > 2:
sqre = [t[3:6,0:3]]
if y > 5:
sqre = [t[6:,0:3]]
elif x <= 5 and x>2:
if y <= 0:
sqre = [t[:3,3:6]]
if y <= 5 and y > 2:
sqre = [t[3:6,3:6]]
if y > 5:
sqre = [t[6:,3:6]]
elif x > 5:
if y <= 0:
sqre = [t[:3,6:]]
if y <= 5 and y > 2:
sqre = [t[3:6,6:]]
if y > 5:
sqre = [t[6:,6:]]
return sqre
for x in range(9):
something = whichsquare(x,0)
print(something)
|
9d6d51f639aad4260feb1aeb1556ac59938453a0 | EvanDHiggins/snake | /textbox.py | 10,919 | 3.65625 | 4 | import pygame
from datetime import datetime
pygame.init()
ANTI_ALIAS = 1
class TextBox:
"""
Attributes:
self.xPos (int): X Position in pixels of the top left corner of the
text box.
self.yPos (int): Y Position in pixels of the tops left corner of the
text box.
self.position (tuple): Tuple containing (xPos, yPos) for easier access
to location
self.fontSize (int): size of text within text box
self.fontColor (tuple): RGB value of text color, doesn't necessarily
match border color
self.fontName (str): String name of font of text within box
self.numberOfChars (int): estimated number of characters which can fit
in the text box. This determines the width of the text
box. Width is determined based off a string of this many
'm' (one of the widest characters).
self.borderThickness (int): The thickness of the text box border in
pixels
self.padding (int): number of pixels of padding between edge of
characters and text box border
self.borderColor (tuple): RGB tuple for color of border
self.inputString (string): String of text displayed within text box.
Changes reflect keypresses of user while textbox is present.
self.shifted (boolean): Reflects whether or not any keypresses by the
user will be capitalized. This defaults to False, is set
True when either right or left shift is pressed, and changes
back to false when a shift is still pressed.
self.font (Font): pygame Font object created from the font name and the
size of the desired font. This is rendered separately
self.label (surface): Rendered image of text from self.font.Font object.
This updates during runtime to reflect inputString.
"""
def __init__(self, (xPos, yPos) = (0, 0), textFieldColor = (255, 255, 255),
borderColor = (0, 0, 0), fontName = None, fontSize = 30,
fontColor = (0, 0, 0), numberOfChars = 20,
borderThickness = 2):
""" (xPos, yPos) - coordinates of upper left corner
borderColor - color of textBox outline
fontSize - size of input string font, will determine vertical
dimension of box
fontColor - color of input string font
numberOfChars - number of characters (approximately) which can fit in
the textbox"""
#Set position
self.xPos = xPos
self.yPos = yPos
self.position = (xPos, yPos)
#Set font properties
self.fontSize = fontSize
self.fontColor = fontColor
self.fontName = fontName
#Textbox properties
self.displayCursor = True
self.numberOfChars = numberOfChars
self.borderThickness = borderThickness
self.padding = 3#px
self.borderColor = borderColor
self.inputString = 'Enter your name'
self.inputList = []
for char in self.inputString:
self.inputList.append(char)
self.shifted = False
self.backSpace = False
self.elapsedBackspaceTime = 0
self.contBackspace = False
self.font = pygame.font.Font(self.fontName, self.fontSize)
self.makeLabels()
#self.label = self.font.render(self.inputString, ANTI_ALIAS,
# self.fontColor)
self.cursorPosition = len(self.labelList) - 1
self.previousTime = float(str(datetime.now())[-9:])
self.elapsedTime = 0
#Dimensions
self.width, self.height = self.determineDimensions(numberOfChars)
self.setPosition(xPos, yPos)
def makeLabels(self):
self.labelList = []
for char in self.inputList:
label = self.font.render(char, ANTI_ALIAS, self.fontColor)
width = label.get_rect().width
height = label.get_rect().height
self.labelList.append((label, width, height))
def setPosition(self, xPos, yPos):
self.xPos = xPos
self.yPos = yPos
self.position = (xPos, yPos)
#Text Position
self.textXPos = self.xPos + self.borderThickness + self.padding
self.textYPos = self.yPos + self.borderThickness + self.padding
self.textPosition = (self.textXPos, self.textYPos)
def setFont(self, fontName):
self.fontName = fontName
self.font = pygame.font.Font(self.fontName, self.fontSize)
self.width, self.height = self.determineDimensions(self.numberOfChars)
def determineDimensions(self, characters):
"""Determines dimensions for text box based on input font size
and length of box.
characters: integer of the number of characters long the textbox
should be.
"""
text = '[g'
for char in xrange(characters):
text += 'm'
text = self.font.render(text, ANTI_ALIAS, (0, 0, 0))
return text.get_rect().width + self.padding, \
text.get_rect().height + self.padding*2
def deleteChar(self):
"""Removes item from inputString at cursor"""
if len(self.inputList) > 0 and self.cursorPosition >= 0:
print 'pop index = ', self.cursorPosition
self.inputList.pop(self.cursorPosition)
self.cursorPosition -= 1
def endOfBuffer(self):
if self.cursorPosition >= self.numberOfChars:
return True
else:
return False
def update(self, events):
"""
Call this method within a loop to update the contents of the
textbox
events - list of events created within a pygame loop with:
events = pygame.events.get()
"""
print(self.cursorPosition)
for event in events:
#Turns shift off when shift goes up
if event.type == pygame.KEYUP:
if (event.key == pygame.K_LSHIFT or
event.key == pygame.K_RSHIFT):
self.shifted = False
elif event.key == pygame.K_BACKSPACE:
self.backSpace = False
self.contBackspace = False
self.elapsedBackspaceTime = 0
#Returns input string when return is pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
self.inputString = ''.join(self.inputList)
return str(self.inputString)
#Turns shift on when shift goes down
elif (event.key == pygame.K_LSHIFT or
event.key == pygame.K_RSHIFT):
self.shifted = True
#This includes alphanumeric characters and special symbols
elif event.key > 31 and event.key < 126:
if self.shifted == True and not self.endOfBuffer():
self.cursorPosition += 1
self.inputList.insert(self.cursorPosition,
chr(event.key).capitalize())
return
elif self.shifted == False and not self.endOfBuffer():
self.cursorPosition += 1
self.inputList.insert(self.cursorPosition,
chr(event.key))
return
#Removes final object in array when backspace is pressed
elif event.key == pygame.K_BACKSPACE:
self.deleteChar()
self.backSpace = True
elif event.key == pygame.K_LEFT:
if self.cursorPosition > -1:
self.cursorPosition -= 1
elif event.key == pygame.K_RIGHT:
if self.cursorPosition < len(self.labelList) - 1:
self.cursorPosition += 1
currentTime = str(datetime.now())
currentTime = float(currentTime[-9:])
self.elapsedTime += currentTime - self.previousTime
if self.backSpace == True:
self.elapsedBackspaceTime += currentTime - self.previousTime
if self.elapsedBackspaceTime > .25:
self.contBackspace = True
if self.elapsedTime > .5:
self.displayCursor = not self.displayCursor
self.elapsedTime = 0
if self.contBackspace == True:
self.deleteChar()
self.previousTime = currentTime
def render(self, screen):
"""function renders textbox at x/y position"""
#Create image of text for rendering
#self.label = self.font.render(self.inputString, ANTI_ALIAS, self.fontColor)
self.makeLabels()
#Draw border rectangle
pygame.draw.rect(screen, self.borderColor, [self.xPos, self.yPos,
self.width, self.height], self.borderThickness)
xPos = self.textXPos
yPos = self.textYPos
#Print cursor if at the left end of the textbox
if self.cursorPosition == -1 and self.displayCursor:
pygame.draw.rect(screen, self.borderColor, [xPos, yPos, 1,
self.height - self.padding*3],
self.borderThickness)
#Render text to screen
for index in xrange(len(self.labelList)):
if len(self.labelList) == 0 and self.displayCursor:
pygame.draw.rect(screen, self.borderColor, [xPos, yPos, 1,
self.height - self.padding*2],
self.borderThickness)
item = self.labelList[index]
screen.blit(item[0], (xPos, yPos))
if index == self.cursorPosition and self.displayCursor:
pygame.draw.rect(screen, self.borderColor, [xPos +
item[0].get_rect().width, yPos, 1, item[2] - self.padding],
self.borderThickness)
xPos += item[1]
#Render text highlight
#Render cursor
def main():
screen = pygame.display.set_mode((500, 500), 0, 32)
pygame.display.set_caption('Text Box Test')
aBox = TextBox()
done = False
aBox.setPosition(20, 20)
aBox.setFont('Inconsolata.otf')
inputString = ''
while not done:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
done = True
inputString = aBox.update(events)
screen.fill((255, 255, 255))
aBox.render(screen)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__" :
main()
|
0e79dd55f7e066da510f2b740e216aa34f7d4bda | therealnacho19/SecondDay | /palindromeCheck.py | 371 | 4.03125 | 4 | number = input("Enter a number: ")
i = -1
for n in number:
if n != number[i]:
print("That is not a palindrome! A palindrome reads backwards the same way as regularly!")
break
else:
i -= 1
if (i * (-1)) > (int(len(number) / 2)):
print("EUREKA! You found a palindrome")
break
|
bdb45c1871c23b390ce7d7f0282abbc588292b0e | jwitover/NPSG1 | /PRNE/PRNE Week 2/s10.5.py | 1,978 | 3.90625 | 4 | # devices_list = [] # Create the outer list for all devices
#
# # Read in the devices from the file
# file = open('devices','r')
# for line in file:
#
# device_info_list = line.strip().split(',') # Get device info into list
# devices_list.append(device_info_list)
#
# file.close() # Close the file since we are done with it
#
# print ''
# print 'Name OS-type IP address Software '
# print '------ ------- ------------------ ------------------'
#
# # Go through the list of devices, printing out values in nice format
# for device in devices_list:
#
# print '{0:8} {1:8} {2:20} {3:20}'.format(device[0],device[1],
# device[2],device[3])
#
# print ''
devices_list = [] # Create the outer list for all devices
file = open('devices','r')
line = file.readline()
while line:
device_info_list = line.strip().split(',') # Get device info into list
# Put device information into dictionary for this one device
device_info = {} # Create the inner dictionary of device info
device_info['name'] = device_info_list[0]
device_info['os-type'] = device_info_list[1]
device_info['ip'] = device_info_list[2]
device_info['version'] = device_info_list[3]
# Now append our device and its info onto our 'devices' list
devices_list.append(device_info)
line = file.readline()
file.close() # Close the file since we are done with it
# Use while loop to print the results
print ''
print 'Name OS-type IP address Software '
print '------ ------- ------------------ ------------------'
index = 0
while index < len(devices_list):
device = devices_list[index]
print '{0:8} {1:8} {2:20} {3:20}'.format(device['name'],
device['os-type'],
device['ip'],
device['version'])
index += 1
print '' |
b00974b367dde53d46d188b035022f35e8a14057 | tksok2009/python_test_code | /hello.py | 105 | 3.96875 | 4 | word=('test2')
for w in word:
print(w)
print('end')
#python2 code example
# word='test'
# print 'end'
|
c681dd31c3b53792e9b5a870a65832b298cb8dd8 | MilenMMinev/hackbulgaria-week0 | /contains_digits/solution.py | 479 | 3.921875 | 4 | def digit_is_in_number(number, digits):
while number != 0:
if number % 10 == digits:
return True
number = number // 10
return False
def contain_digits(number, digits):
for item in digits:
if not digit_is_in_number(number, item):
return False
return True
def main():
print (contain_digits(402123, [0, 3, 4]))
print (contain_digits(666, [6,4]))
print (contain_digits(123456789, [1,2,3,0]))
print (contain_digits(456, []))
if __name__ == '__main__':
main() |
26374da32a25d15311daa83cc9e730682ee249b2 | lohaukai/python268 | /p6.py | 151 | 3.6875 | 4 | number1 = eval(input())
number2 = eval(input())
number3 = round(number1 + number2, 2)
print('%.2f' %number1, '+','%.2f' %number2, '=', '%.2f' %number3) |
45dfcb7d261fb7676d179aec7da0ffca59846e1f | chmh0805/Machine_Learning | /200423_Numerical Derivative_4v.py | 912 | 3.578125 | 4 |
# 예제 3. 4변수함수 f(w,x,y,z) = wx + xyz + 3w + zy^2를 미분하여
## f'(1.0, 2.0, 3.0, 4.0)의 값을 구하여라.
import numpy as np
def numerical_derivative(f, x) :
delta_x = 1e-4
grad = np.zeros_like(x)
it = np.nditer(x, flags=["multi_index"],op_flags=["readwrite"])
while not it.finished :
idx = it.multi_index
tmp_val = x[idx]
x[idx] = tmp_val + delta_x
fx1 = f(x)
x[idx] = tmp_val - delta_x
fx2 = f(x)
grad[idx] = (fx1 - fx2) / (2 * delta_x)
x[idx] = tmp_val
it.iternext()
return grad
def func3(input_obj) :
w = input_obj[0,0]
x = input_obj[0,1]
y = input_obj[1,0]
z = input_obj[1,1]
return ( w*x + x*y*z + 3*w + z*np.power(y,2) )
input = np.array( [[1.0, 2.0], [3.0, 4.0]])
result = numerical_derivative(func3, input)
print (result) |
265ea7e78f17fe7f3447f3a463961f047a3551a8 | cupy/cupy | /cupy/lib/stride_tricks.py | 5,494 | 3.859375 | 4 | import cupy as _cupy
def as_strided(x, shape=None, strides=None):
"""
Create a view into the array with the given shape and strides.
.. warning:: This function has to be used with extreme care, see notes.
Parameters
----------
x : ndarray
Array to create a new.
shape : sequence of int, optional
The shape of the new array. Defaults to ``x.shape``.
strides : sequence of int, optional
The strides of the new array. Defaults to ``x.strides``.
Returns
-------
view : ndarray
See also
--------
numpy.lib.stride_tricks.as_strided
reshape : reshape an array.
Notes
-----
``as_strided`` creates a view into the array given the exact strides
and shape. This means it manipulates the internal data structure of
ndarray and, if done incorrectly, the array elements can point to
invalid memory and can corrupt results or crash your program.
"""
shape = x.shape if shape is None else tuple(shape)
strides = x.strides if strides is None else tuple(strides)
return _cupy.ndarray(shape=shape, dtype=x.dtype,
memptr=x.data, strides=strides)
|
7793d4de2ec2ffb99801b8c2721a9d669894fead | lukeraz/code | /tabuada.py | 438 | 3.96875 | 4 | n1 = int(input("Insira um numero para ser feito a taboada: "))
x1 = n1*1
x2 = n1*2
x3 = n1*3
x4 = n1*4
x5 = n1*5
x6 = n1*6
x7 = n1*7
x8 = n1*8
x9 = n1*9
x10 = n1*10
print(f"{n1} x 1: {x1}")
print(f"{n1} x 2: {x2}")
print(f"{n1} x 3: {x3}")
print(f"{n1} x 4: {x4}")
print(f"{n1} x 5: {x5}")
print(f"{n1} x 6: {x6}")
print(f"{n1} x 7: {x7}")
print(f"{n1} x 8: {x8}")
print(f"{n1} x 9: {x9}")
print(f"{n1} x 10: {x10}") |
361a368f4b5e067bbac0f2014d49804e3f783c89 | Basma1412L/ShowMetheDataStructures | /problem_6.py | 5,898 | 3.78125 | 4 | import copy
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:
out_string += str(cur_head.value) + " -> "
cur_head = cur_head.next
return out_string
def delete(self, value):
if self.head is None:
return
node = self.head
if (node.value==value):
self.head=self.head.next
return
while node and node.next and not (node.next.value == value):
node = node.next
if (node.next and node.next.value == value):
node.next = node.next.next
return
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def size(self):
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
def union(llist_1, llist_2):
llist_11=copy.deepcopy(llist_1)
llist_21 = copy.deepcopy(llist_2)
if llist_11.size() == 0 and llist_21.size() > 0 :
return llist_21
elif llist_11.size() >0 and llist_21.size() == 0 :
return llist_11
elif llist_11.size() == 0 and llist_21.size() == 0 :
return llist_21
else:
current_list11 = llist_11.head
while (current_list11):
value=current_list11.value
current_list21 = llist_21.head
while (current_list21):
value2=current_list21.value
if value==value2:
current_list21 = current_list21.next
llist_21.delete(value2)
else:
current_list21 = current_list21.next
if(current_list11.next==None):
current_list11.next=llist_21.head
return llist_11
break
current_list11 = current_list11.next
return None
def intersection(llist_1, llist_2):
if llist_1.size() == 0 or llist_2.size() == 0 :
return None
else:
intersectionList=LinkedList()
current_list1 = llist_1.head
while (current_list1):
value=current_list1.value
current_list2 = llist_2.head
while (current_list2):
value2=current_list2.value
if value==value2:
intersectionList.append(value)
break
current_list2 = current_list2.next
current_list1 = current_list1.next
if intersectionList.size()==0:
return None
return intersectionList
# Test case 1
linked_list_1 = LinkedList()
linked_list_2 = LinkedList()
element_1 = [10,20,30,40]
element_2 = [30,40,50,60]
for i in element_1:
linked_list_1.append(i)
for i in element_2:
linked_list_2.append(i)
print (union(linked_list_1,linked_list_2))
print (intersection(linked_list_1,linked_list_2))
# Test case 2
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()
element_1 = [4,5,6]
element_2 = [5,6,7,8]
for i in element_1:
linked_list_3.append(i)
for i in element_2:
linked_list_4.append(i)
print (union(linked_list_3,linked_list_4))
print (intersection(linked_list_3,linked_list_4))
union1_solution_array=[10,20,30,40,50,60]
union1_solution_list=LinkedList()
for i in union1_solution_array:
union1_solution_list.append(i)
result1=union(linked_list_1,linked_list_2)
test_case1=[result1,union1_solution_list]
union2_solution_array=[4,5,6,7,8]
union2_solution_list=LinkedList()
for i in union2_solution_array:
union2_solution_list.append(i)
result2=union(linked_list_3,linked_list_4)
test_case2=[result2,union2_solution_list]
intersection1_solution_array=[30,40]
intersection1_solution_list=LinkedList()
for i in intersection1_solution_array:
intersection1_solution_list.append(i)
result3=intersection(linked_list_1,linked_list_2)
test_case3=[result3,intersection1_solution_list]
result4=intersection(linked_list_3,linked_list_4)
intersection2_solution_array=[5,6]
intersection2_solution_list=LinkedList()
for i in intersection2_solution_array:
intersection2_solution_list.append(i)
test_case4=[result4,intersection2_solution_list]
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()
element_1 = [4,5,6]
element_2 = []
for i in element_1:
linked_list_3.append(i)
for i in element_2:
linked_list_4.append(i)
print (union(linked_list_3,linked_list_4))
print (intersection(linked_list_3,linked_list_4))
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()
element_1 = []
element_2 = [5,6,7,8]
for i in element_1:
linked_list_3.append(i)
for i in element_2:
linked_list_4.append(i)
print (union(linked_list_3,linked_list_4))
print (intersection(linked_list_3,linked_list_4))
def test_functions(test_case):
result = test_case[0]
solution = test_case[1]
if solution==None:
if result==None:
print("Pass")
else:
print("Fail")
else:
try:
r_head=result.head
s_head=solution.head
while (r_head and s_head):
if (r_head.value!=s_head.value):
print("Fail")
return
r_head=r_head.next
s_head=s_head.next
print("Pass")
return
else:
print("Fail")
except Exception as e:
print("Fail")
test_functions(test_case1)
test_functions(test_case2)
test_functions(test_case3)
test_functions(test_case4) |
01e9d0aca52dac06d7b35ff4a3847d80d33c8719 | KMrsR/HMR_python | /PythonTutor/lesson_7_16.py | 1,024 | 3.59375 | 4 | '''
Условие
Известно, что на доске 8×8 можно расставить 8 ферзей так, чтобы они не били друг друга.
Вам дана расстановка 8 ферзей на доске, определите, есть ли среди них пара бьющих друг друга.
Программа получает на вход восемь пар чисел, каждое число от 1 до 8 — координаты 8 ферзей.
Если ферзи не бьют друг друга, выведите слово NO, иначе выведите YES.
'''
x=[0]*8
y=[0]*8
m=[]
for i in range(8):
x[i],y[i]= [int(s) for s in input().split()]
for i in range(7):
for j in range(i+1,7):
if x[i]==x[j]:
m.append(1)
elif y[i]==y[j]:
m.append(1)
elif abs(x[i]-x[j])==abs(y[i]-y[j]):
m.append(1)
else:
m.append(0)
if m.count(1)>0:
print("YES")
else:
print("NO")
|
7fce04216a1ae948697dcadc4c3b4d6db339ad31 | Rogiel/ufrgs-projeto-diplomacao | /Classifier/statistics.py | 477 | 3.5625 | 4 | import math
def mean(list):
sum = 0
for n in list:
sum += n
return float(sum) / len(list)
def stddev(list):
m = mean(list)
sum = 0
for n in list:
sum += math.pow(n - m, 2)
return math.sqrt(sum / (len(list) - 1))
def unbiased_stddev(list):
return stddev(list) / c4(float(len(list)))
def c4(N):
return math.sqrt(
2.0 / (N-1.0)
) * (
math.gamma(N / 2.0) /
math.gamma(N / 2.0 - 1.0/2.0)
)
|
a2f66a9fd62c3db1a45b2c2ffebc82e69cde1a2f | serdarcw/python_notes | /python_exercises/Flip the Array.py | 213 | 3.53125 | 4 | https://edabit.com/challenge/QoavwQhmrDpXJhBW9
Flip the Array (Hard)
lst=[1, 2, 3, 4]
B=[]
if lst==[]:
lst=B
if isinstance(lst[0], int):
print([[i] for i in lst])
else:
print([i[0] for i in lst])
|
8e6237ae8748f14f00166300f6556d0d578acb94 | jedzej/tietopythontraining-basic | /students/bec_lukasz/lesson_01_basics/fractional_part.py | 97 | 3.734375 | 4 | # Read an integer:
# a = int(input())
# Print a value:
# print(a)
a = input()
print(float(a)%1)
|
0a9c99d80565ce3befc29c8e8b1922a41c110887 | jmlatham/My-Tests | /classes/printTest.py | 12,345 | 3.875 | 4 | class PrintTests:
def printTest1(self):
print("Hello!")
print("Welcome to Python Essentials!")
print("THIS IS SANDBOX MODE.")
# Click the Run button
print("WELCOME TO PYTHON ESSENTIALS!")
print("Hello, World!")
print("Hello, Python!")
print("Jonathan1")
#print(Jonathan2)
#Traceback (most recent call last):
# File "main.py", line 3, in <module>
# print(Jonathan2)
#NameError: name 'Jonathan2' is not defined
#print Jonathan3
# File "main.py", line 4
# print Jonathan3
# ^
#SyntaxError: Missing parentheses in call to 'print'. Did you mean print(Jonathan3)?
#print "Jonathan4"
# File "main.py", line 9
# print "Jonathan4"
# ^
#SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Jonathan4")?
#print 'Jonathan5'
# File "main.py", line 14
# print 'Jonathan5'
# ^
#SyntaxError: Missing parentheses in call to 'print'. Did you mean print('Jonathan5')?
print('Jonathan6')
#print('Jonathan7')print("Jonathan8")
# File "main.py", line 20
# print('Jonathan7')print("Jonathan8")
# ^
#SyntaxError: invalid syntax
print() # blank line
print("Jonathan""Marshall""Latham") # concatenates
print("Jonathan", "Marshall", "Latham") # separated by a space
print(0, "this is an integer - decimal")
#print(01)
# File "main.py", line 46
# print(01)
# ^
#SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
print(0o5, "this is an octal 5")
#print(0o8)
# File "main.py", line 46
# print(01)
# ^
#SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
print(0o17, "this is an octal 17") # prints 15 - this is octal
print(0.1)
print(0b1, "this is a binary 1")
#print(0b2)
# File "main.py", line 46
# print(01)
# ^
#SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
print(0b11, "this is a binary 11") # prints 3
print(0b100, "this is a binary 100") # prints 4 - this is binary
print(0xa, "this is a hexadecimal a") # prints 10 - this is hexadecimal
print()
print("a \a","a")
print("b \b","b")
print("c \c","c")
print("d \d","d")
print("e \e","e")
print("f \f","f")
print("g \g","g")
print("h \h","h")
print("i \i","i")
print("j \j","j")
print("k \k","k")
print("l \l","l")
print("m \m","m")
print("n \n","n")
print("o \o","o")
print("p \p","p")
print("q \q","q")
print("r \r","r")
print("s \s","s")
print("t \t","t")
#print("u \u")
# File "main.py", line 89
# print("u \u")
# ^
#SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape
print("u-> u4561 \u4561","u")
print("v \v","v")
print("w \w","w")
#print("x \x")
# File "main.py", line 97
# print("x \x")
# ^
#SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \xXX escape
print("x->x27 \x27","x")
print("y \y","y")
print("z \z","z")
print("1 \1","1")
print("2 \2","2")
print("3 \3","3")
print("4 \4","4")
print("5 \5","5")
print("6 \6","6")
print("7 \7","7")
print("8 \8","8")
print("9 \9","9")
print("0 \0","0")
print("\\ \\","\\")
print("\" \"","\"")
print("' \'","'")
print(". \.",".")
print(", \,",",")
print("/ \/","/")
print("[ \[","[")
print("{ \{","{")
print("] \]","]")
print("} \}","}")
print("| \|","|")
print("< \<","<")
print("> \>",">")
print("? \?","?")
print("` \`","`")
print("~ \~","~")
print("! \!","!")
print("@ \@","@")
print("# \#","#")
print("$ \$","$")
print("% \%","%")
print("^ \^","^")
print("& \&","&")
print("* \*","*")
print("( \(","(")
print(") \)",")")
print("- \-","-")
print("_ \_","_")
print("+ \+","+")
print("= \=","=")
print("; \;",";")
print(": \:",":")
#2.1.1.19 LAB: Formatting the output
def printTest2(self):
print("2.1.1.19 LAB: Formatting the output")
print("My", "name", "is", "Monty", "Python.", sep="-", end=" ")
print("What is your name?")
print("My", "name", "is", sep="_", end="*")
print("Monty", "Python.", sep="*", end="*\n")
print("Programming","Essentials","in", sep="***", end="...")
print("Python")
#2.1.1.20 LAB: Formatting the output
def printTest3(self):
print("2.1.1.20 LAB: Formatting the output")
print("Original")
print(" *")
print(" * *")
print(" * *")
print(" * *")
print("*** ***")
print(" * *")
print(" * *")
print(" *****")
print("1. minimize by using \\n")
print(" *"," * *"," * *"," * *","*** ***"," * *"," * *"," *****", sep="\n")
print("2. make arrow twice as large (but keep the proportions)")
print(" **")
print(" **")
print(" ** **")
print(" ** **")
print(" ** **")
print(" ** **")
print(" ** **")
print(" ** **")
print("****** ******")
print("****** ******")
print(" ** **")
print(" ** **")
print(" ** **")
print(" ** **")
print(" **********")
print(" **********")
print("3. duplicate the arrow side by side")
print(" * " * 2)
print(" * * " * 2)
print(" * * " * 2)
print(" * * " * 2)
print("*** ***" * 2)
print(" * * " * 2)
print(" * * " * 2)
print(" ***** " * 2)
print()
print("MORE TESTS")
print()
print(" *")
print(" * *")
print(" * *")
print(" * *")
print("*** ***")
print(" * *")
print(" * *")
print(" *****")
print('---------')
print(' * '*4)
print(' * * '*4)
print(' * * '*4)
print(' * * '*4)
print('*** ***'*4)
print(' * * '*4)
print(' * * '*4)
print(' ***** '*4)
print('---------')
print(" ""*")
print(" ""*"*3)
print(" ""*"*5)
print(" ""*"*7)
print("*"*9)
print(" ""*"*5)
print(" ""*"*5)
print(" ""*"*5)
print('---------')
print(" ","*")
print(" ","*"*3)
print(" ","*"*5)
print(" ","*"*7)
print("*"*9)
print(" ","*"*5)
print(" ","*"*5)
print(" ","*"*5)
print('---------')
print(" ","*", sep="")
print(" ","*"*3, sep="")
print(" ","*"*5, sep="")
print(" ","*"*7, sep="")
print("*"*9, sep="")
print(" ","*"*5, sep="")
print(" ","*"*5, sep="")
print(" ","*"*5, sep="")
print('---------', sep="")
print(" ","*"*2, sep="")
print(" ","*"*6, sep="")
print(" ","*"*10, sep="")
print(" ","*"*14, sep="")
print("*"*18, sep="")
print(" ","*"*10, sep="")
print(" ","*"*10, sep="")
print(" ","*"*10, sep="")
print('---------', sep="")
print(" "*8,"*"*2, sep="")
print(" "*6,"*"*6, sep="")
print(" "*4,"*"*10, sep="")
print(" "*2,"*"*14, sep="")
print(" "*0,"*"*18, sep="")
print(" "*4,"*"*10, sep="")
print(" "*4,"*"*10, sep="")
print(" "*4,"*"*10, sep="")
print('-'*18, sep="")
print(" "*8,"*"*2," "*16,"*"*2, sep="")
print(" "*6,"*"*6," "*12,"*"*6, sep="")
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print(" "*2,"*"*14," "*4,"*"*14, sep="")
print(" "*0,"*"*18," "*0,"*"*18, sep="")
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print('-'*36, sep="")
print(" "*8,"*"*2," "*16,"*"*2, sep="")
print()
print(" "*6,"*"*6," "*12,"*"*6, sep="")
print()
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print()
print(" "*2,"*"*14," "*4,"*"*14, sep="")
print()
print(" "*0,"*"*18," "*0,"*"*18, sep="")
print()
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print()
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print()
print(" "*4,"*"*10," "*8,"*"*10, sep="")
print('-'*36, sep="")
# 2.1.2.2 Python literals
def printTest4(self):
print("Original")
print("2")
print(2)
print("Test 1")
print("2" * 2)
print(2 * 2)
print("Test 2")
#print("2" * "2")
#Traceback (most recent call last):
# File "main.py", line 9, in <module>
# print("2" * "2")
#TypeError: can't multiply sequence by non-int of type 'str'
print(11111111)
print(11_111_111) # the underscores are removed automatically
print(-11111111)
print(-11_111_111) # the underscores are removed automatically
print(" 11111111",11111111, sep=" = ")
print(" 11_111_111",11_111_111, sep=" = ")
print(" -11111111",-11111111, sep=" = ")
print("-11_111_111",-11_111_111, sep=" = ")
print(" 11111111 + 2222222",11111111 + 2222222, sep=" = ")
print(" 11_111_111 + 2_222_222",11_111_111 + 2_222_222, sep=" = ")
print("-11111111 + 2222222",-11111111 + 2222222, sep=" = ")
print("-11_111_111 + 2_222_222",-11_111_111 + 2_222_222, sep=" = ")
# 2.1.2.4 Python Literals
def printTest5(self):
print("2.1.2.4 Python Literals")
print("0o123",0o123, sep=" = ")
print("0O123",0O123, sep=" = ")
print("0x123",0x123, sep=" = ")
print("0X123",0X123, sep=" = ")
# 2.1.2.5 Python Literals
def printTest6(self):
print("2.1.2.5 Python Literals")
print("0.4",0.4, sep=" = ")
print(".4 ", .4, sep=" = ")
print("4.0",4.0, sep=" = ")
print("4. ", 4., sep=" = ")
print("0.4*2",0.4*2, sep=" = ")
print(".4*2 ", .4*2, sep=" = ")
print("4.0*2",4.0*2, sep=" = ")
print("4.*2 ", 4.*2, sep=" = ")
# 2.1.2.6 Python Literals
def printTest7(self):
print("2.1.2.6 Python Literals")
print("300000000", 3E8, sep=" = ")
print(" 1E1",1E1, sep=" = ")
print(".1E1", .1E1, sep=" = ")
print("127E10 * 127E10", 127E10*127E10, sep=" = ")
print(" 2E10 * 2E10 ", 2E10*2E10, sep=" = ")
print("2E-10 * 2E-10", 2E-10 * 2E-10, sep=" = ")
# 2.1.2.10 Python Literals
def printTest8(self):
print("2.1.2.10 Python Literals")
print("True > False", True > False, sep=" = ")
print("True < False", True < False, sep=" = ")
# 2.1.2.11 LAB: Python Literals - strings
def printTest9(self):
print("2.1.2.11 LAB: Python Literals - strings")
print("\"I'm\"",'""learning""','"""Python"""', sep="\n")
# 2.1.3.1 Operators - data manipulation tools
def printTest0(self):
print("2+3 ",2+3, sep=" = ")
print("2-3 ",2-3, sep=" = ")
print("2*3 ",2*3, sep=" = ")
print("2/3 ",2/3, sep=" = ")
print("2.0+3 ",2.0+3, sep=" = ")
print("2.0-3 ",2.0-3, sep=" = ")
print("2.0*3 ",2.0*3, sep=" = ")
print("2.0/3 ",2.0/3, sep=" = ")
print("2+3.0 ",2+3.0, sep=" = ")
print("2-3.0 ",2-3.0, sep=" = ")
print("2*3.0 ",2*3.0, sep=" = ")
print("2/3.0 ",2/3.0, sep=" = ")
print("2.0+3.0 ",2.0+3.0, sep=" = ")
print("2.0-3.0 ",2.0-3.0, sep=" = ")
print("2.0*3.0 ",2.0*3.0, sep=" = ")
print("2.0/3.0 ",2.0/3.0, sep=" = ")
print("-------------------------")
print("2//3 ",2//3, sep=" = ") # Integer Division (integer value to the left of the quotient decimal point)
print("2%3 ",2%3, sep=" = ") # Modulo (remainder of 2/3)
print("2**3 ",2**3, sep=" = ") # Exponent 2^3
print("2.0//3 ",2.0//3, sep=" = ")
print("2.0%3 ",2.0%3, sep=" = ")
print("2.0**3 ",2.0**3, sep=" = ")
print("2//3.0 ",2//3.0, sep=" = ")
print("2%3.0 ",2%3.0, sep=" = ")
print("2**3.0 ",2**3.0, sep=" = ")
print("2.0//3.0",2.0//3.0, sep=" = ")
print("2.0%3.0 ",2.0%3.0, sep=" = ")
print("2.0**3.0",2.0**3.0, sep=" = ")
print("8//3 ",8//3, sep=" = ")
print("8.0//3 ",8.0//3, sep=" = ")
print("8//3.0 ",8//3.0, sep=" = ")
print("8.0//3.0",8.0//3.0, sep=" = ") |
251273773e64cad28159593b37d110d2af1823d6 | robert75RG/python_bootcamp | /zjazd3/OPP/zadanie11.py | 1,110 | 3.6875 | 4 | '''
Zadanie #11
Zaimplementuj klasy odpowiedzialne za tworzenie dokumenty w
składni MarkDown. Stwórz klase bazowa Element zawierajaca
podstawowa implementacje metody render() oraz kilka jej klas
pochodnych. Stwórz klase Document umozliwiajaca wyrendorowanie
dodanych elementów.
Przykład uzycia:
>>> document = Document()
>>> document.add_element(HeaderElement('Header'))
>>> document.add_element(LinkElement('ABC', 'abc.com'))
>>> document.add_element(Element('Simple'))
>>> document.render()
Header
======
(ABC)[http://abc.com]
Simple
'''
class Document():
def __init__(self):
self.conteiner = []
def add_element(self, element):
self.conteiner.append(element)
class Element():
def __init__(self, text):
self.text = text
def render(self):
return self.text
def test_document():
doc = Document()
assert doc.conteiner == []
doc.add_element('TRZY')
assert doc.conteiner == ['TRZY']
def test_element():
element = Element('Ala ma kota')
assert element.text == 'Ala ma kota'
assert element.render() == 'Ala ma kota' |
0bef89f2223151a3ff647dd11cf0ee1a3bf3395d | qrees/aoc | /hackerrank/matrix/main.py | 1,662 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minTime function below.
@profile
def minTime(roads, machines):
machines = set(machines)
def set_leader(node, leader):
leaders[node] = leader
def get_leader(node):
if node == leaders[node]:
return node
leader = get_leader(leaders[node])
if leader != leaders[node]:
set_leader(node, leader)
return leader
leaders = {}
for index in range(0, len(roads) + 1):
leaders[index] = index
sorted_roads = sorted(roads, key=lambda x: x[2], reverse=True)
total_cost = 0
print("start")
to_destroy = len(machines) - 1
for source, destination, cost in sorted_roads:
if to_destroy == 0:
break
source_leader = get_leader(source)
destination_leader = get_leader(destination)
if source_leader in machines and destination_leader in machines:
total_cost += cost
to_destroy -= 1
continue
if source_leader in machines:
set_leader(destination_leader, source_leader)
continue
set_leader(source_leader, destination_leader)
return total_cost
if __name__ == '__main__':
fptr = sys.stdout
nk = input().split()
n = int(nk[0])
k = int(nk[1])
roads = []
for _ in range(n - 1):
roads.append(list(map(int, input().rstrip().split())))
machines = []
for _ in range(k):
machines_item = int(input())
machines.append(machines_item)
result = minTime(roads, machines)
fptr.write(str(result) + '\n')
|
4f19d7bc97538eeba246bc5b00b7197eaab9df62 | aleph2c/meta_programming_in_python | /executing_code_with_local_side_effects_23.py | 1,986 | 3.9375 | 4 | # you are using exec() to executre a fragment of code in the scope of the
# caller, but after execution, noe of its results seem to be visible.
import sys
a = 13
exec('b = a + 1')
print(b) # => 14
# but look
def test():
a = 13
exec('c = a + 1')
print(c)
print('continuing ... ')
# this will crash:
try:
test()
except:
print(sys.exc_info())
print('continuing ... ')
# to fix this problem we need to use the locals() function to obtain a
# dictionary of local variable prior to the call to exec(). Immediately
# afterward, you can extract modified values from the locals dictionary.
def test():
a = 13
loc = locals()
exec("d = a + 1")
d = loc['d']
print(d)
test()
print('continuing ... ')
# The correct use of exec is very tricky. So try and avoid it. The code in
# exec never actually makes any changes to the local variable within a function,
# because the local variables passed to exec are a copy of the locals in the
# function. If you change this copy, it doesn't change the original.
def test1():
x = 0
exec('x += 1')
print(x)
test1()
print('continuing ... ')
# When you call locals() to obtain a copy of the local variables, you get the
# copy of the locals that will be passed to exec.
def test2():
x = 0
loc = locals()
print('before:', loc)
exec('x += 1')
print('after:', loc)
print('x =', x)
test2()
print('continuing ... ')
# With any use of locals(), you need to be careful about the order of
# operations. Each time it is invoked, locals() will take the current value of
# the local variables and overwrite the corresponding entries in the dictionary:
def test3():
x = 0
loc = locals()
print(loc)
exec('x += 1')
print(loc)
locals()
print(loc)
test3()
print('continuing ... ')
# An alternative to using locals is to pass your global and local dictionary to
# the exec function:
def test4():
a = 13
loc = {'a': a}
glb = {}
exec('b = a + 1', glb, loc)
b = loc['b']
print(b)
test4()
|
b7c704442801b3f4a4530d40f577985a4c0ef218 | sxu11/Algorithm_Design | /Contests/C125_MaximumBinaryTreeII.py | 2,428 | 3.921875 | 4 | '''
We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.
Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:
If A is empty, return null.
Otherwise, let A[i] be the largest element of A. Create a root node with value A[i].
The left child of root will be Construct([A[0], A[1], ..., A[i-1]])
The right child of root will be Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
Return root.
Note that we were not given A directly, only a root node root = Construct(A).
Suppose B is a copy of A with the value val appended to it. It is guaranteed that B has unique values.
Return Construct(B).
Example 1:
Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]
Example 2:
Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]
Example 3:
Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]
Note:
1 <= B.length <= 100
'''
# 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 insertIntoMaxTree(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
def recover(node):
if not node:
return []
else:
return recover(node.left) + [node.val] + recover(node.right)
old_list = recover(root)
old_list.append(val)
def find_max_ind(alist):
max_id = 0
for i in range(1, len(alist)):
if alist[i] > alist[max_id]:
max_id = i
return max_id
def construct(alist):
if len(alist) == 0:
return None
# elif len(alist) == 1:
# return TreeNode(alist[0].val)
else:
max_id = find_max_ind(alist)
node = TreeNode(alist[max_id])
node.left = construct(alist[:max_id])
node.right = construct(alist[max_id + 1:])
return node
return construct(old_list)
|
c81f8c03493b11d349e215b4931934646baf3eaf | woojeee/python-ass1 | /assignment1.py | 983 | 3.953125 | 4 | #연습문제 1
list1 = ['Life', 'is', 'too', 'short']
print(" ".join(list1))
print("\n")
#연습문제 2
print("shirt")
print("\n")
#연습문제 3
n = 1
while n < 5:
print("*"*n)
n += 1
print('\n')
#연습문제 4
str1 = 'mutzangesazachurum'
n = 0
for word in str1:
if word in 'aeiou':
n += 1
print(n)
print('\n')
# 과제 1-1
n = 1
sum = 0
while n <= 1000:
if n % 3 == 0:
sum += n
n += 1
print(sum)
print('\n')
# 과제 1-2
n = 10
while n > 0:
print('*'*n)
n -= 1
print('\n')
# 과제 1-3
A = [20, 55, 67, 82, 45, 33, 90, 87, 100, 25]
sum = 0
for score in A:
if score >= 50:
sum += score
print(sum)
print('\n')
# 과제 2-1
for i in range(1, 101):
print(i)
print('\n')
# 과제 2-2
A = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100]
sum = 0
for score in A:
sum += score
print(sum/len(A))
print('\n')
# 과제 2-3
numbers = [1, 2, 3, 4, 5]
result = [n * 2 for n in numbers if n % 2 == 1]
print(result) |
8549bfc8831e54d4210c5679b98096dacf9e355a | lancelote/codechef_2017 | /solutions/team_formation.py | 354 | 3.765625 | 4 | def is_valid_team(total):
return not total % 2
def main():
n = int(input())
while n > 0:
total, pairs = map(int, input().split())
if is_valid_team(total):
print("yes")
else:
print("no")
for _ in range(pairs):
input()
n -= 1
if __name__ == '__main__':
main()
|
d22d99e1e9805396b7c95c944c3aca1fef5b023e | barbaragabriela/networks-generator | /common.py | 5,306 | 3.640625 | 4 | from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
def write_pajek(ntype, graph, n, k):
file = open('pajek/'+ntype+'_'+str(n)+'_'+str(k)+'.net', 'w')
file.write('*Vertices ')
file.write(str(n))
file.write('\n')
file.write('*Edges')
file.write('\n')
for node in graph:
for connection in graph[node]:
file.write(str(node + 1) + ' ' + str(connection + 1) + '\n')
file.close()
def node_degree(graph):
'''
Function that returns the degrees of a graph and the average degree
'''
degrees = []
average = 0
for node in graph:
number_of_nodes = len(graph[node])
average += number_of_nodes
degrees.append(number_of_nodes)
average = average/len(graph)
return degrees, average
def calculate_probability(k, n):
'''
Function that calculates de desired probability from a wanted degree for the ER generation
'''
edges = k * n / 2
print 'edges:', edges
p = edges / (n * (n - 1) / 2)
return p
def plot_degree_distribution(ntype, degrees, n, k, p=0.0):
'''
Function that plots the degree distribution of a network
'''
plt.hist(degrees, normed=True, stacked=True, color="#3F5D7D", bins=len(degrees))
plt.title('Degree Distribution\n Nodes = {}, Probability = {}'.format(n, round(p,2)))
plt.ylabel('Probability', fontsize=16);
plt.xlabel('Degree', fontsize=16);
fig = plt.gcf()
fig.savefig('plots/'+ntype+'_dd_'+str(n)+'_'+str(k)+'.png')
plt.show()
def plot_ccdf(ntype, degrees, n, k, p=None):
'''
Function that plots the degree distribution of a network
'''
plt.hist(degrees, normed=True, histtype='step', color="#3F5D7D", cumulative=True,bins=len(degrees))
plt.title('Complementary Cumulative Degree Distribution\n Nodes = {}, Probability = {}'.format(n, round(p,2)))
plt.ylabel('Probability', fontsize=16);
plt.xlabel('Degree', fontsize=16)
fig = plt.gcf()
fig.savefig('plots/'+ntype+'_ccdf_'+str(n)+'_'+str(k)+'.png')
plt.show()
def linear_regression(degrees, n):
probability_log = defaultdict(float)
probability = defaultdict(float)
for node in degrees:
probability_log[np.log(node)] += 1
probability[node] += 1
sum_x = sum_y = sum_xy = sum_x2 = 0
for degree in probability:
probability[degree] = np.log(probability[degree]/n)
print probability
for degree in probability_log:
y = np.log(probability_log[degree]/n)
probability_log[degree] = y
sum_x += degree
sum_y += y
sum_xy += (degree * y)
sum_x2 += (degree * degree)
a = (sum_xy - (sum_x * sum_y) / len(probability_log)) / (sum_x2 - ((sum_x ** 2) / len(probability_log)))
b = (sum_y - a * sum_x) / len(probability_log)
print 'a', a
print 'b', b
print probability
print probability_log
kmax = max(degrees)
kmin = min(degrees)
x = []
y = []
x.append(np.log(kmin))
y.append(probability_log[x[-1]])
x.append(np.log(kmax))
y.append(probability_log[x[-1]])
return x, y
def plot_log_degree_distribution(ntype, degrees, n, m, p=0.0):
'''
Function that plots the degree distribution of a network
'''
x, y = linear_regression(degrees, n)
plt.hist(np.log(degrees), normed=True, stacked=True, color="#3F5D7D", bins=len(degrees), log=True)
plt.title('Degree Distribution in Log scale\n Nodes = {}, m = {}'.format(n,m))
plt.ylabel('Probability', fontsize=16);
plt.xlabel('Degree', fontsize=16);
plt.plot(x, y, 'r--')
fig = plt.gcf()
fig.savefig('plots/'+ntype+'_log_dd_'+str(n)+'_'+str(m)+'.png')
plt.show()
# plt.semilogy(x, y, 'r--')
# plt.semilogy("log", nonposy='clip')
# plt.show()
def plot_log_ccdf(ntype, degrees, n, m, p=0.0):
'''
Function that plots the degree distribution of a network
'''
plt.hist(np.log(degrees), normed=True, histtype='step', color="#3F5D7D", cumulative=True,bins=len(degrees), log=True)
plt.title('Complementary Cumulative Degree Distribution in Log scale\n Nodes = {}, m = {}'.format(n, m))
plt.ylabel('Probability', fontsize=16);
plt.xlabel('Degree', fontsize=16)
fig = plt.gcf()
fig.savefig('plots/'+ntype+'_ccdf_'+str(n)+'_'+str(m)+'.png')
plt.show()
def mle(n, degrees):
summatory = 0.0
kmin = min(degrees)
for degree in degrees:
summatory += np.log( degree / (kmin - 1/2 ) )
thingy = summatory ** -1
result = 1 + (n * (thingy))
print 'MLE:', result
def log_histogram(degress, bins):
kmin = min(degress)
kmax = max(degress)
log_deg = []
for degree in range(len(degress)):
log_deg.append(np.log(degress[degree]))
bins_vals = np.linspace(np.log(kmin), np.log(kmax+1), bins)
digitized = np.digitize(log_deg, bins_vals)
digitized = digitized.tolist()
bins_values = [0] * bins
for i in range(bins):
bins_values[i] = digitized.count(i+1)
bins_prob = [0] * len(bins_values)
bins_prob_log = [0] * len(bins_values)
for i in range(len(bins_values)):
bins_prob[i] = bins_values[i] / float(len(degress))
if (bins_prob[i] != 0.0):
bins_prob_log[i] = np.log(bins_prob[i])
a, b = np.polyfit(bins_values, bins_prob_log, 1)
plt.loglog(bins_prob, basex=2)
plt.show()
print 'log_deg:', log_deg
print 'bins_vals', bins_vals
print 'bins_values', bins_values
print 'bins_prob', bins_prob
print a, b
|
293f7305dabdbad401a99c3ec37b17fb6bbc2ed0 | lcx94/python_daily | /data_structure/2020-06/20200627/total_hamming_distance.py | 1,519 | 4.34375 | 4 | # -*- coding:utf-8 _*-
'''
@author: lcx
@file: total_hamming_distance.py
@time: 2020/6/28 16:39
@desc:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
'''
def total_hamming_distance(nums):
'''
解释:
构建一个二维矩阵
第一维长度为31,因为最大数字10^9的二进制表达为31位
遍历每一个nums里的数字,对其进行与1的按位与操作,不记录每一个结果,二维数组的一列表示了每一个Num与1按位与操作的结果,将所有1&1相加,记录总和
二维数组遍历,生成一维数组记录所有的和
1的个数表示了该位置相等的Num的个数,而len(nums)-rec_1则表示该位置为0的个数
每个位置的hamming_distance结果即为 一个位置1的个数 * 0的个数
'''
record_ones = [0] * 31
for num in nums:
for i in range(len(record_ones)):
record_ones[i] += 1 if num & 1 else 0
num >>= 1
res = 0
for rec_1 in record_ones:
res += rec_1 * (len(nums) - rec_1)
return res
if __name__ == '__main__':
res = total_hamming_distance([4, 13, 64, 59])
print(res)
'''
Runtime: 716 ms, faster than 42.39% of Python3 online submissions for Total Hamming Distance.
Memory Usage: 15.2 MB, less than 29.60% of Python3 online submissions for Total Hamming Distance.
'''
|
2543f49f251b988ffe5d6760669c64e44fda76ab | eduhmc/CS61A | /Teoria/Class Code/fib_revisited.py | 904 | 3.625 | 4 | import timeit
from math import sqrt
def memo(f):
cache = {}
def memoized(n):
if n not in cache:
cache[n] = f(n)
return cache[n]
return memoized
@memo
def fib(n): ### Non-memoized->theta(phi^n), memoized->theta(n)
if n == 0 or n == 1:
return n
else:
return fib(n-2) + fib(n-1)
def fib_fast(n): ### theta(n)
phi = (1+sqrt(5))/2
return round((phi ** n) / sqrt(5))
def square(x):
return x*x
def exp_fast(b, n):
"""Return b to the n.
>>> exp_fast(2, 10)
1024
"""
if n == 0:
return 1
elif n % 2 == 0:
return square(exp_fast(b, n//2))
else:
return b * exp_fast(b, n-1)
def fib_veryfast(n): ### theta(log(n))
phi = (1+sqrt(5))/2
return round(exp_fast(phi,n) / sqrt(5))
#print(fib(1035))
print("Time:",timeit.timeit("fib_veryfast(35)","from __main__ import fib_veryfast", number=1)) |
86661ad52a8775db8e5eadb7cc0128c027fd4268 | cami-la/python_curso_em_video | /Mundo03:estruturas-compostas/exercicio-python#096-funcao-que-calcula-area.py | 681 | 4.3125 | 4 | from termcolor import cprint
'''
Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.
'''
def play():
exercise()
print(" Terrain control ")
print("-----------------")
area(width = float(input("Width(m): ")), length = float(input("Length(m): ")))
def exercise():
cprint("Make a program that has a function called area (), that takes the dimensions of a rectangular terrain (width and length) and shows the area of the terrain.\n","green", attrs=["blink"])
def area(width, length):
print(f"The area of terrain {width}x{length} is {width*length}m².")
|
724d7b67cc6db738f833a4a20028026547a59e62 | JorgeSchelotto/practica_2 | /archivos.py | 1,229 | 3.578125 | 4 | #!/usr/bin/env python3
import os
# Crear dentro del archivo "archivos.py" la funcion leer_archivos() que genere un diccionario en donde cada clave corresponda al nombre de un subdirectorio de "imagenes", y su valor sea una lista con los nombres de los archivos.
#Por ejemplo, para la siguiente estructura de directorios:
#./imagenes/dir06/Excepcion5.png
#./imagenes/dir06/Excepcion9.png
#./imagenes/dir07/Excepcion6.png
#./imagenes/dir02/school.jpg
#Devuelva el siguiente diccionario:
#{'dir06': ['Excepcion5.png', 'Excepcion9.png'], 'dir07': ['Excepcion6.png'], 'dir02': ['school.jpg']}
def leer_archivos(path):
"""Modulo que recibe una ruta y devuelve un diccionario cuya claves serán sus subdirectorios, y el valor por cada clave será
una lista con los archivos que se encuentran en dichos subdirectorios"""
diccio = {}
for ruta, dir, archivos in os.walk(path, topdown=False):
if os.path.split(ruta)[1] != os.path.split(path)[1]:
ruta2 = os.path.split(ruta)[1]
diccio[ruta2] = archivos
return diccio
#En la variable path debe ingresarse la ruta de la carpeta a leer o la funcion os.getcwd()
path= 'C:/Users\Mozquito\Desktop\imagenes'
print(leer_archivos(path)) |
51b64a2cf9224ca61ae797a89a725405b625cec4 | ScXin/Machine-learning-data-processing | /MatPlotLib/straightLine.py | 224 | 3.734375 | 4 | import matplotlib.pyplot as plt
import numpy as np
x1 = np.array([1,2,3])
y1 = x1
x2 = x1+1
y2 = y1+1
plt.plot(x1, y1, color='green', linestyle='dashed', marker='o',
markerfacecolor='blue', markersize=12)
plt.show() |
ca47b8d04bccd354a8153679d65de51ea33f087e | whistler420/school-projects | /bored.py | 449 | 3.640625 | 4 | from tkinter import *
def reduce(c):
global outList
outList = [0,0,0]
outList[0] = c[0]//3
outList[1] = c[1]//3
outList[2] = c[2]//3
return outList
broke = 1
try:
c0 = int(input("Please give me a value: "))
c1 = int(input("Now give me another: "))
c2 = int(input("And another: "))
col1 = (c0,c1,c2)
reduce(col1)
print(outList)
broke <= 1
except ValueError:
print("pls I said a value or integer")
broke = 1
root = Tk()
root.mainloop()
|
72c214d2b1f8357b3ab2b2e8227c4c17e0a3482e | AndrewDowns/AdventOfCode | /Day 22/Puzzle44.py | 8,187 | 3.84375 | 4 | def init_game():
"""
A function to initialise the game by loading in the player's starting hands
:return players: list
"""
fh = open("Input.txt")
players = []
for player in fh.read().split("\n\n"):
hand = []
for line in player.split("\n"):
if not line.startswith("Player"):
hand.append(int(line))
players.append(hand)
return players
def winner(players):
"""
A function to check if either player is the winner.
The winner is determined to be the player who has all of the available cards.
-------------------
players:
A list of lists that represent each played hand of cards
-------------------
:parameter players:list
:return boolean
"""
for player in players:
if len(player) == 0:
return True
return False
def play_round(players):
"""
A function to simulate one round of combat.
Before either player deals a card, if there was a previous round in this game that had exactly
the same cards in the same order in the same players' decks, the game instantly ends in a win for player 1.
Previous rounds from other games are not considered. (This prevents infinite games of Recursive Combat,
which everyone agrees is a bad idea.)
Otherwise, this round's cards must be in a new configuration; the players begin the round by each drawing the
top card of their deck as normal.
If both players have at least as many cards remaining in their deck as the value of the card they just drew,
the winner of the round is determined by playing a new game of Recursive Combat (see below).
Otherwise, at least one player must not have enough cards left in their deck to recurse; the winner
of the round is the player with the higher-value card.
As in regular Combat, the winner of the round (even if they won the round by winning a sub-game) takes
the two cards dealt at the beginning of the round and places them on the bottom of their own deck
(again so that the winner's card is above the other card). Note that the winner's card might be the lower-valued of
the two cards if they won the round due to winning a sub-game. If collecting cards by winning the round causes
a player to have all of the cards, they win, and the game ends.
-------------------
players:
A list of lists that represent each played hand of cards
-------------------
:parameter players:list
:return players:list
"""
cards_in_play = []
for i, player in enumerate(players):
card = player.pop(0)
print("Player", i+1, "plays:", card)
cards_in_play.append(card)
if cards_in_play[0] <= len(players[0]) and cards_in_play[1] <= len(players[1]):
print("Playing a sub-game to determine the winner...")
new_players = [players[0][:cards_in_play[0]], players[1][:cards_in_play[1]]]
round_winner = start_game(new_players)
if round_winner == 0:
players[round_winner].append(cards_in_play[0])
players[round_winner].append(cards_in_play[1])
else:
players[round_winner].append(cards_in_play[1])
players[round_winner].append(cards_in_play[0])
else:
if cards_in_play[0] > cards_in_play[1]:
round_winner = 0
else:
round_winner = 1
cards_in_play.sort(reverse=True)
for card in cards_in_play:
players[round_winner].append(card)
print("Player", round_winner+1, "wins the round")
return players
def instant_end_game(players, game):
"""
A function to handle the instant win rule of Recursive Combat.
Similar to end_game this function shows the results of the current game.
If the game is the main game and not a sub-game then it will finish the game.
If an instant win occurs Player 1 autmatically gets the win.
-------------------
players:
A list of lists that represent each played hand of cards
game:
An integer determining which game is currentling being played.
-------------------
:parameter players:list
:parameter game:integer
:return integer
"""
if game == 1:
print("== Post-game results ==")
for j, player in enumerate(players):
print("Player", j + 1, "hand:", player)
print("Player 1 wins the game")
print("Win by INSTANT WIN")
winner = 0
winning_score = 0
for i, card in enumerate(players[winner]):
winning_score += card * (len(players[winner])-i)
print("Winning Score:", winning_score)
else:
print("Player 1 wins game", game)
return 0
def end_game(players, game):
"""
A function to process the end of the game and show the results.
This function also handles then end of game scenario for sub-games
started during recursive combat.
-------------------
players:
A list of lists that represent each played hand of cards
game:
An integer representing the current game. Game 1 will always be the main game.
-------------------
:parameter integer
"""
if game == 1:
print("== Post-game results ==")
for j, player in enumerate(players):
print("Player", j + 1, "hand:", player)
if len(players[0]) == 0:
print("Player 2 wins game", game)
winner = 1
else:
print("Player 1 wins game", game)
winner = 0
winning_score = 0
for i, card in enumerate(players[winner]):
winning_score += card * (len(players[winner])-i)
print("Winning Score:", winning_score)
else:
if len(players[0]) == 0:
print("Player 2 wins game", game)
return 1
else:
print("Player 1 wins game", game)
return 0
def check_instant_win(players, game):
"""
A function to check if the current hand of each player has been played in this exact order before
during this game and therefore determine if this game should instantly end awarding Player 1 the win.
-------------------
players:
A list of lists that represent each played hand of cards
game:
An integer representing the current game.
-------------------
:parameter players:list
:parameter game:integer
:return boolean
"""
if players in round_record[str(game)]:
return True
else:
return False
def start_game(players):
"""
A function to start a game of combat and continue playing rounds until a winner is decided
-------------------
players:
A list of lists that represent each played hand of cards
-------------------
:parameter players:list
"""
round = 1
if len(round_record) == 0:
game = 1
else:
game = len(round_record)+1
instant_win = False
round_record[str(game)] = []
print()
print("=== Game",game,"===")
print()
while not winner(players) and not instant_win:
print("--Round", round, "Game",game, "--")
for j, player in enumerate(players):
print("Player", j+1,"hand:", player )
if not check_instant_win(players, game):
new_players = []
for i, player in enumerate(players):
new_player = []
for item in player:
new_player.append(item)
new_players.append(new_player)
round_record[str(game)].append(new_players)
players = play_round(players)
print()
round += 1
else:
print()
instant_win = True
break
if instant_win:
return instant_end_game(players, game)
else:
return end_game(players, game)
players = init_game()
round_record = dict()
start_game(players)
|
de73def3f3cceea8711dcb87170beab4fe64c5b0 | JasonDClarke/codingground | /New Project-20170705/editDictionary.py | 709 | 3.828125 | 4 | def editDictionary(dictionary, currentKey, nextKey, keyToAdd):
#if know value of next key, write value of new key as current value plus first character of next value
if (dictionary[nextKey] != None):
dictionary[keyToAdd] = dictionary[currentKey] + dictionary[nextKey][0]
#if don't know value of next key, write value of new key as current value plus first character of current value
#if you don't know the next key, the key you were about to create must have been used. The first character of
#the value of this key is the first character of the value of the current key
else:
dictionary[keyToAdd] = dictionary[currentKey] + dictionary[nextKey][0]
return dictionary |
60972ea0e909cf1e183e2177105cb1cb3b139d06 | diavy/tensorflow-without-a-phd | /tensorflow-mnist-tutorial/self_practice_mnist_2.x_five_layers.py | 5,860 | 3.53125 | 4 | ########## Deep 5-layers NN built for digit recognition ###################
############ Import modules #################
import math
import mnistdata
import tensorflow as tf
tf.set_random_seed(0)
# Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)
mnist = mnistdata.read_data_sets("data", one_hot=True, reshape=False)
########### Define input, label, training parameters (weight and bias) ################
# input X: 28 * 28 gray-scale pixels
X = tf.placeholder(dtype=tf.float32, shape=[None, 28, 28, 1], name='input_digits_2D')
# label Y_: the expected label
Y_ = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='truth_label')
# variable learning rate
#lr = tf.placeholder(tf.float32)
# Probability of keeping a node during dropout = 1.0 at test time (no dropout) and 0.75 at training time
pkeep = tf.placeholder(tf.float32)
# step for variable learning rate
step = tf.placeholder(tf.int32)
#### five layers and their number of neurons respectively. THe last layer has 10 softmax neurons #######
L, M, N, O = 200, 100, 60, 30
######## five weights matrix ###########
W1 = tf.Variable(initial_value=tf.truncated_normal([28*28, L], stddev=0.1))
W2 = tf.Variable(initial_value=tf.truncated_normal([L, M], stddev=0.1))
W3 = tf.Variable(initial_value=tf.truncated_normal([M, N], stddev=0.1))
W4 = tf.Variable(initial_value=tf.truncated_normal([N, O], stddev=0.1))
W5 = tf.Variable(initial_value=tf.truncated_normal([O, 10], stddev=0.1))
######## five bias vectors #############
# B1 = tf.Variable(initial_value=tf.zeros([L]))
# B2 = tf.Variable(initial_value=tf.zeros([M]))
# B3 = tf.Variable(initial_value=tf.zeros([N]))
# B4 = tf.Variable(initial_value=tf.zeros([O]))
# B5 = tf.Variable(initial_value=tf.zeros([10]))
# When using RELUs, make sure biases are initialised with small *positive* values for example 0.1 = tf.ones([K])/10
B1 = tf.Variable(initial_value=tf.ones([L])/10)
B2 = tf.Variable(initial_value=tf.ones([M])/10)
B3 = tf.Variable(initial_value=tf.ones([N])/10)
B4 = tf.Variable(initial_value=tf.ones([O])/10)
B5 = tf.Variable(initial_value=tf.zeros([10]))
########### Define model, expected output, loss function and training method ###########
## flatten the 28*28 image into 1 single line of pixels
XX = tf.reshape(X, shape=[-1, 28*28])
# the model
# Y1 = tf.nn.sigmoid(tf.matmul(XX, W1) + B1)
# Y2 = tf.nn.sigmoid(tf.matmul(Y1, W2) + B2)
# Y3 = tf.nn.sigmoid(tf.matmul(Y2, W3) + B3)
# Y4 = tf.nn.sigmoid(tf.matmul(Y3, W4) + B4)
# Y1 = tf.nn.relu(tf.matmul(XX, W1) + B1)
# Y2 = tf.nn.relu(tf.matmul(Y1, W2) + B2)
# Y3 = tf.nn.relu(tf.matmul(Y2, W3) + B3)
# Y4 = tf.nn.relu(tf.matmul(Y3, W4) + B4)
#
# Ylogits = tf.matmul(Y4, W5) + B5
### add drop out ###########
Y1 = tf.nn.relu(tf.matmul(XX, W1) + B1)
Y1d = tf.nn.dropout(Y1, pkeep)
Y2 = tf.nn.relu(tf.matmul(Y1d, W2) + B2)
Y2d = tf.nn.dropout(Y2, pkeep)
Y3 = tf.nn.relu(tf.matmul(Y2d, W3) + B3)
Y3d = tf.nn.dropout(Y3, pkeep)
Y4 = tf.nn.relu(tf.matmul(Y3d, W4) + B4)
Y4d = tf.nn.dropout(Y4, pkeep)
Ylogits = tf.matmul(Y4d, W5) + B5
Y = tf.nn.softmax(Ylogits)
# loss function: use built-in cross entropy with logits function to avoid log(0) if it happens
#cross_entropy = - tf.reduce_sum(Y_ * tf.log(Y))
cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=Ylogits, labels=Y_)
cross_entropy = tf.reduce_mean(cross_entropy) * 100 # make it comparable with test dataset with 10000 samples
#cross_entropy = tf.reduce_sum(cross_entropy) # this should be equal to above
# optimizer set up: GradientDecent(mini-batch), learning rate is 0.003
# lr = 0.003
# using decay learning rate
# step for variable learning rate
#step = tf.placeholder(tf.int32)
lr = 0.0001 + tf.train.exponential_decay(0.003, step, 2000, 1/math.e)
train_step = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss = cross_entropy)
# accuracy of the prediction
correct_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#########################################################################################
########################### set up training process ####################
## initialization
init = tf.global_variables_initializer() #
sess = tf.Session()
sess.run(init)
## batch training actions definition ##
def do_training(i):
batch_X, batch_Y = mnist.train.next_batch(100) # get batch-size data
##### print training accuracy and loss ############
train_a, train_c = sess.run([accuracy, cross_entropy], feed_dict={X: batch_X, Y_:batch_Y,
step:i, pkeep:1.0})
print("training " + str(i) + ": accuracy: " + str(train_a) + " loss: " + str(train_c))
##### print testing accuracy and loss ##############
test_a, test_c = sess.run([accuracy, cross_entropy], feed_dict={X: mnist.test.images, Y_:mnist.test.labels,
step:i, pkeep:1.0})
print("testing " + str(i) + ": ********* epoch " + str(i * 100 // mnist.train.images.shape[0] + 1) +
" ********* test accuracy:" + str(test_a) + " test loss: " + str(test_c))
##### backpropagation training ########
sess.run(train_step, feed_dict={X:batch_X, Y_:batch_Y, step:i, pkeep:0.75}) ### drop out at training stage
with sess:
iterations = 5000
for i in range(iterations):
do_training(i)
print("#############final performance on testing data###############")
test_a, test_c = sess.run([accuracy, cross_entropy], feed_dict={X: mnist.test.images, Y_: mnist.test.labels,
step:iterations, pkeep:1.0})
print("accuracy:" + str(test_a) + " loss: " + str(test_c))
##### print testing accuracy and loss ##############
|
adbe116fc4c8386aa47c2c2032d4d66152af8306 | Yeshwanthyk/algorithms | /leetcode/150_reverse_polish_notation.py | 1,908 | 4.3125 | 4 | """
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
"""
# Psuedocode
# ----------
# 1) Iterate through the list and add items to stack
# 2) If we come across +, -, /, * we evaluate last two digits
# 3) Keep moving through until stack is empty
# 4) Output result
import math
def eval_RPN(tokens):
stack = []
valid_operators = ("-", "+", "/", "*")
for token in tokens:
if token not in valid_operators:
stack.append(token)
else:
right = stack.pop()
left = stack.pop()
# computed_var = (eval(str(var2) + token + str(var1)))
if token == "+":
computed_var = left + right
elif token == "-":
computed_var = left - right
elif token == "*":
computed_var = left * right
else:
computed_var = left / right
if computed_var > 0:
computed_var = math.floor(computed_var)
else:
computed_var = math.ceil(computed_var)
stack.append(computed_var)
return stack.pop()
tokens = ["4", "13", "5", "/", "+"]
ans = (eval_RPN(tokens))
print(ans)
|
92180279b6add30380a514f252e90db77367b923 | ryandavis3/leetcode | /maximum_subarray/maximum_subarray.py | 1,165 | 3.953125 | 4 | from typing import List
# https://leetcode.com/problems/maximum-subarray/
def maxSubArray(nums: List[int]) -> int:
"""
Given an integer array nums, find the contiguous
subarray (containing at least one number) which has the
largest sum and return the sum.
"""
for i, val in enumerate(nums):
# Set max value and max contiguous value on first
# iteration.
if i == 0:
max_val = val
max_cont = val
continue
# Positive value and negative contiguous sum -> reset
# contiguous sum to include only value.
if val > 0 and max_cont <= 0:
max_cont = val
# Value (not necessarily positive) greater than existing
# max value -> reset contiguous sum.
elif val > max_val and max_cont <= 0:
max_cont = val
# Add value to contiguous sum.
else:
max_cont += val
# Update max contiguous sum for full array.
if max_cont > max_val:
max_val = max_cont
return max_val
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
return maxSubArray(nums)
|
5ba7c19d34025ef2452ee4035cc60ee719e10beb | manjusha18119/manju18119python | /python/mul12.py | 204 | 4.09375 | 4 | #generation of multiplication table
print("multiplication table")
x=[7*j for j in range(2,20)]
y=[8*j for j in range(2,20)]
print("multiplication of 7",x)
print("multiplication of 8",y)
print(x)
print(y)
|
0fa3c8ed3f81e46eec70ce77f0e3f7da00c34f4d | Ygormrs/Algoritmos-de-Escalonamento | /Main.py | 1,935 | 3.953125 | 4 | from funcoes import *
# MAIN
while True:
# Chamando o Menu
menu()
typeAlg = int(input('Escolha o algorítmo: '))
if typeAlg == 0:
break
# Caso o usuário entre com uma opção errada
while typeAlg < 1 or typeAlg > 5:
print('Opção Inválida, escolha os números de 1 até 5!')
typeAlg = input('Escolha o algorítmo:\n')
# FCFS
if typeAlg == 1:
typeAlg2 = int(input('1 - FCFS01\n2 - FCFS02 '))
if typeAlg2 == 0:
break
# Caso o usuário entre com uma opção errada
while typeAlg2 < 1 or typeAlg2 > 2:
print('Opção Inválida, escolha os números de 1 ou 2!')
typeAlg2 = input(':FCFS01 OU FCFS02')
if typeAlg2 == 1:
fcfs01()
if typeAlg2 == 2:
fcfs02()
# SJF
if typeAlg == 2:
typeAlg2 = int(input('1 - SJF01\n2 - SJF02\n3 - SJF03 '))
if typeAlg2 == 0:
break
# Caso o usuário entre com uma opção errada
while typeAlg2 < 1 or typeAlg2 > 3:
print('Opção Inválida, escolha os números de 1 até 3!')
typeAlg2 = input(':SJF01 / SJF02 / SJF03')
if typeAlg2 == 1:
sjf01()
if typeAlg2 == 2:
sjf02()
if typeAlg2 == 3:
sjf03()
# Round Robin (RR)
if typeAlg == 3:
typeAlg2 = int(input('1 - RR01\n2 - RR02\n3 - RR03 '))
if typeAlg2 == 0:
break
# Caso o usuário entre com uma opção errada
while typeAlg2 < 1 or typeAlg2 > 3:
print('Opção Inválida, escolha os números de 1 até 3!')
typeAlg2 = input(':RR01 / RR02 / RR03')
if typeAlg2 == 1:
rr01()
if typeAlg2 == 2:
rr02()
if typeAlg2 == 3:
rr03()
|
3de3071418e435fe99d66f62146bef426a73dfd0 | AnoopKunju/code_eval | /moderate/detecting_cycles.py2 | 1,574 | 4.1875 | 4 | #!/usr/bin/env python2
# encoding: utf-8
"""
Detecting Cycles.
Challenge Description:
Given a sequence, write a program to detect cycles within it.
Input sample:
Your program should accept as its first argument a path to a filename
containing a sequence of numbers (space delimited). The file can have multiple
such lines. E.g
2 0 6 3 1 6 3 1 6 3 1
3 4 8 0 11 9 7 2 5 6 10 1 49 49 49 49
1 2 3 1 2 3 1 2 3
Output sample:
Print to stdout the first cycle you find in each sequence. Ensure that there
are no trailing empty spaces on each line you print. E.g.
6 3 1
49
1 2 3
The cycle detection problem is explained more widely on wiki
http://en.wikipedia.org/wiki/Cycle_detection
Constrains:
The elements of the sequence are integers in range [0, 99]
The length of the sequence is in range [0, 50]
"""
import sys
with open(sys.argv[1], 'r') as input:
test_cases = input.read().strip().splitlines()
# Using Floyd's algorithm
for test in test_cases:
sequence = [int(i) for i in test.split()]
seq_length = len(sequence)
# find the cycle
x, y = 0, 1
while sequence[x] != sequence[y]:
x = (x + 1) % seq_length
y = (y + 2) % seq_length
# find the begin of the cycle
begin = 0
y, x = abs(y - x), 0
while sequence[x] != sequence[y]:
x = (x + 1) % seq_length
y = (y + 1) % seq_length
begin += 1
# find the cycle length
length, y = 1, x + 1
while sequence[x] != sequence[y]:
y += 1
length += 1
print ' '.join(str(i) for i in sequence[begin:begin + length])
|
cd459945b9f5cfbaefcbf8f99b4e0747a4804f67 | RaamRaam/python-session-1-RaamRaam | /session1.py | 442 | 3.5 | 4 | def myfunc():
string='Cppsecrets'
n=len(string)
arr=[]
for i in range(n):
for j in range(i+1,n+1):
a=string[i:j]
arr.append(a)
print(arr)
def my_func():
pass
class Rectangle:
def __init__(self, WIDTH, HEIGHT):
self.width = WIDTH
self.height = HEIGHT
def __repr__(self):
return f'Rectangle({self.width}, {self.height})'
|
4a5c17bc9754b8cc2eb1c9210861832193133e15 | summer-vacation/AlgoExec | /tencent/Tree.py | 3,823 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
File Name: Tree
Author : jing
Date: 2020/3/23
"""
class Node(object):
def __init__(self,e=None,lchild=None,rchild=None):
self.e=e
self.lchild=lchild
self.rchild=rchild
# 树类
class Tree(object):
def __init__(self, root=Node(None, None, None)):
self.root = root
self.height = 0
self.MyQueue = []
# 按层序添加节点到树中
def add(self, e):
node = Node(e)
if self.root.e == None:
self.root = node
if not node == None:
self.height += 1
self.MyQueue.append(self.root)
else:
treeNode = self.MyQueue[0]
if treeNode.lchild == None:
treeNode.lchild = node
if not node == None:
self.height += 1
self.MyQueue.append(treeNode.lchild)
else:
treeNode.rchild = node
self.MyQueue.append(treeNode.rchild)
self.MyQueue.pop(0)
# 层序遍历
def level(self):
if self.root == None:
return
MQ = []
node = self.root
MQ.append(node)
while MQ:
node = MQ.pop(0)
print(node.e)
if node.lchild:
MQ.append(node.lchild)
if node.rchild:
MQ.append(node.rchild)
# 前序遍历
def front(self, root):
if root == None:
return
print(root.e)
self.front(root.lchild)
self.front(root.rchild)
# 中序遍历
def middle(self, root):
if root == None:
return
self.middle(root.lchild)
print(root.e)
self.middle(root.rchild)
# 后序遍历
def post(self, root):
if root == None:
return
self.post(root.lchild)
self.post(root.rchild)
print(root.e)
# 定义一个树节点
class TreeNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left # 左子树
self.right = right # 右子树
# 实例化一个树节点
node1 = TreeNode("A",
TreeNode("B",
TreeNode("D"),
TreeNode("E")
),
TreeNode("C",
TreeNode("F"),
TreeNode("G")
)
)
# 前序遍历
def preTraverse(root):
if root is None:
return
print(root.value)
preTraverse(root.left)
preTraverse(root.right)
# 中序遍历
def midTraverse(root):
if root is None:
return
midTraverse(root.left)
print(root.value)
midTraverse(root.right)
# 后序遍历
def afterTraverse(root):
if root is None:
return
afterTraverse(root.right)
afterTraverse(root.left)
print(root.value)
def levelOrder(root):
# 如果根节点为空,则返回空列表
res = []
if root is None:
return res
# 模拟一个队列储存节点
q = []
# 首先将根节点入队
q.append(root)
# 列表为空时,循环终止
while len(q) != 0:
length = len(q)
for i in range(length):
# 将同层节点依次出队
r = q.pop(0)
if r.left is not None:
# 非空左孩子入队
q.append(r.left)
if r.right is not None:
# 非空右孩子入队
q.append(r.right)
print(r.value)
if __name__ == "__main__":
preTraverse(node1)
print("------------------------")
midTraverse(node1)
print("------------------------")
afterTraverse(node1)
|
7415c4136e5c35207fdf4afc258b1758d7c7aeeb | johnf24/data-structures-and-algorithms | /prime-numbers.py | 390 | 4.09375 | 4 | '''A program that displays all the prime numbers within an interval. A prime number is a number greater
than 1 that cannot be formed by multiplying two smaller numbers. The output should be 2, 3, 5'''
lower = 0
upper = 5
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num) |
87147d06bba514e50c69578b7ce972d3b4249312 | ShunKaiZhang/LeetCode | /valid_perfect_square.py | 597 | 4.21875 | 4 | # python3
# Given a positive integer num, write a function which returns True if num is a perfect square else False.
# Note: Do not use any built-in library function such as sqrt.
# Example 1:
# Input: 16
# Returns: True
# Example 2:
# Input: 14
# Returns: False
# Use Newton's Method
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
i = num
while i*i >= num:
if i*i == num:
return True
i = (i + num/i) / 2
return False
|
ae00dbf81d722eee6afb7c23809bf4093c33d9ee | dsuz/techacademy-python | /ch05ss2_1_ex.py | 236 | 3.953125 | 4 | import sys
x = 2
if x < 2:
sys.exit()
if x == 2:
print("素数")
sys.exit()
if x % 2 == 0:
sys.exit()
y = 3
while y**2 <= x:
if x % y == 0:
sys.exit()
y = y + 2
print("素数")
|
867014b8f4ab90224f70d5a4938285a040b7a8fc | Cactusson/towers | /data/components/button.py | 647 | 3.828125 | 4 | import pygame as pg
class Button(pg.sprite.Sprite):
"""
Class for buttons. They have some text on them, can change color.
Action is a function that needs to be called when button is clicked.
"""
def __init__(self, text, font, location, action):
pg.sprite.Sprite.__init__(self)
self.color = pg.Color('black')
self.font = font
self.text = text
self.action = action
self.image = self.font.render(self.text, True, self.color)
self.rect = self.image.get_rect(center=location)
def change_color(self, color):
self.image = self.font.render(self.text, True, color)
|
8b157265058c484fa433b65bb849aad57e03c4c8 | Carmenliukang/leetcode | /算法分析和归类/树/删点成林.py | 2,403 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
给出二叉树的根节点 root,树上每个节点都有一个不同的值。
如果节点值在 to_delete 中出现,我们就把该节点从树上删去,最后得到一个森林(一些不相交的树构成的集合)。
返回森林中的每棵树。你可以按任意顺序组织答案。
示例:
输入:root = [1,2,3,4,5,6,7], to_delete = [3,5]
输出:[[1,2,null,4],[6],[7]]
提示:
树中的节点数最大为 1000。
每个节点都有一个介于 1 到 1000 之间的值,且各不相同。
to_delete.length <= 1000
to_delete 包含一些从 1 到 1000、各不相同的值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-nodes-and-return-forest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# TODO 这里还是需要更加深入的理解才可以,对于递归的理解还是不够深入。
def delNodes(self, root: TreeNode, to_delete: list[int]) -> list[TreeNode]:
# 如果树为空,那么就返回 []
if not root:
return []
# 使用 set 方式提升速度
to_delete_set = set(to_delete)
# 如果 根节点 不在需要删除的节点中,那么就说明这个节点是 林中节点
ans = [root] if root.val not in to_delete_set else []
# 使用 DFS 递归尝试
def dfs(node, parent, par):
# node 为当前节点
# parent 为父节点
# par 为当前节点为 父节点的 哪一个 子树
if not node:
return
dfs(node.left, node, "left")
dfs(node.right, node, "right")
if node.val in to_delete_set:
# 如果这些数据为
if node.left:
ans.append(node.left)
if node.right:
ans.append(node.right)
# 将父节点的左右子树置位空
if par == "left":
parent.left = None
if par == "right":
parent.right = None
dfs(root, None, None)
return ans
|
d2aa10b2b310fee9f948cd922230a950ecf1b9c3 | sourishjana/demopygit | /functions_python.py | 286 | 3.78125 | 4 |
def greet():
print("hello","good morning")
greet()
greet()
def add(x,y):
c=x+y
print(c)
add(3,4)
def add(x,y):
c=x+y
return c
print(add(2,4))
def add_sub(x,y):
return(x+y),(x-y)
result1,result2=add_sub(3,4)
print(result1)
print(result2) |
7b138d896449491d855c028aa347d2184fb17958 | mrmaxguns/Misc-Python | /old/password-gen-v2.2.1.py | 1,977 | 3.953125 | 4 | '''
Password Generator
V2.2.l
Maxim Rebguns
'''
import random
from proofread import *
err = "Please select a natural number!"
def run():
def generate(c, cap, numb, x):
passw = [1]
if cap:
passw.append(2)
if numb:
passw.append(3)
if x:
passw.append(4)
caps = "QWERTYUIOPASDFGHJKLZXCVBNM"
alpha = "qwertyuiopasdfghjklzxcvbnm"
num = "1234567890"
xtra = "!@#$%^&*()_-+={}[]:;'<>?,./"
password = []
print("")
for _ in range (c):
char = random.choice((passw))
if char == 1:
password.append(random.choice(alpha))
if char == 2:
password.append(random.choice(caps))
if char == 3:
password.append(random.choice(num))
if char == 4:
password.append(random.choice(xtra))
return ''.join(password)
#amount = int(input("How many characters do you want in your password? "))
amount = integer_check("How many characters do you want in your password? ", "x", "err", 1, err, err)
if amount > 10000:
areyousure = input("WARNING! Are you sure you want to proceed? This long of a password may slow your computer. Continue? Type n to quit. ")
if areyousure == "n":
quit()
capitals1 = input("Do you want to include capitals? y/n ")
if "y" in capitals1:
capitals = True
else:
capitals = False
numbers1 = input("Do you want to include numbers? y/n ")
if "y" in numbers1:
numbers = True
else:
numbers = False
xtrachars1 = input("Do you want to include other characters? y/n ")
if "y" in xtrachars1:
xtrachars = True
else:
xtrachars = False
print(generate(amount, capitals, numbers, xtrachars))
print("Welcome to password generator Version 2")
run()
|
0e78870a72166957e482f5c1098d263493f45ed4 | nevesnunes/env | /linux/bin/sqlite_count.py | 1,371 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import csv
import os
import pprint
import sqlite3
import sys
def explore(filename, encoding):
with open(filename, 'r', encoding=encoding) as source:
csv_reader = csv.DictReader(source, delimiter=',', quotechar='"')
columns = csv_reader.fieldnames
conn = sqlite3.connect(':memory:')
curs = conn.cursor()
sql_create = 'create table main (' + \
','.join('"' + column + '"' + ' text' for column in columns) + \
')'
conn.execute(sql_create)
sql_inserts = 'insert into main (' + \
','.join('"' + column + '"' for column in columns) + \
') values ({})'.format(','.join('?' for column in columns))
for row in csv_reader:
conn.execute(sql_inserts, list(row.values()))
sql_counts = 'select ' + \
','.join('\'{0}:{1}\', count(distinct "{1}")'.format(i, column)
for i, column in enumerate(columns)) + \
'from main;'
curs.execute(sql_counts)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(curs.fetchall())
filename = sys.argv[1]
encoding = 'utf-8'
try:
with open(filename, 'r') as source:
source.read()
except UnicodeDecodeError:
encoding = 'iso-8859-1'
explore(filename, encoding)
|
b8a54e151a2edcca73bfc94f0a518ab9831dc72d | Arun-foxyy/python | /python/abstract_method.py | 786 | 4.3125 | 4 | #abstract method has only declaration and not have definition
#python default does not support abstract class
#we cann't create object
#ABC - Abstract Base Class
#And also we cann't inherit the subclass buy using abstract class
#we defind that method means we can access that
from abc import ABC,abstractmethod
class computer(ABC):
@abstractmethod
def process():
pass
class laptop(computer):
def process(self):
print("it working now")
#com = computer()
#com.process()
com1=laptop()
com1.process()
from abc import ABC,abstractmethod
class employee_name(ABC):
@abstractmethod
def info():
pass
class employee_id():
def detail(self):
print("it process")
obj = employee_id()
obj.detail()
|
769452eff66512540e0dad4818e62a880316d84a | varshanth/Coding_Algorithms | /Linked_Lists/odd_even_linked_list.py | 2,417 | 4 | 4 | '''
LeetCode: Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even
nodes. Please note here we are talking about the node number and not the value
in the nodes.
You should try to do it in place. The program should run in O(1) space
complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain as it was
in the input.
The first node is considered odd, the second node even and so on ...
Solution: Time: O(n) Space: O(n)
Algorithm:
1) Create 2 dummy heads as odd head and even head and init their nexts to
None. Init 2 iterators, odd iterator and even iterator to the respective
dummy heads
2) Use an iterator and init and iterator index to 1 (indicating that we are
starting from the 1st node) and keep track of the iterator index
3) If the iterator index is odd, update the odd_iterator.next to this
iterator and update the odd_iterator to odd_iterator.next. If the iterator
index is even, update the even_iterator.next to this iterator and update
the even_iterator to even_iterator.next
4) Update the iterator to iterator.next and repeat until iterator is None
5) At the end, update the even iterator.next to None, odd iterator.next
to the even head.next and return the odd head.next
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# Size is 0, 1, or 2
if head is None or head.next is None or head.next.next is None:
return head
head_odd = ListNode(0)
head_odd.next = None
head_even = ListNode(0)
head_even.next = None
odd_iter = head_odd
even_iter = head_even
i = 1
iterator = head
while iterator:
if i % 2 != 0:
odd_iter.next = iterator
odd_iter = odd_iter.next
else:
even_iter.next = iterator
even_iter = even_iter.next
iterator = iterator.next
i += 1
even_iter.next = None
odd_iter.next = head_even.next
return head_odd.next |
d34e61dfcf589b7e3c346a496b9efe2d27bb44e9 | MYXAMOP1337/Learning_Python | /chapter_3/otgaday_chislo.py | 866 | 3.96875 | 4 | print("\t\t\tЗдравствуй, игрок!")
print("Тебе предстоить сыграть с компьютером в 'Числа'.")
print("Надо загадать число от 1 до 100, а компьютер попытается отгадать его.")
number = int(input("Введите загаданное число: "))
computer_number = 50
tries = 1
low = 1
high = 100
print(computer_number)
while computer_number != number:
if computer_number > number:
high = computer_number
else:
low = computer_number
computer_number = low + (high - low) // 2
print(computer_number)
tries += 1
print("Компьютер потратил", tries, "попытки(ок) на отгадывание твоего числа.")
input("\n\nНажмите Enter, чтобы выйти из программы...") |
809fc06536aa9e64cbbf640eef109a099fbfc18c | soundless/alg_basics_python | /queues/BoundedQueue.py | 1,536 | 3.734375 | 4 | #!/usr/bin/env python
class BoundedQueue(object):
def __init__(self, capacity=10):
self.array = [None for i in xrange(capacity)]
self.size = 0
self.head = 0
self.tail = 0
def __repr__(self):
return repr(self.array)
def enqueue(self, item):
if self.isFull():
raise Exception("Cannot add to full queue")
self.array[self.tail] = item
self.tail = (self.tail + 1) % len(self.array)
self.size += 1
def dequeue(self):
if self.isEmpty():
raise Exception("Cannot remove from empty queue")
item = self.array[self.head]
self.array[self.head] = None
self.head = ( self.head + 1 ) % len(self.array)
self.size -= 1
return item
def peek(self):
if self.isEmpty():
raise Exception("Cannot peek into empty queue")
return self.array[self.head]
def isEmpty(self):
return self.size == 0
def isFull(self):
return self.size == len(self.array)
def size(self):
return self.size
if __name__ == '__main__':
bq = BoundedQueue(capacity=5)
bq.enqueue("A")
bq.enqueue("B")
bq.enqueue("C")
bq.enqueue("D")
bq.enqueue("E")
print bq.dequeue() == "A"
bq.enqueue("F")
print bq.peek() == "B"
print bq
print bq.size
for i in xrange(5):
print bq.dequeue()
# should be empty queue
print bq
try:
print bq.peek()
except Exception as e:
print str(e)
|
b86d3e7a1d6e9660dce8919f401e30b1f0f234f9 | emreozgoz/KodlamaEgzersizleri | /Döngüler/ikisayitopla.py | 135 | 3.703125 | 4 | sayi1 = input("1.Sayı")
sayi2 = input("2. Sayi")
toplam = 0
for i in range(int(sayi1)+1,int(sayi2)):
toplam += i
print(toplam) |
4a118eb1463d349fdc310a59ae3b113c253a3317 | andreplacet/exercicios_python | /pratica-aula9.py | 810 | 4.15625 | 4 | frase = 'Curso em video Python'
print(frase.count('o'))
print('''eae carai, vou fazer um super texo prar printar de uma vez só
sem precisar ficar fazendo varios prints''')
frase = 'Curso em video Python'
print(len(frase))
frase = ' Curso em video Python'
print(len(frase.strip()))
frase = 'Curso em video Python'
print(len(frase))
frase = 'Curso em video Python'
print(frase.replace('Python', 'Android'))
frase = 'Curso em video Python'
print('Curso' in frase)
frase = 'Curso em video Python'
print(frase.find('Python'))
frase = 'Curso em video Python'
print(frase.find('python'))
frase = 'Curso em video Python'
print(frase.lower().find('python'))
frase = 'Curso em video Python'
divido = frase.split()
print(divido)
frase = 'Curso em video Python'
dividido = frase.split()
print(dividido[2][2]) |
cd15b494b85064c30d0174f1384339a697626e5a | Dgeka24/MineSweeper | /main.py | 4,024 | 3.53125 | 4 | import Game
import Solver
def CheckName(name: str) -> bool:
if len(name) > 10:
return False
return name.isalnum()
def ArgumentsOfCreation() -> tuple:
print("Введите размеры поля и количество мин [int] [int] [int] (размеры не должны превышать 50)")
command = list(filter(None, input().split(' ')))
if len(command) != 3:
print("Неверный формат ввода")
return None, None, None
for x in command:
if not x.isdigit():
print("Неверный формат ввода")
return None, None, None
rows = int(command[0])
columns = int(command[1])
mines = int(command[2])
if rows > 50 or rows < 0 or columns > 50 or columns < 0 or mines > rows*columns or mines < 0:
print("Некорректное поле")
return None, None, None
return rows, columns, mines
def CreationCommand() -> Game.Game:
print("Создать новую игру или загрузить старую? [new/load] [name] (имя латинские буквы и цифры без пробелов, длина не более 10 символов)")
command = input()
parsed = list(filter(None, command.split(' ')))
if len(parsed) != 2:
print("Неправильный формат ввода")
return None
if parsed[0] not in ["new", "load"]:
print("Неправильный формат ввода")
return None
if not CheckName(parsed[1]):
print("Неправильный формат ввода")
return None
if parsed[0] == "new":
rows = None
columns = None
mines = None
while rows is None:
(rows, columns, mines) = ArgumentsOfCreation()
return Game.NewGame(rows, columns, mines, parsed[1])
else:
return Game.LoadGame(parsed[1])
def move(game: Game.Game):
point = (None, None)
move_type = None
while point[0] is None:
print("Сделайте ход! Координаты и тип хода [int] [int] [Flag/Open/Recommend/Solve]")
command = list(filter(None, input().split(' ')))
if len(command) == 1 and command[0] in ["Recommend", "Solve"]:
point = (1, 1)
move_type = command[0]
elif len(command) == 3 and command[0].isdigit() and command[1].isdigit() and command[2] in ["Flag", "Open", "Recommend", "Solve"]:
point = (int(command[0]), int(command[1]))
move_type = command[2]
if not game.isPointCorrect((point[0]-1, point[1]-1)):
point = (None, None)
move_type = None
print("Некорректный ход")
else:
print("Некорректный ход")
if move_type in ["Flag", "Open"]:
game.make_move(point, move_type)
elif move_type == "Recommend":
move = Solver.RecommendMove(game.player_field)
move = ((move[0][0]+1, move[0][1]+1), move[1])
if not (move is None):
print("Рекомендуемый ход: ", move)
else:
print("Нет рекомендуемого хода")
else:
while game.GameState:
move = Solver.RecommendMove(game.player_field)
if move is None:
for i in range(game.amount_of_rows):
for j in range(game.amount_of_columns):
if game.player_field[i][j] == game.CONST_FlagSymbol:
game.make_move((i+1,j+1), "Flag")
else:
move = ((move[0][0] + 1, move[0][1] + 1), move[1])
print("Ход ", move)
game.make_move(move[0], move[1])
if __name__ == '__main__':
game = None
while game is None:
game = CreationCommand()
while game.GameState:
game.printField()
move(game)
game.printField()
print("Игра завершена")
|
c7dc8870b8ecdf96278398160627573d4f680638 | KingBobJoeIV/StoreCapacityFinder | /convertdatav2.py | 1,065 | 3.5625 | 4 | import csv, sqlite3
def updateDB():
con = sqlite3.connect("store.db") # change to 'sqlite:///your_filename.db'
cur = con.cursor()
#cur.execute("CREATE TABLE IF NOT EXISTS my_table (StoreName,Type,x,y,TotalCapacitance,NumPeople,RateofTraffic);") # use your column names here
with open('store.csv','r') as fin: # `with` statement available in 2.5+
# csv.DictReader uses first line in file for column headings by default
dr = csv.DictReader(fin) # comma is default delimiter
#to_db = [(i['StoreName'], i['Type'],i['x'],i['y'],i['TotalCapacitance'],i['NumPeople'],i['RateofTraffic']) for i in dr]
for i in dr:
#print(i['NumPeople'], i['StoreName'], i['Type'])
sql_update_query = """UPDATE my_table SET NumPeople = """ + i['NumPeople'] + """ WHERE StoreName = '""" + i['StoreName'] + """'"""
print(sql_update_query)
cur.execute(sql_update_query)
#cur.executemany("INSERT OR REPLACE INTO my_table (StoreName,Type,x,y,TotalCapacitance,NumPeople,RateofTraffic) VALUES (?,?,?,?,?,?,?);", to_db)
con.commit()
con.close()
|
929756541abdebffe73fb122671a726c6ff1de70 | ATTPC/pytpc | /pytpc/utilities.py | 9,653 | 3.75 | 4 | """
Utilities
=========
Some common functions that could be useful in many places.
"""
import numpy as np
from numpy import sin, cos
from functools import wraps
import sqlite3
from xml.etree import ElementTree
from itertools import product
import os
import re
import logging
logger = logging.getLogger(__name__)
def numpyize(func):
"""Decorator that converts all array-like arguments to NumPy ndarrays.
Parameters
----------
func : function
The function to be decorated. Any positional arguments that are non-scalar
will be converted to an ndarray
Returns
-------
decorated : function
The decorated function, with all array-like arguments being ndarrays
"""
@wraps(func)
def decorated(*args, **kwargs):
newargs = list(args)
for i, a in enumerate(newargs):
if not np.isscalar(a):
newargs[i] = np.asanyarray(a)
return func(*newargs, **kwargs)
return decorated
def skew_matrix(angle):
"""Creates a left/right skew transformation matrix.
Parameters
----------
angle : float
The angle to skew by, in radians
Returns
-------
mat : ndarray
The transformation matrix
"""
mat = np.array([[1, 1/np.tan(angle)],
[0, 1]])
return mat
def rot_matrix(angle):
"""Creates a two-dimensional rotation matrix.
Parameters
----------
angle : float
The angle to rotate by, in radians
Returns
-------
mat : ndarray
The transformation matrix
"""
mat = np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
return mat
def tilt_matrix(angle):
"""Creates a 3D rotation matrix appropriate for the detector's tilt angle.
This corresponds to a rotation about the x axis of ``-angle`` radians.
Parameters
----------
angle : float
The angle to rotate by, in radians. Note that the matrix will be for a rotation of **negative** this angle.
Returns
-------
mat : ndarray
The rotation matrix
"""
mat = np.array([[1, 0, 0],
[0, np.cos(-angle), -np.sin(-angle)],
[0, np.sin(-angle), np.cos(-angle)]])
return mat
def euler_matrix(phi, theta, psi):
"""Return the Euler matrix for a three-dimensional rotation through the given angles.
The particular rotation scheme used here is z-y-z, or the following operations:
1) A rotation of phi about the z axis
2) A rotation of theta about the new y axis
3) A rotation of psi about the new z axis
The source matrices for each operation use the convention found in Goldstein [1]_, which appears to be
a negative rotation (or perhaps a passive transformation?).
Parameters
----------
phi : number
The angle for the first rotation, about z, in radians.
theta : number
The angle for the second rotation, about y, in radians.
psi : number
The angle for the third rotation, about z, in radians.
Returns
-------
mat : ndarray
The Euler angle rotation matrix.
References
----------
.. [1] Goldstein, H., Poole, C., and Safko, J. (2002). *Classical mechanics*, 3rd ed.
Addison Wesley, San Francisco, CA. Pg. 153.
"""
mat = np.array([[cos(theta)*cos(phi)*cos(psi) - sin(phi)*sin(psi),
cos(theta)*cos(psi)*sin(phi) + cos(phi)*sin(psi),
-(cos(psi)*sin(theta))],
[-(cos(psi)*sin(phi)) - cos(theta)*cos(phi)*sin(psi),
cos(phi)*cos(psi) - cos(theta)*sin(phi)*sin(psi),
sin(theta)*sin(psi)],
[cos(phi)*sin(theta), sin(theta)*sin(phi), cos(theta)]])
return mat
def constrain_angle(x):
"""Constrain the given angle to lie between 0 and 2*pi.
Angles outside the bounds are rotated by 2*pi until they lie within the bounds.
Parameters
----------
x : number
The angle to constrain, in radians.
Returns
-------
y : number
The constrained angle, which will lie between 0 and 2*pi.
"""
y = x % (2*np.pi)
if y < 0:
y += 2*np.pi
return y
def create_fields(emag, bmag, tilt):
"""Convenience function to create electric and magnetic field vectors.
Parameters
----------
emag : number
The electric field magnitude, in SI units.
bmag : number
The magnetic field magnitude, in Tesla.
tilt : number
The detector tilt angle, in radians.
Returns
-------
ef : ndarray
The electric field
bf : ndarray
The magnetic field
"""
ef = np.array([0, 0, emag])
bf_orig = np.array([0, 0, bmag])
trans = tilt_matrix(tilt)
bf = trans.dot(bf_orig)
return ef, bf
def find_vertex_energy(beam_intercept, beam_enu0, beam_mass, beam_chg, gas):
ei = beam_enu0 * beam_mass
ri = gas.range(ei, beam_mass, beam_chg) # this is in meters
rf = ri - (1.0 - beam_intercept)
ef = gas.inverse_range(rf, beam_mass, beam_chg)
return ef
def find_vertex_position_from_energy(vertex_enu0, beam_enu0, beam_mass, beam_chg, gas):
ei = beam_enu0 * beam_mass
ri = gas.range(ei, beam_mass, beam_chg) # this is in meters
rf = gas.range(vertex_enu0 * beam_mass, beam_mass, beam_chg)
return 1.0 + (rf - ri)
class SQLWriter(object):
def __init__(self, dbpath):
self.dbpath = dbpath
self.conn = sqlite3.connect(self.dbpath)
self._tables = {}
def create_table(self, name, columns):
curs = self.conn.cursor()
get_name_sql = 'SELECT name FROM sqlite_master WHERE type="table" AND name="{}"'.format(name)
if curs.execute(get_name_sql).fetchone():
logger.warning('An old table called %s was present in the DB. It will be dropped.', name)
curs.execute('DROP TABLE {}'.format(name))
self._tables[name] = columns
create_table_sql = "CREATE TABLE {name} ({items})".format(name=name,
items=', '.join([' '.join(r) for r in columns]))
curs.execute(create_table_sql)
self.conn.commit()
def write(self, name, res):
curs = self.conn.cursor()
columns = self._tables[name]
insert_sql = 'INSERT INTO {name} VALUES ({items})'.format(name=name,
items=', '.join([':{}'.format(r[0])
for r in columns]))
curs.execute(insert_sql, res)
self.conn.commit()
def find_run_number(filename):
m = re.search('run_(\d+).*', os.path.basename(filename))
if m:
return int(m.group(1))
else:
raise ValueError('Count not extract run number from filename: {}'.format(filename))
def find_exclusion_region(xcfg, lookup):
"""Read the low-gain and trigger exclusion regions from a GET config file.
The excluded pads are identified by having the `TriggerInhibition` key set to `inhibit_trigger`. The
low-gain pads are found by assuming that any pad with an individually set gain is a low-gain pad. No effort is
made to check if this is actually a lower gain than the global one.
Parameters
----------
xcfg : str or file-like
The path to the config file, or a file-like object with the contents of the config file.
lookup : dict
The pad number lookup table, as a dictionary mapping tuples (cobo, asad, aget, channel) -> pad number.
Returns
-------
excl_pads : list
The set of excluded pad numbers.
low_gain_pads : list
The set of low-gain pad numbers (see above for definition of "low-gain").
"""
tree = ElementTree.parse(xcfg)
root = tree.getroot()
excl_pads = []
low_gain_pads = []
for cobo, asad, aget, ch in product(range(10), range(4), range(4), range(68)):
path = "./Node[@id='CoBo']/Instance[@id='{}']/AsAd[@id='{}']/Aget[@id='{}']/channel[@id='{}']"
node = root.find(path.format(cobo, asad, aget, ch))
if node is not None:
trig = node.find("TriggerInhibition")
if trig is not None and trig.text == 'inhibit_trigger':
excl_pads.append(lookup[(cobo, asad, aget, ch)])
gain = node.find("Gain")
if gain is not None:
low_gain_pads.append(lookup[(cobo, asad, aget, ch)])
return sorted(excl_pads), sorted(low_gain_pads)
def read_lookup_table(path):
"""Reads the lookup table from the CSV file given by `path`.
Parameters
----------
path : str
The path to the lookup table.
Returns
-------
lookup : dict
A dictionary with tuple keys `(cobo, asad, aget, channel)` and int values `pad_number`.
"""
lookup = {}
with open(path) as f:
for line in f:
parts = line.strip().split(',')
lookup[tuple([int(i) for i in parts[:-1]])] = int(parts[-1])
return lookup
class Base(object):
"""A base class that discards all arguments sent to its initializer.
The mixins in this package take arguments in their initializers, and they pass these on to the next class in the
MRO using `super`. However, `object.__init__` does not take any arguments, so if one of these `super` calls
reaches `object`, it will cause an error. Therefore the mixins inherit from this class instead.
"""
def __init__(self, *args, **kwargs):
pass
|
1141721b8d3660b6c9ea670fe6afd2791ae138af | abhilashak/my_python_programs | /reduce.py | 229 | 3.65625 | 4 | def add(x,y):
return x+y
def sub(x,y):
return x-y
def reducee(fun,list):
""" Acts like python reduce function"""
i=0
sum=0
while(i<len(list)):
sum=fun(sum,list[i])
i=i+1
return sum
print reducee (add,range(1,11))
|
cc01271e580ba0215b5a4dcb58e6b1398826ee08 | docolou/snake_game | /snake_game.py | 6,042 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 31 15:34:28 2019
@author: a9302
"""
import pygame
import random
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# set clock of the game(數字越大越快)
Gb_game_clock = 120
# set the width and height of base surf
Gb_base_surf_width = 640
Gb_base_surf_height = 480
# set the width and height of snake and point
Gb_snake_width = 22
Gb_snake_height = 22
Gb_point_width = 22
Gb_point_height = 22
# direction of snake
HeadRight = 0
HeadLeft = 1
HeadUp = 2
HeadDown = 3
def goNextPosition( headDirection, snake_position, point_px, point_py, eatPoint ):
# get the head position
px = snake_position[0][0]
py = snake_position[0][1]
if headDirection == HeadRight:
px += 1
elif headDirection == HeadLeft:
px -= 1
elif headDirection == HeadUp:
py -= 1
elif headDirection == HeadDown:
py += 1
if eatPoint:
snake_position.insert(0, [point_px, point_py])
if len(snake_position) > 1 : # 如果有body
# 刪除最後一個 body position
snake_position.pop()
# 將頭的位置新增在最前面
snake_position.insert(0, [px, py])
else:
snake_position[0][0] = px
snake_position[0][1] = py
return snake_position
def showSnake(base_surf, snake_obj, snakeBody_obj, snake_position):
base_surf.blit(snake_obj, (snake_position[0][0], snake_position[0][1])) # 貼 snake head 在base_surf 的 snake_px, snake_py
for i in range ( len(snake_position) ):
px = snake_position[i][0]
py = snake_position[i][1]
base_surf.blit(snake_obj, (px, py)) # 貼 snake head 在base_surf 的 snake_px, snake_py
def eatFood(snake_obj, point_obj, snake_position, point_px, point_py):
# get the position of snake head
snake_px = snake_position[0][0]
snake_py = snake_position[0][1]
# get the attribute of snake and point
snake_rect_first = snake_obj.get_rect()
point_rect_first = point_obj.get_rect()
snake_rect = pygame.Rect(snake_px, snake_py, snake_rect_first.width, snake_rect_first.height)
point_rect = pygame.Rect(point_px, point_py, point_rect_first.width, point_rect_first.height)
# 如果蛇有吃到點
if snake_rect.colliderect(point_rect):
return True
else:
return False
def run():
pygame.init() # initial pygame
# set sound of the game
sound_obj = pygame.mixer.Sound('sound01.wav')
basic_font = pygame.font.SysFont("arial", 16) # 設定字型
# 開視窗
base_surf = pygame.display.set_mode((Gb_base_surf_width, Gb_base_surf_height))
# read image
snake_obj = pygame.image.load('snake_head.png') # for head of snake
snake_obj = pygame.transform.scale( snake_obj, (Gb_snake_width, Gb_snake_height) ) # 縮小圖片大小
snakeBody_obj = pygame.image.load('snake_head.png') # for body of snake
snakeBody_obj = pygame.transform.scale( snakeBody_obj, (Gb_snake_width, Gb_snake_height) ) # 縮小圖片大小
point_obj = pygame.image.load('point.jpg') # for point
point_obj = pygame.transform.scale( point_obj, (Gb_point_width, Gb_point_height) ) # 縮小圖片大小
isRunning = True # boolean for game running or not
snake_position = [] # initialize the position of snake body
snake_position.append([10, 20]) # initialize the position of snake head
print(snake_position)
direction = HeadRight # intial the direction
# set the position of point
point_px = random.randint(0, Gb_base_surf_width)
point_py = random.randint(0, Gb_base_surf_height)
player_point = 0
pygame.key.set_repeat(1) # 打開連續鍵盤輸入
main_clock = pygame.time.Clock()
while isRunning:
main_clock.tick(Gb_game_clock) # set clock of the game(數字越大越快)
for event in pygame.event.get():
if event.type == pygame.QUIT: # 使用者離開
isRunning = False
if event.type == pygame.KEYDOWN: # press keyboard
# 使用者輸入上下左右
if event.key == pygame.K_LEFT and direction != HeadRight:
direction = HeadLeft # set the direction of snake
if event.key == pygame.K_RIGHT and direction != HeadLeft:
direction = HeadRight # set the direction of snake
if event.key == pygame.K_UP and direction != HeadDown:
direction = HeadUp # set the direction of snake
if event.key == pygame.K_DOWN and direction != HeadUp:
direction = HeadDown # set the direction of snake
if event.type == pygame.MOUSEBUTTONDOWN:
sound_obj.play()
eatPoint = False
# 如果蛇有吃到點
if eatFood(snake_obj, point_obj, snake_position, point_px, point_py):
# snake body ++
player_point += 1
# change position of point
point_px = random.randint(0, ( Gb_base_surf_width - Gb_point_width ) )
point_py = random.randint(0, ( Gb_base_surf_height - Gb_point_height ) )
eatPoint = True
# snake go next position
snake_position = goNextPosition( direction, snake_position, point_px, point_py, eatPoint )
print('after next position : ', snake_position)
#設定物件屬性
base_surf.fill(BLACK) # 上色,讓上一張blit的圖片消失
#base_surf.blit(snake_obj, (snake_px, snake_py)) # 貼 img_obj 在base_surf 的px, py
showSnake(base_surf, snake_obj, snakeBody_obj, snake_position)
base_surf.blit(point_obj, (point_px, point_py)) # 貼加命菇 在base_surf 的 point_px, point_py
#更新畫面
pygame.display.update() #更新畫面
exit()
run() |
7b5da227a0ef784fac91a213b7d12ec51ff2b84e | AdnanFarra1/School | /Pre-Release_Material/Version 1/Task_1.2.py | 378 | 3.96875 | 4 | #Searching for multiple instaces
ItemDescription = [1,2,3,4,5,9,7,8,9,10]
is_found = False
search_value = int(input("Please input a search value: "))
for i in range(0,9):
if ItemDescription[i] == search_value:
print("The index of search value: ", i)
is_found = True
elif i == 9 & is_found == False:
print("The item is not found")
|
6b91f534706dddea8548fde85218c3f34798e183 | angishen/algorithms-datastructures | /ch06_strings.py | 7,607 | 4.09375 | 4 | import functools
# 6.1 Interconvert strings and ints
def str_to_int(string):
sum = 0
for i in range(len(string)):
ord_of_magnitude = len(string) - i - 1
num = ord(string[i]) - 48
sum += num * (10 ** ord_of_magnitude)
return sum
def int_to_str(integer):
string = ""
while integer > 0:
char = chr((integer % 10) + 48)
string += char
integer = integer // 10
return string[::-1]
def base_converter(st, b1, b2):
def base_to_decimal(st, b1):
sum = 0
current_place = len(st) - 1
while current_place >= 0:
if st[current_place].isalpha():
dig = ord(st[current_place]) - 55
else:
dig = int(st[current_place])
sum += dig * b1 ** (len(st) - current_place - 1)
current_place -= 1
return sum
def decimal_to_base(b2):
decimal_int = base_to_decimal(st,b1)
result_st = ""
while decimal_int > 0:
remainder = decimal_int % b2
if remainder > 9:
remainder = chr(remainder + 55)
result_st += str(remainder)
decimal_int //= b2
return result_st[::-1]
return decimal_to_base(b2)
# 6.3 COMPUTE THE SPREADSHEET ENCODING
def spreadsheet_encoding(column_name):
int_val = 0
for i, letter in enumerate(column_name):
letter = letter.upper()
ascii_val = ord(letter) - 64
power = len(column_name) - 1 - i
val = 26 ** power * ascii_val
int_val += val
return int_val
# 6.4 REPLACE AND REMOVE
def replace_and_remove(st, count):
idx, count = 0, count
result_arr = []
while count > 0 and idx < len(st):
if st[idx] == "b":
count -= 1
idx += 1
continue
elif st[idx] == "a":
result_arr.extend(["d", "d"])
count -= 1
else:
result_arr.append(st[idx])
idx += 1
return ("").join(result_arr)
# 6.5 TEST FOR PALINDROMICITY
def is_palindrome(st):
for i in range(len(st) // 2):
if st[i] != st[len(st)-1-i]:
return False
return True
# 6.6 REVERSE ALL WORDS IN A SENTENCE
def reverse_sentence(sentence):
return (" ").join(sentence.split(" ")[::-1])
def reverse_sentence2(sentence):
reversed_sentence = ""
sentence += " "
start_idx = 0
for i in range(len(sentence)):
if sentence[i].isspace() or i == len(sentence)-1:
reversed_sentence = sentence[start_idx:i] + " " + reversed_sentence
start_idx = i+1
return reversed_sentence
def reverse_sentence_BOOK(s):
# assume s is a string encoded as a bytearray
def reverse_words(s):
# first, reverse the whole string
s.reverse()
def reverse_range(s, start, end):
s[start], s[end] = s[end], s[start]
start, end = start + 1, end - 1
start = 0
while True:
end = s.find(b' ', start)
if end < 0:
break
#.reverse each word in the string
reverse_range(s, start, end-1)
start = end + 1
# reverses the last word
reverse_range(s, start, len(s)-1)
def look_and_say(n):
def next_num(prev_num):
result, i = [], 0
while i < len(prev_num):
num_occurances = 1
while i + 1 < len(prev_num) and prev_num[i] == prev_num[i+1]:
num_occurances += 1
i += 1
result.append(str(num_occurances) + prev_num[i])
i += 1
return ''.join(result)
prev_num = '1'
for i in range(1, n):
prev_num = next_num(prev_num)
return prev_num
def look_and_say_BOOK(n):
def next_number(s):
result, i = [], 0
while i < len(s):
count = 1
while i + 1 < len(s) and s[i] == s[i+1]:
i += 1
count += 1
result.append(str(count) + s[i])
i += 1
return ''.join(result)
s = '1'
for i in range(1, n):
s = next_number(s)
return s
def phone_mnemonic_BOOK(phone_number):
MAPPING = ('0', '1', 'ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ')
def phone_mnemonic_helper(digit):
if digit == len(phone_number):
mnemonics.append(''.join(partial_mnemonic))
else:
for c in MAPPING[int(phone_number[digit])]:
partial_mnemonic[digit] = c
phone_mnemonic_helper(digit + 1)
mnemonics, partial_mnemonic = [], [0] * len(phone_number)
phone_mnemonic_helper(0)
return mnemonics
def roman_to_int(roman_num):
mapping = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
exceptions = {'I': ['V', 'X'], 'X': ['L', 'C'], 'C': ['D', 'M']}
sum = 0
for letter in roman_num:
sum += mapping[letter]
for i in range(len(roman_num)-1):
if roman_num[i] in exceptions and roman_num[i+1] in exceptions[roman_num[i]]:
sum -= mapping[roman_num[i]] * 2
return sum
def roman_to_integer_BOOK(s):
T = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
return functools.reduce(
lambda val, i: val + (-T[s[i]] if T[s[i]] < T[s[i+1]] else T[s[i]]),
reversed(range(len(s)-1)), T[s[-1]])
# 6.10 COMPUTE ALL VALID IP ADDRESSES
def all_valid_ips(s):
def is_valid(substr):
return int(substr) < 256
valid_ips = []
for i in range(len(s)-1):
ip = [0] * 4
if not is_valid(s[0:i+1]):
continue
for j in range(i+1, len(s)-1):
if not is_valid(s[i+1:j+1]):
continue
for k in range(j+1, len(s)-1):
if not is_valid(s[j+1:k+1]) or not is_valid(s[k+1:]):
continue
ip[0] = s[0:i+1]
ip[1] = s[i+1:j+1]
ip[2] = s[j+1:k+1]
ip[3] = s[k+1:]
valid_ips.append(".".join(ip))
return valid_ips
# 6.11 WRITE A STRING SINUSOIDALLY
def snake_letters(st):
snake = [0] * len(st)
num_top = len(st) // 2 // 2
num_middle = len(st) // 2 if len(st) % 2 == 0 else len(st) // 2 + 1
top_idx, mid_idx, bottom_idx = 0, num_top, num_top + num_middle
odd_top = True
for i in range(len(st)):
if i % 2 == 0:
snake[mid_idx] = st[i]
mid_idx += 1
else:
if odd_top:
snake[top_idx] = st[i]
top_idx += 1
else:
snake[bottom_idx] = st[i]
bottom_idx += 1
odd_top = not odd_top
print(snake)
return "".join(snake)
# 6.12 IMPLEMENT RUN LENGTH ENCODING
def encode(st):
result = []
count = 1
if len(st) == 1:
result.append(str(count) + st)
else:
for i in range(len(st)-1):
if st[i] == st[i+1]:
count += 1
else:
result.append(str(count) + st[i])
count = 1
return "".join(result)
def decode(st):
result = []
for i in range(len(st)-1):
if st[i].isdigit():
result.append(st[i+1] * int(st[i]))
return "".join(result)
# 6.13 FIND THE FIRST OCCURANCE OF A SUBSTRING
def find_substring(s, t):
for i in range(len(t)-len(s)+1):
slice = t[i:i+len(s)]
if slice == s:
return i, i+len(s)
return None
def main():
s = "world"
t = "Hello, world, this is me, Angi, world"
print(find_substring(s, t))
main() |
19e774f02751d1d8e32b005c13bc0b4f51893ef1 | Shrijeet16/image_basicoperations | /imgp_mouse_event.py | 764 | 3.640625 | 4 |
import cv2
import numpy as np
#mouse callback function
def draw_circle(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img,(x,y),50,(255,0,234),-1)
cv2.imshow('assasa',img)
print('clicked')
#creating a black image using numpy
img = np.zeros((2048,2048,3),np.uint8)
cv2.namedWindow("assasa")
cv2.setMouseCallback('assasa',draw_circle)
while(1):
cv2.imshow('assasa',img)
if cv2.waitKey(0):
break
cv2.destroyAllWindows()
#cv2.COLOR_BGR2GRAY converts any normal image into grayscale image
#cv2.imwrite saves the imagea the image with the given arguments
#arguments in cv2.imwrite
#(name by whch image is to be saved,image to be saved)
|
d088689198729505023d1bf7176a2a9ca72f7bad | nano-machine/program | /python/seminar/sum/sum.py | 147 | 3.5625 | 4 | class Cal:
def __init__(self):
self.sum=0
def cal_sum(self,num):
for i in xrange(num):
self.sum+=i
else:
print "last_num:",i
|
7ceca3517bfdb6d412f1d0208b932b3d76f775bf | deepsjuneja/tathastu_week_of_code | /day6/program14.py | 646 | 4.0625 | 4 | n = int(input("Enter the no. of rows and columns: "))
A = []
print("Enter elements one by one: ")
for i in range(n):
matrix = []
for j in range(n):
matrix.append(int(input()))
A.append(matrix)
print("Original Matrix: ")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print()
for i in range(n):
for j in range(i,n-i-1):
temp = A[i][j]
A[i][j] = A[n-j-1][i]
A[n-j-1][i] = A[n-i-1][n-j-1]
A[n-i-1][n-j-1] = A[j][n-i-1]
A[j][n-i-1] = temp
print("Rotated Matrix: ")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print()
|
fcf496c56f8f6fc929da7cf9c4f6baa2b1580a9b | InderdipShere/xmgrace | /xmgrace_color_gray.py | 600 | 3.5625 | 4 | ###!/usr/bin/python
### This is obtained from :http://lptms.u-psud.fr/wiki/index.php/Generating_color_palette_for_Xmgrace
def LinearGray(num):
print "@map color 0 to (255, 255, 255), \"white\""
print "@map color 1 to (0, 0, 0), \"black\""
N=int(255/num)
for i in range(1,num):
n = str(N*i)
print "@map color "+str(i+1)+" to ("+n+','+n+','+n+"), \"gray"+str(i)+"\""
LinearGray(int(input("##How many number of gray shades?")))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.