blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
34e40c0c0a03ff7962e2ef4d31eca21e4d90962b | Origamijr/MusicFun | /analysis/utils.py | 524 | 3.9375 | 4 | def rationalize(x, N):
""" Rational approximation using farey's algorithm """
a, b = 0, 1
c, d = 1, 1
while (b <= N and d <= N):
mediant = float(a+c)/(b+d)
if x == mediant:
if b + d <= N:
return a+c, b+d
elif d > b:
return c, d
else:
return a, b
elif x > mediant:
a, b = a+c, b+d
else:
c, d = a+c, b+d
if (b > N):
return c, d
else:
return a, b |
3aa38b8a48b971e4d413bf0b51f4e96d4ee261d5 | chaderdwins/interview_problems | /Python/l476.py | 966 | 3.84375 | 4 | # Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
# Note:
# The given integer is guaranteed to fit within the range of a 32-bit signed integer.
# You could assume no leading zero bit in the integer’s binary representation.
# Example 1:
# Input: 5
# Output: 2
# Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
# Example 2:
# Input: 1
# Output: 0
# Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
class Solution:
def findComplement(self, num: 'int') -> 'int':
s = bin(num)[2:]
li = ''
for char in s:
if char == '0':
li += '1'
else:
li += '0'
return int(li, 2)
s = Solution()
print(s.findComplement(5)) |
1484de4271f86d8ed0436910d372d5a055f68e63 | mandark97/MazeSolving1 | /myMaze.py | 8,300 | 3.953125 | 4 | # Author: William Zhang
# Description: This is a maze solving algorithm. This is an implementation of the Wall Follower Algorithm.
# It uses the "left hand" of the robot as a means to solve the maze.
# Date: April 23, 2018
# Copyright 2018
import sys, pygame
from pygame.locals import *
import random
from entities import *
size_x = 32
size_y = 32
change_x = 32
change_y = 32
Size = 32
SPEED = 32
timer = 375
COLORS = {
'DAY9YELLOR': (255, 167, 26),
'PURPLE': (144, 124, 180),
'PINK': (255, 124, 180),
'BLUE': (50, 50, 255),
'CYAN': (55, 202, 180),
'GREEN': (55, 202, 18),
'BROWN': (113, 49, 18),
'DARKBLUE': (0, 36, 255),
'LIGHTPURPLE': (178, 174, 255),
'DARKPURPLE': (178, 53, 255),
}
DAY9YELLOW = (255, 167, 26)
GOAL = (245, 163, 183)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (200, 200, 200)
BLUE = (50, 50, 255)
DIRECTIONS = {
'up':(0, 32),
'down':(0, -32),
'right': (32, 0),
'left':(-32, 0)
}
m = 21
n = 21
goal_x = 640
goal_y = 576
# List to hold all the sprites
all_sprite_list = pygame.sprite.Group()
clock = pygame.time.Clock()
# x--->
# 0 ------------------> 21
maze = [ [1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], # 0 y
[1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1], # 1 |
[1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1], # 2 \ | /
[1,0,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,1,1,1], # 3 \ /
[1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1], # 4 `
[1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1], # 5
[1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1], # 6
[1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1], # 7
[1,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,1,1], # 8
[1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1], # 9
[1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1], # 10
[1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1], # 11
[1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1], # 12
[1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1], # 13
[1,0,0,0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1], # 14
[1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1], # 15
[1,1,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,1], # 16
[1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,1], # 17
[1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,1], # 18
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], # 19
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], # 20
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ] # 21
visited = [[[] for cell in line] for line in maze]
class Robot(pygame.sprite.Sprite):
def __init__(self, x, y, id, color=DAY9YELLOW):
# Call the parent's constructor
super().__init__()
# Set height, width
self.image = pygame.Surface([Size, Size])
self.image.fill(color)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
self.face = 5
self.lhs = 4
# Set speed vector
self.change_x = 0
self.change_y = 0
self.walls = None
self.goals = None
self.space = None
self.path = []
self.id = id
def get_directions(self):
directions = []
position_x, position_y = int(self.rect.x/32), int(self.rect.y/32)
if maze[position_x][position_y + 1] in [0,2]:
directions.append('up')
if maze[position_x][position_y - 1] in [0,2]:
directions.append('down')
if maze[position_x + 1][position_y] in [0,2]:
directions.append('right')
if maze[position_x - 1][position_y] in [0,2]:
directions.append('left')
return directions
def move(self, direction):
return (self.rect.x + direction[0], self.rect.y + direction[1])
def update(self):
""" Update the robot position. """
# Move left/right=====
self.rect.x += self.change_x
self.rect.y += self.change_y
visited[int(self.rect.x/32)][int(self.rect.y/32)].append(self.id)
self.path.append((int(self.rect.x/32), int(self.rect.y/32)))
# if(self.rect.x == goal_x) & (self.rect.y == goal_y):
# pygame.quit()
# sys.exit(0)
self.change_x = 0
self.change_y = 0
# Left-Hand Rule wall following algorithm
def LHRwallFollowing(robot, screen):
directions = robot.get_directions()
best_directions = []
good_directions = []
for direction in directions:
new_pos = robot.move(DIRECTIONS[direction])
if len(visited[int(new_pos[0]/32)][int(new_pos[1]/32)]) == 0:
best_directions.append(direction)
elif robot.id not in visited[int(new_pos[0]/32)][int(new_pos[1]/32)]:
good_directions.append(direction)
if len(best_directions) > 0:
direction = random.choice(best_directions)
elif len(good_directions) > 0:
direction = random.choice(good_directions)
else:
robot.path.pop()
robot.rect.x = robot.path[-1][0]*32
robot.rect.y = robot.path[-1][1]*32
robot.path.pop()
return
robot.change_x = DIRECTIONS[direction][0]
robot.change_y = DIRECTIONS[direction][1]
def move_robots(robots, screen, movement_function=LHRwallFollowing):
for robot in robots:
movement_function(robot, screen)
def create_entities():
# Make the walls. (x_pos, y_pos, width, height)
wall_list = pygame.sprite.Group()
# Make the goal. (x_pos, y_pos, width, height)
goal_list = pygame.sprite.Group()
# Make the space. (x_pos, y_pos, width, height)
space_list = pygame.sprite.Group()
# robots
robots = pygame.sprite.Group()
for j in range(0, n):
for i in range(0, m):
if(maze[i][j] == 1):
wall = Wall(i*32, j*32, Size, Size)
wall_list.add(wall)
all_sprite_list.add(wall)
if(maze[i][j] == 2):
goal = Goal(i*32, j*32, Size, Size)
goal_list.add(wall)
all_sprite_list.add(goal)
if(maze[i][j] == 0):
space = Space(i*32, j*32, Size, Size)
space_list.add(space)
all_sprite_list.add(space)
for index, color in enumerate(COLORS.values()):
robot = Robot(32, 32, index, color=color)
robot.face = 1
robot.lhs = 0
robot.walls = wall_list
robot.goals = goal_list
robot.space = space_list
robots.add(robot)
all_sprite_list.add(robot)
return wall_list, goal_list, space_list, robots, all_sprite_list
def init_game():
pygame.init()
size = width, height = 640, 640
screen = pygame.display.set_mode(size)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill(WHITE)
return screen
def create_visited(visited_cells):
visited_cells.empty()
for i, line in enumerate(visited):
for j, cell in enumerate(line):
if len(cell) > 0:
visited_cells.add(VisitedLocation(i*32, j*32, Size, Size))
def all_visited():
for i, line in enumerate(visited):
for j, cell in enumerate(line):
if len(cell) == 0 and maze[i][j] == 0:
return False
pygame.quit()
return True
def main():
screen = init_game()
_, _, _, robots, all_sprite_list = create_entities()
visited_cells = pygame.sprite.Group()
clock = pygame.time.Clock()
iterations = 0
while not all_visited():
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
move_robots(robots, screen, LHRwallFollowing)
all_sprite_list.update()
screen.fill(GREY)
create_visited(visited_cells)
visited_cells.draw(screen)
all_sprite_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.time.wait(timer)
iterations +=1
print('{0} iterations to finish'.format(iterations))
pygame.quit()
if __name__ == '__main__':
main()
|
78cc09b08fe901023131cdf1705493604982eab0 | venkateshsuvarna/box-plot-python | /assignment2.py | 406 | 3.515625 | 4 |
#Necessary imports
import pandas as pd
import matplotlib.pyplot as plt
# Reading data locally
df = pd.read_csv('/Users/Venkatesh Suvarna/PycharmProjects/DataMining_Assignment2/winequality-red.csv',sep=';')
#plotting boxplot
ax = df.plot(title = 'Box Plot of Various Parameters for Red Wine Dataset', kind = 'box')
ax.set_xlabel('Columns for Wine Quality Data Set')
ax.set_ylabel('Number of instances')
plt.show(ax) |
d743a49af0739e7c5ed29dc5e341dbc7a1b1f9e9 | sbtries/Class_Polar_Bear | /Code/Derrick/Python/lab5_Blackjack/blackjack_helper.py | 1,881 | 3.828125 | 4 | import random
# vars #
cards = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10,
}
playerCards = {
'firstCard': input('What is your first card'),
'secondCard': input('What is your second card'),
'thirdCard': input('What is your third card?')
}
sum = 0
# functions #
def printTotal(msg):
print(msg)
def hitStayBust(n):
if n == 21:
printTotal(n)
print('BLACKJACK!')
exit()
elif n > 21:
printTotal(n)
print('BUST!')
exit()
elif n > 17 and n < 21:
printTotal(n)
print('Stay.')
exit()
else:
while n < 21:
if n < 17:
printTotal(n)
print('Hit.')
randChoice = random.choice(list(cards.keys()))
randCard = cards[randChoice]
n += randCard
print(f'Your newest card has a value of {randChoice}. Your total is now {n}')
if n > 21:
print('BUST')
break
if n == 21:
print('BLACKJACK!')
break
else:
continue
elif n == 21:
printTotal(n)
print('BLACKJACK!')
break
else:
printTotal(n)
print('Stay.')
break
# Logic #
for card in playerCards:
if playerCards[card] == 'A':
playerCards[card] = 1
elif playerCards[card] == 'J' or playerCards[card] == 'Q' or playerCards[card] == 'K':
playerCards[card] = 10
else:
playerCards[card] = int(playerCards[card])
sum += playerCards[card]
# Run blackjack helper #
hitStayBust(sum)
|
1a6ec2ec6572e629fc49f64ae34dd0c6f1d56397 | dineshkumarsarangapani/leetcode-solutions | /python/source/dynamic_programming/max_subarray.py | 483 | 3.625 | 4 | import sys
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
current_sum = best_sum = ~sys.maxsize
for i in range(0, len(nums)):
current_sum = max(nums[i], current_sum + nums[i])
best_sum = max(current_sum, best_sum)
return best_sum
if __name__ == '__main__':
s = Solution()
a = s.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
print(a)
|
be79a446df8c29d80bfabf93ccc24658b5fe4e2d | Yuuuuumk/DS | /hw/HW3Solution/Question4_pascal.py | 330 | 3.546875 | 4 | def pascal(n):
if n ==1:
return [[1]]
else:
newline = [1]
for i in range(n-2):
ele = pascal(n-1)[n-2][i]+pascal(n-1)[n-2][i+1]
newline.append(ele)
newline.append(1)
return pascal(n-1)+[newline]
#print(pascal(1)) # [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] |
b3c9e5b73f0bfcdddebac325bcd2d8cc8d74e00a | xiaokexiang/start_python | /csv/_write_.py | 437 | 3.765625 | 4 | """
csv写入
"""
import csv
class Write:
def __init__(self, filename):
self.filename = filename
def write(self):
with open(self.filename, 'w', newline='') as f: # 取消换行
writer = csv.writer(f)
for row in [['1', '2', '3'], ['4', '5', '6']]: # 写入数据到csv
writer.writerow(row)
if __name__ == '__main__':
write = Write('output.csv')
write.write()
|
c7c0f857c94c378841927cfcbb3faf5f6229f9e5 | denysdenys77/Beetroot_Academy | /data_structures/queue.py | 966 | 4.125 | 4 | # Реализовать работу очереди (добавление/удаление элементов) на основе связного списка.
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return f'Data: {self.data}. Next node object: {self.next.data}'
class Queue:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def dell(self):
prev = None
curr = self.head
while curr.next is not None:
prev = curr
curr = curr.next
prev.next = None
del curr
def print_llist(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
q = Queue()
q.push(1)
q.push(2)
q.push(3)
q.print_llist()
q.dell()
print()
q.print_llist() |
90b9f7bf07d3b19e5357e7b257ec53ac8603b500 | HarperHao/python | /exercise/021.py | 933 | 4 | 4 | """
题目:将一个正整数分解质因数。
例如:输入90,打印出90=2*3*3*5。
"""
def fun(number):
list1 = fun1(number)
list2 = []
for i in list1:
while number != 1:
if number % i == 0:
number = number / i
list2.append(i)
else:
break
return list2
# 求出[2,number]间所有的质因数
def fun1(number):
list1 = []
list1.append(2)
j = 2
for i in range(3, number + 1):
while j < i:
if i % j != 0:
j = j + 1
else:
break
if j == i:
list1.append(i)
return list1
number = int(input("请输入一个数:"))
list2 = fun(number)
print('{} = '.format(number), end='')
for i in range(len(list2)):
if i == len(list2) - 1:
print('{}'.format(list2[i]))
else:
print('{}'.format(list2[i]), end=' * ')
|
75969f36ee2aee9d3b0f9083393193a58a58db32 | Dania-sl/KOL_2 | /22.py | 381 | 3.671875 | 4 | '''
Знайти добуток елементів масиву, кратних 3 і 9. Розмірність масиву - 10.
Заповнення масиву здійснити випадковими числами від 5 до 500.
'''
import numpy as np
X = np.random.randint(5, 500, 10)
s = 1
for i in X:
if i % 3 == 0:
s *= i
print(X)
print(s)
|
e5d3b28b071fcef8f63f0ebce85f027f57f92650 | tinawu-23/christmas-2019 | /d1/rocket2.py | 259 | 3.734375 | 4 | def getfuel(fuel):
fuel = fuel // 3 - 2
if fuel < 9:
return fuel
fuel += getfuel(fuel)
return fuel
total = 0
with open('input.txt') as f:
for line in f:
mass = int(line.strip())
total += getfuel(mass)
print(total)
|
599f604d8db57cb72aeca89f75e8998175fe8550 | JohnOiko/python-learning-projects | /school_database/school_database.py | 14,401 | 3.78125 | 4 | from pupils import Pupils
from teachers import Teachers
from lessons import Lessons
def input_menu_choice():
# read action type choice
action_type_choice = input("Available actions:\n"
"1. Manage pupils\n"
"2. Manage teachers\n"
"3. Manage lessons\n"
"4. Exit application\n\n"
"Pick an action: ").strip()
while action_type_choice not in [str(number) for number in range(1, 5)]:
action_type_choice = input("Pick an action (1 to 4): ")
print(f"\n{'=' * 75}\n")
if action_type_choice == "4":
return 13
if action_type_choice == "1":
action_choice_menu = ("Available actions:\n"
"1. Create pupil\n"
"2. Print pupil(s)\n"
"3. Update pupil\n"
"4. Delete pupil\n"
"5. Exit application\n\n"
"Pick an action: ")
elif action_type_choice == "2":
action_choice_menu = ("Available actions:\n"
"1. Create teacher\n"
"2. Print teacher\n"
"3. Update teacher\n"
"4. Delete teacher\n"
"5. Exit application\n\n"
"Pick an action: ")
else:
action_choice_menu = ("Available actions:\n"
"1. Create lesson\n"
"2. Print lesson\n"
"3. Update lesson\n"
"4. Delete lesson\n"
"5. Exit application\n\n"
"Pick an action: ")
action_choice = input(action_choice_menu).strip()
while action_choice not in [str(number) for number in range(1, 6)]:
action_choice = input("Pick an action (1 to 5): ")
print(f"\n{'=' * 75}\n")
if action_choice == "5":
return 13
return (int(action_type_choice) - 1) * 4 + int(action_choice)
def create_pupil(pupils):
pupils.create_pupil()
def print_pupils(pupils):
# if the pupils database is empty, print an according message and return
if len(pupils.pupils) == 0:
print("No pupils saved in the database currently.")
return
# read action choice
action_choice = input("Available actions:\n"
"1. Print single pupil\n"
"2. Print all pupils with extensive info\n"
"3. Print all pupils with basic info\n\n"
"Pick an action: ").strip()
while action_choice not in {"1", "2", "3"}:
action_choice = input("Pick an action (1 to 3): ")
print(f"\n{'=' * 75}\n")
action_choice = int(action_choice)
if action_choice == 1:
# read the pupil's id
pupil_id = input("Give the id of the student you want printed: ").strip()
while not pupil_id.isdigit() or int(pupil_id) <= 1000:
pupil_id = input("Give the student's id (must be an integer >= 1000): ").strip()
print()
# find the pupil in the database
pupil = pupils.search_pupil_by_id(pupil_id)
if pupil is not None:
print(f"{pupil}")
else:
print("Pupil not in the system.")
elif action_choice == 2:
print(pupils)
else:
pupils.print_pupils_names()
def update_pupil(pupils):
# read search type
search_type = input("Do you want to search by id (\"i\") or by last name (\"s\"): ").strip().lower()
while search_type != "i" and search_type != "s":
search_type = input("Pick a valid search method (\"i\" for id or \"s\" for last name): ").strip().lower()
# search by id
if search_type == "i":
# read id to search for
pupil_id = input("Give an id to search for: ").strip()
if not pupil_id.isdigit() or int(pupil_id) <= 1000:
pupil_id = input("Give an id to search for (must be an integer >= 1000): ").strip()
pupil_id = int(pupil_id)
pupils.pupil_update(pupil_id)
# search by last name
else:
# read last name to search for
last_name = input("Give a last name to search for: ").strip().capitalize()
if not last_name.isalpha() or len(last_name) < 1:
last_name = input("Give a valid last name to search for: ").strip().capitalize()
pupils_to_be_updated = pupils.search_pupil_by_last_name(last_name)
# if no pupils with the searched for last name were found print error message
if len(pupils_to_be_updated) == 0:
print("There is no pupils in the database with the given last name.")
# else if only one pupil was found update their information
elif len(pupils_to_be_updated) == 1:
print(f"\n{'=' * 75}\n")
print(f"{pupils_to_be_updated[0]}\n\n{'=' * 75}\n")
pupils.input_updated_details(pupils_to_be_updated[0])
# else if more than one pupils were found, let the user pick one based on their id and update their information
else:
# print each pupil found and their id
print("Here is the list of students that match the last name you entered:")
for pupil in pupils_to_be_updated:
print(f"\n{pupil}")
# keep reading ids until the one given exists in the list of pupils found with the given last name
pupil_to_be_updated = None
pupil_id = input("\nGive the id of the pupil whose details you want to update: ").strip()
if pupil_id.isdigit() and int(pupil_id) > 1000:
for pupil in pupils_to_be_updated:
if pupil.pupil_id == int(pupil_id):
pupil_to_be_updated = pupil
break
while pupil_to_be_updated is None:
pupil_id = input("Give the id of the pupil whose details you want to update: ")
if pupil_id.isdigit() and int(pupil_id) > 1000:
for pupil in pupils_to_be_updated:
if pupil.pupil_id == int(pupil_id):
pupil_to_be_updated = pupil
break
print(f"\n{'=' * 75}\n")
# update the information of the pupil chosen based on their last name and id
pupils.input_updated_details(pupil_to_be_updated)
def delete_pupil(pupils, lessons):
# read search type for deletion
deletion_type = input("Do you want to delete by id (\"i\") or by last name (\"s\"): ").strip().lower()
while deletion_type != "i" and deletion_type != "s":
deletion_type = input("Pick a valid deletion method (\"i\" for id or \"s\" for last name): ").strip().lower()
# delete by id
if deletion_type == "i":
# read id to search for
pupil_id = input("Give the id of the student you want to delete: ").strip()
if not pupil_id.isdigit() or int(pupil_id) <= 1000:
pupil_id = input("Give the id of the student you want to delete (must be an integer > 1000): ").strip()
pupil_id = int(pupil_id)
pupils.delete_pupil_by_id(pupil_id)
lessons.delete_pupil(pupil_id)
# search by last name
else:
# read last name to search for
last_name = input("Give the last name of the student you want to delete: ").strip().capitalize()
if not last_name.isalpha() or len(last_name) < 1:
last_name = input("Give the valid last name of the student you want to delete: ") \
.strip().capitalize()
pupils_to_be_deleted = pupils.search_pupil_by_last_name(last_name)
# if no pupils with the searched for last name were found print error message
if len(pupils_to_be_deleted) == 0:
print("There are no pupils in the database with the given last name.")
# else if only one pupil was found delete them
elif len(pupils_to_be_deleted) == 1:
pupils.delete_pupil_by_id(pupils_to_be_deleted[0].pupil_id)
lessons.delete_pupil(pupils_to_be_deleted[0].pupil_id)
# else if more than one pupils were found, let the user pick one based on their id and delete them
else:
# print each pupil found and their id
print("Here is the list of students that match the last name you entered:")
for pupil in pupils_to_be_deleted:
print(f"\n{pupil}")
# keep reading ids until the one given exists in the list of pupils found with the given last name
pupil_to_be_deleted = None
pupil_id = input("\nGive the id of the pupil you want to delete: ").strip()
if pupil_id.isdigit() and int(pupil_id) > 1000:
for pupil in pupils_to_be_deleted:
if pupil.pupil_id == int(pupil_id):
pupil_to_be_deleted = pupil
break
while pupil_to_be_deleted is None:
pupil_id = input("Give the id of the pupil you want to delete: ")
if pupil_id.isdigit() and int(pupil_id) > 1000:
for pupil in pupils_to_be_deleted:
if pupil.pupil_id == int(pupil_id):
pupil_to_be_deleted = pupil
break
print(f"\n{'=' * 75}\n")
# delete the selected pupil
pupils.delete_pupil_by_id(pupils_to_be_deleted[0].pupil_id)
lessons.delete_pupil(pupils_to_be_deleted[0].pupil_id)
def create_teacher(teachers):
# read name
first_name = input("Give first name: ").strip().capitalize()
while not first_name.isalpha():
first_name = input("Give first name (must only include letters): ").strip().capitalize()
# read last name
last_name = input("Give last name:\t ".expandtabs(16)).strip().capitalize()
while not last_name.isalpha():
last_name = input("Give last name (must only include letters): ").strip().capitalize()
# create the new teacher
teachers.create_teacher(first_name, last_name)
def print_teacher(teachers):
# if the teachers database is empty, print an according message and return
if len(teachers.teachers) == 0:
print("No teachers saved in the database currently.")
return
# else find the teacher that matches the given teacher id and print their information
teacher = teachers.read_teacher(teachers.input_teacher_id("print"))
if teacher is None:
print("No teacher with the given id in the database.")
else:
print(f"\n{teacher}")
def update_teacher(teachers):
# if the teachers database is empty, print an according message and return
if len(teachers.teachers) == 0:
print("No teachers saved in the database currently.")
return
# else if there are teachers in the database update the teacher that matches the given teacher id
teachers.update_teacher(teachers.input_teacher_id("update"))
def delete_teacher(teachers, lessons):
teachers.delete_teacher(lessons)
def create_lesson(lessons):
# read lesson name
lesson_name = input("Give lesson's name: ").strip().capitalize()
while not lesson_name.isalpha():
lesson_name = input("Give lesson's name (must only include letters): ").strip().capitalize()
# create the new teacher
lessons.create_lesson(lesson_name)
def print_lesson(lessons, teachers, pupils):
# if the lessons database is empty, print an according message and return
if len(lessons.lessons) == 0:
print("No lessons saved in the database currently.")
return
# else find the lesson that matches the given lesson id and print their information
lesson = lessons.read_lesson(lessons.input_lesson_id("print"))
if lesson is None:
print("No lesson with the given id in the database.")
else:
print(f"\n{lesson.to_string(teachers, pupils)}")
def update_lesson(lessons, teachers, pupils):
# if the lessons database is empty, print an according message and return
if len(lessons.lessons) == 0:
print("No lessons saved in the database currently.")
return
# else if there are lessons in the database update the lesson that matches the given lesson id
lessons.update_lesson(lessons.input_lesson_id("update"), teachers, pupils)
def delete_lesson(lessons):
lessons.delete_lesson()
def main():
# load pupils and teachers from the disk
pupils = Pupils()
teachers = Teachers()
lessons = Lessons()
# print the action menu and read the user's desired action
print(f"{'=' * 75}\n")
action_choice = input_menu_choice()
# keep completing actions until the user chooses to exit the application (action 9)
while action_choice != 13:
# perform the action that corresponds to the index of the user's action choice
if action_choice == 1:
create_pupil(pupils)
elif action_choice == 2:
print_pupils(pupils)
elif action_choice == 3:
update_pupil(pupils)
elif action_choice == 4:
delete_pupil(pupils, lessons)
elif action_choice == 5:
create_teacher(teachers)
elif action_choice == 6:
print_teacher(teachers)
elif action_choice == 7:
update_teacher(teachers)
elif action_choice == 8:
delete_teacher(teachers, lessons)
elif action_choice == 9:
create_lesson(lessons)
elif action_choice == 10:
print_lesson(lessons, teachers, pupils)
elif action_choice == 11:
update_lesson(lessons, teachers, pupils)
elif action_choice == 12:
delete_lesson(lessons)
# print separator after every completed action and read the next action after printing the main menu
print(f"\n{'=' * 75}\n")
action_choice = input_menu_choice()
# save the pupils' and teachers' data in a json file in the disk
pupils.save_pupils_data()
teachers.save_teachers_data()
lessons.save_lessons_data()
print(f"Exiting application.\n\n{'=' * 75}")
main()
|
f2065463f3c9e0f69a6f5f5f8e84f8806bdbc233 | HenDGS/Aprendendo-Python | /python/while.py | 161 | 4.09375 | 4 | numero=1
while numero<6:
print(numero)
numero+=1
mensagem=input("Digite 'quit' para sair: ")
while mensagem != "quit":
print(mensagem)
mensagem=input()
|
ec7fcea25d4300af41c68517818f08347cb3e725 | soo-youngJun/pyworks | /exercise/test03.py | 896 | 3.796875 | 4 | # p. 146 1번
a = "Life is too short, you need python"
if "wife" in a:
print("wife")
elif "python" in a and "you" not in a:
print("python")
elif "shirt" not in a:
print("shirt")
elif "need" in a:
print("need")
else:
print("none")
# 2번
result = 0
i = 1
while i <= 1000:
if i % 3 == 0:
result += i
i += 1
print(result)
# 3번
'''
i = 0
while True:
i += 1
if i > 5:
break
print("*" * i)
'''
for i in range(1, 6):
for j in range(1, i+1):
print("*", end=" ")
print()
# 4번
'''
for i in range(1, 101):
print(i)
'''
# 5번
A = [70,60,55,75,95,90,80,80,85,100]
total = 0
for score in A:
total += score
avg = total / len(A)
print(avg)
# 6번
numbers = [1,2,3,4,5]
'''
result = []
for n in numbers:
if n % 2 ==1:
result.append(n*2)
'''
result = [n * 2 for n in numbers if n % 2 == 1]
print(result)
|
da20d6f568ec568428815be0bd8e9689060f4138 | ucaiado/Customer_Segments | /eda.py | 7,472 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Library to explore the the dataset used
@author: ucaiado
Created on 05/16/2016
"""
# load required libraries
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def features_boxplot(all_data, samples, indices, b_log=False):
'''
Return a matplotlib object with a boxplot of all features in the dataset
pointing out the data in the sample using dots. The legend is the indices
of the sample in all_data
:param all_data: DataFrame. all dataset with 6 columns
:param samples: DataFrame. a sample of all data with 6 columns and 3 lines
:param indices: list. the original indices of the sample in all_data
'''
# reshape the datasets
data2 = pd.DataFrame(all_data.stack())
data2.columns = ['annual spending']
data2.index.names = ['IDX', 'Product']
data2.reset_index(inplace=True)
# reshape the sample
samples2 = samples.copy()
samples2.index = indices
samples2 = pd.DataFrame(samples2.stack())
samples2.columns = ['annual spending']
samples2.index.names = ['IDX', 'Product']
samples2.reset_index(inplace=True)
samples2.index = samples2.IDX
# Plot the annual spending with horizontal boxes
ax = sns.boxplot(x='annual spending', y='Product', data=data2,
whis=np.inf, color='lightgrey')
# Add in points to show each selected observation
sns.stripplot(x='annual spending',
y='Product',
data=samples2,
hue='IDX',
size=9,
palette=sns.color_palette('Set2', 5),
linewidth=0)
if b_log:
ax.set_xscale('log')
ax.set_xlabel('log(annual spending)')
# insert a title
ax.set_title('Annual Spending in Monetary Units by Product',
fontsize=16, y=1.03)
return ax
def cluster_results(reduced_data, preds, centers, pca_samples):
'''
Visualizes the PCA-reduced cluster data in two dimensions
Adds cues for cluster centers and student-selected sample data
:param reduced_data: pandas dataframe. the dataset transformed and cleaned
:param preds: numpy array. teh cluster classification of each datapoint
:param centers: numpy array. the center of the clusters
:param pca_samples: numpy array. the sample choosen
'''
predictions = pd.DataFrame(preds, columns=['Cluster'])
plot_data = pd.concat([predictions, reduced_data], axis=1)
# Generate the cluster plot
fig, ax = plt.subplots(figsize=(14, 8))
# Color map
cmap = sns.color_palette('Set2', 11)
# Color the points based on assigned cluster
for i, cluster in plot_data.groupby('Cluster'):
cluster.plot(ax=ax, kind='scatter', x='Dimension 1', y='Dimension 2',
color=cmap[i],
label='Cluster %i' % (i),
s=30)
# Plot centers with indicators
for i, c in enumerate(centers):
ax.scatter(x=c[0], y=c[1], color='white', edgecolors='black',
alpha=1, linewidth=2, marker='o', s=200)
ax.scatter(x=c[0], y=c[1], marker='$%d$' % (i), alpha=1, s=100)
# Plot transformed sample points
ax.scatter(x=pca_samples[:, 0], y=pca_samples[:, 1],
s=150, linewidth=4, color='black', marker='x')
# Set plot title
s_title = 'Cluster Learning on PCA-Reduced Data - Centroids Marked by'
s_title += ' Number\nTransformed Sample Data Marked by Black Cross\n'
ax.set_title(s_title, fontsize=16)
def channel_results(reduced_data, outliers, pca_samples, na_index):
'''
Visualizes the PCA-reduced cluster data in two dimensions using the full
dataset Data is labeled by "Channel" and cues added for student-selected
sample data
:param reduced_data: pandas dataframe. the dataset transformed and cleaned
:param outliers: list. the datapoint considered outliers
:param pca_samples: numpy array. the sample choosen
:param pca_samples: numpy array. the original IDs of the sample
'''
# Check that the dataset is loadable
try:
full_data = pd.read_csv('customers.csv')
except:
print 'Dataset could not be loaded. Is the file missing?'
return False
# Create the Channel DataFrame
channel = pd.DataFrame(full_data['Channel'], columns=['Channel'])
channel = channel.drop(channel.index[outliers]).reset_index(drop=True)
labeled = pd.concat([reduced_data, channel], axis=1)
# Generate the cluster plot
fig, ax = plt.subplots(figsize=(14, 8))
# Color map
# cmap = cm.get_cmap('gist_rainbow')
cmap = sns.color_palette('Set2', 11)
# Color the points based on assigned Channel
labels = ['Hotel/Restaurant/Cafe', 'Retailer']
grouped = labeled.groupby('Channel')
for i, channel in grouped:
channel.plot(ax=ax, kind='scatter', x='Dimension 1', y='Dimension 2',
color=cmap[i],
label=labels[i-1],
s=30)
# Plot transformed sample points
for i, sample in zip(na_index, pca_samples):
ax.scatter(x=sample[0], y=sample[1], s=200,
linewidth=3,
color='black',
marker='o',
facecolors='none')
ax.scatter(x=sample[0]+0.25, y=sample[1]+0.3,
marker='$%d$' % (i),
alpha=1,
s=125)
# Set plot title
s_title = 'PCA-Reduced Data Labeled by "Channel"\nTransformed Sample Data'
s_title += ' Circled'
ax.set_title(s_title)
def pca_results(good_data, pca):
'''
Create a DataFrame of the PCA results. Includes dimension feature weights
and explained variance Visualizes the PCA results
:param good_data: DataFrame. all dataset log transformed with 6 columns
:param pca: Sklearn Object. a PCA decomposition object already fitted
'''
# Dimension indexing
dimensions = dimensions = ['Dimension {}'.format(i)
for i in range(1, len(pca.components_)+1)]
# PCA components
components = pd.DataFrame(np.round(pca.components_, 4),
columns=good_data.keys())
components.index = dimensions
# PCA explained variance
ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)
variance_ratios = pd.DataFrame(np.round(ratios, 4),
columns=['Explained Variance'])
variance_ratios.index = dimensions
# reshape the data to be plotted
df_aux = components.unstack().reset_index()
df_aux.columns = ['Feature', 'Dimension', 'Variance']
# Create a bar plot visualization
fig, ax = plt.subplots(figsize=(14, 8))
# Plot the feature weights as a function of the components
sns.barplot(x='Dimension', y='Variance', hue='Feature', data=df_aux, ax=ax)
ax.set_ylabel('Feature Weights')
ax.set_xlabel('')
ax.set_xticklabels(dimensions, rotation=0)
# Display the explained variance ratios
for i, ev in enumerate(pca.explained_variance_ratio_):
ax.text(i-0.40, ax.get_ylim()[1] + 0.05,
'Explained Variance\n %.4f' % (ev))
# insert a title
# ax.set_title('PCA Explained Variance Ratio',
# fontsize=16, y=1.10)
# Return a concatenated DataFrame
return pd.concat([variance_ratios, components], axis=1)
|
63693d3d7a2e22471bd212f1efe14d2324eff391 | rishinkaku/Software-University---Software-Engineering | /Programming-Basics/For Loop/Number sequence/Number sequence.py | 173 | 3.71875 | 4 | n = int(input())
min = 0
max = 0
l = list()
for i in range(n):
num = int(input())
l.append(num)
l.sort()
print(f"Max number: {l[-1]}")
print(f"Min number: {l[0]}")
|
7ad3a64a8e1d676c7af64c7df1d9871d3f0859cc | Reshma081996/Python_Django | /variable_length_args/nested_dict_employee.py | 1,510 | 4.125 | 4 | employee={
1000:{"id":1000,"name":"tom","salary":25000,"exp":1},
1001:{"id":1001,"name":"jhon","salary":30000,"exp":2},
1002:{"id":1002,"name":"danie","salary":35000,"exp":2},
1003:{"id":1003,"name":"jack","salary":30000,"exp":2}
}
# nested dictionary
#if 1000 in employee: # key 1000 values
#print(employee[1000]) # check for key 1000 in employees
#{'id': 1000, 'name': 'tom', 'salary': 25000, 'exp': 1}
#print name of employee id =1001
if 1001 in employee:
print(employee[1001]["name"])
else:
print("employee with this id does not exist")
#salary of id =1003
if 1001 in employee:
print(employee[1001]["salary"])
else:
print("employee with this id does not exist")
#create a method and it will print corresponding employee name
def print_employ(**kwargs):
#print(kwargs) #{'id': 1002, 'prop': 'salary'}
if id in employee:
print(employee[id]["name"])
else:
print("#employee with this id does not exist")
#print_employ(id=1002)
print_employ(id=1002,prop="salary")
#create a method
def print_employee(**kwargs):
#print(kwargs) #{'id': 1000, 'prop': 'salary'}
id=kwargs["id"]# id =kwarg['id']
if id in employee:
print(employee[id]["name"])
if "prop" in kwargs:
salary=kwargs["prop"]
print(employee[id][salary])
else:
pass
else:
print("employee with this id does not exist")
print_employee(id=1000,prop="salary") |
71b86a27ddaeffe23134c5da30269184a1d33c9f | UlianaDzhumok/dog-breed-image-classifier | /adjust_results4_isadog.py | 2,463 | 3.703125 | 4 | def adjust_results4_isadog(results_dic, dogfile):
"""
Adjusts the results dictionary to determine if classifier correctly
classified images 'as a dog' or 'not a dog' especially when not a match.
Demonstrates if model architecture correctly classifies dog images even if
it gets dog breed wrong (not a match).
Parameters:
results_dic - Dictionary with 'key' as image filename and 'value' as a
List. Where the list will contain the following items:
index 0 = pet image label (string)
index 1 = classifier label (string)
index 2 = 1/0 (int) where 1 = match between pet image
and classifer labels and 0 = no match between labels
------ where index 3 & index 4 are added by this function -----
NEW - index 3 = 1/0 (int) where 1 = pet image 'is-a' dog and
0 = pet Image 'is-NOT-a' dog.
NEW - index 4 = 1/0 (int) where 1 = Classifier classifies image
'as-a' dog and 0 = Classifier classifies image
'as-NOT-a' dog.
dogfile - A text file that contains names of all dogs from the classifier
function and dog names from the pet image files. This file has
one dog name per line dog names are all in lowercase with
spaces separating the distinct words of the dog name. Dog names
from the classifier function can be a string of dog names separated
by commas when a particular breed of dog has multiple dog names
associated with that breed (ex. maltese dog, maltese terrier,
maltese) (string - indicates text file's filename)
Returns:
None - results_dic is mutable data type so no return needed.
"""
dognames=set()
with open(dogfile) as file:
for line in file:
dognames.add(line.lower().strip())
for key, value in results_dic.items():
if value[0] in dognames:
value.append(1)
else:
value.append(0)
classifier_labels=value[1].lower().strip().split(",")
classifier_flag=0
for label in classifier_labels:
if label.strip() in dognames:
classifier_flag=1
value.append(classifier_flag)
|
a95d0896f29a022f1332875cd00363c541ded514 | ledbagholberton/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/1-regular.py | 1,083 | 3.6875 | 4 | #!/usr/bin/env python3
"""
P is a is a square 2D numpy.ndarray of shape (n, n) representing
the transition matrix
P[i, j] is the probability of transitioning from state i to state j
n is the number of states in the markov chain
Returns: a numpy.ndarray of shape (1, n) containing
the steady state probabilities, or None on failure
"""
import numpy as np
def regular(P):
"""
determines the steady state probabilities of a regular markov chain
"""
try:
if (not isinstance(P, np.ndarray)):
return None
if len(P.shape) != 2:
return None
if P.shape[0] is not P.shape[1]:
return None
a = np.sum(P) / P.shape[0]
if a != 1:
return None
n = P.shape[0]
S = np.ones((1, n))/n
Pj = P.copy()
while True:
Multi = S
S = np.matmul(S, P)
Pj = P * Pj
if np.any(Pj <= 0):
return None
if np.all(Multi == S):
break
return S
except Exception:
return None
|
f35841fe3426df7d89cdb0238cdebbec3b649ead | MaksimKatorgin/module17 | /task1.py | 1,331 | 3.671875 | 4 | #Команде лингвистов понравилось качество ваших программ, и они решили заказать у вас функцию для анализатора текста, которая
#создавала бы список гласных букв текста, а заодно считала бы их количество.
#Напишите программу, которая запрашивает у пользователя текст и генерирует список из гласных букв этого текста
#(сама строка вводится на русском языке). Выведите в консоль сам список и его длину.
#Пример:
#Введите текст: Нужно отнести кольцо в Мордор!
#Список гласных букв: ['у', 'о', 'о', 'е', 'и', 'о', 'о', 'о', 'о']
#Длина списка: 9
result = []
word = str(input('Введите текст: '))
vowels = ['а', 'е', 'ё', 'и', 'о', 'у', 'э', 'ю', 'я',
'А', 'Е', 'Ё', 'И', 'О', 'У', 'Э', 'Ю', 'Я']
for ch in word.lower():
if ch in vowels:
result.append(ch)
print('Список гласных букв:', result)
print('Длина списка:', len(result)) |
6d86e3817e8f657833806f81d98708e05f264b7e | youfeng243/hackerrank | /Domains/Data Structures/Reverse a linked list/Reverse a linked list.py | 335 | 3.890625 | 4 |
def Reverse(head):
if head == None:
return head
if head.next == None:
return head
prepoint = head
point = head.next
prepoint.next = None
while point != None:
temp = point.next
point.next = prepoint
prepoint = point
point = temp
return prepoint |
82a051a683db4409b6abce482083f13a9b97426f | Galvin-wjw/DataAnalysis | /puncount.py | 163 | 3.734375 | 4 | aStr = "Hello,World!"
bStr = aStr[:6] + "Python!"
print(bStr)
count = 0
for ch in bStr:
if ch in ',.!?': #计算标点符号
count += 1
print(count) |
40205b9174355c744db2a5a4b7b7c897d6bcac06 | 89himanshu-dwivedi/Other_Language_Program | /python/continue.py | 115 | 3.71875 | 4 | for a in range(1,5):
while a<=5:
if a%2==0:
continue
print a
print "for go" |
be1de077d288000603faa6a52e1d386796ef1d9b | JakubKazimierski/PythonPortfolio | /Coderbyte_algorithms/Medium/LetterCount/LetterCount.py | 970 | 4.28125 | 4 | '''
Letter Count from Coderbyte
December 2020 Jakub Kazimierski
'''
import re
def LetterCount(strParam):
'''
Have the function LetterCount(str)
take the str parameter being passed
and return the first word with the
greatest number of repeated letters.
For example: "Today, is the greatest day ever!"
should return greatest because it has 2 e's (and 2 t's)
and it comes before ever which also has 2 e's.
If there are no words with repeating letters return -1.
Words will be separated by spaces.
'''
words = list(filter(None, re.split(r'[^a-zA-Z]', strParam)))
max_occurence_from_all = 1
max_word = "-1"
for word in words:
max_occurence_current = max(word.count(letter) for letter in set(word))
if max_occurence_current > max_occurence_from_all:
max_occurence_from_all = max_occurence_current
max_word = word
return max_word
|
64be63ec9c731b72492e848f1adae9626839622c | Ken0706/Crash_Course_Book_Python | /5.4_Alien_Colors_#2.py | 723 | 3.703125 | 4 | import random
def check_input():
global alien_color
global second, first
color = ["green", "yellow", "red"]
first, second = random.sample(color,2)
while True:
try :
alien_color = input("Enter color (green, yellow, red) : ")
if alien_color in color:
break
elif len(alien_color) == 0:
print("You fail!!!")
else:
print("Try again...")
except ValueError:
print("Try again...")
def play_game(alien_color, first, second):
if alien_color == first:
print("+ 10 points... You first!!!")
elif alien_color == second:
print("+ 5 points... You second!!!")
else:
print("You fail!!!")
def main():
check_input()
play_game(alien_color,first, second)
if __name__ == "__main__":
main() |
73ceb39114c905708b650df42a9a5159d2dbdcc8 | rzalog/Random-Box-Game | /randbox.py | 6,802 | 3.546875 | 4 | # randbox.py
# Simple game where a box moves around, and user has to click on it
import random, pygame, sys
from pygame.locals import *
FPS = 30
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
SCREENCENTER = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
SCREENCENTERX = WINDOWWIDTH / 2
SCREENCENTERY = WINDOWHEIGHT / 2
MENUMARGIN = 50
XMARGIN = 20
YMARGIN = 20
BOXSIZE = 100
FRAMES_UNTIL_NEW = 40 # how long program waits to draw a new random box
TIMELIMIT = 60 # time limit of game in seconds
POINTS_PER_BOX = 10
# colors
# R G B
WHITE = ( 255, 255, 255)
BLACK = ( 0, 0, 0)
GREY = ( 100, 100, 100)
# the box colors (aka the pretty colors)
# R G B
RED = ( 255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
YELLOW = ( 255, 255, 0)
ORANGE = ( 255, 128, 0)
PURPLE = ( 255, 0, 255)
CYAN = ( 0, 255, 255)
BOXCOLORS = [RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN]
BGCOLOR = WHITE
DEFAULT_BOX_COLOR = RED
TEXTCOLOR = BLACK
FONT = "freesansbold.ttf"
FONTSIZE = 16
BIGFONTSIZE = 24
def main():
global FPSCLOCK, DISPLAYSURF
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode( (WINDOWWIDTH, WINDOWHEIGHT) )
pygame.display.set_caption("Random Box Game")
gameEnded = False
wantsToRestart = False
mousex = 0
mousey = 0
timeFrames = 0 # to keep track of time
squareFrames = 0 # to keep track of when to make a new random square
score = 0
boxesClicked = 0
secondsLeft = TIMELIMIT
pointsPerBox = POINTS_PER_BOX
framesUntilNew = FRAMES_UNTIL_NEW
DISPLAYSURF.fill(BGCOLOR)
scoreRect = updateScore(score)
timeRect = updateTime(secondsLeft)
# creates a "protective" box around menu so random squares don't collide with it
menuRect = pygame.Rect(0, 0, timeRect.width + 2 * YMARGIN, scoreRect.height + timeRect.height + 2 * YMARGIN)
menuRect.center = SCREENCENTER
currentRandSquare = drawRandSquareOnBoard(True, menuRect)
while True:
# main game loop
mouseClicked = False
timeFrames += 1
squareFrames += 1
for event in pygame.event.get():
# event handling loop
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONUP:
mousex, mousey = pygame.mouse.get_pos()
mouseClicked = True
elif gameEnded:
if event.type == KEYUP and event.key == K_r:
wantsToRestart = True
if not gameEnded:
if timeFrames == FPS:
# if one second has passed, update the time
secondsLeft -= 1
if secondsLeft == 0:
timeExpired(score)
gameEnded = True
else:
timeRect = updateTime(secondsLeft, timeRect)
timeFrames = 0
if squareFrames == FRAMES_UNTIL_NEW:
# if enough frames have passed to draw a new square
currentRandSquare = drawNewSquare(currentRandSquare, menuRect)
squareFrames = 0
if mouseClicked:
# Check if we clicked on the square, otherwise don't do anything
if currentRandSquare.collidepoint(mousex+1, mousey+1):
boxesClicked += 1
score += pointsPerBox
clickedSquare(score)
if boxesClicked % 5 == 0 and framesUntilNew >= 15:
# after a certain amount of boxes, incrase speed
# and the score per box
framesUntilNew -= 5
pointsPerBox += 5
currentRandSquare = drawNewSquare(currentRandSquare, menuRect)
squareFrames = 0
if gameEnded and wantsToRestart:
main()
pygame.display.update()
FPSCLOCK.tick(FPS)
def giveRandRect(width, height, xmin, xmax, ymin, ymax, color):
# generic function to produce a Rect object within a given set of coordinates
x = random.randint(xmin, xmax+1)
y = random.randint(ymin, ymax+1)
rect = pygame.Rect(x,y, width,height)
return rect
def drawRandSquareOnBoard(chooseRandColor=True, menuRect=None):
# specialized function to draw a random square on the game board
# option to specify a given menu rectangle to avoid placing random squares in that area
xmin = 0 + XMARGIN
xmax = WINDOWWIDTH - BOXSIZE - XMARGIN
ymin = 0 + MENUMARGIN + YMARGIN
ymax = WINDOWHEIGHT - BOXSIZE - YMARGIN
if chooseRandColor:
# pick a random color, not including the background color
color = random.choice(BOXCOLORS)
while color == BGCOLOR:
color = random.choice(BOXCOLORS)
else:
color = BOXCOLOR
randSquare = giveRandRect(BOXSIZE, BOXSIZE, xmin, xmax, ymin, ymax, color)
if menuRect != None:
# if requested, make sure randSquare does not collide with the menuRect
while menuRect.colliderect(randSquare):
randSquare = giveRandRect(BOXSIZE, BOXSIZE, xmin, xmax, ymin, ymax, color)
if menuRect != None and menuRect.colliderect(randSquare):
print("THEY ARE GOING TO COLLIDE!")
pygame.draw.rect(DISPLAYSURF, color, randSquare)
return randSquare
def drawNewSquare(currentSquare, menuRect=None):
# remove the square at (x, y) and draw a new random square
pygame.draw.rect(DISPLAYSURF, BGCOLOR, (currentSquare.x, currentSquare.y, BOXSIZE, BOXSIZE))
newRect = drawRandSquareOnBoard(True, menuRect)
return newRect
def clickedSquare(score):
# what we are going to do if user succesfully clicks a square
updateScore(score)
def updateScore(score):
# draw and update the score
scoreFont = pygame.font.Font(FONT, FONTSIZE)
scoreObj = scoreFont.render("Score: %d" % score, False, TEXTCOLOR)
scoreRectObj = scoreObj.get_rect()
scoreRectObj.center = SCREENCENTER
scoreRectObj.top = SCREENCENTERY # give room for time label
pygame.draw.rect(DISPLAYSURF, BGCOLOR, scoreRectObj)
DISPLAYSURF.blit(scoreObj, scoreRectObj)
return scoreRectObj
def updateTime(timeLeft, oldTimeRect=None):
timeFont = pygame.font.Font(FONT, FONTSIZE)
timeObj = timeFont.render("Time left: %d" % timeLeft, True, TEXTCOLOR)
timeRectObj = timeObj.get_rect()
timeRectObj.center = SCREENCENTER
timeRectObj.bottom = SCREENCENTERY # move it up above score label
if oldTimeRect != None:
pygame.draw.rect(DISPLAYSURF, BGCOLOR, oldTimeRect) # white out the old time rectangle
DISPLAYSURF.blit(timeObj, timeRectObj)
return timeRectObj
def timeExpired(score):
# when the game ends, blank out the screen and send a message to the user
DISPLAYSURF.fill(BGCOLOR)
finalScoreFont = pygame.font.Font(FONT, BIGFONTSIZE)
finalScoreObj = finalScoreFont.render("Final Score: %d" % score, True, TEXTCOLOR)
finalScoreObjRect = finalScoreObj.get_rect()
finalScoreObjRect.center = SCREENCENTER
finalScoreObjRect.bottom = SCREENCENTERY
restartMsgFont = pygame.font.Font(FONT, BIGFONTSIZE)
restartMsgObj = restartMsgFont.render("Press 'r' to restart and break your score!", True, TEXTCOLOR)
restartMsgObjRect = restartMsgObj.get_rect()
restartMsgObjRect.center = SCREENCENTER
restartMsgObjRect.top = SCREENCENTERY
DISPLAYSURF.blit(finalScoreObj, finalScoreObjRect)
DISPLAYSURF.blit(restartMsgObj, restartMsgObjRect)
if __name__ == "__main__":
main()
|
3d59d5d771c85cbeac3e44e55b54b997cd49c397 | yoderw/math121 | /hw/hw1/hw1_menu.py | 1,266 | 3.90625 | 4 | """
Restaurant name? Bobby's
First entree? Pasta verde
First entree price? 15
Second entree? Filet mignon w/ lobster and caviar
Second entree price? 107
Third entree? Hamburger with fries
Third entree price? 9
1234567890123456789012345678901234567890
Bobby's Entrees
---------------
Pasta verde.........................$ 15
Filet mignon w/ lobster and caviar..$107
Hamburger with fries................$ 9
"""
restaurant_name = str(input("Restaurant name? "))
first_name = str(input("First entree? "))
first_price = str(input("First entree price? "))
second_name = str(input("Second entree? "))
second_price = str(input("Second entree price? "))
third_name = str(input("Third entree? "))
third_price = str(input("Third entree price? "))
line1 = "{} Entrees".format(restaurant_name)
line2 = "-" * len(line1)
line3 = first_name + ("." * (36 - len(first_name))) + "$" + (" " * (3 - len(first_price))) + first_price
line4 = second_name + ("." * (36 - len(second_name))) + "$" + (" " * (3 - len(second_price))) + second_price
line5 = third_name + ("." * (36 - len(third_name))) + "$" + (" " * (3 - len(third_price))) + third_price
print()
print("1234567890123456789012345678901234567890")
print()
print(line1)
print(line2)
print(line3)
print(line4)
print(line5) |
6eb156eb50314d0a0d4f4ecc29efa3b142727721 | curaai/EulerProject | /27.py | 651 | 3.625 | 4 | import math
def prime_check(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
elif i > math.sqrt(n):
return True
def formular(a, b):
for i in range(0, 1000):
res = pow(i, 2) + (i * a) + b
if prime_check(res) is False:
return i
if __name__ == '__main__':
big = 0
max_a, max_b = 0, 0
for a in range(-999, 1000):
for b in range(-999, 1000):
result = formular(a , b)
if result > big:
big = result
max_a = a
max_b = b
print(max_a*max_b) |
fb2a6f52be2cd6ede0004fe9976b840e81fb183e | leonardokiyota/Python-Training | /LivroPythonInt/Exercises/Chapter 05 /5.3.py | 241 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
Faça um programa para escrever a contagem regressiva do lançamento de um
foguete. Conte de de 10 a 0 e Fogo.
'''
x = 10
while x >= 0:
print(x)
x = x - 1
print("Fogo!")
|
7cdf86bd0628f3c3beb48192a464a48723ff0926 | onkcharkupalli1051/pyprograms | /week4_dobblegame.py | 1,015 | 3.65625 | 4 | import string
import random
symbols = []
symbols = list(string.ascii_letters)
card1 = [0]*5
card2 = [0]*5
pos1 = random.randint(0,4)
pos2 = random.randint(0,4)
#pos1 and pos2 are same symbol positions in card1 and card2
samesymbol = random.choice(symbols)
symbols.remove(samesymbol)
if(pos1 == pos2):
card2[pos1] = samesymbol
card1[pos1] = samesymbol
else:
card1[pos1] = samesymbol
card2[pos2] = samesymbol
card1[pos2] = random.choice(symbols)
symbols.remove(card1[pos2])
card2[pos2] = random.choice(symbols)
symbols.remove(card2[pos2])
i=0
while(i<5):
if(i != pos1 and i != pos2):
alphabet1 = random.choice(symbols)
symbols.remove(alphabet1)
alphabet2 = random.choice(symbols)
symbols.remove(alphabet2)
card1[i] = alphabet1
card2[i] = alphabet2
i += 1
print("CARD 1 : ",card1)
print("CARD 2 : ",card2)
ch = input("SPOT THE SIMILAR SYMBOL : ")
if ch == samesymbol:
print("\t**RIGHT")
else:
print("\t*WRONG")
|
325e192c87d7bda9c92866342becf0e900b3c356 | in-s-ane/easyctf-2014 | /Obfuscation 1/obfuscated.py | 1,842 | 3.78125 | 4 | #! /usr/bin/python
# The output of this program is: NICEJOBFIGURINGOUTWHATTHISPROGRAMDOESTHEFLAGISVINEGARISTHEBESTCIPHER
text = "SWQHRGZZUSSWWBJWMRQTMRYVWVXJMADMKICSVBZCZXMENGJLVWEUDUQYVSEMKRWUBFJF"
apple = "FOODISYUMMY"
""" OLD CODE:
from itertools import starmap, cycle
def mystery(a, b):
a = filter(lambda _: _.isalpha(), a.upper())
#important
def enc(c,k): return chr(((ord(k) + ord(c)) % 26) + ord('A'))
return "".join(starmap(enc, zip(a, cycle(b))))
final = mystery(text, apple)
print (text)
print (final)
"""
# Decided to just unobfuscate the original code ^_^
def mymystery(text, key):
filtered = []
for char in text:
if char.isalpha():
filtered.append(char.upper())
def enc(char, key):
new = (ord(key) + ord(char)) % 26
return chr(new + ord('A'))
charlist = []
cyclerIndex = 0
for char in text:
if cyclerIndex >= len(key):
cyclerIndex = 0
charlist.append(enc(char, key[cyclerIndex]))
cyclerIndex += 1
return "".join(charlist)
encrypted = mymystery(text, apple)
print "Original Text: " + text
#print "Encryption Test: " + encrypted
def mymysterydecode(text, key):
filtered = []
for char in text:
if char.isalpha():
filtered.append(char.upper())
def dec(char, key):
new = ord(char) - ord('A')
if (new < ord(key) % 26):
new += 26
new -= ord(key) % 26
while (new < ord('A')):
new += 26
return chr(new)
charlist = []
cyclerIndex = 0
for char in text:
if cyclerIndex >= len(key):
cyclerIndex = 0
charlist.append(dec(char, key[cyclerIndex]))
cyclerIndex += 1
return "".join(charlist)
decoded = mymysterydecode(text, apple)
print "Decoded Text: " + decoded
|
1d53f8e1fc81980e3fdba675377506442db44baa | kucherskyi/pytrain | /lesson5/lesson1.py | 758 | 3.5 | 4 | import re
from nt import write
def print_empty():
out = open('alice01.txt', 'w')
lines = 0
for lin in open('alice.txt', 'r'):
if re.match('\n', lin):
lines +=1
else:
out.write(lin)
print '%s empty lines were found!' % lines
#print_empty()
def remove_whitespace():
out = open('alice02.txt', 'w')
lines = 0
for lin in open('alice.txt', 'r'):
if re.match('\s', lin):
out.write(lin.strip()+'\n')
lines +=1
else:
out.write(lin)
# print '%s lines with whitespace' % lines
if __name__ == '__main__':
import timeit
print timeit.timeit("remove_whitespace()", setup="from __main__ import remove_whitespace")
|
0d88489b1d3f2d470a1f0c17e90fdab348cfde1e | aewaddell/lpthw | /excercises/ex10.py | 1,271 | 3.78125 | 4 | tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
# You can use triple single quote instead
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)
# \\ : backslash
# \' : single-quote
# \" : double-quotes
# \a : ASCII bell
# \b : ASCII backspace
# \f : ASCII formfeed
# \n : ASCII linefeed (newline)
# \N{name} : character named name in Unicode database
# \r : ASCII carriage return
# \t : ASCII horizontal tab
# more...
# while True:
# for i in ["/", "-", "|", "\\", "|"]:
# print("%r\r" % i,)
#Assign string value for each variable
intro = "I'll print a week:"
mon = "Mon"
tue = "Tue"
wed = "Wed"
thu = "Thu"
fri = "Fri"
sat = "Sat"
sun = "Sun"
print("%s\n%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (intro, mon, tue, wed, thu, fri, sat, sun))
# %s uses the string function and %r uses the repr function
# %r prints what you'd write in your file (for debugging)
# escape characters don't work in this mode
#but %s prints it the way you'd like to see it. (for displaying)
print("%r" % intro)
print("%r" % "She said \"I'll print a week\"")
print("%s" % intro)
print("%s" % "She said \"I'll print a week\"")
|
9a96b6728b364fd03104e5a2c7a9ddc610927669 | KristofferNyvoll/ntnu | /TDT4110_ITGK/Assignment_6/gangetabell_lister.py | 620 | 3.75 | 4 | # a)
def separate(numbers, threshold):
less_than = []
more_than = []
length = len(numbers)
for x in range(length):
if numbers[x] < threshold:
less_than.append(x)
else:
more_than.append(x)
return less_than, more_than
less_than, more_than = separate([0, 1, 2, 3, 4, 5], 3)
print(less_than)
print(more_than)
# b)
new_list = []
def multiplication_table(n):
for y in range(1, n+1):
ny_rad = []
for j in range(1, n+1):
ny_rad.append(j*y)
new_list.append(ny_rad)
multiplication_table(6)
for rad in new_list:
print(rad) |
a643d196184cc5360bc28e32a22e4ea420844908 | MaxXSoft/article-gen | /article_gen/wordfreq.py | 1,551 | 3.5 | 4 | class WordFreq(object):
def __init__(self, head_word=None, next_word=None,
head_pos=None, next_pos=None, word_pos=None):
self.head_word = head_word
self.next_word = next_word
self.head_pos = head_pos
self.next_pos = next_pos
self.word_pos = word_pos
def __bool__(self):
return bool(self.head_word and self.next_word and self.head_pos \
and self.next_pos and self.word_pos)
def __inc_dict_dict(d, v0, v1):
value = d.get(v0, {})
value[v1] = value.get(v1, 0) + 1
d[v0] = value
def get_freq(l):
head, next_word = {}, {}
head_pos, next_pos = {}, {}
word_pos = {}
last_word, last_prop = '', ''
# calculate word freq
for word, prop in l:
word_pos[word] = prop
if prop != 'x':
if last_word and last_prop:
__inc_dict_dict(next_word, last_word, word)
__inc_dict_dict(next_pos, last_prop, prop)
last_word, last_prop = word, prop
else:
head[word] = head.get(word, 0) + 1
head_pos[prop] = head_pos.get(prop, 0) + 1
last_word, last_prop = word, prop
else:
if last_word and last_prop:
__inc_dict_dict(next_word, last_word, word)
__inc_dict_dict(next_pos, last_prop, prop)
last_word, last_prop = '', ''
# return the result
return WordFreq(head, next_word, head_pos, next_pos, word_pos)
if __name__ == '__main__':
pass
|
754ea34f3b23661761a1c63043b940b1d49f0291 | ChyanMio/LeetCode | /036_valid_sudoku.py | 836 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 13:21:27 2019
@author: zhang
"""
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
row = [[False for _ in range(9)] for _ in range(9)]
col = [[False for _ in range(9)] for _ in range(9)]
block = [[False for _ in range(9)] for _ in range(9)]
for i in range(9):
for j in range(9):
if board[i][j] == '.': continue
d = eval(board[i][j]) - 1
if row[i][d]: return False
row[i][d] = True
if col[j][d]: return False
col[j][d] = True
if block[i // 3 * 3 + j // 3][d]: return False
block[i // 3 * 3 + j // 3][d] = True
return True |
95bf212e7b5bbad9e11e25c6782a3a0482689a98 | INM-6/Python-Module-of-the-Week | /session35_generators/1_iterators_next.py | 739 | 3.875 | 4 | colors = ['mauve', 'taupe', 'teal', 'razzmatazz', 'gamboge']
class List_Iterator():
def __init__(self, ListyMcListface):
self.ListyMcListface = ListyMcListface
self.n = len(ListyMcListface)
self.current_element = 0
def __next__(self):
if self.current_element == self.n:
raise StopIteration
else:
return_value = self.ListyMcListface[self.current_element]
self.current_element += 1
return return_value
LI = List_Iterator(colors)
# print(next(LI))
# print(next(LI))
# print(next(LI))
# print(next(LI))
# print(next(LI))
# print(next(LI))
# while(True):
# try:
# print(next(LI)[::-1])
# except StopIteration:
# break
|
45fdace6d1d4ffb7870c7d56131278b089d7417a | TD2106/Competitive-Programming | /ACM Contest/NorthWestPacific/recap/Alphabet/Alphabet.py | 1,613 | 3.96875 | 4 |
import sys
import pdb
def get_longest_increasing_subsequence(sequence):
p = [None for _ in xrange(0, len(sequence))]
m = [None for _ in xrange(0, len(sequence) + 1)]
l = 0
for i in xrange(0, len(sequence)):
# Binary search on lengths:
# bsearch for the largest positive j <= L such that x[m[j]] < x[i]
# this finds us a guy we can extend
lo = 1
hi = l
while lo <= hi:
mid = int((lo + hi) / 2) + 1 if lo != hi else lo
if sequence[m[mid]] < sequence[i]:
lo = mid + 1
else:
hi = mid - 1
# After searching, lo is 1 greater than the
# length of the longest prefix of sequence[i]
newL = lo
# The predecessor of sequence[i] is the last index of
# the subsequence of length newL-1
p[i] = m[newL - 1]
# why don't you need to check that sequence[i] < sequence[m[newL]]?
# m stores the indices of the least sequence-values but it's obvious that
# the above inequality holds
m[newL] = i
if newL > l:
# If we found a subsequence longer than any we've found yet, update L
l = newL
longest_increasing_subsequence = [None for _ in xrange(0, l)]
k = m[l]
for i in xrange(l - 1, -1, -1):
longest_increasing_subsequence[i] = sequence[k]
k = p[k]
return longest_increasing_subsequence
def main():
sequence = list(sys.stdin.readline().strip())
print 26 - len(get_longest_increasing_subsequence(sequence))
if __name__ == '__main__':
main()
|
2950c1f25fa37b720644258a3b63bb686c6873d7 | shahakshay11/Backtracking-2 | /palindrome_partitioning.py | 1,835 | 3.640625 | 4 | """
// Time Complexity : O(n^2) n - number of characters in the string
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
Algorithm explanation
Recursive approach + backtracking
Global var -> all_palindromes
1) Base case -> if the pos is reached till end of string, add the list of palindromic substrings into outer list
2) for i = 1 to n:
Slice the string in all possible k combinations and call the partition recursively only for palindromic substring
"""
class Solution:
def partition(self, s: str) -> List[List[str]]:
"""
Recursive approach + backtracking
Global var -> all_palindromes
1) Base case -> if the pos is reached till end of string, add the list of palindromic substrings into outer list
2) for i = 1 to n:
Slice the string in all possible k combinations and call the partition recursively only for palindromic substring
"""
result = []
final = []
def isPalindrome(s,low,high):
while low < high:
if s[low]!=s[high]:
return False
low+=1
high-=1
return True
#return s == s[::-1]
def partitionrec(s,pos):
if pos == len(s):
#we are exhausting the string, so we must have found some set of palindromic substrings
final.append(result[::])
for i in range(pos,len(s)):
if isPalindrome(s,pos,i):
result.append(s[pos:i+1])
partitionrec(s,i+1)
result.pop()
partitionrec(s,0)
return final |
e67b28841d7e574082a9c99432c7e4c34a4212a9 | legeannd/codigos-cc-ufal | /ED/Estruturas de manipulação de dados/Lista/Prova_q2.py | 269 | 3.625 | 4 | from lista import chainedList
lista = chainedList()
lista2 = []
while True:
nome = input("Digite o nome (0 para sair )")
if nome == '0':
break
num = int(input("Digite o numero "))
lista2 = [nome, num]
lista.push(lista2)
lista.listPrint()
print(lista.search(0)) |
c0532f2a717c568cb0bad6cfeed6a39351dfdd6b | CodeHemP/CAREER-TRACK-Data-Scientist-with-Python | /09_Introduction to Data Visualization with Seaborn/02_Visualizing Two Quantitative Variables/05_Interpreting line plots.py | 1,310 | 3.71875 | 4 | '''
05 - Interpreting line plots
In this exercise, we'll continue to explore Seaborn's mpg dataset,
which contains one row per car model and includes information such as
the year the car was made, its fuel efficiency (measured in "miles per
gallon" or "M.P.G"), and its country of origin (USA, Europe, or Japan).
How has the average miles per gallon achieved by these cars changed over
time? Let's use line plots to find out!
Instructions 1/2
- Use relplot() and the mpg DataFrame to create a line plot with "model_year"
on the x-axis and "mpg" on the y-axis.
'''
# Import Matplotlib and Seaborn
import matplotlib.pyplot as plt
import seaborn as sns
# Create line plot
sns.relplot(x='model_year',
y='mpg',
data=mpg,
kind='line')
# Show plot
plt.show()
'''
Instructions 2/2
Question:
Which of the following is NOT a correct interpretation of this line plot?
Possible Answers
- The average miles per gallon has generally increased over time.[X]
- The distribution of miles per gallon is smaller in 1973 compared to 1977.[Correct]
- The 95% confidence interval for average miles per gallon in 1970 is approximately
16 - 19.5 miles per gallon.[X]
- This plot assumes that our data is a random sample of all cars in the US, Europe, and Japan.[X]
'''
|
a93ce8c7ddf27dc7ed35ed2fc4fa045a72cfaf6b | hanzohasashi33/Competetive_programming | /Camp-Summer-Training/week1/5/testing.py | 556 | 3.625 | 4 | import unittest
from week1_5 import evenness
class TestSum(unittest.TestCase) :
def testcase1(self) :
n = 5
l = [2,4,7,8,10]
result = evenness(l,n)
self.assertEqual(result,3)
def testcase2(self) :
n = 4
l = [1,2,1,1]
result = evenness(l,n)
self.assertEqual(result,2)
"""
def testcase3(self) :
n = 8
pos = 8
result = number(n,pos)
self.assertEqual(result,8)
"""
if __name__ == "__main__":
unittest.main() |
f82b372c017a46f40ce511c9e85e1da0a077bae6 | amyanchen/Tower-of-Hanoi | /Tower of Hanoi.py | 20,024 | 3.9375 | 4 |
# coding: utf-8
# In[1]:
'''
Created by Div Dasani and Amy Chen
EECS 348
10/3/17
Assignment 1- Tower Of Hanoi
'''
from TOH_DFS import Solve_By_DepthFS
from TOH_BFS import Solve_By_BreadthFS
from TOH_TFS import Solve_By_BestFS
number_of_disks = 5
print ("Solve by Depth First Search method:")
Solve_By_DepthFS(number_of_disks)
print ("Solve by Breadth First Search method:")
Solve_By_BreadthFS(number_of_disks)
print ("Solve by Best First Search method:")
Solve_By_BestFS(number_of_disks)
# In[ ]:
import math
'''
Logic:
I am going to assign a numerical value to each disk as 2^n. The first disk(smallest) will have value of 2, second disk value of 4, third disk value of 8, fourth disk value of 16 and so on
Numerical Value of any Disk = 2^(n)
Value of each peg(pole) will be sum of all values of disk on that peg at given time. For e.g. if the peg currently has Disk 1 and 3, than the value of that peg is 2 + 8 = 10
Value of all disks will be 2^1 + 2^2....2^(n) = (2^n) - 2. For e.g. the total value of 4 disks will be 2^4 - 2 = 30
I am using "Bitwise And" operator to decide if a given disk exists on the peg. For e.g.
-if the peg value is 20 (Disk 2 and 4) then 20 "Bitwise And" 2 will equal to 0 which means that peg doesn't have Disk 1
-if the peg value is 20 (Disk 2 and 4) then 20 "Bitwise And" 4 will equal to 4 which means that peg does have Disk 2
To check if I am not placing bigger disk on top of smaller disk, I used the Modulus (find the remainder) operator. For e.g.
-if the peg has value of 18(Disk 1 and 4), then 18 % 4 will be 2 which means I cannot place Disk 2 on this peg
-if the peg has a value of 24 (Disk 3 and 4) then 24 % 4 will be 0 which means I can place Disk 2 on this peg
'''
# Depth First Search will use the Last In First Out logic. That way we are going to keep going deep(vertical) before we search horizontal states.
def Solve_By_DepthFS(n):
#Declare Variables
#Values of each Peg
peg1_value=peg2_value=peg3_value = 0
#LIFO List to store the adjacent states
state_LIFO = []
#LIFO list used to save the actions we have taken till for every LIFO item, so we can trace back. The size of this list will always be same as size of other LIFO list
steps_till_now_LIFO = []
#This List is to store the states which we have already encountered, so that we do not go into infinite loop
past_states = []
#temporary variables to store the steps for current working state and next adjacent state
steps_till_current_state = steps_till_next_state = []
#Temporary variable to store the value of disk being moved
Value_of_Disk = 0
#Temporary variable to store current state and the next adjacent state
current_state = new_state = []
#Temporary variable to store the disk being moved
disk_on_top = 0
#Boolean variables
state_found_before = solution_found = False
#Find the total value of all disks based on n number of disks
Value_of_All_Disks = int(math.pow(2,n+1))-2
#Initial state where all disks are in Peg1. Because Lists are indexed starting 0, we will just ignore the 0th index.
current_state = [0, Value_of_All_Disks, 0, 0]
#Insert the starting state in the LIFO list
state_LIFO.append(current_state)
steps_till_now_LIFO.append(steps_till_current_state)
past_states.append(current_state)
#Loop till we find the solution
while solution_found == False and len(state_LIFO) > 0:
#Get the next state based on LIFO logic
current_state = state_LIFO.pop()
#Get the corresponding steps on LIFO logic
steps_till_current_state = steps_till_now_LIFO.pop()
#Loop all pegs for source for disk movement
for source_peg in range(3,0,-1):
#if the peg has no disk as of now, then move on to next peg
if (current_state[source_peg] == 0):
continue
# Loop all pegs for destination for disk movement
for dest_peg in range(3, 0, -1):
#Source Peg and Dest Peg cannot be same
if (solution_found == True or source_peg == dest_peg):
continue
#Loop for each disk size from small to big
for disk_size in range(1,n+1):
Value_of_Disk = int(math.pow(2,disk_size))
#Using Bitwise AND operator find the disk on top of this source peg
if ((current_state[source_peg] & Value_of_Disk) == Value_of_Disk):
disk_on_top = disk_size
break
#Destination peg should either be empty or top disk should be bigger than the disk being moved
if (current_state[dest_peg] == 0 or current_state[dest_peg] % Value_of_Disk == 0):
#Following steps move the disk from source to dest peg, and create a new state out of current state
new_state = list(current_state)
new_state[source_peg] = new_state[source_peg] - Value_of_Disk
new_state[dest_peg] = new_state[dest_peg] + Value_of_Disk
next_step = [disk_on_top, source_peg, dest_peg]
steps_till_next_state = list(steps_till_current_state)
steps_till_next_state.append(next_step)
#Check if the new State is the Final Solution we are looking for (all disks on peg 3)
if (new_state[3] == Value_of_All_Disks):
steps = 1
output = ""
for aseq in steps_till_next_state:
output = output + str(steps) + ": Move Disk " + str(aseq[0]) + " From " + str(aseq[1]) + " To " + str(aseq[2]) + "\n"
steps = steps + 1
print (output)
solution_found = True
return
#else - we did't find the solution yet
else:
#make sure the new state is not already discovered before
state_found_before = False
for past_state in past_states:
if (past_state[1] == new_state[1] and past_state[2] == new_state[2] and past_state[3] == new_state[3]):
state_found_before = True
break
#if this is the new state which we discovered before, then append it to the LIFO lists
if state_found_before == False:
state_LIFO.append(new_state)
steps_till_now_LIFO.append(steps_till_next_state)
past_states.append(new_state)
# In[ ]:
import math
'''
Logic:
I am going to assign a numerical value to each disk as 2^n. The first disk(smallest) will have value of 2, second disk value of 4, third disk value of 8, fourth disk value of 16 and so on
Numerical Value of any Disk = 2^(n)
Value of each peg(pole) will be sum of all values of disk on that peg at given time. For e.g. if the peg currently has Disk 1 and 3, than the value of that peg is 2 + 8 = 10
Value of all disks will be 2^1 + 2^2....2^(n) = (2^n) - 2. For e.g. the total value of 4 disks will be 2^4 - 2 = 30
I am using "Bitwise And" operator to decide if a given disk exists on the peg. For e.g.
-if the peg value is 20 (Disk 2 and 4) then 20 "Bitwise And" 2 will equal to 0 which means that peg doesn't have Disk 1
-if the peg value is 20 (Disk 2 and 4) then 20 "Bitwise And" 4 will equal to 4 which means that peg does have Disk 2
To check if I am not placing bigger disk on top of smaller disk, I used the Modulus (find the remainder) operator. For e.g.
-if the peg has value of 18(Disk 1 and 4), then 18 % 4 will be 2 which means I cannot place Disk 2 on this peg
-if the peg has a value of 24 (Disk 3 and 4) then 24 % 4 will be 0 which means I can place Disk 2 on this peg
'''
# Breadth First Search will use the First In First Out logic. That way we are going to try all the states(nodes) which we discovered first(horizontal), before searching states(nodes) found later.
def Solve_By_BreadthFS(n):
#Declare Variables
#Values of each Peg
peg1_value=peg2_value=peg3_value = 0
#FIFO List to store the adjacent states
state_FIFO = []
#FIFO list used to save the actions we have taken till for every FIFO item, so we can trace back. The size of this list will always be same as size of other FIFO list
steps_till_now_FIFO = []
#This List is to store the states which we have already encountered, so that we do not go into infinite loop
past_states = []
#temporary variables to store the steps for current working state and next adjacent state
steps_till_current_state = steps_till_next_state = []
#Temporary variable to store the value of disk being moved
Value_of_Disk = 0
#Temporary variable to store current state and the next adjacent state
current_state = new_state = []
#Temporary variable to store the disk being moved
disk_on_top = 0
#Boolean variables
state_found_before = solution_found = False
#Find the total value of all disks based on n number of disks
Value_of_All_Disks = int(math.pow(2,n+1))-2
#Initial state where all disks are in Peg1. Because Lists are indexed starting 0, we will just ignore the 0th index.
current_state = [0, Value_of_All_Disks, 0, 0]
#Insert the starting state in the FIFO list
state_FIFO.append(current_state)
steps_till_now_FIFO.append(steps_till_current_state)
past_states.append(current_state)
#Loop till we find the solution
while solution_found == False and len(state_FIFO) > 0:
#Get the next state based on FIFO logic
current_state = state_FIFO.pop(0)
#Get the corresponding steps on FIFO logic
steps_till_current_state = steps_till_now_FIFO.pop(0)
#Check to see if this state is the solution we are looking for
if (current_state[3] == Value_of_All_Disks):
steps = 1
output = ""
for aseq in steps_till_current_state:
output = output + str(steps) + ": Move Disk " + str(aseq[0]) + " From " + str(aseq[1]) + " To " + str(
aseq[2]) + "\n"
steps = steps + 1
print(output)
solution_found = True
return
#Loop all pegs for source for disk movement
for source_peg in range(3,0,-1):
#if the peg has no disk as of now, then move on to next peg
if (current_state[source_peg] == 0):
continue
# Loop all pegs for destination for disk movement
for dest_peg in range(3, 0, -1):
#Source Peg and Dest Peg cannot be same
if (solution_found == True or source_peg == dest_peg):
continue
#Loop for each disk size from small to big
for disk_size in range(1,n+1):
Value_of_Disk = int(math.pow(2,disk_size))
#Using Bitwise AND operator find the disk on top of this source peg
if ((current_state[source_peg] & Value_of_Disk) == Value_of_Disk):
disk_on_top = disk_size
break
#Destination peg should either be empty or top disk should be bigger than the disk being moved
if (current_state[dest_peg] == 0 or current_state[dest_peg] % Value_of_Disk == 0):
#Following steps move the disk from source to dest peg, and create a new state out of current state
new_state = list(current_state)
new_state[source_peg] = new_state[source_peg] - Value_of_Disk
new_state[dest_peg] = new_state[dest_peg] + Value_of_Disk
next_step = [disk_on_top, source_peg, dest_peg]
steps_till_next_state = list(steps_till_current_state)
steps_till_next_state.append(next_step)
#make sure the new state is not already discovered before
state_found_before = False
for past_state in past_states:
if (past_state[1] == new_state[1] and past_state[2] == new_state[2] and past_state[3] == new_state[3]):
state_found_before = True
break
#if this is the new state which we discovered before, then append it to the FIFO lists
if state_found_before == False:
state_FIFO.append(new_state)
steps_till_now_FIFO.append(steps_till_next_state)
past_states.append(new_state)
# In[ ]:
import math
'''
Logic:
I am going to assign a numerical value to each disk as 2^n. The first disk(smallest) will have value of 2, second disk value of 4, third disk value of 8, fourth disk value of 16 and so on
Numerical Value of any Disk = 2^(n)
Value of each peg(pole) will be sum of all values of disk on that peg at given time. For e.g. if the peg currently has Disk 1 and 3, than the value of that peg is 2 + 8 = 10
Value of all disks will be 2^1 + 2^2....2^(n) = (2^n) - 2. For e.g. the total value of 4 disks will be 2^4 - 2 = 30
I am using "Bitwise And" operator to decide if a given disk exists on the peg. For e.g.
-if the peg value is 20 (Disk 2 and 4) then 20 "Bitwise And" 2 will equal to 0 which means that peg doesn't have Disk 1
-if the peg value is 20 (Disk 2 and 4) then 20 "Bitwise And" 4 will equal to 4 which means that peg does have Disk 2
To check if I am not placing bigger disk on top of smaller disk, I used the Modulus (find the remainder) operator. For e.g.
-if the peg has value of 18(Disk 1 and 4), then 18 % 4 will be 2 which means I cannot place Disk 2 on this peg
-if the peg has a value of 24 (Disk 3 and 4) then 24 % 4 will be 0 which means I can place Disk 2 on this peg
'''
# Best First Search will use the Last In First Out logic. That way we are going to keep going deep(vertical) before we search horizontal states.
def Solve_By_BestFS(n):
# Declare Variables
# Values of each Peg
peg1_value = peg2_value = peg3_value = 0
# List to store the adjacent states
state_COLLECTION = []
# list used to save the actions we have taken till for every item in previous list, so we can trace back. The size of this list will always be same as size of other COLLECTION list
steps_till_now_COLLECTION = []
# This List is to store the states which we have already encountered, so that we do not go into infinite loop
past_states = []
# temporary variables to store the steps for current working state and next adjacent state
steps_till_current_state = steps_till_next_state = []
# Temporary variable to store the value of disk being moved
Value_of_Disk = 0
# Temporary variable to store current state and the next adjacent state
current_state = new_state = []
# Temporary variable to store the disk being moved
disk_on_top = 0
# Boolean variables
state_found_before = solution_found = False
# Find the total value of all disks based on n number of disks
Value_of_All_Disks = int(math.pow(2, n + 1)) - 2
# Initial state where all disks are in Peg1. Because Lists are indexed starting 0, we will just ignore the 0th index.
current_state = [0, Value_of_All_Disks, 0, 0]
# Insert the starting state in the COLLECTION list
state_COLLECTION.append(current_state)
steps_till_now_COLLECTION.append(steps_till_current_state)
past_states.append(current_state)
# Loop till we find the solution
while solution_found == False and len(state_COLLECTION) > 0:
# Get the BEST state in stack
best_item = - 1
for item in range(0,len(state_COLLECTION)):
state = state_COLLECTION[item]
for d in range(n-1, 0, -1):
partial_solution_val = math.pow(2, d+1)-2
if ((n+d)%2 == 0):
partial_solution_peg = 3
else:
partial_solution_peg = 2
if (state[partial_solution_peg] == partial_solution_val):
best_item = item
break
if (best_item > -1):
break
if best_item == -1:
best_item = 0
current_state = state_COLLECTION.pop(best_item)
# Get the corresponding steps on COLLECTION logic
steps_till_current_state = steps_till_now_COLLECTION.pop(best_item)
# Loop all pegs for source for disk movement
for source_peg in range(3, 0, -1):
# if the peg has no disk as of now, then move on to next peg
if (current_state[source_peg] == 0):
continue
# Loop all pegs for destination for disk movement
for dest_peg in range(3, 0, -1):
# Source Peg and Dest Peg cannot be same
if (solution_found == True or source_peg == dest_peg):
continue
# Loop for each disk size from small to big
for disk_size in range(1, n + 1):
Value_of_Disk = int(math.pow(2, disk_size))
# Using Bitwise AND operator find the disk on top of this source peg
if ((current_state[source_peg] & Value_of_Disk) == Value_of_Disk):
disk_on_top = disk_size
break
# Destination peg should either be empty or top disk should be bigger than the disk being moved
if (current_state[dest_peg] == 0 or current_state[dest_peg] % Value_of_Disk == 0):
# Following steps move the disk from source to dest peg, and create a new state out of current state
new_state = list(current_state)
new_state[source_peg] = new_state[source_peg] - Value_of_Disk
new_state[dest_peg] = new_state[dest_peg] + Value_of_Disk
next_step = [disk_on_top, source_peg, dest_peg]
steps_till_next_state = list(steps_till_current_state)
steps_till_next_state.append(next_step)
# Check if the new State is the Final Solution we are looking for (all disks on peg 3)
if (new_state[3] == Value_of_All_Disks):
steps = 1
output = ""
for aseq in steps_till_next_state:
output = output + str(steps) + ": Move Disk " + str(aseq[0]) + " From " + str(
aseq[1]) + " To " + str(aseq[2]) + "\n"
steps = steps + 1
print(output)
solution_found = True
return
# else - we did't find the solution yet
else:
# make sure the new state is not already discovered before
state_found_before = False
for past_state in past_states:
if (past_state[1] == new_state[1] and past_state[2] == new_state[2] and past_state[3] ==
new_state[3]):
state_found_before = True
break
# if this is the new state which we discovered before, then append it to the COLLECTION lists
if state_found_before == False:
state_COLLECTION.append(new_state)
steps_till_now_COLLECTION.append(steps_till_next_state)
past_states.append(new_state)
|
e6cd52ea2f93f9d6b604a86199e13e1062c077c6 | syurskyi/Python_Topics | /070_oop/001_classes/_exercises/exercises/Learning Python/029_002_Indexing and Slicing __getitem__ and __setitem__.py | 1,711 | 3.65625 | 4 | # c_ Indexer:
# ___ -g ____ index
# r_ ? ** 2
#
# X = I.
# print('#' * 23 + ' X[i] calls X.__getitem__(i)')
# print(X[2]) # X[i] calls X.__getitem__(i)
#
#
# # for i in range(5):
# # print(X[i], end=' ') # Runs __getitem__(X, i) each time
#
#
# L = [5, 6, 7, 8, 9]
# print('#' * 23 + ' Slice with slice syntax')
# print(L[2:4]) # Slice with slice syntax
#
# print(L[1:])
#
# print(L[:-1])
#
# print(L[::2])
#
# print('#' * 23 + ' Slice with slice objects')
# print(L[slice(2, 4)]) # Slice with slice objects
#
# print(L[slice(1, None)])
#
# print(L[slice(None, -1)])
#
# print(L[slice(None, None, 2)])
#
#
# c_ Indexer
# data = [5, 6, 7, 8, 9]
# ___ -g ____ index # Called for index or slice
# print('getitem:' ?
# r_ ____.d. i.. # Perform index or slice
#
# X = I...
# print('#' * 23 + ' Indexing sends __getitem__ an integer')
# (X[0]) # Indexing sends __getitem__ an integer
#
# X[1]
#
# X[-1]
#
# print('#' * 23 + ' Slicing sends __getitem__ a slice object')
# X[2:4] # Slicing sends __getitem__ a slice object
#
# X[1:]
#
# # X[:-1]
#
# X[::2]
#
#
# ___ -s_i_ ____ index value # Intercept index or slice assignment
#
# ____.data i.. = v.. # Assign index or slice
#
#
# # method __index is only in Python 3.0
# c_ C
# ___ -i ____
# r_ 255
#
# X = C()
# # print(hex(X)) # Integer value
#
# print(bin(X))
#
# # print(oct(X))
#
#
# print(('C' * 256)[255])
#
# print(('C' * 256)[X]) # As index (not X[i])
#
# print(('C' * 256)[X:]) # As index (not X[i:])
#
|
a89a070f334f385affe828fb48825fe57e7d8a2a | huberthoegl/start_python | /demos/math/glsys-2d/simple_numpy.py | 2,449 | 3.71875 | 4 | # simple_numpy.py
# H. Hoegl, November 2012, 2017
from __future__ import print_function
from __future__ import division
'''
Einfache Array und Matrizen Operationen
Literatur
Die wichtigsten Array und Matrix Operationen:
https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
Dieser Text verweist auf
https://docs.scipy.org/doc/numpy/reference/routines.html
Vergleich mit Matlab:
https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html
Vergleich mit IDL:
http://mathesaurus.sourceforge.net/idl-numpy.html
'''
import numpy as np
import matplotlib.pyplot as plt
print("% --- Arrays ---")
# array is an alias for ndarray
a = np.array([[1, 2], [3, 4]])
print("% a\n", a)
print()
b = np.array([[4, 1], [2, 5]])
print("% b =\n", b)
print()
print("% a*b\n", a*b) # elementweise Multiplikation
print()
print("% dot(a,b)", np.dot(a,b)) # Arrays muss man mit dot() multiplizieren
print()
# Matrizen kann man mit * multiplizieren
b = np.ones(10)
print("% ones(10)\n", b)
print()
# += and *= work in place
print("id(b)", id(b))
b += 1
print("b += 1")
print(b)
print("id(b)", id(b))
print()
print("b = b + 1")
b = b + 1
print(b)
print("id(b)", id(b))
print()
print("% outer(b,b)\n", np.outer(b,b))
print()
# arange returns an array object
c = np.arange(60)
print("% np.arange(60)\n", c)
print()
c.resize(3, 4, 5)
print("% c.resize(3, 4, 5)\n", c)
print()
print("c.shape\n", c.shape)
print()
print("c[2][0][4] =", c[2][0][4])
# bei c[2][0][5]: IndexError: index out of bounds
c.resize(2, 10, 3)
print("% c.resize(2, 10, 3)\n", c)
print()
c.resize(2, 2, 20)
print("% c.resize(2, 2, 20)\n", c)
print(c)
print()
print("% --- Matrizen ---")
A = np.matrix([[1, 2], [3, 4]])
print("% A\n", A)
print()
B = np.array([[4, 1], [2, 5]])
print("% B\n", B)
print()
print("% B.shape = ", B.shape)
print()
P = A*B
print("% P = A*B\n", P)
print()
print("% P transponiert\n", P.T)
print()
print("% P invers\n", P.I)
print()
K = np.matrix([[0.5, -1], [-0.25, -1]])
B = np.matrix([-1, -5])
# http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html
print("np.linalg.solve()")
P = np.linalg.solve(K, B.T)
# check
print("P = \n")
print(P)
print("check")
print((np.dot(K, P) == B.T).all())
x = np.linspace(-2, 12, 1000)
y1 = 0.5 * x + 1
y2 = -0.25 * x + 5
plt.grid()
plt.plot(x, y1, 'r')
plt.plot(x, y2, 'g')
plt.plot(P[0], P[1], 'bo')
plt.show()
|
8f24d9ce06e00efb552d92a0554cf7bca51e3b87 | yifanzhou106/leetcode | /EncodeandDecodeStrings.py | 1,304 | 3.78125 | 4 |
"""
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode and decode
"""
class Solution:
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single string.
"""
"""
word -> :;
: -> ::
"""
def encode(self, strs):
# write your code here
encodes = []
for str1 in strs:
if str1 == ':':
encodes.append('::')
else:
encodes.append(str1)
encodes.append(':;')
return "".join(encodes)
"""
@param: str: A string
@return: dcodes a single string to a list of strings
"""
def decode(self, str):
# write your code here
strs = []
decode = []
i = 0
while i < len(str) - 1:
if str[i] == ':':
if str[i + 1] == ':':
strs.append(str[i])
i += 2
elif str[i + 1] == ';':
strs.append("".join(decode))
decode = []
i += 2
else:
decode.append(str[i])
i += 1
return strs
|
1277901d6a9661b1e6658bf4bccf09d72f3844e0 | xferra/ggrc-core | /test/selenium/src/lib/date.py | 793 | 3.84375 | 4 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module for date operations"""
import calendar
from datetime import datetime
def get_days_in_current_month():
"""Gets days in current month
Returns:
int
"""
now = datetime.now()
_, days_in_month = calendar.monthrange(now.year, now.month)
return days_in_month
def get_month_start(date):
"""Gets a date object with the date of the first of the month.
Args:
date (datetime)
Returns:
datetime
"""
return date.replace(day=1)
def get_month_end(date):
"""Gets month end of the input date object.
Args:
date (datetime)
Returns:
datetime
"""
return date.replace(day=calendar.monthrange(date.year, date.month)[1])
|
8053d2fd3b292771e26b77c215d8838e814f2fd0 | rohithdara/CPE101-Labs | /LAB6/char.py | 654 | 4.21875 | 4 | #Lab 6 Character Manipulation
#
#Name: Rohith Dara
#Instructor: S. Einakian
#Section: 01
#This function returns True if the character is lowercase and False if not
#str->bool
def is_lower_101(char1):
if ord('a') <= ord(char1) <= ord('z'):
return True
else:
return False
#This function returns the rot13 encoding of the inputted character
#str->str
def char_rot13(char2):
x = ord(char2)
if ord('a') <= x <= ord('z'):
if x <= ord('m'):
x += 13
elif x > ord('m'):
x -= 13
elif ord('A') <= x <= ord('Z'):
if x <= ord('M'):
x += 13
elif x > ord('M'):
x -= 13
return chr(x)
|
44e2b353d987fa105b2e0c1258b2500f7ac9125f | therealkevinli/ML_ipynb | /Scikit_knn/knn.py | 1,571 | 3.5625 | 4 | #example from this: https://www.youtube.com/watch?v=1i0zu9jHN6U
import numpy as np
from sklearn import preprocessing,cross_validation,neighbors
import pandas as pd
df = pd.read_csv('breast-cancer-wisconsin.data.txt')
df.replace('?',-99999,inplace=True) #this is to treat these as outliers when there is missing data
df.drop(['id'],1,inplace = True) #drop the id column
#df.dropna(inplace=True) #this will just drop all the missing stuff
#X = np.array(df.drop(['class'],1)) #define X as the features
#we include everything in the features except the class column
y = np.array(df['class']) #define y as labels (class)
#df.drop(['class'],1,inplace = True)
print(type(df))
#https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html
print(df.columns)
X = np.array(df.drop(['class'],1)) #define X as the features
print(len(X))
#the test size is 20 percent
#quickly shuffle the data and seperate it into training and testing chunks
X_train, X_test, y_train,y_test = cross_validation.train_test_split(X,y,test_size = 0.2)
clf = neighbors.KNeighborsClassifier()
clf.fit(X_train,y_train) #fit the xtrain and ytrain
accuracy = clf.score(X_test,y_test)
print(accuracy)
example_measures = np.array([[4,2,1,2,2,2,3,2,1],[4,2,1,5,1,2,3,2,1]]) #don't forget 2d list,
#even if you have only one list
#example_measures = example_measures.reshape(1,-1)
prediction = clf.predict(example_measures)
print(prediction)
print(np.shape(X_train))
print(np.shape(X_test))
print(np.shape(y_train))
print(np.shape(y_test))
|
8d3b1c37477cd499fd19db3512c344bc2e3c4f2f | dubblin27/pythonfordatascience | /Movie_recommendation_adv.py | 4,630 | 3.546875 | 4 | #colloborative filtering will be used
# model based CF using singular value Decomposition and
# Memeory based Decomposition by cosine simularity
from math import sqrt
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.metrics import mean_squared_error
import scipy.sparse as sp
from scipy.sparse.linalg import svds
columns_name = ['user_id','item_id','rating','timestamp']
df = pd.read_csv('dataset and ipynb/19-Recommender-Systems/u.data',sep='\t',names=columns_name)
# print(df.head())
# we only have the ID of the movies
movie_titles = pd.read_csv('dataset and ipynb/19-Recommender-Systems/Movie_Id_Titles')
df = pd.merge(df,movie_titles,on='item_id')
# print(df.head())
#to find unique users and movies
n_users = df.user_id.nunique()
n_items = df.item_id.nunique()
print(n_items,"\n",n_users)
#split training and testing of data
train_data,test_data = train_test_split(df,test_size = 0.25 )
#memory based colloborative filtering
# Memory-Based Collaborative Filtering approaches can be divided into two main sections:
# user-item filtering and item-item filtering.
# A user-item filtering will take a particular user,
# find users that are similar to that user based on similarity of ratings, and
# recommend items that those similar users liked.
# In contrast, item-item filtering will take an item,
# find users who liked that item, and find other items that those users or
# similar users also liked. It takes items and outputs other items as recommendations.
# Item-Item Collaborative Filtering: “Users who liked this item also liked …”
# User-Item Collaborative Filtering: “Users who are similar to you also liked …”
#eg : netflix
# In both cases, you create a user-item matrix which built from the entire dataset.
# Since we have split the data into testing and training we will need to create two [943 x 1682] matrices (all users by all movies).
# The training matrix contains 75% of the ratings and the testing matrix contains 25% of the ratings.
# now to create 2 matrices - train and test
train_data_matrix = np.zeros((n_users,n_items))
for line in train_data.itertuples():
train_data_matrix[line[1]-1, line[2]-1] = line[3]
test_data_matrix = np.zeros((n_users, n_items))
for line in test_data.itertuples():
test_data_matrix[line[1]-1, line[2]-1] = line[3]
# to calculate Cosine Similarity
#op will range from 0-1 as the ratings are all positive
user_similarity = pairwise_distances(train_data_matrix, metric='cosine')
item_similarity = pairwise_distances(test_data_matrix.T, metric='cosine')
def predict(ratings, similarity, type='user'):
if type == 'user' :
mean_user_rating = ratings.mean(axis = 1)
#np.newaxis - mean_user_ratings have same format as the rating
ratings_diff = (ratings - mean_user_rating[:,np.newaxis])
pred = mean_user_rating[:, np.newaxis] + similarity.dot(ratings_diff) / np.array([np.abs(similarity).sum(axis=1)]).T
elif type == 'item' :
pred = ratings.dot(similarity) / np.array([np.abs(similarity).sum(axis=1)])
return pred
item_prediction = predict(train_data_matrix, item_similarity, type='item')
user_prediction = predict(train_data_matrix, user_similarity, type='user')
#evaluation - using Root mean squared error
# prediction[ground_truth.nonzero()] - only to obtain the ratings that are in the test data set
def rmse(prediction,ground_truth) :
prediction = prediction[ground_truth.nonzero()].flatten()
ground_truth = ground_truth[ground_truth.nonzero()].flatten()
return sqrt(mean_squared_error(prediction, ground_truth))
print('User-based CF RMSE: ' + str(rmse(user_prediction, test_data_matrix)))
print('Item-based CF RMSE: ' + str(rmse(item_prediction, test_data_matrix)))
# draw backs of memory based algo are not scalable to the real world scnerio
# model colloborative filtering
sparsity=round(1.0-len(df)/float(n_users*n_items),3)
print('The sparsity level of MovieLens100K is ' + str(sparsity*100) + '%')
# factorization method using single value decomposition
# U is an (m x r) orthogonal matrix
# S is an (r x r) diagonal matrix with non-negative real numbers on the diagonal
# V^T is an (r x n) orthogonal matrix
# Elements on the diagnoal inSare known as *singular values of X
u, s, vt = svds(train_data_matrix, k = 20)
s_diag_matrix=np.diag(s)
X_pred = np.dot(np.dot(u, s_diag_matrix), vt)
print('User-based CF MSE: ' + str(rmse(X_pred, test_data_matrix)))
|
369eb10dcff5d82e37a793cee695c913826ce7b7 | BrendanArthurRing/code | /katas/fraction-to-mixed-number.py | 10,778 | 4.28125 | 4 | # https://www.codewars.com/kata/simple-fraction-to-mixed-number-converter/train/python
'''
Task
Given a string representing a simple fraction x/y, your function must return a string representing the corresponding mixed fraction in the following format:
[sign]a b/c
where a is integer part and b/c is irreducible proper fraction. There must be exactly one space between a and b/c. Provide [sign] only if negative (and non zero) and only at the beginning of the number (both integer part and fractional part must be provided absolute).
If the x/y equals the integer part, return integer part only. If integer part is zero, return the irreducible proper fraction only. In both of these cases, the resulting string must not contain any spaces.
Division by zero should raise an error (preferably, the standard zero division error of your language).
Value ranges
-10 000 000 < x < 10 000 000
-10 000 000 < y < 10 000 000
Examples
Input: 42/9, expected result: 4 2/3.
Input: 6/3, expedted result: 2.
Input: 4/6, expected result: 2/3.
Input: 0/18891, expected result: 0.
Input: -10/7, expected result: -1 3/7.
Inputs 0/0 or 3/0 must raise a zero division error.
Note
Make sure not to modify the input of your function in-place, it is a bad practice.
'''
from fractions import gcd
from fractions import Fraction
from re import match
from fractions import Fraction as frac
def mixed_fraction(string):
# Use RegEx to extract the fractions parts
expression = r'(-?\d*)(/)(-?\d*)'
matched = match(expression, string)
num = int(matched.group(1))
den = int(matched.group(3))
whole_num = 0
simple_fract = 0
print(f"Original: {string}")
print(f'Matched: {num}/{den}')
# Check for zero division
try:
num / den
except ZeroDivisionError:
print('Denominator cannot be 0.')
raise ZeroDivisionError
# Zero Numerator
if num == 0:
print('Zero Numerator')
return '0'
# Double Negative
if num < 0 and den < 0:
print('Double Negative')
whole_num = num // den
num = abs(num) % abs(den)
den = abs(den)
print(f'Mixed Fraction: {whole_num} {num}/{den}')
simple_fract = frac(f'{num}/{den}')
print(f'Simple Mixed Fraction: {whole_num} {simple_fract}')
# Negative Numerator | Num < Den
elif num < 0 and den > 0 and abs(num) < abs(den):
print('Negative Numberator | Num < Den')
whole_num = (num // den) + 1
if whole_num == 0:
simple_fract = frac(f'{num}/{den}')
print(f'Simple Fraction: {simple_fract}')
num = simple_fract.numerator
den = simple_fract.denominator
else:
num = (num % den) - 1
print(f'Negative Numerator: {whole_num} {num}/{den}')
# Negative Numerator | Num > Den
elif num < 0 and den > 0 and abs(num) > abs(den):
print('Negative Numerator | Num > Den')
simple_fract = frac(f'{num}/{den}')
print(f'Simple Fraction: {simple_fract}')
num = simple_fract.numerator
den = simple_fract.denominator
if den == 1:
whole_num = num
else:
whole_num = (num // den) + 1
num = abs(num) % abs(den)
# Negative Denominator | Num < Den
elif num > 0 and den < 0 and abs(num) < abs(den):
print('Negative Denominator | Num < Den')
whole_num = (num // den) + 1
if whole_num == 0:
den = abs(den)
num = num * -1
simple_fract = frac(f'{num}/{den}')
print(f'Simple Fraction: {simple_fract}')
num = simple_fract.numerator
den = simple_fract.denominator
else:
num = num % den
den = abs(den)
print(f'Negative Denominator: {whole_num} {num}/{den}')
# Negative Denominator | Num > Den
elif num > 0 and den < 0 and abs(num) > abs(den):
print('Negative Denominator | Num > Den')
if abs(num) % abs(den) == 0:
return f'{int(num / den)}'
else:
whole_num = (num // den) + 1
num = abs(num) % abs(den)
den = abs(den)
print(f'Negative Denominator: {whole_num} {num}/{den}')
# Negative Denominator | Num = Den
elif num > 0 and den < 0 and abs(num) == abs(den):
return '-1'
# Normal Fraction
elif num > 0 and den > 0:
whole_num = num // den
num = num % den
print(f'Normal Fraction: {whole_num} {num}/{den}')
# Simplify Fraction if numerator is not 0
simple_fract = frac(f'{num}/{den}')
print(f"Result: {whole_num} and {simple_fract}")
# Return results
if whole_num and num:
result = f'{whole_num} {simple_fract}'
print(result)
return result
if whole_num and not num:
result = f'{whole_num}'
print(result)
return result
if not whole_num and num:
result = f'{simple_fract}'
print(result)
return result
if not whole_num and not num:
result = '0'
print(result)
return result
# Test Block
class Test:
def assert_equals(a, b):
if a == b:
print("Passed \n \n")
if a != b:
print(f"Failed\n{a} should equal {b}\n\n")
def describe(text):
print(text)
def expect_error(text, test_function):
print(text)
if test_function == ZeroDivisionError:
print("Passed")
print("Failed")
def it(text):
print(text)
# Print('Zero Division Tests')
# Test.assert_equals(mixed_fraction('0/18891'), '0')
# Test.expect_error("Must raise ZeroDivisionError", lambda: mixed_fraction(0, 0))
# Test.expect_error("Must raise ZeroDivisionError", lambda: mixed_fraction(3, 0))
def mixed_fraction(s):
f = Fraction(*map(int, s.split('/')))
if f.denominator == 1:
return str(f.numerator)
n = abs(f.numerator) / f.denominator * (1 if f.numerator > 0 else -1)
f = abs(f - n) if n else f - n
return "{} {}".format(n, f) if n else str(f)
print('--- Zero Numerator Tests ---')
Test.assert_equals(mixed_fraction('0/-8192867'), '0')
print('-----------------------------------------\n\n')
# # Regular Fractions
# print('--- Regular Fraction Tests ---\n')
# Test.assert_equals(mixed_fraction('42/9'), '4 2/3')
# Test.assert_equals(mixed_fraction('6/3'), '2')
# Test.assert_equals(mixed_fraction('4/6'), '2/3')
# print('-----------------------------------------\n\n')
# print('--- Double Negative Tests ---\n')
# Test.assert_equals(mixed_fraction('-22/-7'), '3 1/7')
# print('-----------------------------------------\n\n')
print('--- Negative Numerator | Num < Den | Tests ---\n')
Test.assert_equals(mixed_fraction('-1639839/5749154'), '-1639839/5749154')
print('--- Negative Numerator | Num > Den | Tests ---\n')
Test.assert_equals(mixed_fraction('-10/7'), '-1 3/7')
Test.assert_equals(mixed_fraction('-9056102/8938892'), '-1 58605/4469446')
Test.assert_equals(mixed_fraction('-2487956/1243978'), '-2')
print('-----------------------------------------\n\n')
print('--- Negative Denominator | Num < Den | Tests ---\n')
Test.assert_equals(mixed_fraction('1820963/-6645345'), '-1820963/6645345')
print('-----------------------------------------\n\n')
print('--- Negative Denominator | Num > Den | Tests ---\n')
Test.assert_equals(mixed_fraction('8877176/-210033'), '-42 55790/210033')
Test.assert_equals(mixed_fraction('12145792/-6072896'), '-2')
print('-----------------------------------------\n\n')
print('--- Negative Denominator | Num = Den | Tests ---\n')
Test.assert_equals(mixed_fraction('9628608/-9628608'), '-1')
print('-----------------------------------------\n\n')
'''
if numer and denom < 0:
string = f'{numer * -1}/{denom * -1}'
numer = numer * -1
denom = denom * -1
p_frac = frac(string)
p_numer = p_frac.numerator
p_denom = p_frac.denominator
w_num = p_numer // p_denom
# Check if fraction needs reducing
if numer != p_numer and denom != p_denom:
numer = p_numer % p_denom
denom = p_denom
print('')
print('')
print(f'Original: {string}')
print(f'Whole Number: {w_num}')
print(f'Numerator: {numer}')
print(f'Denominator: {denom}')
if w_num and numer:
result = f'{w_num} {numer}/{denom}'
print(result)
return result
if w_num and not numer:
result = f'{w_num}'
print(result)
return result
if not w_num and numer:
result = f'{numer}/{denom}'
print(result)
return result
if not w_num and not numer:
result = '0'
print(result)
return result
'''
# Wow
'''
In retrospect I got totally schooled here, took me about 10 hours of work to get my code that passed all the tests. Wrote 122 lines of code. The best pracitce is ... 7 lines of code ... the pain! But actually am finding that it does not pass the tests - so am wondering how this got to be a best practice?
'''
def mixed_fraction(s):
f = Fraction(*map(int, s.split('/')))
if f.denominator == 1:
return str(f.numerator)
n = abs(f.numerator) / f.denominator * (1 if f.numerator > 0 else -1)
f = abs(f - n) if n else f - n
return "{} {}".format(n, f) if n else str(f)
def mixed_fraction(s):
# Uses split to get the values, and maps to int becuse int() is a func
# The star packs the values into the Fraction tuple
f = Fraction(*map(int, s.split('/')))
# Returns the numerator if denominator is 1
if f.denominator == 1:
return str(f.numerator)
# Crazy math logic distilled into one line
n = abs(f.numerator) / f.denominator * (1 if f.numerator > 0 else -1)
f = abs(f - n) if n else f - n
return "{} {}".format(n, f) if n else str(f)
# The ZeroDivisionError is built-in to the Fraction module
'''
The best practice 2nd place is from the guy who made this kata
'''
def mixed_fraction(s):
x, y = map(int, s.split('/'))
signx = x/abs(x) if x else 1
signy = y/abs(y) if y else 1
sign = signx * signy
x, y = map(abs, (x, y))
a, b = divmod(x, y)
g = gcd(b, y)
b, c = b/g, y/g
result = (str(a) * bool(a) + ' ' * bool(a) *
bool(b) + (str(b) + '/' + str(c)) * bool(b))
if not result:
return '0'
if sign < 0:
result = '-' + result
return result
|
e209dd20bca0f9ef8caba0a8785e9ffefa698757 | GabrielReira/Python-Exercises | /25 - Maioridade.py | 488 | 3.765625 | 4 | # PROGRAMA QUE LEIA O ANO DE NASCIMENTO DE X PESSOAS E DIGA QUANTAS PESSOAS
# SÃO MAIORES DE IDADE, UTILIZANDO A BIBLIOTECA DE DATAS.
from datetime import date
ano = date.today().year
maior = menor = 0
total = int(input('Qual o número de pessoas? '))
for x in range(total):
nasc = int(input(f'Em que ano a {x +1}ª pessoa nasceu? '))
if ano - nasc < 18:
menor += 1
else:
maior += 1
print(f'{maior} pessoas são maiores de idade e {menor} são menores.') |
f0f7bedadacf48f40314d3d6fb8cbe51d31a5679 | RomanAdriel/AlgoUnoDemo | /RomanD/ejercicios_rpl/estructuras_basicas/ej_7_calculando_potencias.py | 733 | 4.3125 | 4 | """Escribir un programa que solicite el ingreso de un valor correspondiente a una base y un valor correspondiente
a una potencia e imprima por pantalla el resultado de elevar la base ingresada a la potencia ingresada.
El cálculo de la potencia debe ser realizado a través de la realización de multiplicaciones sucesivas.
No se puede utilizar el operador "**".
Ingrese la base: 2
Ingrese la potencia: 4
16"""
base = int(input("Ingrese la base: "))
potencia = int(input("Ingrese la potencia: "))
if base == 1 or (base == 0 and potencia == 0):
resultado = 1
elif potencia == 1:
resultado = base
else:
resultado = base
for i in range(1, potencia):
resultado = resultado * base
print(resultado) |
6374e0c5c6d5aa58cbe34284f14bce9464e534b2 | lawalton/oo-project | /code/model/studentfactory.py | 1,256 | 3.640625 | 4 | import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from student import *
class StudentFactory(object):
"""
Creates different types of students
"""
def getStudent(self, studentType, name, year, args):
"""
Creates a type of Student based on the type.
:param str studentType: type of student
:param str name: student name
:param str year: student's academic year
:param list args: list of additional arguments required to create the student
:return: the student
:rtype: Member or Officer
"""
# studentType is either "member" or "officer"
# args is the list of arguments for that type of student
if studentType.lower() == "member":
student = Member(name, year)
# args[0] is number of events attended
student.setNumEventsAttended(args[0])
return student
elif studentType.lower() == "officer":
student = Officer(name, year)
# args[0] is number of events helped, args[1] is position
student.setNumEventsHelped(args[0])
student.setPosition(args[1])
return student
else:
return None
|
a46b979d5da3aa6cbc8b130717943d6fb74aead9 | wassimajjali/Astar | /Astar_Wirth-Ajjali/city.py | 819 | 3.78125 | 4 | # -*-coding:Latin-1-*
__author__ = "Wirth Jeremy & Wassim Ajjali"
class City:
def __init__(self, name, x,y, parent):
self.name = name
self.x = x
self.y = y
self.parent = parent
self.d = 0
self.h = 0
self.listConnection = []
def __repr__(self):
return self.name
def addConnection(self, city):
self.listConnection.append(city)
def getConnection(self):
return self.listConnection
def __lt__(self, other):
return self.h < other.h
def __eq__(self, other):
return self.name == other.name
def parcours(self):
listParent = [self]
parent = self.parent
result = ""
while parent != None:
listParent.append(parent)
parent = parent.parent
for city in reversed(listParent):
result += city.name + " (" + str(city.d) +" km)\n"
return result |
cc03726ded912109d0de6f07c7ab23eee8d07cbc | Arnkrishn/ProjectEuler | /Problem2/problem2.py | 567 | 3.53125 | 4 | import time
def fibo(num):
return num if num in (1, 2) else fibo(num - 1) + fibo(num - 2)
def even_fibo_sum(val_limit):
fibo_sum = 0
i = 1
if val_limit <= 0:
print "Please have limit > 0"
else:
while 1:
fibo_num = fibo(i)
if fibo_num % 2 == 0:
fibo_sum += fibo_num
if fibo_num < val_limit:
i += 1
else:
break
return fibo_sum
#Test
start_time = time.time()
print even_fibo_sum(4000000)
print time.time() - start_time, " seconds"
|
323ce23bf7083a6d648b56e95e9fc1e9b449b0f5 | Walop/AdventOfCode2017 | /millisecond4/millisecond4_1.py | 276 | 3.578125 | 4 | import re
with open("input") as file:
input_txt = file.read()
phrases = input_txt.split("\n")
valid = 0
invalid_re = re.compile(r"(\b\w+\b).*\1")
for phrase in phrases:
if invalid_re.search(phrase) == None:
valid += 1
print(valid)
|
caf87164d2fb434c38bcd5fbc2dec9621ea390a3 | ASaltedF1sh/jianzhi_offer | /字节跳动/Reverse_List.py | 291 | 3.6875 | 4 | class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if len(s) == 0:
return
tmp = s[0]
del s[0]
self.reverseString(s)
s.append(tmp)
|
551b9a22e660bc083f0e0422eee6c0fcb364f097 | RadkaValkova/SoftUni-Web-Developer | /Programming Basics Python/05 Loops Part 2/Sequence 2k+1.py | 241 | 3.765625 | 4 | n = int(input())
number = 1
while number <= n:
print(number)
number = number * 2 +1
# n = int(input())
# result = 1
# for num in range (1, n+1):
# print(result)
# result = result*2+1
# if result > n:
# break
|
dc7276102c023abe5aa2b379123f34be09996ade | Dhamastana/Quiz-4-Alpro | /Quiz43_DhamastanaDD_1201180226.py | 248 | 3.65625 | 4 | listGPA = [2.1,2.5,4,3]
def hadiah(GPA):
bonus = 500000
hadiah = GPA*bonus
return hadiah
for GPA in listGPA:
if GPA > 2.5 :
print("hadiah anda : Rp", hadiah(GPA))
else:
print("maaf coba lagi")
|
df59ae842e78a86d455c9877a0223a49c2b38978 | nrsimonelli/python-server-side-master | /main.py | 812 | 3.609375 | 4 | from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
# making a dictionary
names = {"nick": {"age": 30, "gender": "male"},
"danielle": {"age": 26, "gender": "female"}}
class HelloWorld(Resource):
# defining GET
def get(self, name):
# setting the return
# python dictionary, key and values // data and helloworld
# you want to return json serializable objects // use python dictionareis like below
return {"name": name}
# where you can access the GET from // how you find it
# Get request to /helloworld should yield "hello world"
# use <> to define parameters in the path
api.add_resource(HelloWorld, "/helloworld<string:name>")
if __name__ == "__main__":
# only for dev enviornment, do not run in production
app.run(debug=True) |
d02726cc7b03db8afe8414ad7b78238ace8477b2 | tri2sing/IntroPython | /HelloWorld.py | 259 | 3.984375 | 4 | if __name__ == '__main__':
name = input("Please enter your name: ")
print('Hello World from ' + name)
n = int(input("Please enter a number: "))
print(n)
print(type(n))
print("Hello " * n + name)
print(("Hello " + name + ' ' ) * 3)
|
f699d6da51f3ae6027e53ea19b68253f62933349 | treno/project-euler | /euler_7_bruteforce.py | 1,498 | 4.125 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13 we can see that the 6th prime is 13.
What is the 10,001st prime number?
"""
LIMIT = 100
list_of_primes = [2]
# since no prime numbers are even, we can loop over odds only (starting with 3 and step by 2)
for candidate_prime in range(3, LIMIT * LIMIT, 2):
print('\n' + 'candidate = ' + str(candidate_prime))
# check to see if we have the LIMITth prime number
# if we don't, continue to generate prime numbers until we get it
if len(list_of_primes) != LIMIT:
for n in list_of_primes:
print('n = ' + str(n))
# if the candidate prime is already in our list
# or if it evenly divides into a prime number less than it
# we know it's not prime and we can break and try the next candidate
if candidate_prime in list_of_primes or candidate_prime % n == 0:
break
# if we try to divide the candidate by all prime numbers smaller than itself
# and every divisor generates a non-zero remainder, we know the
# number is prime and we add it to our growing list of prime numbers
elif list_of_primes.index(n) == len(list_of_primes) - 1:
list_of_primes.append(candidate_prime)
print(list_of_primes)
print(len(list_of_primes))
# if we do have the LIMITth prime number, break and print answer
else:
break
print(list_of_primes[LIMIT - 1])
|
53c32ca29e68d6f366f0dc4367a939b4f2b5dc94 | ajnirp/leetcode | /easy/even-digits.py | 199 | 3.796875 | 4 | # https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(len(str(num)) % 2 == 0 for num in nums) |
010259d1d592c70211d0ab3d95627c5efd5af46a | joshuaBagnall/python_practice | /return_statement.py | 83 | 3.515625 | 4 |
def cube(number):
return number*number*number
result = cube(5)
print(result) |
6ceb7010f6b77ef0a9c616a068e55a5cbdd36a43 | BJV-git/leetcode | /math/add_digits.py | 131 | 3.515625 | 4 |
def add_digits(n):
if n == 0:
return 0
rem = n % 9
if rem == 0:
return 9
else:
return rem |
564fe6203c11f3866cb83aa2048cc61d426a1882 | Maxim-Krivobokov/python-practice | /Book_automation/ch4/allcats1.py | 478 | 3.84375 | 4 | print('Enter the name of cat №1:')
catname1 = input()
print('Enter the name of cat №2:')
catname2 = input()
print('Enter the name of cat №3:')
catname3 = input()
print('Enter the name of cat №4:')
catname4 = input()
print('Enter the name of cat №5:')
catname5 = input()
print('Enter the name of cat №6:')
catname6 = input()
print('The cat names are:')
print(catname1 + ' ' + catname2 + ' ' + catname3 +
' ' + catname4 + ' ' + catname5 + ' ' + catname6)
|
d5e02ebb88fe4fcabfad56717a0ebabe0029b74d | manimanis/2SC | /progs/seance03.py/tortue_lievre_v2.py | 558 | 3.71875 | 4 | from random import randint
pos_lievre = 0
pos_tortue = 0
while True:
de = randint(1, 6)
print('dé =', de)
if de != 6:
pas = (de + 1) // 2
pos_tortue += pas
if pos_tortue > 8:
pos_tortue = 8
print("La tortue avance à la position :", pos_tortue)
else:
pos_lievre = pos_lievre + 4
print("Le lièvre avance à la position :", pos_lievre)
if pos_lievre == 8 or pos_tortue == 8:
break
if pos_lievre == 8:
print('Le lièvre gagne.')
else:
print('La tortue gagne.') |
75c831338f88e911a863ee8ef5d59951b462dc6a | ckopecky/Python-OOP-Toy | /src/ball.py | 3,569 | 3.921875 | 4 | import math
from pygame.math import Vector2
class Ball:
"""
base class for bouncing objects - base class is the root class that other classes inherit from
"""
def __init__(self, bounds, position, velocity, color, radius):
self.position = position
self.velocity = velocity
self.bounds = bounds
self.color = color
self.radius = radius
def update(self): #this is a method
# bounce at edges. TODO: Fix sticky edges
nxt = self.position + self.velocity
left_edge_nxt = nxt.x < 0 + self.radius
right_edge_nxt = nxt.x > self.bounds[0] - self.radius
top_edge_nxt = nxt.y < 0 + self.radius
bottom_edge_nxt = nxt.y > self.bounds[1] - self.radius
if left_edge_nxt:
self.position.x = self.radius * 2 - nxt.x
self.velocity.x *= -1
elif right_edge_nxt:
self.position.x = (self.bounds[0] - self.radius) * 2 - nxt.x
self.velocity.x *= -1
else:
self.position.x += self.velocity.x
if top_edge_nxt:
self.position.y = self.radius * 2 - nxt.y
self.velocity.y *= -1
elif bottom_edge_nxt:
self.position.y = (self.bounds[1] - self.radius) * 2 - nxt.y
self.velocity.y *= -1
else:
self.position.y += self.velocity.y
def draw(self, screen, pygame):
# cast x and y to int for drawing
pygame.draw.circle(screen, self.color, [int(self.position.x), int(self.position.y)], self.radius)
class BouncingBall(Ball):
def __init__(self, bounds, position, velocity, color, radius, gravity):
self.gravity = gravity
super().__init__(bounds, position, velocity, color, radius)
# """
# ball affected by gravity
# """
# # TODO: update
def update(self):
self.velocity.y += self.gravity
super().update()
class RainbowBall(Ball):
# """
# Ball that changes colors
# """
# # TODO: update
def update(self):
r = (self.color[0]+ 5) % 256
g = (self.color[1] + 2) % 256
b = (self.color[2] - 1) % 256
self.color = [r, g, b]
super().update()
class BouncingRainbow(BouncingBall, RainbowBall):
# """
# Ball that changes color and is affected by gravity
# """
# # TODO:
def update(self):
BouncingBall(self, self.position, self.velocity, self.color, self.radius, self.gravity)
RainbowBall(self, self.position, self.velocity, self.color, self.radius)
super().update()
class KineticBall(Ball):
# """
# A ball that collides with other collidable balls using simple elastic circle collision
# """
# # TODO: update
def __init__(self, ball_list, bounds, position, velocity, color, radius):
self.ball_list = ball_list
super().__init__(bounds, position, velocity, color, radius)
def update(self):
for ball in self.ball_list:
if ball == self:
continue
else:
distance = ball.position.distance_to(self.position)
sumradius = self.radius + ball.radius
if distance < sumradius:
print("Collision!")
super().update()
# class KineticBouncing():
# """
# A ball that collides with other collidable balls using simple elastic circle collision
# And is affected by gravity
# """
# class AllTheThings(???):
# """
# A ball that does everything!
# """ |
628717decff3b0e76e820a1003a48f1b6065566f | pbmuller/graph | /src/Node.py | 1,298 | 3.609375 | 4 | from src.Vector import Vector
class Node:
__special_status = ['none', 'sink', 'star']
__node_ids = set()
NULLNODE = None
def __init__(self, node_id, neighbors=set()):
if node_id not in Node.__node_ids:
self.node_id = node_id
Node.__node_ids.add(self.node_id)
else:
raise ValueError("Can't repeat node ids")
self.vectors = self.__make_path(neighbors)
self.__init_null_node()
def __make_path(self, neighbors):
vectors_to_neighbors = set()
for neighbor in neighbors:
vectors_to_neighbors.add(Vector.make_vector(self, neighbor, 1))
return vectors_to_neighbors
def __repr__(self):
rep = 'node_id = {}\n'.format(self.node_id)
rep += 'vectors\n'
for vector in self.vectors:
rep += '\t{}\n'.format(vector)
return rep
def add_neighbor(self, neighbor_node):
if self == Node.NULLNODE:
raise ValueError('You can node add neighbors to the NULLNODE')
if not isinstance(neighbor_node, Node):
raise TypeError("neighbor_node must be of type Node")
# if neighbor_node in self.vectors
def __init_null_node(self):
if Node.NULLNODE is not None:
self.__init__(None) |
9a540af3c2bf7a4f7fb3d43c86cb01b803387c56 | sanchezolivos-unprg/trabajo. | /verificador#02.py | 304 | 3.890625 | 4 | # verificador de la calculadora 02
nombre= "inercia"
aceleracion= 7.5
masa= 45
fuerza= masa*aceleracion
print("el calculo de una fuerza")
print("la masa es:", masa)
print("la aceleracion es:", aceleracion)
# verificador
verificador= (fuerza==337.5)
print("la fuerza es 337.5:", verificador) |
e31932be23e5f1c5c2e8125a4bf63c4fbb4b6579 | kopchik/itasks | /tallentbuddy.co/max_sum.py | 543 | 3.78125 | 4 | #!/usr/bin/env python3
from __future__ import print_function
cache = {}
def maxsum(v):
if v in cache:
return cache[v]
answer = 0
i = 0
while i<len(v):
answer = max(answer,v[i]+maxsum(v[i+2:]))
i += 1
cache[v] = answer
return answer
def find_max_sum2(v):
print(maxsum(tuple(v)))
def find_max_sum(v):
s1, s2 = 0, 0
for i in range(len(v)):
s = max(s1, s2 + v[i])
s2 = s1
s1 = s
print(s1)
if __name__ == '__main__':
v= [2, 6, 7, 8]
assert find_max_sum(v) == find_max_sum2(v)
|
f78ff6fa4059a963bad624b362c92a997032808a | Anz131/luminarpython | /flow controls/looping/while.py | 151 | 3.828125 | 4 | #looping
#for
#while
#syntax
# 1. Initialization
# 2. Condition
# 3. Statement
# 4. Incr/Decr
# i=1
# while(i<=10):
# print("Anz...")
# i+=1 |
098771be954cc6053a919b74cfc90f1bcad4b42b | kruglov-dmitry/algos_playground | /list_deep_copy.py | 787 | 3.5625 | 4 | #
# https://leetcode.com/problems/copy-list-with-random-pointer
#
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
def solution(head):
if not head:
return head
mapping = {None: None}
new_mapping = {None: None}
root = head
while root:
mapping[root.val] = root.random.val if root.random else None
new_mapping[root.val] = Node(root.val, None, None)
root = root.next
root = head
while root:
cur_node = new_mapping[root.val]
if root.next:
cur_node.next = new_mapping[root.next.val]
cur_node.random = new_mapping[mapping[root.val]]
root = root.next
return new_mapping[head.val]
|
0ec50b652c2ab57ece97cbc2ced83a9af848eb9b | Lukas8733/pythonlesson1 | /talkToMe.py | 204 | 3.59375 | 4 | #talkToMe
print("Hello HTL Leoben!")
ich = input("Wie geht es dir?")
print("Schön dass es dir", ich, " geht! Mir geht es gut!")
name=input("Wie heisst du?")
print("Hallo, schön dich zu treffen", name, "!")
|
d38d393c93c5406b265a4016ffd00bc8cd6decf7 | erjan/coding_exercises | /longest_substring_with_at_least_k_repeating_characters.py | 2,507 | 3.734375 | 4 | '''
Given a string s and an integer k, return the length of
the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.
'''
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
cnt = collections.Counter(s)
st = 0
maxst = 0
for i, c in enumerate(s):
if cnt[c] < k:
maxst = max(maxst, self.longestSubstring(s[st:i], k))
st = i + 1
return len(s) if st == 0 else max(maxst, self.longestSubstring(s[st:], k))
-------------------------------------------------------------------------------------
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
if k > len(s):
# k is too large, larger than the length of s
# Quick response for invalid k
return 0
# just for the convenience of self-recursion
f = self.longestSubstring
## dictionary
# key: unique character
# value: occurrence
char_occ_dict = collections.Counter(s)
# Scan each unique character and check occurrence
for character, occurrence in char_occ_dict.items():
if occurrence < k:
# If occurrence of current character is less than k,
# find possible longest substring without current character in recursion
return max( f(sub_string, k) for sub_string in s.split(character) )
# -------------------------------
# If occurrences of all characters are larger than or equal to k
# the length of s is the answer exactly
return len(s)
-----------------------------------------------------------------------------------------------
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
problematic_letters = []
valid = True
counter = Counter(s)
for letter in counter:
if counter[letter] < k:
problematic_letters.append(letter)
valid = False
if valid:
return len(s)
for letter in problematic_letters:
s = s.replace(letter, ' ')
strings_after_divide = s.split()
ans = 0
for string in strings_after_divide:
ans = max(ans, self.longestSubstring(string, k))
return ans
|
2f3b3e05fb1c7fc23affc91aab5a79ebbc837f2e | pandwon/Week-9 | /week7.py | 467 | 3.953125 | 4 | stocks = {"tsla":883.45,"amd":94.44,"dis":169.56,"pep":141.80,"nflx":561.93,\
"ko":49.29,"amzn":3326.13,"ebay":59.17,"aal":15.53,"tsn":66.57}
ticker = input("Enter a stock ticker symbol. Type quit to stop: ")
while not ticker == "quit":
if ticker in stocks:
print("{}:{}" .format(ticker, stocks[ticker]))
else:
print("{} not found" .format(ticker))
ticker = input("Enter a stock ticker symbol. Type quit to stop: ") |
d0e2ee64220bd5a1fcb846bfba6e638e9f7ea961 | RiverRobins/Python-App | /Main/practice/sort.py | 1,046 | 3.5 | 4 | def bubble(n):
changed = True
while changed:
i = 0
while i < len(n) - 1:
if n[i] > n[i + 1]:
temp = n[i]
n[i] = n[i + 1]
n[i + 1] = temp
changed = True
break
else:
changed = False
i += 1
return n
def linear(n):
next = 0
prev = 0
changed = True
while changed:
i = 0
while i < len(n) - 1:
if n[i] < n[0]:
locals()
temp = n[i]
i2 = 0
next = 0
prev = 0
while i2 < len(n) - 1:
locals()
next = n[i2 + 1]
n[i2] = prev
i2 += 1
n[0] = temp
changed = True
break
else:
changed = False
i += 1
return n
nums = [10, 3, 1, 2, 4, 11, 8, 6, 7]
print(bubble(nums))
# print(linear(nums))
|
509dd98ad3c8200626fbe28acecda205e75df376 | AndreKauffman/EstudoPython | /Exercicios/ex103 - Ficha do Jogador.py | 316 | 3.546875 | 4 | def jogador(player= '<desconhecido>', gols = 0):
print(f"O jogador {player} fez {gols} gols na partida...")
nome = str(input("Nome: "))
gol = str(input("Gols: "))
if gol.isnumeric():
gol = int(gol)
else:
gol = 0
if nome.strip() == '':
jogador(gols = gol)
else:
jogador(nome, gol)
|
2badc00a7c73f0ba582ddec96d765289e586b605 | wtomalves/exerciciopython | /ex099funcao_valores.py | 454 | 4.09375 | 4 | from time import sleep
def numeros(*num):
maior = 0
sleep(1)
print('Analizados os valores passados...')
for valor in num:
print(f'{valor}', end=' ')
sleep(0.3)
if valor > maior:
maior = valor
print(f'Foram informados {len(num)} valores ao todo.')
sleep(1)
print(f'O Maior valor informado foi {maior}.' )
numeros(2, 9, 4, 5, 7, 1)
numeros(4, 7, 0)
numeros(1, 2)
numeros(6)
numeros(0)
|
35c34d9d3dd35c667a3654012890a9c5b71a5774 | OviDanielB/FoI17-18 | /esercizi_esame/problema5.py | 1,415 | 3.90625 | 4 | """
* Problema 5
* Si definisca una classe PoligonoRegolare. Ogni oggetto della classe ha come attributi
* il numero di lati e la lunghezza di un lato, e come operazioni due metodi che restituiscono,
* rispettivamente, la lunghezza del lato e il perimetro del poligono. Si definisca inoltre una classe
* Qadrato, derivata dalla classe PoligonoRegolare, che ha un metodo aggiuntivo che restituisce l'area
* del quadrato. Dare la definizione completa delle due classi in Python, che include la definizione dei
* rispettivi costruttori e dei metodi indicati. Fornire, inoltre, alcuni frammenti di codice Python che
* esemplificano l'uso delle classi (creazione di oggetti delle due classi, uso dei metodi).
"""
class PoligonoRegolare:
def __init__(self, n, len):
# @param n: Int
# @param len: Float
self.n = n
self.len = len
def getLen(self):
return self.len
def getPerimetro(self):
return self.n * self.len
class Quadrato(PoligonoRegolare):
def __init__(self, len):
PoligonoRegolare.__init__(self,4, len)
def getArea(self):
return self.len * self.len
# usage examples
poligono = PoligonoRegolare(5, 2.5)
poligono.getLen() # 2.5
poligono.getPerimetro() # 12.5
quadrato = Quadrato(2)
quadrato.getLen() # 2
quadrato.getPerimetro() # 8
quadrato.getArea() # 4
poligono.getArea() # ERRORE: metodo definito solo per classe Quadrato
|
48f15ec0da33187cba65ef622b7de5e5b2587bc6 | BaduMa/python-self-study | /list.py | 847 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/9 11:44
# @Author : maxu
# list是一种有序的集合,可以随时添加和删除其中的元素;list里面的元素的数据类型也可以不同
classmates = ['1', '2', '3']
classmates.append('4') #列表最后位置添加4
classmates.insert(3,'Ture') #列表第4个位置添加布尔True
classmates[1]='22222' #列表第2的位置换成22222字符串
print(len(classmates)) #执行完以上命令后输出列表长度
classmates.pop() #列表最后位置的元素删除
print(classmates)
print(classmates[2]) #第3个
print(classmates[-1]) #倒数第1个
list1 = ['a',True,123,['A','B','C']] #list元素也可以是另一个list
print(list1)
list2 =[] #如果一个list中一个元素也没有,就是一个空的list,它的长度为0
print(len(list2)) |
a1501663a9b5964eb25d35b265d3dced4d792bda | walzate/machine-learning | /knn_fruits.py | 1,544 | 4.375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
# based on https://hub.coursera-notebooks.org/user/smppgbjoljzaooewjwbuoj/notebooks/Module%201.ipynb
fruits = pd.read_table('fruit_data_with_colors.txt')
print(fruits.head())
# create a mapping from fruit label value to fruit name to make results easier to interpret
lookup_fruit_name = dict(zip(fruits.fruit_label.unique(), fruits.fruit_name.unique()))
print(lookup_fruit_name)
# For this example, we use the mass, width, and height features of each fruit instance
X = fruits[['mass', 'width', 'height']]
y = fruits['fruit_label']
# default is 75% / 25% train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
#Create classifier object
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 5)
#Train the classifier (fit the estimator) using the training data
knn.fit(X_train, y_train)
#Estimate the accuracy of the classifier on future data, using the test data
print(knn.score(X_test, y_test))
#Use the trained k-NN classifier model to classify new, previously unseen objects
# first example: a small fruit with mass 20g, width 4.3 cm, height 5.5 cm
fruit_prediction = knn.predict([[20, 4.3, 5.5]])
print(lookup_fruit_name[fruit_prediction[0]])
# second example: a larger, elongated fruit with mass 100g, width 6.3 cm, height 8.5 cm
fruit_prediction = knn.predict([[192, 8.4, 7.3]])
print(lookup_fruit_name[fruit_prediction[0]])
|
a67ce9552dcb85833b22bc3f4d5e9d319c271ea8 | zufardhiyaulhaq/CodeChallenge | /hacker-rank/Interview Preparation Kit/Sorting/Sorting: Bubble Sort/program.py | 839 | 3.65625 | 4 | _ = input()
data = list(map(int,input().split()))
def bubbleSort(data):
global swapCount
for i in range(0,len(data)):
for j in range(0,len(data)-1):
if data[j] > data[j+1]:
data[j],data[j+1] = data[j+1],data[j]
swapCount += 1
return data
swapCount = 0
data = bubbleSort(data)
print("Array is sorted in",swapCount,"swaps.")
print("First Element:",data[0])
print("Last Element:",data[-1])
# input()
# li = list(map(int, input().split()))
# count = 0
# for j in range(0, len(li)-1):
# for i in range(0, len(li)-1):
# if(li[i] > li[i+1]):
# temp = li[i]
# li[i] = li[i+1]
# li[i+1] = temp
# count+=1
# print("Array is sorted in", count, "swaps.")
# print("First Element:", li[0])
# print("Last Element:", li[-1]) |
bca97e6de2ad75ff73d0432f58580561f6f5fd02 | JuanFuentes20/some-python | /Python/player.py | 1,769 | 3.609375 | 4 | '''
Created on 19 Nov 2018
@author: juan
'''
class Player:
def __init__(self,new_name):
self.__name = new_name
self.__no_of_games = 0
self.__total = 0
self.__record = 0
def get_name(self):
return self.__name
def get_no_of_games(self):
return self.__no_of_games
def get_record(self):
return self.__record
def add_game(self, points):
if points >= 0:
self.__no_of_games += 1
self.__total += points
if points > self.__record:
self.__record = points
def average(self):
if self.__no_of_games > 0:
ka = self.__total / self.__no_of_games
else:
ka = 0.0
return ka
def is_master(self):
if self.__no_of_games > 0:
ka = self.__total / self.__no_of_games
if self.__total >= 3000 and ka > 2000:
return True
else:
return False
def is_better(self, another_player):
if self.__record > another_player.get_record():
return True
if self.__record == another_player.get_record() and self.average() > another_player.average():
return True
else:
return False
def __str__(self):
if self.is_master():
str1 = "{:s}, number of games {:d}, record {:d} points, MASTER.".format(self.__name, self.__no_of_games, self.get_record())
return str1
else:
str2 = "{:s}, number of games {:d}, record {:d} points, has not achieved master title.".format(self.__name, self.__no_of_games, self.get_record())
return str2
|
89751989aec47167a601a5b8d1de4a7bbe2407a8 | Amir-Omidfar/C247 | /hw2/nndl/softmax.py | 8,600 | 4 | 4 | import numpy as np
class Softmax(object):
def __init__(self, dims=[10, 3073]):
self.init_weights(dims=dims)
def init_weights(self, dims):
"""
Initializes the weight matrix of the Softmax classifier.
Note that it has shape (C, D) where C is the number of
classes and D is the feature size.
"""
self.W = np.random.normal(size=dims) * 0.0001
def loss(self, X, y):
"""
Calculates the softmax loss.
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
Returns a tuple of:
- loss as single float
"""
# Initialize the loss to zero.
loss = 0.0
# ================================================================ #
# YOUR CODE HERE:
# Calculate the normalized softmax loss. Store it as the variable loss.
# (That is, calculate the sum of the losses of all the training
# set margins, and then normalize the loss by the number of
# training examples.)
# ================================================================ #
a = X.dot(self.W.T)
#print(y.shape)
#print(X.shape)
#print(self.W.shape)
#print(a.shape)
i = 0
for row in a:
row -= np.max(row) #To avoid overflow
loss += - np.log( np.exp(row[y[i]]) /sum(np.exp(row)) )
i = i+1
loss = loss/y.shape[0]
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return loss
def loss_and_grad(self, X, y):
"""
Same as self.loss(X, y), except that it also returns the gradient.
Output: grad -- a matrix of the same dimensions as W containing
the gradient of the loss with respect to W.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
grad = np.zeros_like(self.W)
# ================================================================ #
# YOUR CODE HERE:
# Calculate the softmax loss and the gradient. Store the gradient
# as the variable grad.
# ================================================================ #
# dL/dW = dL/da*da/dW
# dL/da = Score - 1(y == i)
# da/dW = X'
a = self.W.dot(X.T) # numOfClass * numOfSample
a_exp = np.exp(a)
Score = np.zeros_like(a_exp)
for j in range(Score.shape[1]):
Score[:,j] = a_exp[:,j]/np.sum(a_exp[:,j])
Score[y, range(Score.shape[1])] -=1
dLda = Score
grad = np.dot(dLda,X)
grad /= y.shape[0]
loss = self.loss(X, y)
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return loss, grad
def grad_check_sparse(self, X, y, your_grad, num_checks=10, h=1e-5):
"""
sample a few random elements and only return numerical
in these dimensions.
"""
for i in np.arange(num_checks):
ix = tuple([np.random.randint(m) for m in self.W.shape])
oldval = self.W[ix]
self.W[ix] = oldval + h # increment by h
fxph = self.loss(X, y)
self.W[ix] = oldval - h # decrement by h
fxmh = self.loss(X,y) # evaluate f(x - h)
self.W[ix] = oldval # reset
grad_numerical = (fxph - fxmh) / (2 * h)
grad_analytic = your_grad[ix]
rel_error = abs(grad_numerical - grad_analytic) / (abs(grad_numerical) + abs(grad_analytic))
print('numerical: %f analytic: %f, relative error: %e' % (grad_numerical, grad_analytic, rel_error))
def fast_loss_and_grad(self, X, y):
"""
A vectorized implementation of loss_and_grad. It shares the same
inputs and ouptuts as loss_and_grad.
"""
loss = 0.0
grad = np.zeros(self.W.shape) # initialize the gradient as zero
# ================================================================ #
# YOUR CODE HERE:
# Calculate the softmax loss and gradient WITHOUT any for loops.
# ================================================================ #
a = X.dot(self.W.T) # numOfSample *numOfClass
a = (a.T - np.amax(a,axis = 1)).T
num_train = y.shape[0]
a_exp = np.exp(a)
Score = np.zeros_like(a_exp)
Score = a_exp / np.sum(a_exp, axis = 1, keepdims = True)
#loss += - np.log( np.exp(row[y[i]]) /sum(np.exp(row)) )
loss = np.sum( -np.log(a_exp[np.arange(a.shape[0]), y] / np.sum(a_exp, axis = 1)) )
Score[range(num_train),y] -= 1
dLda = Score
grad = dLda.T.dot(X)
grad /= num_train # NumOfClass * NumOfDimension
loss = loss/num_train
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return loss, grad
def train(self, X, y, learning_rate=1e-3, num_iters=100,
batch_size=200, verbose=False):
"""
Train this linear classifier using stochastic gradient descent.
Inputs:
- X: A numpy array of shape (N, D) containing training data; there are N
training samples each of dimension D.
- y: A numpy array of shape (N,) containing training labels; y[i] = c
means that X[i] has label 0 <= c < C for C classes.
- learning_rate: (float) learning rate for optimization.
- num_iters: (integer) number of steps to take when optimizing
- batch_size: (integer) number of training examples to use at each step.
- verbose: (boolean) If true, print progress during optimization.
Outputs:
A list containing the value of the loss function at each training iteration.
"""
num_train, dim = X.shape
num_classes = np.max(y) + 1 # assume y takes values 0...K-1 where K is number of classes
self.init_weights(dims=[np.max(y) + 1, X.shape[1]]) # initializes the weights of self.W
# Run stochastic gradient descent to optimize W
loss_history = []
for it in np.arange(num_iters):
X_batch = None
y_batch = None
# ================================================================ #
# YOUR CODE HERE:
# Sample batch_size elements from the training data for use in
# gradient descent. After sampling,
# - X_batch should have shape: (dim, batch_size)
# - y_batch should have shape: (batch_size,)
# The indices should be randomly generated to reduce correlations
# in the dataset. Use np.random.choice. It's okay to sample with
# replacement.
# ================================================================ #
index = np.random.choice(np.arange(num_train), batch_size)
X_batch = X[index]
y_batch = y[index]
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
# evaluate loss and gradient
loss, grad = self.fast_loss_and_grad(X_batch, y_batch)
loss_history.append(loss)
# ================================================================ #
# YOUR CODE HERE:
# Update the parameters, self.W, with a gradient step
# ================================================================ #
self.W = self.W - grad* learning_rate
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
if verbose and it % 100 == 0:
print('iteration {} / {}: loss {}'.format(it, num_iters, loss))
return loss_history
def predict(self, X):
"""
Inputs:
- X: N x D array of training data. Each row is a D-dimensional point.
Returns:
- y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional
array of length N, and each element is an integer giving the predicted
class.
"""
y_pred = np.zeros(X.shape[1])
# ================================================================ #
# YOUR CODE HERE:
# Predict the labels given the training data.
# ================================================================ #
y_pred = np.argmax(X.dot(self.W.T),axis=1)
# ================================================================ #
# END YOUR CODE HERE
# ================================================================ #
return y_pred
|
2c3d98aec03ca4f47f8036925482413e14b9c716 | thang14nguyen/PhythonHW | /lab8a.py | 7,678 | 3.78125 | 4 | ## LAB 8
## Section C
#Section C.1
import collections
Dish = collections.namedtuple('Dish', 'dish price calories')
def read_menu_with_count(file_name:str):
"Take file name as string, and return list of Dish"
file = open(file_name).read()
dishes = file.split(sep='\n')
dishes = dishes[1:]
num_of_dish = len(dishes)
menu = []
for index in range(num_of_dish):
current_dish = dishes[index]
current_dish = current_dish.split(sep = '\t')
dish = current_dish[0]
price = float(current_dish[1].replace('$', ''))
calories = float(current_dish[2])
menu_item = Dish(dish, price, calories)
menu.append(menu_item)
return menu
print(read_menu_with_count('menu1.txt'))
print(read_menu_with_count('menu2.txt'))
#Section C.2
def read_menu(file_name:str):
"Take file name as string, and return list of Dish"
file = open(file_name).read()
dishes = file.split(sep='\n')
##dishes = dishes[1:]
num_of_dish = len(dishes)
menu = []
for index in range(num_of_dish):
current_dish = dishes[index]
current_dish = current_dish.split(sep = '\t')
dish = current_dish[0]
price = float(current_dish[1].replace('$', ''))
calories = float(current_dish[2])
menu_item = Dish(dish, price, calories)
menu.append(menu_item)
return menu
dishes = (read_menu('menu3.txt'))
#Section C.3
def write_menu(list_of_dish:list, file_name:str): #Is the styling correct? It should be list_of_Dish
"Takes a list of dish, and writes to text file"
file_length = len(list_of_dish)
str_to_write = ''
for index in range(file_length):
current_dish = list_of_dish[index]
current_dish_str = "{}\t${:.2f}\t{}".format(current_dish.dish, current_dish.price, int(current_dish.calories))
str_to_write = "{}\n{}".format(str_to_write, current_dish_str)
write_to_file = str(file_length) + str_to_write
outfile = open(file_name, 'w', encoding='utf8')
outfile.write(write_to_file)
write_menu(dishes, 'menu4.txt')
##Section D
Course = collections.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 = collections.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])
sV = Student('41223344', 'Programmer, Virgina', 'SR', 'ICS', [ics31, mgt1])
StudentBody = [sW, sX, sY, sZ, sV]
#Section D.1
def Students_at_level(list_of_Students:list, class_lvl:str):
"Take a list of Students, and returns list of Studens who's class lvl matches"
student_match = []
for index in range(len(list_of_Students)):
current_student = list_of_Students[index]
if current_student.level == class_lvl:
student_match.append(current_student)
return student_match
print('\n\n')
print(Students_at_level(StudentBody,'FR'))
#Section D.2
def Students_in_majors(list_of_Students:list, major:str):
"Take a list of Students, and returns list of Studens who's major matches"
student_match = []
for index in range(len(list_of_Students)):
current_student = list_of_Students[index]
if current_student.major == major:
student_match.append(current_student)
return student_match
print('\n\n')
print(Students_in_majors(StudentBody,'PSB'))
#Section D.3
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)
'''
match = 0
if c1.dept == c2.dept:
match = match + 1
if c1.num == c2.num:
match = match + 1
return match == 2
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.
'''
match = 0
for index in range(len(SL)):
current_course = SL[index]
if Course_equals(c, current_course):
match = match + 1
return match >= 1
assert Course_on_studylist(ics31, sW.studylist)
assert not Course_on_studylist(wr39b, sW.studylist)
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)
'''
match = False
for index in range(len(S.studylist)):
current_course = S.studylist[index]
if department == current_course.dept:
if coursenum == current_course.num:
match = True
return match
assert Student_is_enrolled(sW, 'ICS', '31')
def Student_in_class(SL: list, dept: str, num: str):
"""Returns a list of student who are enrolled in stated class based on dept and class num"""
student_match = []
for index in range(len(SL)):
current_student = SL[index]
if Student_is_enrolled( current_student, dept, num):
student_match.append(current_student)
return student_match
print('\n\n')
print (Student_in_class(StudentBody, 'ICS', '31'))
#Section D.4
def Student_names(SL: list):
"""Returns list of name from list of Students"""
names = []
for index in range(len(SL)):
current_student = SL[index]
names.append(current_student.name)
return(names)
print ('\n\n')
print (Student_names(StudentBody))
#Section D.5
majors = ['CS', 'CSE', 'BIM', 'INFX', 'CGS', 'SE', 'ICS']
def Students_in_ICS(SL: list):
"""Returns list of student with majors from school of ICS"""
students = []
for index in range(len(SL)):
current_student = SL[index]
if current_student.major in majors:
students.append(current_student)
return students
print ('\n\n')
print (Students_in_ICS(StudentBody))
def names_in_ICS(SL:list):
"""Return list of name from student in school of ICS"""
students = Students_in_ICS(SL)
names = Student_names(students)
return(names)
print ('\n\n')
print (names_in_ICS(StudentBody))
def number_in_ICS(SL:list):
students = len(Students_in_ICS(SL))
return students
print ('\n\n')
print (number_in_ICS(StudentBody))
def senior_in_ICS(SL:list):
sr_student = []
students = Students_in_ICS(SL)
for index in range(len(students)):
current_student = students[index]
if current_student.level == 'SR':
sr_student.append(current_student)
return sr_student
print ('\n\n')
print (senior_in_ICS(StudentBody))
def sr_num_ICS(SL:list):
sr_num = len(senior_in_ICS(SL))
return sr_num
print ('\n\n')
print (sr_num_ICS(StudentBody))
def percent_sr_ICS(SL: list):
students = number_in_ICS(SL)
seniors = sr_num_ICS(SL)
return seniors / students
print ('\n\n')
print (percent_sr_ICS(StudentBody))
## Section E
#Section E.1
|
c4b08b2f45576a408bff63b8e9f450c1c63f3419 | Kanazawanaoaki/software-memo | /soft2/lec06/python/selection-sort.py | 654 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def selection_sort(num):
for i in range(len(num)):
min = num[i] # 仮の最小値
min_pos = i # 仮の最小値の場所
for n in range(i+1, len(num)):
if num[n] < min : # 比較対象の数字が仮の最小値より小さければ,仮の最小値を更新
min = num[n]
min_pos = n
tmp = num[i] # 最小値と最初の数を入れ替え
num[i] = min
num[min_pos] = tmp
return num
if __name__ == '__main__' :
f = open('rand.txt', 'r')
num = eval(f.read())
selection_sort(num)
print(num)
|
047190be9ed6dd1c6f6cfd7c9b9279a528ff70aa | XuuRee/python-data-structures | /01 Queue, Stack, LinkedList/stack.py | 2,868 | 3.890625 | 4 | #!/usr/bin/env python3
class Item:
"""Trida Item slouzi pro reprezentaci objektu v zasobniku.
Atributy:
value reprezentuje ulozenou hodnotu/objekt
below reference na predchazejici prvek v zasobniku
"""
def __init__(self):
self.value = None
self.below = None
class Stack:
"""Trida stack reprezentuje zasobnik.
Atributy:
top reference na vrchni prvek v zasobniku
"""
def __init__(self):
self.top = None
def push(stack, value):
"""Metoda push() vlozi na vrchol zasobniku (stack) novy prvek
s hodnotou (value).
"""
i = Item()
i.below = stack.top
i.value = value
stack.top = i
def pop(stack):
"""Metoda pop() odebere vrchni prvek zasobniku. Vraci hodnotu
(value) odebraneho prvku, pokud je zasobnik prazdny vraci None.
"""
if stack.top is None:
return None
v = stack.top.value
stack.top = stack.top.below
return v
def is_empty(stack):
"""Metoda is_empty() vraci True v pripade prazdneho zasobniku,
jinak False.
"""
return stack.top is None
# Testy implementace
def test_push_empty():
print("Test 1. Vkladani do prazdneho zasobniku: ", end="")
s = Stack()
push(s, 1)
if s.top is None:
print("FAIL")
return
if s.top.value == 1 and s.top.below is None:
print("OK")
else:
print("FAIL")
def test_push_nonempty():
print("Test 2. Vkladani do neprazdneho zasobniku: ", end="")
s = Stack()
i = Item()
i.below = None
i.value = 1
s.top = i
push(s, 2)
if s.top is None:
print("FAIL")
return
if s.top.value == 2 and s.top.below == i:
print("OK")
else:
print("FAIL")
def test_pop_empty():
print("Test 3. Odebirani z prazdneho zasobniku: ", end="")
s = Stack()
v = pop(s)
if v is not None or s.top is not None:
print("FAIL")
else:
print("OK")
def test_pop_nonempty():
print("Test 4. Odebirani z neprazdneho zasobniku: ", end="")
s = Stack()
i = Item()
i.value = 1
i.below = None
s.top = i
v = pop(s)
if v != 1 or s.top is not None:
print("FAIL")
else:
print("OK")
def test_is_empty_empty():
print("Test 5. is_empty na prazdnem zasobniku: ", end="")
s = Stack()
if is_empty(s):
print("OK")
else:
print("FAIL")
def test_is_empty_nonempty():
print("Test 6. is_empty na neprazdnem zasobniku: ", end="")
s = Stack()
i = Item()
i.below = None
i.value = 1
s.top = i
if is_empty(s):
print("FAIL")
else:
print("OK")
if __name__ == '__main__':
test_push_empty()
test_push_nonempty()
test_pop_empty()
test_pop_nonempty()
test_is_empty_empty()
test_is_empty_nonempty()
|
29774f437fb40fef84743398c855fcb1a5b4cf33 | zsimo/MOOC | /cs101_introduction_computer_Science/unit05/unit05-time.py | 3,356 | 4.21875 | 4 | # -*- coding: cp1252 -*-
# Hash Table: in Python si chiama Dictionary
# a set of key/value pairs mutable
# the key can be either string or number
dic = {}
dic1 = {'uno': 1, 'due': 2}
dic2 = {1: 1, 'due': 2}
print dic2[1]
# Hash function: keyword -> number
# takes a keyword and produces a number that gives the position
# in the hash table where is the buckets in which the keyword appears
import time
#start = time.clock()
#for i in range(100):
#print i
#print time.clock() - start
def time_execution(code):
start = time.clock()
result = eval(code)
run_time = time.clock() - start
return result, run_time
def spin_loop(n):
i = 0
while i < n:
i = i + 1
# Define a function, hash_string,
# that takes as inputs a keyword
# (string) and a number of buckets,
# and returns a number representing
# the bucket for that keyword.
def hash_string(keyword, buckets):
# signature
# string, number -> number
# in input the keyword and the size of the hash table
# the output is a number compreso tra 0 e b-1 (b il numero di buckets)
# in python:
# ord('one_letter_string') -> the index number of that letter
# this 2 method are reversible
# chr(number) -> 'one_letter_string'
# Modulus operator '%'
output = 0
for l in keyword:
output = (output + ord(l))%buckets
return output
#print hash_string('a',12)
#>>> 1
#print hash_string('b',12)
#>>> 2
#print hash_string('a',13)
#>>> 6
#print hash_string('au',12)
#>>> 10
#print hash_string('udacity',12)
#>>> 11
def hashtable_get_bucket(htable,keyword):
return htable[hash_string(keyword, len(htable))]
# Creating an Empty Hash Table
# Define a procedure, make_hashtable,
# that takes as input a number, nbuckets,
# and returns an empty hash table with
# nbuckets empty buckets.
def make_hashtable(nbuckets):
table = []
for n in range(nbuckets):
table.append([])
return table
table = [[['Francis', 13], ['Ellis', 11]], [], [['Bill', 17],
['Zoe', 14]], [['Coach', 4]], [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]]
#print hashtable_get_bucket(table, "Zoe")
#>>> [['Bill', 17], ['Zoe', 14]]
#print hashtable_get_bucket(table, "Brick")
#>>> []
#print hashtable_get_bucket(table, "Lilith")
#>>> [['Louis', 29], ['Rochelle', 4], ['Nick', 2]]
def hashtable_lookup(htable,key):
bucket = hashtable_get_bucket(htable,key)
for el in bucket:
if el[0] == key:
return el[1]
return None
def hashtable_add(htable,key,value):
bucket = hashtable_get_bucket(htable, key)
bucket.append([key, value])
return htable
def hashtable_update(htable,key,value):
bucket = hashtable_get_bucket(htable,key)
for entry in bucket:
if entry[0] == key:
entry[1] = value
return
bucket.append([key,value])
table = make_hashtable(5)
hashtable_add(table,'Bill', 17)
hashtable_add(table,'Coach', 4)
hashtable_add(table,'Ellis', 11)
hashtable_add(table,'Francis', 13)
hashtable_add(table,'Louis', 29)
hashtable_add(table,'Nick', 2)
hashtable_add(table,'Rochelle', 4)
hashtable_add(table,'Zoe', 14)
print table
#>>> [[['Ellis', 11], ['Francis', 13]], [], [['Bill', 17], ['Zoe', 14]],
#>>> [['Coach', 4]], [['Louis', 29], ['Nick', 2], ['Rochelle', 4]]]
|
859fd88a7e2ea39de8bc8b8b51c4c8d03f9bb83e | jlehenbauer/python-projects-public | /random_card.py | 3,620 | 3.65625 | 4 | import random
def card():
return ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'][random.randint(0, 12)]
def suit():
return ['♠', '♦', '♥', '♣'][random.randint(0, 3)]
def pick_card_with_replacement(number_of_cards):
cards = []
for num in range(number_of_cards):
cards.append((card(), suit()))
return cards
def pick_card_without_replacement(number_of_cards):
cards = []
while len(cards) < number_of_cards:
new_card = (card(), suit())
if new_card not in cards:
cards.append(new_card)
return cards
def print_cards(cards):
lines = []
if len(cards) % 2:
# add the individual card on a line by line basis
while cards != []:
space = ' '
if cards[0][0] == '10':
space = ''
lines.append('┌─────────┐')
lines.append('│{}{} │'.format(cards[0][0], space)) # use two {} one for char, one for space or char
lines.append('│ │')
lines.append('│ │')
lines.append('│ {} │'.format(cards[0][1]))
lines.append('│ │')
lines.append('│ │')
lines.append('│ {}{}│'.format(space, cards[0][0]))
lines.append('└─────────┘')
del cards[0]
else:
while cards != []:
space1 = ' '
if cards[0][0] == '10':
space1 = ''
space2 = ' '
if cards[1][0] == '10':
space2 = ''
lines.append('┌─────────┐ ┌─────────┐')
lines.append('│{}{} │ │{}{} │'.format(cards[0][0], space1, cards[1][0], space2)) # use two {} one for char, one for space or char
lines.append('│ │ │ │')
lines.append('│ │ │ │')
lines.append('│ {} │ │ {} │'.format(cards[0][1], cards[1][1]))
lines.append('│ │ │ │')
lines.append('│ │ │ │')
lines.append('│ {}{}│ │ {}{}│'.format(space1, cards[0][0], space2, cards[1][0]))
lines.append('└─────────┘ └─────────┘')
del cards[0]
del cards[0]
for line in lines:
print(line)
return True
def print_card_list(cards):
for card in cards[:-1]:
print(card[0] + card[1], end=", ")
print(cards[-1][0] + cards[-1][1])
"""
TODO:
///- add checks for card limits (without replacement)
///- add better menu for options selection
"""
while 1:
replacement_choice = input("Would you like to draw with or without replacement? (type \'with\' or \'without\') \n")
if replacement_choice == "exit":
break
display_choice = input("Would you like the cards printed or returned as a list? (type \'print\' or \'list\') \n")
if display_choice == "exit":
break
elif replacement_choice == "with":
times = input("How many cards would you like to draw? (type \'exit\' to exit) \n")
print('')
if times == 'exit':
break
if display_choice == "print":
print_cards(pick_card_with_replacement(int(times)))
elif display_choice == "list":
print_card_list(pick_card_with_replacement(int(times)))
print('')
elif replacement_choice == "without":
times = input("How many cards would you like to draw? (type \'exit\' to exit) \n")
print('')
if times == 'exit':
break
if display_choice == "print" and int(times) <= 52:
print_cards(pick_card_without_replacement(int(times)))
elif display_choice == "list" and int(times) <= 52:
print_card_list(pick_card_without_replacement(int(times)))
else:
print("Please select a valid choice.")
print('')
else:
print("Please select a valid choice.") |
6603e7c30b5a27bd0d5be960dcd90fc5b0e21783 | THEBEAST310/LeetCode-May2020-31DayChallenge | /Kth_Smallest_Element_in_a_BST.py | 613 | 3.6875 | 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
def recursive(curr,list1)->list:
if curr==None:
return list1
else:
list1.append(curr.val)
list1=recursive(curr.left,list1)
list1=recursive(curr.right,list1)
return list1
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
list1=[]
list1=recursive(root,list1)
list1.sort()
return(list1[k-1])
|
6227dc458adda55b0c25e15ac4035944faf6cbd1 | Cyberceptive/cs1-sullivan | /code/python/imageproc/image_processing.py | 3,608 | 3.8125 | 4 | import pygame as pg
################### PIXEL OPERATIONS ######################
# grayPixel: pixel -> pixel
# compute and return a gray pixel with the same intensity
# as the given pixel. A little complication: the intensity
# values in the 3D numpy array representing the pixels are
# expressed as 8-bit integers. The range is 0..255. The
# problem is that if one adds together three of these, to
# get aonther 8-bit integer, there can be an overflow! So
# we convert the 8-bit integers to values of type "int" before
# we do the addition. The "int" type in Python can hold
# integer values of any size.
#
def grayPixel(pixel):
red_intensity = int(pixel[0])
green_intensity = int(pixel[1])
blue_intensity = int(pixel[2])
ave_intensity = (red_intensity + green_intensity + blue_intensity)//3
return ((ave_intensity, ave_intensity, ave_intensity))
# channel: pixel -> channel -> pixel
# return a gray pixel with intensity from given channel of given pixel
def channel(pixel,chan):
return (pixel[chan],pixel[chan],pixel[chan])
# inverse: pixel -> pixel
# return the color negative of the given pixel
def inverse(pixel):
return (255-pixel[0], 255-pixel[1], 255-pixel[2])
# intensify: pixel -> nat255 -> pixel
# brighten each channel of pixel by quantity
#
# NOTE: there might be an overflow bug in this code!
# If so, reason through it and fix it. Consider the
# possible need for a function that brightens an
# individual pixel intensity, never returning a result
# greater than 255 or less than 0.
#
# helper function: add intensity but keep result
# between 0 and 255
def intensify_channel(intensity, quantity):
if (intensity + quantity > 255):
return 255
if (intensity + quantity < 0):
return 0;
return intensity + quantity
def intensify(pixel,quantity):
return (intensify_channel(pixel[0], quantity),
intensify_channel(pixel[1], quantity),
intensify_channel(pixel[2], quantity))
################### IMAGE OPERATIONS ######################
# invert: modifies image pixel array of image_surf in place
# replace each pixel with its photographic "negative"
#
def invert(image_surf):
# get pixel dimensions of image
rows = image_surf.get_size()[0]
cols = image_surf.get_size()[1]
# get reference to and lock pixel array
pixels3d = pg.surfarray.pixels3d(image_surf)
# update pixels in place (side effect!)
for x in range(rows):
for y in range(cols):
pixels3d[x,y] = inverse(pixels3d[x,y])
# bw: modifies image pixel array of image_surf in place
# replaces each pixel with a corresponding gray-scale pixel
def grayscale(image_surf):
# get pixel dimensions of image
rows = image_surf.get_size()[0]
cols = image_surf.get_size()[1]
# get reference to and lock pixel array
pixels3d = pg.surfarray.pixels3d(image_surf)
# update pixels in place (side effect!)
for x in range(rows):
for y in range(cols):
pixels3d[x,y] = grayPixel(pixels3d[x,y])
# invert: modifies image pixel array of image_surf in place
# replace each pixel with its photographic "negative"
#
def brighten(image_surf):
# get pixel dimensions of image
rows = image_surf.get_size()[0]
cols = image_surf.get_size()[1]
# get reference to and lock pixel array
pixels3d = pg.surfarray.pixels3d(image_surf)
intensify_amount = 10
# update pixels in place (side effect!)
for x in range(rows):
for y in range(cols):
pixels3d[x,y] = intensify(pixels3d[x,y], intensify_amount)
|
9fd268aff523508d3dca7f1425b37b97143b276d | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/68_text_justification.py | 4,429 | 3.90625 | 4 | """
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
Note:
A word is defined as a character sequence consisting of non-space characters only.
Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
The input array words contains at least one word.
"""
My solution
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
i = 0
result= []
while i < len(words):
j = i + 1
length = len(words[i])
while j < len(words):
if length + 1 + len(words[j]) <= maxWidth:
length += 1 + len(words[j])
j += 1
else:
break
count = (j-i-1)
line = []
# single word line or last line
if count == 0 or j == len(words):
for k in range(i, j):
line.append(words[k])
if k == j -1:
break
line.append(" ")
line.append(" " * (maxWidth - length))
else:
spaces = 1 + (maxWidth - length) // count
extra_spaces = (maxWidth - length) % count
for k in range(i, j):
line.append(words[k])
if k == j - 1: #no space after last word in a line
break
line.append(" "*(spaces + (0 if extra_spaces <=0 else 1)))
extra_spaces -= 1
i = j
result.append("".join(line))
return result
def fullJustify(self, words, maxWidth):
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
cur[i%(len(cur)-1 or 1)] += ' '
res.append(''.join(cur))
cur, num_of_letters = [], 0
cur += [w]
num_of_letters += len(w)
return res + [' '.join(cur).ljust(maxWidth)]
How does it work? Well in the question statement, the sentence "Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right" was just a really long and awkward way to say round robin. The following line implements the round robin logic:
for i in range(maxWidth - num_of_letters):
cur[i%(len(cur)-1 or 1)] += ' '
What does this line do? Once you determine that there are only k words that can fit on a given line, you know what the total length of those words is num_of_letters. Then the rest are spaces, and there are (maxWidth - num_of_letters) of spaces. The "or 1" part is for dealing with the edge case len(cur) == 1.
The following is my older solution for reference, longer and less clear. The idea is the same, but I did not figure out the nice way to distribute the space at the time.
def fullJustify(self, words, maxWidth):
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
if len(cur) == 1:
res.append( cur[0] + ' '*(maxWidth - num_of_letters) )
else:
num_spaces = maxWidth - num_of_letters
space_between_words, num_extra_spaces = divmod( num_spaces, len(cur)-1)
for i in range(num_extra_spaces):
cur[i] += ' '
res.append( (' '*space_between_words).join(cur) )
cur, num_of_letters = [], 0
cur += [w]
num_of_letters += len(w)
res.append( ' '.join(cur) + ' '*(maxWidth - num_of_letters - len(cur) + 1) )
return res
|
65b389de527814b3d085dbe8cbb6f327e9eb713b | cpe202spring2019/lab0-AndersonKyle324 | /planets.py | 352 | 3.796875 | 4 | def weight_on_planets():
# write your code here
earthWeight = int(input("What do you weigh on earth? "))
marsWeight = earthWeight * .38
jupWeight = earthWeight * 2.34
print("\nOn Mars you would weigh", marsWeight, "pounds.\nOn Jupiter you would weigh", jupWeight, "pounds.")
if __name__ == '__main__':
weight_on_planets()
|
cfd2af7c0db1e118173f4fcb580dc55d6df8d25f | davidbezerra405/PytonExercicios | /ex061.py | 210 | 3.828125 | 4 | a1 = int(input('Informe o 1º termo da PA: '))
rz = int(input('Informe a razão da PA: '))
termo = 1
while termo <= 10:
print('{:3}, '.format(a1), end='')
a1 += rz
termo += 1
print('')
print('fim')
|
31ae1ee8261304327b207dd3f11c5ee0349335ef | BrayanStewartGuerrero/Basic_Concepts_of_Python | /strings.py | 537 | 4.0625 | 4 | myStr = "Brayan Guerrero"
# print(dir(myStr))
# print(myStr.upper())
# print(myStr.lower())
# print(myStr.swapcase())
# print(myStr.capitalize())
# print(myStr.replace("Hello", "Bye").upper())
# print(myStr.count("l"))
# print(myStr.startswith("Hello"))
# print(myStr.endswith("World"))
# print(myStr.split())
# print(myStr.find("o"))
# print(len(myStr))
# print(myStr.index("e"))
# print(myStr.isnumeric())
# print(myStr.isalpha())
print(myStr[0])
print(myStr[3])
print(myStr[-1])
print("]My name is "+ myStr)
print(f"My name is {myStr}") |
aa67687d05586e837ccc1228d25fb2fe49ba8dca | Emmandez/MachineLearning_A-Z | /Part 2 - Regression/Section 5 - Multiple Linear Regression/Multiple_Linear_Regression/My_multiple_linear_regression.py | 2,254 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 3 23:27:47 2018
@author: eherd
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
#Encoding categorical data
#encoding the independent variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:,-1] = labelencoder_X.fit_transform(X[:,-1])
onehotencoder = OneHotEncoder(categorical_features=[-1])
X = onehotencoder.fit_transform(X).toarray()
#avoiding the dummy variable Trap. Have n-1 dummy variables
X = X[:,1: ]
#splitting the dataset into the training set and the test
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2, random_state=0)
#Fitting multiple Linear Regressin to the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#Predicting the Test set results
y_pred = regressor.predict(X_test)
#Building the optimal model using Backward Elimination
import statsmodels.formula.api as sm
#Adding X to a column of ones. to modify the formula
# y = b0*x0+b1*x1 ... bn*xn
X = np.append(arr= np.ones((50,1)).astype(int) , values = X , axis=1)
#STEP 2
#contains the independent variables that are statiscally significant to the dependent variable
X_opt = X[:,[0,1,2,3,4,5]]
#OLS Ordinary Least Squares
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
#To see the p-values
regressor_OLS.summary()
#Removing x2 (second categorical column) predictor with index 2
X_opt = X[:,[0,1,3,4,5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
#Removing x1 (first categorical column) predictor with index 1
X_opt = X[:,[0,3,4,5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
#Removing x2 (Administration column) predictor with index 2
X_opt = X[:,[0,3,5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
#Removing x2 (Marketing column) predictor with index 2
X_opt = X[:,[0,3]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
|
897c2ebfbc64710a25d98517561ac805e0e1f873 | treedbox/python-3-basic-exercises | /class/app.py | 621 | 4.125 | 4 | """Class building example."""
class calculator:
"""Calculate basic operations."""
def addiction(x, y):
"""Adiction."""
added = x + y
print(added)
def subtraction(x, y):
"""Subtraction."""
subtracted = x - y
print(subtracted)
def multiplication(x, y):
"""Multiplication."""
multiplied = x * y
print(multiplied)
def division(x, y):
"""Division."""
divided = x / y
print(divided)
calculator.addiction(3, 2)
#
calculator.subtraction(3, 2)
#
calculator.multiplication(3, 2)
#
calculator.division(3, 2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.