blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2e9ef545996a677286c77da9f055e70d9b6de325 | nafryer97/ppl_hw7 | /hw7.py | 952 | 3.734375 | 4 | def is_prime(n):
if n < 2 : return False
i = 2
while i * i <= n:
if n % i == 0: return False
i += 1
return True
def primes():
yield 2
i = 3
while True:
if is_prime(i):
yield i
i += 2
def square_primes():
yield 2*2
i = 3
while True:
if is_prime(i):
yield i*i
i += 2
#square_generator = square_primes()
#for i in square_generator:
# print (i)
def is_spsp(n):
if n < 6: return False
elif n == 6: return True
else:
for x in square_primes():
if x >= n: return False
elif is_prime(n - x): return True
def spsp_nums(n):
if is_spsp(n+1): yield (n + 1)
else:
i = n + 2
while True:
if is_spsp(i):
yield i
i += 1
student_id = 113387301 * 10
x = 0;
for i in spsp_nums(student_id):
print i
x += 1
if x > 9:
break |
ee2d3a0f9c2edd9da9272313517a5d207df84ae9 | bopopescu/python-practice | /pycharm/telusko/constructor-self-comparing-objects.py | 469 | 3.90625 | 4 | class computer:
#--- __init__ method is a constructor
def __init__(self,cpu,ram):
self.cpu = cpu
self.ram = ram
def compare(self,other):
if self.ram == other.ram:
return True
else:
return False
c1 = computer('i3',16)
c2 = computer('i5',8)
c1.ram=8
#--- Comparing objects, compare is not built-in function
if c1.compare(c2):
print("objects are same")
else:
print("objects are not same")
|
66dc508edada577dd42c0c9f83cecbbe729a4602 | jasonpark3306/python | /.vscode/Sort/merge_sort.py | 913 | 3.9375 | 4 | import random
def merge_two_sorted_list(arr1 : list, arr2 : list, org : list) -> None :
i = j = idx = 0
len1 = len(arr1)
len2 = len(arr2)
while i < len1 and j < len2 :
if arr1[i] <= arr2[j] :
org[idx] = arr1[i]
i+=1
else :
org[idx] = arr2[j]
j+=1
idx+=1
while i < len1 :
org[idx] = arr1[i]
i+=1
idx+=1
while j < len2 :
org[idx] = arr2[j]
j+=1
idx+=1
def merge_sort(arr : list) -> None :
if len(arr) <= 1 :
return
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
merge_two_sorted_list(left, right, arr)
if __name__ == '__main__' :
arr = []
for i in range(20) :
arr.append(random.randint(1, 100))
print(arr)
merge_sort(arr)
print(arr) |
d5060e0048054ccd11b8da9767e93c499b5201fd | byungjur96/Algorithm | /2442.py | 166 | 3.8125 | 4 | line = int(input())
for i in range(line):
for _ in range(line-i-1):
print(" ", end="")
for _ in range(2*i+1):
print('*', end="")
print()
|
7087096424871135b2f32a82bc33d29350099f1e | ArminOonk/AdventCode2016 | /day1.py | 2,310 | 4.0625 | 4 | # The Document indicates that you should start at the given coordinates (where you just landed) and face North.
# Then, follow the provided sequence: either turn left (L) or right (R) 90 degrees, then walk forward the given number
# of blocks, ending at a new intersection.
#
# There's no time to follow such ridiculous instructions on foot, though, so you take a moment and work out the
# destination. Given that you can only walk on the street grid of the city, how far is the shortest path to
# the destination?
import math
import numpy
def turn_right(d):
return math.fmod(d + 90.0, 360.0)
def turn_left(d):
return math.fmod(360.0 + d - 90.0, 360.0)
# instruction = 'R2, L3'
# instruction = 'R2, R2, R2'
# instruction = 'R5, L5, R5, R3'
instruction = 'R3, L5, R1, R2, L5, R2, R3, L2, L5, R5, L4, L3, R5, L1, R3, R4, R1, L3, R3, L2, L5, L2, R4, R5, R5, L4, L3, L3, R4, R4, R5, L5, L3, R2, R2, L3, L4, L5, R1, R3, L3, R2, L3, R5, L194, L2, L5, R2, R1, R1, L1, L5, L4, R4, R2, R2, L4, L1, R2, R53, R3, L5, R72, R2, L5, R3, L4, R187, L4, L5, L2, R1, R3, R5, L4, L4, R2, R5, L5, L4, L3, R5, L2, R1, R1, R4, L1, R2, L3, R5, L4, R2, L3, R1, L4, R4, L1, L2, R3, L1, L1, R4, R3, L4, R2, R5, L2, L3, L3, L1, R3, R5, R2, R3, R1, R2, L1, L4, L5, L2, R4, R5, L2, R4, R4, L3, R2, R1, L4, R3, L3, L4, L3, L1, R3, L2, R2, L4, L4, L5, R3, R5, R3, L2, R5, L2, L1, L5, L1, R2, R4, L5, R2, L4, L5, L4, L5, L2, L5, L4, R5, R3, R2, R2, L3, R3, L2, L5'
# instruction = 'R8, R4, R4, R8'
inList = instruction.split(', ')
print('Length: ' + str(len(inList)))
direction = 0.0 # Heading north
x = 0.0
y = 0.0
offset = 400
grid = numpy.zeros((800, 800))
for v in inList:
if v[0] == 'R':
direction = turn_right(direction)
elif v[0] == 'L':
direction = turn_left(direction)
else:
print('Unknown direction!')
distance = int(v[1:])
for ii in range(0,distance):
x += round(math.cos(direction * math.pi / 180.0))
y += round(math.sin(direction * math.pi / 180.0))
if grid[int(x+offset), int(y+offset)] == 1:
print('Found location! ' + str(x) + ", " + str(y) + ' distance: ' + str(abs(x)+abs(y)))
grid[x + offset, y + offset] = 1
print("@position " + str(x) + ", " + str(y))
print('Distance travelled: ' + str(abs(x)+abs(y)))
|
a2d24996713a7030961045d219dffa454696e41a | 824zzy/Leetcode | /D_TwoPointers/DifferentDirection/L1_581_Shorest_Unsorted_Continuous_Subarray.py | 499 | 3.71875 | 4 | """ https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
1. sort the array
2. find left&right most different elements by two pointers
Time: O(nlogn) due to sort function
"""
class Solution:
def findUnsortedSubarray(self, A: List[int]) -> int:
sorted_A = sorted(A)
l, r = 0, len(A)-1
while l<r:
if sorted_A[l]==A[l]: l += 1
elif sorted_A[r]==A[r]: r -= 1
else: break
if l==r: return 0
else: return r-l+1 |
6629748d83bfc95c95abbb833f5663225dd87d8a | jokerGin/Password-Generator | /Password generator.py | 1,798 | 3.890625 | 4 | """
A simple password generator program that uses random numbers and letters to generate
passwords of desired length
"""
# import needed modules
from tkinter import *
from PIL import ImageTk, Image
import time
root = Tk()
root.title('Password Generator')
root.iconbitmap("icons/favicon.ico")
#root.geometry('420x350')
root.configure(bg='#252323')
# textbox
e = Text(root, width=25, height=2, relief=SUNKEN)
# The definitions
def gen():
num = e.get('1.0', END)
for i in range(10):
s = 'qwertyuiopasdfghjklzxcvbnm1234567890'
p = list(s)
l = []
global m
m = ''
for i in range(int(num)):
from random import choice
l.append(choice(p))
for ele in l:
m += ele
if m[0] in '0123456789':
global myLabel1
myLabel1 = Label(root, text=f'Your generated password is {m} ' , font=("Book Antiqua", 12), bg='#252323', fg='white')
myLabel1.grid(row=3, column=0)
break
else:
continue
def clear():
myLabel1.destroy()#Destroys the widget
e.delete('1.0', END)
# root.bind('<Return>', gen)
# root.bind('<Delete>', clear)
# align widgets in a frame
frame = Frame(root)
myLabel = Label(root, text='Enter the length of the Password you want', font=("Book Antiqua", 12), bg='#252323', fg='white')
button = Button(frame, text='Generate', font=("Book Antiqua", 12), command=gen, bg='#252323', fg='white')
button_clear = Button(frame, text='Clear', font=("Book Antiqua", 12), command=clear, bg='#252323', fg='white')
# place the widgets on screen
myLabel.grid(row=0, column=0, columnspan=2)
e.grid(row=1, column=0, columnspan=2, pady=10 )
frame.grid(row=2, column=0, pady=10, columnspan=2)
button.grid(row=0, column=0)
button_clear.grid(row=0, column=1)
# run the program
mainloop() |
8307c7232958a95709d2cb8e5ae729e6fc974c1d | Arctiss/A2-Coursework | /Simulatorv4.py | 8,203 | 3.75 | 4 | import random, math, pygame, time, sys
class node():
def __init__(self, size, board, unhappy, blanks, bias, ratio, groups):
self.size = size
#self.coordinates = coordinates
self.population = 0
self.board = board
self.unhappy = unhappy
self.blanks = blanks
self.squares = size**2
self.bias = bias
self.ratio = ratio
self.groups = groups
#self.diversity = 0
class agent():
def __init__(self, coordinates, node, aType):
self.coordinates = coordinates
self.currentNode = node
self.speed = 5
self.targetNode = None
self.unhappyMoves = 0
self.threshold = 3
self.route = []
self.segregation = 0
self.type = aType
def getDir(self, currentNode, targetNode):
pass
def checkMove(self):
pass
def getMove(self, nodes):
pass
def updateMove(self, nodes):
pass
def getSegregation(self, board):
pass
def getSize():
size = 0
while True:
try:
size = int(input("How big would you like the board to be? "))
if size <= 0 or size >= 101:
print("Numbers between 1 and 100 only")
else:
return size
except:
print("Numbers only")
def getBoundaries():
bias = 0
while True:
try:
bias = int(input("What percentage similar to be happy? "))
if bias < 0 or bias > 100:
print("Numbers between 0 and 100 only")
else:
return bias
except:
print("Numbers only")
def getGroups():
groups = 0
while True:
try:
groups = int(input("How many groups? "))
if groups < 2 or groups > 5:
print("Numbers between 2 and 5 only")
else:
return groups
except:
print("Numbers only")
def getRatio(groups, size):
ratio = []
total = 0
temp = 0
for i in range (0, groups):
while True:
temp = int(input("How many in group " + str(i+1) + ": "))
total += temp
if size**2 - total < groups - i:
print("Not enough space for the other groups")
total -= temp
else:
for j in range(0, temp):
ratio.append(i)
break
total += ratio[-1]
for i in range(0, size**2-total):
ratio.append("B")
return ratio
def populateBoard(size, ratio, agents):
board = []
blanks = []
ratio2 = ratio.copy()
for i in range (0, size):
new = []
for j in range (0, size):
bob = random.choice(ratio2)
if bob == "B":
blanks.append((i, j))
ratio2.remove(bob)
new.append(bob)
if bob != "B":
a = agent([i,j], None, bob)
agents.append(a)
board.append(new)
return board, blanks
def drawBoard(board, colours, screen, k, boardSize, size):
screen.fill(pygame.Color(20,20,20))
for y, x in enumerate(board):
for y2, x2 in enumerate(x):
if x2 != "B":
#pygame.draw.rect(screen,colours[x2],(int(y2*k), int(y*k), int(k)-1, int(k)-1))
pygame.draw.circle(screen,colours[x2],(int(y2*k)+int(k/2), int(y*k)+int(k/2)), int(k/2)-1)
def getUnhappy(board, size, bias, ratio):
unhappy = []
for y, x in enumerate(board):
for y2, x2 in enumerate(x):
current = board[y][y2]
if current != "B":
if checkHappy(size, board, current, bias, y, y2, ratio):
pass
else:
unhappy.append((y, y2))
else:
pass
return unhappy
def selectAgent(unhappy):
i = random.randint(0, len(unhappy)-1)
return unhappy[i][0], unhappy[i][1]
def checkHappy(size, board, current, bias, i, j, ratio):
similar = 0
adjacent = 8
for x in (-1, 0, 1):
for y in (-1, 0, 1):
if (x == 0 and y == 0):
pass
else:
if (i+x) < 0 or (i+x) > size-1 or (j+y) > size-1 or (j+y) < 0 or board[i+x][j+y] == ratio[-1]:
adjacent -= 1
else:
if board[i+x][j+y] == current:
similar += 1
if adjacent != 0:
percentage = (similar/adjacent)*100
if percentage < bias:
return False
else:
return True
else:
return False
def updateUnhappy(board, size, bias, ratio, i, j, unhappy):
similar = 0
adjacent = 8
for x in (-1, 0, 1):
for y in (-1, 0, 1):
if (x == 0 and y == 0):
pass
else:
try:
current = board[i+x][j+y]
if checkHappy(size, board, current, bias, i, j, ratio):
pass
else:
if (i+x, j+y) not in unhappy:
unhappy.append((i+x, j+y))
except:
pass
return unhappy
def moveCell(blanks, board, i, j, size, bias, ratio, agents):
for z in agents:
if z.coordinates == [i, j]:
if checkHappy(size, board, z.type, bias, i, j, ratio):
z.unhappyMoves == 0
else:
z.unhappyMoves += 1
moveto = random.choice(blanks)
blanks.remove(moveto)
blanks.append((i, j))
temp = board[i][j]
board[i][j] = "B"
board[moveto[0]][moveto[1]] = temp
return board, blanks, moveto[0], moveto[1]
def switchNode(nodes, activeNode):
for i in range(0, len(nodes)):
if activeNode == nodes[i]:
try:
activeNode = nodes[i+1]
except:
activeNode = nodes[0]
return activeNode
def main():
agents = []
nodes = []
colours = {0: (252, 183, 50), 1: (2, 120, 120), 2: (243, 115, 56), 3:(194, 35, 38), 4: (128, 22, 56)}
boardSize = 800
for z in range(0, random.randint(2, 4)):
size = getSize()
bias = getBoundaries()
groups = getGroups()
ratio = getRatio(groups, size)
board, blanks = populateBoard(size, ratio, agents)
unhappy = getUnhappy(board, size, bias, ratio)
n = node(size, board, unhappy, blanks, bias, ratio, groups)
nodes.append(n)
activeNode = nodes[0]
screen = pygame.display.set_mode((boardSize,boardSize))
k = (boardSize/activeNode.size)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
activeNode = switchNode(nodes, activeNode)
k = (boardSize/activeNode.size)
if len(activeNode.unhappy) != 0:
i, j = selectAgent(activeNode.unhappy) #SELECTS THE COORDINATES NOT THE ACTUAL THING
activeNode.board, activeNode.blanks, movetox, movetoy = moveCell(activeNode.blanks, activeNode.board, i, j, activeNode.size, activeNode.bias, activeNode.ratio, agents)
activeNode.unhappy = updateUnhappy(activeNode.board, activeNode.size, activeNode.bias, activeNode.ratio, i, j, activeNode.unhappy)
activeNode.unhappy.remove((i, j))
activeNode.unhappy = updateUnhappy(activeNode.board, activeNode.size, activeNode.bias, activeNode.ratio, movetox, movetoy, activeNode.unhappy)
drawBoard(activeNode.board, colours, screen, k, boardSize, activeNode.size)
pygame.display.update()
#time.sleep(0.05)
else:
print("All happy")
pygame.image.save(screen, "screenshot.jpeg")
pygame.event.wait()
exit()
main()
|
9603ff74c0bb6e7ef1b48b11077b7aeb002faf31 | PreslavaKuzova/Python101 | /week03/Queries/queries.py | 1,977 | 3.5 | 4 | import csv
from operator import itemgetter
def filter(file_name, **kwargs):
result = []
with open('data.csv', mode = 'r') as csv_file:
data = csv.DictReader(csv_file)
for row in data:
flag = True
order = False
index_to_order_by = ''
for key, value in kwargs.items():
key_word, sep, condition = key.partition('__')
if condition != '':
if condition == 'startswith':
if not row[key_word].startswith(value):
flag = False
if condition == 'contains':
if not value in row[key_word]:
flag = False
if condition == 'gt':
if not int(value) < int(row[key_word]):
flag = False
if condition == 'lt':
if not int(value) > int(row[key_word]):
flag = False
else:
if key_word == 'order_by':
order = True
index_to_order_by = ['full_name', 'favourite_color', 'company_name', 'email', 'phone_number', 'salary'].index(value)
continue
if row[key_word] != value:
flag = False
if flag:
result.append(list(row.values()))
if order:
return sorted(result, key=itemgetter(index_to_order_by))
return result
def main():
print(filter('data.csv', full_name="Diana Harris", favourite_color="lime"))
print(filter('data.csv', full_name__startswith="Gary"))
print(filter('data.csv', email__contains="@gmail"))
print(filter('data.csv', salary__gt=9930))
print(filter('example_data.csv', salary__lt=700, order_by='salary'))
if __name__ == '__main__':
main() |
4d34a5c481d97ece8e2291455a272b320792bdd7 | sealanguage/april2021refresh | /digit_sum/digit_sum.py | 1,397 | 3.890625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'superDigit' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING n
# 2. INTEGER k
#
def superDigit(n, k):
# Write your code here
one = 1
sum = 0
res = [int(n[idx: idx + one]) for idx in range(0, len(n), one)]
# holder = []
# holderStack = []
count = 0
print(k, res)
contained = res
print('contained ', contained)
# def addToSum():
# This works to add the numbers in the initial res
for count in range(k): # count is 0 0 0 1 1 1 2 2 2, getting input 3 times
for i in contained:
sum = sum + i
print("count ", count)
if sum < 10:
print(sum)
else:
print('sum more than 10')
# [int(i) for i in str(12345)]
# list(str(12345))
res = list(str(sum))
print(res)
print('contained ', contained)
# holderStack.append(i)
# print("hS ", holderStack)
# return sum
# addToSum()
# if sum < 10:
# print("sum less 10 ", sum)
# else:
# for n in holderStack:
# sum = sum + n
# print("sum = sum + n; ", sum)
# print("hS2 ", holderStack)
# print(k, res)
|
ff0f519ab9e9cf4346dc5ee93e44bc9e52a45189 | SamanehGhafouri/Data-Structures-and-Algorithms-in-python | /Experiments/find_minimum_element.py | 660 | 4.125 | 4 | # ############ Find the minimum number in an array ############# #
def find_smallest(arr):
if len(arr) == 0:
return None
smallest = arr[0]
for i in range(len(arr)):
if arr[i] < smallest:
smallest = arr[i]
return smallest
ar = [90, 69, 23, 120, 180]
print(find_smallest(ar))
# ############# Test Cases ##############
test_data = [
([1, 45, 23, 5, 67], 1),
([-3, -7, 1, 4, 2, -9], -9),
([-4, -1, -9, -3], -9),
([1, 45, 23, 5, 67, 97, 35], 1),
([], None)
]
for item in test_data:
expected = item[1]
computed = find_smallest(item[0])
print(expected, computed, expected == computed)
|
c7b922f174da993f9f41b739d7afb37c88b68e71 | mrchary/oreilly-python-1 | /Exercises/check_string.py | 349 | 4.4375 | 4 | #!/usr/local/bin/python3
"""Check if a string is all upper case and ends with a period."""
uin = input("Please enter an upper-case string ending with a period: ")
if uin != uin.upper():
print("Input is not all upper case.")
elif uin.endswith("."):
print("Input meets both requirements.")
else:
print("Input does not end with a period.")
|
77ea04c13f1ac07a6cca4c27bfec4fda44461e23 | tasnuva83/pythonlarning | /funtion_2.py | 203 | 3.78125 | 4 | def increasedprice(price):
newprice=price*1.20
print("revised price now:", newprice)
return newprice
x=increasedprice(12)
amount_increased=x-12
print("increased amount is:",amount_increased ) |
fa777902aa84dcc8ef5eff56c278c1dffb5eca1b | samaosborne/Uno | /players.py | 8,278 | 3.90625 | 4 | from cards import Pile, Card
class Player:
def __init__(self, name, hand=None, points=0):
"""
:param name: Name of player
:type name: str
:param hand: The player's hand
:type hand: Pile | None
:param points: The player's points
:type points: int
"""
self.name = name
if hand is None:
self.hand = Pile()
else:
self.hand = hand
self.points = points
def display_hand(self):
"""
Prints the cards in a player's hand together with an identifying number
"""
self.hand.sort()
for i, card in enumerate(self.hand.cards):
print(f"{i + 1}: {card.name}")
print("\n")
def draw(self, num, deck):
"""
Moves cards from the deck to a player's hand, and returns the last drawn card
:param num: The number of cards to draw
:type num: int
:param deck: The deck to draw from
:type deck: Deck
:return: The most recent card drawn
:rtype: Card | None
"""
drawn_card = None
for _ in range(num):
drawn_card = deck.draw()
self.hand.add(drawn_card)
return drawn_card
def draw_and_offer(self, deck, discard_pile):
"""
When the player has to draw a card, draw it then check if it's playable, if it is offer to play it
:param deck: The deck to draw cards from
:type deck: Deck
:param discard_pile: The discard pile cards are played onto
:type discard_pile: Pile
:return: The card played, if any
:rtype: Card | None
"""
played_card = None
drawn_card = self.draw(1, deck)
if self.playable_card(drawn_card, discard_pile):
while True:
play = input(f"You drew {drawn_card.name}, do you want to play it?\t").lower()
if play in ("y", "yes", "yeah", "yep"):
self.play(drawn_card, discard_pile)
played_card = drawn_card
break
elif play in ("n", "no", "nah", "nope"):
break
else:
print("Please answer (Y)es or (N)o")
else:
print(f"You drew {drawn_card.name}, but you can't play it")
return played_card
def play(self, card, discard_pile):
"""
Play the given card from the player's hand, update it's colour if it's a wild-card
:param card: The card to be played
:type card: Card
:param discard_pile: The discard pile cards are played onto
:type discard_pile: Pile
"""
# move card from hand to discard pile
self.hand.remove(card)
discard_pile.add(card)
# make card variable specifically the card on top of the discard pile so colour can be changed if necessary
card = discard_pile.top
if card.colour == "W":
card.wild_colour(self)
def playable_card(self, card, discard_pile):
"""
Checks if it possible for a given card to be played
:param card: The card to check
:type card: Card
:param discard_pile: The discard pile cards are played onto
:type discard_pile: Pile
:return: Whether the card can be played
:rtype: bool
"""
top_card = discard_pile.top
card_playable = False
attribute_matches = [i == j is not None for i, j in zip(card.attributes, top_card.attributes)]
colour_matches = [top_card.colour == card.colour for card in self.hand.cards]
if card == Card("W") or True in attribute_matches:
card_playable = True
elif card == Card("W", action="+4") and True not in colour_matches:
card_playable = True
return card_playable
def playable_hand(self, discard_pile):
"""
Checks if it possible for the player to play any cards from their hand
:param discard_pile: The discard pile cards are played onto
:type discard_pile: Pile
:return: Whether the player can play a card
:rtype: bool
"""
hand_playable = False
for card in self.hand.cards:
if self.playable_card(card, discard_pile):
hand_playable = True
return hand_playable
class Group:
def __init__(self, *players):
"""
:param players: A group of players
:type players: Player
"""
self.players = list(players)
self.player_number = None
self.current_player = None
@property
def longest_name(self):
"""
Finds the length of the longest player name
:return: The length of the name
:rtype: int
"""
return max(len(player.name) for player in self.players)
@property
def size(self):
"""
The number of players in the group
:return: The number of players
:rtype: int
"""
return len(self.players)
@property
def standings(self):
"""
Gives the current standings sorted by number of points
:return: The standings
:rtype: list[Player]
"""
points = [(player.points, player.name, player) for player in self.players]
points.sort(reverse=True)
points = [position[2] for position in points]
return points
def add(self, player):
"""
Add a player to the group
:param player: The player to be added
:type player: Player
"""
self.players.append(player)
def give_points(self):
"""
Give the current player (the winner) points equal to total value of every other player's cards
"""
game_points = sum(player.hand.value for player in self.players if player is not self.current_player)
self.current_player.points += game_points
print(f"Well done {self.current_player.name}! You've won the game and got {game_points} points!")
def initial(self, state):
"""
Determine the player who goes first
:param state: The state of the game
:type state: State
"""
self.player_number = min(state.turn_order, 0) % self.size
self.current_player = self.players[self.player_number]
def winner_first(self):
"""
Causes the winner of the game to go first in the next game by rotating play order
"""
pos = self.players.index(self.current_player)
for _ in range(pos):
player = self.players.pop(0)
self.add(player)
def next(self, state):
"""
Moves on to the next player based on the turn order
:param state: The state of the game
:type state: State
"""
self.player_number = (self.player_number + state.turn_order) % self.size
self.current_player = self.players[self.player_number]
class State:
def __init__(self, turn_order=1, skip=0, forced_draw=0):
"""
:param turn_order: 1 if turn order is normal, -1 if it's reversed
:type turn_order: int
:param skip: The number of turns to skip, 0 normally
:type skip: int
:param forced_draw: The number of cards the next player is forced to draw, 0 normally
:type forced_draw: int
"""
self.turn_order = turn_order
self.skip = skip
self.forced_draw = forced_draw
def neutralise(self):
"""
Removes any turn skipping, forced draws or colour choice, but leaves turn order as is
"""
self.skip = 0
self.forced_draw = 0
def update(self, card):
"""
Updates state of the game based on the action of the played card
:param card: The played card
:type card: Card
"""
if card.action == "rev":
self.turn_order *= -1
self.neutralise()
elif card.action == "skip":
self.skip = 1
self.forced_draw = 0
elif "+" in str(card.action):
self.skip = 1
self.forced_draw = int(card.action[1:])
else:
self.neutralise()
|
4dcfb6585bc4d653ecbb5b67a6eb7745df32708e | booji/Exercism | /python/bank-account/bank_account.py | 1,882 | 3.84375 | 4 | import threading
class BankAccount(object):
def locking(func):
"""
Given a method returns a method that uses lock calls the given method
and then releases the lock
"""
def wrapper(self, *args):
with self.lock:
return func(self, *args)
return wrapper
def is_open(func):
"""
Given a method that checks to see if open state is True and then runs
the given method
"""
def wrapper(self, *args):
if not(self.openState):
raise ValueError(f"Account is not open. openState: {self.openState}")
return func(self, *args)
return wrapper
def is_positive_amount(func):
"""
Check if amount is postive
"""
def wrapper(self, amount):
if amount < 0:
raise ValueError(f"Cannot have negative amount: {amount}")
else:
func(self, amount)
return wrapper
def __init__(self):
self.balance = None
self.openState = False
self.lock = threading.Lock()
@locking
@is_open
def get_balance(self):
return self.balance
@locking
def open(self):
if self.openState:
raise ValueError(f"Account already open. openState: {self.openState}")
self.balance = 0
self.openState = True
@locking
@is_open
@is_positive_amount
def deposit(self, amount):
self.balance += amount
@locking
@is_open
@is_positive_amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError(f"Withdraw amount ({amount}) is greater than balance amount ({self.balance})")
self.balance -= amount
@locking
@is_open
def close(self):
self.balance=None
self.openState=False
|
94868a226f27210b3b3e50660cd67df86b826434 | maveric-coder/practice_arena | /happy_ladybugs.py | 309 | 3.515625 | 4 |
import re
def happy(n,st):
if st.count("_") == 0 and len(re.sub(r'((.)\2+)', "", st)) != 0:
return "NO"
for i in st:
if i != "_" and st.count(i) == 1:
return "NO"
return "YES"
for j in range(int(input())):
n=int(input())
st=input()
print(happy(n,st))
|
3157866bad52cd919dfb09fd71560ada3ab77b58 | Sadegh28/AI99001 | /Codes/CSP/NQueen_HillClimbing.py | 1,494 | 3.515625 | 4 | import random
from matplotlib import pyplot as plt
class nqueen_csp:
def __init__(self, q_num):
#q_num: number of queens
self.size = q_num
def initial_assignment(self):
assignment = [random.randrange(self.size) for i in range(self.size) ]
return assignment
def next_assignment(self,assignment):
best_neighbour = assignment.copy()
for i in range(self.size):
neighbour = assignment.copy()
neighbour[i] = random.randrange(self.size)
if(self.eval(neighbour) < self.eval(best_neighbour)):
best_neighbour = neighbour
return best_neighbour
def eval(self,assignment):
#count the num of conflicts
conflict_num = 0
#Diagonal check
for r in range(self.size):
for k in range(1,self.size-r):
if (assignment[r+k] == assignment[r] or assignment[r+k] == assignment[r]+k) or (assignment[r+k] == assignment[r]-k):
conflict_num = conflict_num + 1
return conflict_num
def search(self):
current = self.initial_assignment()
print(current)
while(True):
print(self.eval(current))
next = self.next_assignment(current)
if(self.eval(next) >= self.eval(current)):
break
current = next
return current
a = nqueen_csp(50)
print(a.search())
|
d67a89c4e517af3478dedc63189866e865d77d26 | i35186513/270201057 | /Lab8/example1.py | 181 | 3.5625 | 4 |
def summ(a_list):
a_sum = 0
for i in range(len(a_list)):
a_sum += i
return a_sum
a_list = [12, -7, 5, -89.4, 3, 27, 56, 57.3]
a_sum = summ(a_list)
print(a_sum*a_sum)
|
b9d16e4a06e0485a6e4e5c26bf4673d063c1eb7e | JaydeepKachare/Python-Classwork | /Session3/Arithematic6.py | 429 | 4.125 | 4 | # addition of two number
def addition(num1, num2):
ans = num1+num2
return ans
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2)
print("Addition : ",ans)
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2) # reusing same function (function call)
print("Addition : ",ans)
|
b615ccec79317abc4feee6a4793b6fa985c5a7a4 | miniyk2012/scratches | /scratch_32 | 12,088 | 4.375 | 4 | # Exercise2
import re
print('number')
def is_number(number):
# Write a function to match decimal numbers.
# We want to allow an optional - and we want to match numbers with or without one decimal point:
NUM_RE = re.compile(r'^-*(\d+\.|\.\d+|\d+.\d+|\d+)$')
print(NUM_RE.search(number), end=':')
return bool(NUM_RE.search(number))
print(is_number("5"))
print(is_number("5."))
print(is_number(".5."))
print(is_number(".5"))
print(is_number("01.5"))
print(is_number("-123.859"))
print(is_number("-123.859."))
print(is_number("."))
print('\nhex color')
def is_hex_color(color):
# Write a function to match hexadecimal color codes.
# Hex color codes consist of an octothorpe symbol followed by either 3 or 6 hexadecimal digits (that's 0 to 9 or a to f).
HEX_RE = re.compile(r'^#([\da-f]{6}|[\da-f]{3})$', re.IGNORECASE)
print(HEX_RE.search(color), end=': ')
return bool(HEX_RE.search(color))
print(is_hex_color("#639"))
print(is_hex_color("#6349"))
print(is_hex_color("#63459"))
print(is_hex_color("#634569"))
print(is_hex_color("#663399"))
print(is_hex_color("#000000"))
print(is_hex_color("#00"))
print(is_hex_color("#FFffFF"))
print(is_hex_color("#decaff"))
print(is_hex_color("#decafz"))
with open('dictionary.txt') as dict_file:
dictionary = dict_file.read()
print('\nPalindromes回文')
PAL_RE = re.compile(r'\b((.)(.).\3\2)\b')
print([ele[0] for ele in PAL_RE.findall(dictionary)])
print('\nDoubleDouble')
DOUBLE_RE = re.compile(r'(\b.*((.)\3).\2.*\b)')
print([ele[0] for ele in DOUBLE_RE.findall(dictionary)]) # 好丑
print('\nRepetitive Words')
REP_RE = re.compile(r'\b((.{2,})\2)\b')
print([ele[0] for ele in REP_RE.findall(dictionary)])
REP_RE = re.compile(r'\b(?P<total>(?P<name>.{2,})(?P=name))\b')
print([ele.group('total') for ele in REP_RE.finditer(dictionary)]) # 分组命名,可以用一下哟
print('\nSubstitution Exercises')
print('Get File Extension')
def get_extension(filename):
"""
Make a function that accepts a full file path and returns the file extension.
:param filename:
:return: extension
"""
EXTEN_RE = re.compile(r'.*\.(.*)$')
return EXTEN_RE.search(filename).group(1)
pass
print(get_extension('archive.zip'))
print(get_extension('image.jpeg'))
print(get_extension('index.xhtml'))
print(get_extension('archive.tar.gz'))
print('\nNormalize JPEG Extension')
def normalize_jpeg(filename):
"""
Make a function that accepts a JPEG filename and returns a new filename with jpg lowercased without an e.
:param filename:
:return:
"""
JPG_RE = re.compile(r'(.*\.)(jp[e]?g)$', re.IGNORECASE)
return JPG_RE.sub(r'\1jpg', filename)
print(normalize_jpeg('avatar.jpeg'))
print(normalize_jpeg('Avatar.JPEG'))
print(normalize_jpeg('AVATAR.Jpg'))
print(normalize_jpeg('AVATAR.xx.JpG'))
print('\nNormalize Whitespace')
def normalize_whitespace(sentence):
"""
Make a function that replaces all instances of one or more whitespace characters with a single space:
:param sentence:
:return:
"""
s = re.sub(r'\s+', r' ', sentence)
return re.sub(r'\s+$', '', s) # 去除结尾的空格
print(normalize_whitespace("hello there"))
print(normalize_whitespace("""Hold fast to dreams
For if dreams die
Life is a broken-winged bird
That cannot fly.
Hold fast to dreams
For when dreams go
Life is a barren field
Frozen with snow. """))
print('\nCompress blank links')
def compress_blank_lines(lines, max_blanks):
"""
Write a function that accepts a string and an integer N and
compresses runs of N or more consecutive empty lines into just N empty lines.
:param lines:
:return:
"""
print('*'*100)
COMPRESS_RE = re.compile(r'\n{%s,}'%(max_blanks+1))
return COMPRESS_RE.sub(r'\n'*(max_blanks+1), lines)
pass
print(compress_blank_lines("a\n\nb", max_blanks=1))
print(compress_blank_lines("a\n\nb", max_blanks=0))
print(compress_blank_lines("a\n\n\n\nb", max_blanks=2))
print(compress_blank_lines("a\n\n\n\n\nb\nc", max_blanks=2))
print(r'\nNormalize URL')
def normalize_domain(url):
"""
I own the domain treyhunner.com. I prefer to link to my website as https://treyhunner.com, but I have some links that use http or use a www subdomain.
Write a function that normalizes all www.treyhunner.com and treyhunner.com links to use HTTPS and remove the www subdomain.
:param url:
:return:
"""
url1 = re.sub(r'^http[s]?', r'https', url)
url2 = re.sub(r'(://)(www.)', r'\1', url1)
return url2
print(normalize_domain("http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/"))
# 'https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/'
print(normalize_domain("https://treyhunner.com/2016/02/how-to-merge-dictionaries-in-python/"))
# 'https://treyhunner.com/2016/02/how-to-merge-dictionaries-in-python/'
print(normalize_domain("http://www.treyhunner.com/2015/11/counting-things-in-python/"))
# 'https://treyhunner.com/2015/11/counting-things-in-python/'
print(normalize_domain("http://www.treyhunner.com"))
# 'https://treyhunner.com'
print(normalize_domain("http://trey.in/give-a-talk"))
# 'http://trey.in/give-a-talk'
print(r'Linebreaks')
def convert_linebreaks(text):
"""
Write a function that accepts a string and converts linebreaks to HTML in the following way:
text is surrounded by paragraphs
text with two line breaks between is considered two separate paragraphs
text with a single line break between is separated by a <br>
:param text:
:return:
"""
print('*'*100)
text1 = re.sub(r'([^\n])(\n)([^\n])', r'\1<br>\3', text)
text2 = re.sub(r'([^\s]+)', r'<p>\1<p>', text1)
return re.sub(r'\s+', r'', text2)
pass
print(convert_linebreaks("hello"))
# '<p>hello</p>'
print(convert_linebreaks("hello\nthere"))
# '<p>hello<br>there</p>'
print(convert_linebreaks("hello\n\nthere"))
# '<p>hello</p><p>there</p>'
print(convert_linebreaks("hello\nthere\n\nworld"))
# '<p>hello<br>there</p><p>world</p>'
# 找到所有word
sentence = "Oh what a day, what a lovely day! what kdfa what d"
print(re.findall(r'\b\w+\b', sentence))
# 找到相同的两个单词
print(re.findall(r'\b(\w+)\b.*?\b\1\b', sentence)) # 非贪婪
print(re.findall(r'\b(\w+)\b.*\b\1\b', sentence)) # 贪婪
print('\nLookahead Exercises')
# 不消耗字符串,而只往后看,用到Lookahead
sentence = "Oh what a day, what a lovely day! ni hao ya"
print(re.findall(r'\b(\w+)\b(?=.*\b\1\b)', sentence)) # 不消耗字符串(?=), Zero-width match confirming abc will match upcoming chars
print(re.findall(r'(.)x', 'axxxx'))
print(re.findall(r'(.)(?=x)', 'axxxx')) # 找出所有后面跟着x的字母,用lookahead,这样才会不会消耗后面跟随的x
print('\nnegative lookahead')
print(re.findall(r'([a-z]).*\1', 'aba bcc')) # 找到相同的字母
print(re.findall(r'([a-z]).*(?!\1)', 'a'))
print(re.findall(r'([a-z]).*(?!\1)', 'a '))
print(re.search(r'([a-z]).*(?!\1)[a-z]', 'ab')) # 这个理解比较难,这里的意思是,紧跟着的字母不能和前面的[a-z]相同,这是因为(?!不消耗字母!)
print(re.search(r'([a-z]).*(?!\1)[a-z]', 'aa'))
print(re.search(r'([a-z]).*(?!\1)[a-z]', 'a b'))
print(re.search(r'([a-z]{2}).*(?!\1)[a-z]{2}', 'abac')) # 这里的意思是,后面2个字母不能和前面的2个字母相同,这是因为(?!不消耗字母!)
print(re.search(r'([a-z]{2}).*(?!\1)[a-z]{2}', 'abab')) # 这里的意思是,后面2个字母不能和前面的2个字母相同,这是因为(?!不消耗字母!)
def normarize_whitespace(string):
return re.sub(r'\s*', ' ', string) # 替换的含义是找到所有匹配项,每个匹配项替换成所要求的形式.这里消耗一个字母就找到一个0长度的\s,然后将其替换成空格
print(normarize_whitespace('hello \n world'))
print(re.findall(r'\b((?=.*a.*)(?=.*i.*).{3})\b', dictionary))
print(re.findall(r'\b((?=.*a.*)(?=.*e.*)(?=.*i.*)(?=.*o.*)(?=.*u.*).{1,9})\b', dictionary)) # 因为lookahead不消耗字母,因此就具有了任意顺序的功能
def all_vowels_words(dictionary):
"""
Find all words that are at most 9 letters long and contain every vowel (a, e, i, o, u) in any order.
:param dictionary:
:return:
"""
return re.findall(r'\b((?=.*a.*)(?=.*e.*)(?=.*i.*)(?=.*o.*)(?=.*u.*).{1,9})\b', dictionary)
print(all_vowels_words(dictionary))
print('\nUnique Letter')
def unique_letters(dictionary):
"""
Find all words that are 10 letters long and do not have any repeating letters.
:param dictionary:
:return:
"""
return [ele.group('letter') for ele in re.finditer(r'\b(?!.*(\w).*\1.*)(?P<letter>.{10})\b', dictionary)]
print(unique_letters(dictionary))
print('\nHTML Encode Ampersands')
def encode_ampersands(text):
"""
Replace all & characters which are not part of HTML escape sequences by an HTML-encoded ampersand (&).
:param text:
:return:
"""
# print(re.search(r'&(?!.{3};)', text))
return re.sub(r'&(?!.{3};)', '&', text)
print(encode_ampersands("This & that & that & this."))
# 'This & that & that & this.'
print(encode_ampersands("A&W"))
# 'A&W'
print('\nBroken Markdown Links')
def find_broken_links(text):
"""
Make a function that accepts a string and returns a list of all reference-style markdown links
that do not have a corresponding link definition.
"""
LINK_RE = re.compile(r'''
\[
(?P<key>.+)
\]
\[
(?P<link>.+)
\]
(?!(?:.|\n)*\[(?P=link)\]) # 意思是后面不出现相同的link,注意(.|\n)使用,是为了匹配newline和任意字符,因为.不能匹配newline
''', re.VERBOSE|re.IGNORECASE)
return LINK_RE.findall(text)
print(find_broken_links(r"""
[working link][Google]
[broken link][baidu]
[working link][Python]
[google]: www.google.com
[python]: https://www.python.org/"""))
# [('broken link', 'baidu')]
def new_find_broken_links(text):
LINK_RE = re.compile(r'''
\[
(?P<link>.+)
\]
\[
(?P<url>.*)
\]
(?!(?:.|\n)*\[(?P=link)\]) # 意思是后面不出现相同的link,注意(.|\n)使用,是为了匹配newline和任意字符,因为.不能匹配newline
''', re.VERBOSE|re.IGNORECASE)
return [('broken link', ele.group('link')) for ele in LINK_RE.finditer(text)]
print(new_find_broken_links("""
[Python][]
[Google][]
[python]: https://www.python.org/"""))
# [('broken link', 'Google')]
print('\nCamel Case to Underscore')
def convert2underscore(string):
return re.sub(r'([A-Z])', r'_\1', string).lower()
print(convert2underscore('myCarYourMoney'))
print('\nGet Inline Markdown Links')
def get_inline_links(text):
"""
Make a function that accepts a string and returns a list of all inline markdown links in the given string.
"""
LINK_RE = re.compile(r'''
\[
(?P<language>.+)
\]
\(
(?P<link>.+)
\)
''', re.VERBOSE|re.IGNORECASE)
print(LINK_RE.search(text))
return [(ele.group('language'), ele.group('link')) for ele in LINK_RE.finditer(text)]
print(get_inline_links("""
[Python](https://www.python.org)
[Google](https://www.google.com)"""))
# [('Python', 'https://www.python.org'), ('Google', 'https://www.google.com')]
print('\nGet All Markdown Links')
def new_get_inline_links(text):
# 不会...感觉有些难
pass
get_inline_links("""
[Python](https://www.python.org)
[Google][]
[Another link][example]
[google]: https://www.google.com
[example]: http://example.com""")
# [('Python', 'https://www.python.org'), ('Google', 'https://www.google.com'), ('Another link', 'http://example.com')] |
892270cc7bd25a39e8b899cfd2ebc7de5cc2fd10 | DahaLogy/homework | /hw_2_2.py | 547 | 4.15625 | 4 | fib_arr = int(input("Enter the number of array: "))
n1 = 1
n2 = 1
arr = {}
if fib_arr <= 0:
print("The number of terms should be positive")
elif fib_arr == 1:
print("Fibonacci sequence for", fib_arr, "is:")
print(n1)
else:
print("Fibonacci sequence for", fib_arr, "is:")
for count in range(fib_arr):
# print(n1)
arr[count] = n1
print(arr[count])
nth = n1 + n2
n1 = n2
n2 = nth
print("Element [", fib_arr, "] of Fibonacci array number series = ", arr[count])
|
c35335bbdf6171e9f9fe55edba6c273dfaac174e | LukaszMalucha/Python-Various-Useful | /review/refresh_14_map-reduce.py | 379 | 3.78125 | 4 | # -*- coding: utf-8 -*-
maps = map(lambda x: x**2, range(5))
type(maps)
list(maps)
def add(t):
return t[0] + t[1]
list(map(add, [(0,0), [1,1], range(2,4)]))
######################################################################## StarMap
from itertools import starmap
def add(x,y):
return x + y
list(starmap(add, [(0,0), (1,1), (2,3)])) |
91cf37abf5ecc8758dc830f4a040032b01989e9d | amusabji/Coursera | /Algorithmic Toolbox/week2_algorithmic_warmup/4_least_common_multiple/lcm.py | 606 | 3.75 | 4 | # Uses python3
import sys
def gcd(a, b):
# assert 0 <= a <= 2 * 10 ** 9 and 0 <= b <= 2 * 10 ** 9
small = min(a, b)
big = max(a, b)
remainder = 1
while remainder != 0:
remainder = big % small
big = small
small = remainder
return big
def lcm(a, b):
assert 1 <= a <= 2 * 10 ** 9 and 1 <= b <= 2 * 10 ** 9
return a * b // gcd(a, b)
if __name__ == '__main__':
# inputt = sys.stdin.read()
a, b = map(int, input().split())
print(lcm(a, b))
# input_n = str(input())
# a, b = map(int, input_n.split())
# print(lcm_naive(a, b))
|
d72be5ac33387c91adf8a60336f6008757dcd29b | comicxmz001/LeetCode | /Python/224_BasicCalculator.py | 1,520 | 3.671875 | 4 | class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
# the string is actually converted to [+num1,-num2,-num3...]
# so, you should always get the sign before the number.
# There is a trap with negative operation, since int()/int() will round down, e.g. 2/3 = 1,
# when dealing with negatevie, -2/3 = round.down(-2/3) = round.down(-0.333) = -1. This will result in wrong restul.
# Thus, simple change tmp to -tmp, and then change back after the operation.
num = 0
sign = "+" #be default, the first num has to be added to the stack
stack = []
for i in xrange(len(s)):
# calculate num
if s[i].isdigit():
num = num*10 + int(s[i])
# calculate sign
if (not s[i].isdigit() and not s[i].isspace()) or (i == len(s) -1):
# still using the previous sign
if sign == "+":
stack.append(num)
elif sign == "-":
stack.append(-num)
elif sign == "*":
stack.append(stack.pop()*num)
else: # /
tmp = stack.pop ()
if tmp < 0:
stack.append(-(tmp/-num))
else:
stack.append(tmp/num)
num = 0
sign = s[i] # update to new sign.
return sum(stack)
if __name__ == '__main__':
exp = "3 - 2/3 + 3 - 2 + 3*2" # 7
exp2 = "3+5 / 2 "
print Solution().calculate(exp2) |
84a56dbd51f4416721af54c9eb834b33d4f04ced | Feng-Xu/TechNotes | /python/geektime/classCode/chineseZodiac.py | 319 | 3.515625 | 4 | # 记录十二生肖,根据年费判断生效
chinese_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊'
#print(chinese_zodiac[0:4])
#print(chinese_zodiac[-2])
year = 2018
print(year%12)
print(chinese_zodiac[year % 12])
print('狗' in chinese_zodiac)
print(chinese_zodiac + "heheheheh")
print(chinese_zodiac * 2) |
a3aacc8cf4ee0ac791836419cf576d93e8f00b5c | PoojaLokanath/PythonCode | /highest2no.py | 218 | 3.859375 | 4 | x = int(input("Enter value x : "))
y = int(input("Enter value y : "))
if x > y:
print("first")
high=x
elif y > x:
print("Second")
high=y
elif x == y:
print("Same")
print(high*high) |
6b623aeb8c9fdc1f09b8a076ddb5db6a9ac5b36d | BrianMath-zz/ExerciciosPython | /Exercicios - Mundo1/Ex026.py | 239 | 3.984375 | 4 | #Ex. 026
nome = str(input("Digite uma frase: ")).strip().lower()
print("\nQuantidade de letras 'a':", nome.count("a"))
print("Posição da primeira letra 'a':", nome.find("a")+1)
print("Posição da última letra 'a':", nome.rfind("a")+1)
|
d323a53c3ee287d4f560a9a01ca5ecbcc8f35dd5 | kidult00/NatureOfCode-Examples-Python | /chp04_systems/simplePolymorphism/Shape.py | 500 | 3.90625 | 4 | # The Nature of Code - Python Version
# [kidult00](https://github.com/kidult00)
# Example 22-1: Inheritance
class Shape(object):
def __init__(self, x_, y_, r_):
self.x = x_
self.y = y_
self.r = r_
def jiggle(self):
self.x += random(-1, 1)
self.y += random(-1, 1)
# A generic shape does not really know how to be displayed.
# This will be overridden in the child classes.
def display(self):
point(self.x, self.y) |
d041770066425d495ecc159b045741f55ad7c43d | sevenhe716/LeetCode | /LinkedList/test_q082_remove_duplicates_from_sorted_list_ii.py | 882 | 3.5 | 4 | import unittest
from LinkedList.q082_remove_duplicates_from_sorted_list_ii import Solution
from common import ListNode
class TestRemoveDuplicatesFromSortedListIi(unittest.TestCase):
"""Test q082_remove_duplicates_from_sorted_list_ii.py"""
def test_remove_duplicates_from_sorted_list_ii(self):
s = Solution()
self.assertEqual(ListNode.generate([]), s.deleteDuplicates(ListNode.generate([])))
self.assertEqual(ListNode.generate([1]), s.deleteDuplicates(ListNode.generate([1])))
self.assertEqual(ListNode.generate([]), s.deleteDuplicates(ListNode.generate([1, 1])))
self.assertEqual(ListNode.generate([1, 2, 5]), s.deleteDuplicates(ListNode.generate([1, 2, 3, 3, 4, 4, 5])))
self.assertEqual(ListNode.generate([2, 3]), s.deleteDuplicates(ListNode.generate([1, 1, 1, 2, 3])))
if __name__ == '__main__':
unittest.main()
|
6798b8438dc5f531ff47405dcdfbdb1f3d856df4 | thouseef46/MOHAMMED-THOUSEEF-S-ENLIST-BOOTCAMP | /days13.py | 1,112 | 3.578125 | 4 | import re
def is_allowed_specific_char(string):
charRe=re.compile(r'[^a-z,A-Z,0-9]')
string=charRe.search(string)
return not bool(string)
print (is_allowed_specific_char("ABCDEFabcdf123459"))
print( is_allowed_specific_char("122345@#$$%"))
#-------
def text_match(text):
patterns='\w*ab./w*'
if re.search(patterns,text):
return 'found'
else:
return 'not found'
print(text_match("puyhionik"))
print(text_match("ababababab"))
#--------
def end_num(string):
text=re.compile(r".*[0-9]$")
if text_match(string):
return True
else:
return False
print(end_num('asfftyf33455'))
print(end_num('fdsdfdfd'))
#-----
length=re.finditer(r'.*[0-9]{1,3}','exercise num 1,9,11,ans 222 are important')
print("number 1 to 3")
for n in length:
print(n.group(0))
#-------
def text_match(text):
patterns ='^[a-z,A-Z0-9_]*$'
if re.search(patterns,text):
return ' found'
else:
return 'not found'
print(text_match("tytytuytuytu"))
print(text_match("DYTFFFHGFGHF"))
|
55f322c6b60ce3f480d1e4ffa214768513915907 | wujunlin21/Code | /Code 2/56 Merge Intervals.py | 868 | 3.984375 | 4 | # 56. Merge Intervals
'''
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
'''
#Array, Sort
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals=sorted(intervals,key=lambda x:x.start)
result=[]
for interval in intervals:
if len(result)==0 or interval.start>result[-1].end:
result.append(interval)
else:
result[-1].end=max(result[-1].end,interval.end)
return result
|
dc24ac98dbdd097b5e1b767e8f396a7abe6524c4 | kevincovey/fit-rossby | /scripts/fit_period_log.py | 10,890 | 3.59375 | 4 | # Originally written by Stephanie T. Douglas (2012-2014)
# Modified by Kevin Covey (2019)
# under the MIT License (see LICENSE.txt for full details)
import numpy as np
import emcee
import matplotlib.pyplot as plt
def quantile(x,quantiles):
""" Calculates quantiles - taken from DFM's triangle.py """
xsorted = sorted(x)
qvalues = [xsorted[int(q * len(xsorted))] for q in quantiles]
return list(zip(quantiles,qvalues))
def rossby_model_log(parameters,Ro):
"""
computes the saturated/unsaturated activity model for a given parameter set
For Ro < turnover, the model values are equal to the saturation level
For Ro >= turnover, the model values follow a power-law with slope beta
Inputs and outputs are in log space (ie, saturation level is -3., rather than 10.**(-3.); similar for loglxlbol values)
Input
-----
parameters : array-like (3)
parameters for the model: saturation level (expressed as Log L_{whatever}/L_{bol}, turnover_Ro, beta
Ro : array-like
Rossby number values. The model Log L_{whatever}/L_{bol} values will
be computed for these Rossby numbers
Output
------
: numpy.ndarray (same size as Ro)
Model Log L_{whatever}/L_{bol} values corresponding to input Ro
"""
#save the parameters with intuitive names
sat_level,turnover,beta = parameters[0],parameters[1],parameters[2]
#calculate the pivot constant that ensures that the power law reaches the saturation point at the turnover point
pivot_constant = sat_level - beta * np.log10(turnover)
#define the Log_LxLbol array and fill with saturated level datapoints
Log_LxLbol = np.ones(len(Ro))*sat_level
#find unsaturated objects and calculate their Log_LxLbols based on the assumed power law behavior
un_sat = np.where(Ro>=turnover)[0]
Log_LxLbol[un_sat] = pivot_constant + beta * np.log10(Ro[un_sat])
return Log_LxLbol
def lnprior(parameters):
"""
simple method of setting (flat) priors on model parameters
If input parameters are within the priors, a (constant) likelihood is returned;
if the input parameters are outside the priors, a negative infinity is returned
to indicate an unacceptable fit.
Input
-----
parameters : array-like (3)
parameters for the model: saturation level (expressed as Log L_{whatever}/L_{bol}, turnover_Ro, beta
Output
------
: value
0.0 if parameters are within priors; -np.inf if not.
"""
sat_level, turnover, beta, lnf = parameters[0], parameters[1], parameters[2], parameters[3]
## USE THE LINE BELOW TO CONSTRAIN THE FIT TO THE SLOPE FOUND BY CENKEN!
#if -4.0 < sat_level < -2.0 and 0.05 < turnover < 0.3 and -1.9 < beta < -1.85 and -10.0 < lnf < 1.0:
if -4.0 < sat_level < -2.0 and 0.05 < turnover < 0.3 and -4 < beta < 0 and -10.0 < lnf < 1.0:
return 0.0
return -np.inf
def lnlike(parameters, rossby_no, log_LxLbol ,err_ll):
"""
Calculates the natural log of the likelihood for a given model fit to a given input dataset (with errors).
Input
-----
parameters : array-like (4)
parameters for the model: saturation level, turnover, beta, multiplicative error inflator
rossby_no : array-like
Data Rossby number values
log_LxLbol : array-like
Data activity values (L_{whatever}/L_{bol} - in the original case, LxLbol
error_ll : array-like
Uncertainties in the data activity values.
Output
------
lnprob : float
natural log of the likelihood of the model given the data
"""
sat_level, turnover, beta, lnf = parameters[0], parameters[1], parameters[2], parameters[3]
#if ((sat_level>1e-1) or (sat_level<1e-8) or (turnover<0.001) ## stephanie's original method of setting priors;
# or (turnover>2) or (beta>2) or (beta<-6)): ## now offloaded to lnprior
# return -np.inf
model_ll = rossby_model_log(parameters, rossby_no)
#inv_sigma2 = 1.0/(err_ll**2) ## inverse sigma assuming only quoted errors
inv_sigma2 = 1.0/(err_ll**2 + model_ll**2*np.exp(2*lnf)) ## inverse sigma assuming errors are underestimated by some multiplicative factor
ln_like = -0.5*(np.sum((log_LxLbol-model_ll)**2*inv_sigma2 - np.log(inv_sigma2)))
return ln_like
def lnprob(parameters, rossby_no, log_LxLbol, err_ll):
"""
Calculates the natural log of the probability of a model, given a set of priors, the defined likelihood function, and the observed data
Input
-----
parameters : array-like (4)
parameters for the model: saturation level, turnover, beta, multiplicative error inflator
rossby_no : array-like
Data Rossby number values
log_LxLbol : array-like
Data activity values (L_{whatever}/L_{bol} - in the original case, LxLbol
error_ll : array-like
Uncertainties in the data activity values.
Output
------
lnprob : float
natural log of the likelihood of the model given the data and the priors
(by adding prior and model likelihood terms, which are
calculated by lnprior() and lnlike() respectively)
"""
lp = lnprior(parameters)
if not np.isfinite(lp):
return -np.inf
return lp + lnlike(parameters, rossby_no, log_LxLbol, err_ll)
def run_rossby_fit(start_p, data_rossby, data_ll, data_ull,
nwalkers=256,nsteps=10000):
"""
Sets up the emcee ensemble sampler, runs it, prints out the results,
then returns the samples.
Input
-----
start_p : (3)
starting guesses for the three model parameters
saturation level, turnover point, and power-law slope (beta)
data_rossby : array-like (ndata)
Data Rossby number values
data_ll : array-like (ndata)
Data activity values (L_{whatever}/L_{bol} - in my case
I was using L_{Halpha}/L_{bol})
data_ull : array-like (ndata)
Uncertainties in the data activity values.
Output
------
samples : array-like (nwalkers*nsteps,3)
all the samples from all the emcee walkers, reshaped so there's
just one column per parameter
"""
ndim = 4
p0 = np.zeros((nwalkers,ndim))
# initialize the walkers in a tiny gaussian ball around the starting point
for i in range(nwalkers):
p0[i] = start_p + (1e-1*np.random.randn(ndim)*start_p)
sampler = emcee.EnsembleSampler(nwalkers,ndim,lnprob,
args=[data_rossby,data_ll,data_ull])
pos,prob,state=sampler.run_mcmc(p0,nsteps/2)
sampler.reset()
pos,prob,state=sampler.run_mcmc(pos,nsteps)
sl_mcmc = quantile(sampler.flatchain[:,0],[.16,.5,.84])
#sl_mcmc.info()
#print(sl_mcmc)
to_mcmc = quantile(sampler.flatchain[:,1],[.16,.5,.84])
#print(to_mcmc)
be_mcmc = quantile(sampler.flatchain[:,2],[.16,.5,.84])
#print(be_mcmc)
var_mcmc = quantile(sampler.flatchain[:,3],[.16,.5,.84])
print('sat_level={0:.7f} +{1:.7f}/-{2:.7f}'.format(
sl_mcmc[1][1],sl_mcmc[1][1]-sl_mcmc[0][1],sl_mcmc[2][1]-sl_mcmc[1][1]))
print('turnover={0:.3f} +{1:.3f}/-{2:.3f}'.format(
to_mcmc[1][1],to_mcmc[1][1]-to_mcmc[0][1],to_mcmc[2][1]-to_mcmc[1][1]))
print('beta={0:.3f} +{1:.3f}/-{2:.3f}'.format(
be_mcmc[1][1],be_mcmc[1][1]-be_mcmc[0][1],be_mcmc[2][1]-be_mcmc[1][1]))
print('var={0:.3f} +{1:.3f}/-{2:.3f}'.format(
var_mcmc[1][1],var_mcmc[1][1]-var_mcmc[0][1],var_mcmc[2][1]-var_mcmc[1][1]))
samples = sampler.flatchain
return samples
def plot_rossby_log(samples,data_rossby,data_ll,data_ull,plotfilename=None,ylabel=r'$L_{X}/L_{bol}$', sampleName=None):
"""
Plot fit results with data
Input
-----
samples : array-like (nwalkers*nsteps,3)
all the samples from all the emcee walkers, reshaped so there's
just one column per parameter
data_rossby : array-like (ndata)
Data Rossby number values
data_ll : array-like (ndata)
Data activity values (L_{whatever}/L_{bol} - in my case
I was using L_{Halpha}/L_{bol})
data_ull : array-like (ndata)
Uncertainties in the data activity values.
plotfilename : string (optional; default=None)
if not None, the plot will be saved using this filename
"""
sl_mcmc = quantile(samples[:,0],[.16,.5,.84])
to_mcmc = quantile(samples[:,1],[.16,.5,.84])
be_mcmc = quantile(samples[:,2],[.16,.5,.84])
var_mcmc = quantile(samples[:,3],[.16,.5,.84])
plt.figure()
ax = plt.subplot(111)
ax.set_xscale('log')
#ax.set_yscale('log')
# Just trying to reduce the number of plotted points...
xl = np.append(np.arange(0.001,0.2,0.001),np.arange(0.2,2.5,0.02))
# xl = np.arange(0.001,2.0,0.005)
#for p in list(samples[np.random.randint(len(samples), size=100)]):
# ax.plot(xl,rossby_model(p,xl),color='LightGrey')
sat_level = sl_mcmc[1][1]
turnover = to_mcmc[1][1]
x = np.asarray([turnover,2.0])
# x = np.arange(turnover,2.0,0.001)
#constant = sat_level/(turnover**-1.)
#ax.plot(x,constant*(x**-1.),'k--',lw=1.5,label=r'$\beta=\ -1$')
#constant = sat_level/(turnover**-2.1)
#ax.plot(x,constant*(x**-2.1),'k-.',lw=1.5,label=r'$\beta=\ -2.1$')
#constant = sat_level/(turnover**-2.7)
#ax.plot(x,constant*(x**-2.7),'k:',lw=2,label=r'$\beta=\ -2.7$')
star_color = 'BlueViolet'
ax.errorbar(data_rossby,data_ll,data_ull,color=star_color,fmt='.',capsize=0,
ms=4,mec=star_color)
#print('parameters for model plot:')
#print('xl: ')
#print(xl)
#print('model inputs: ')
#print([sl_mcmc[1][1],to_mcmc[1][1],be_mcmc[1][1]])
#print('model: ')
#print(
ax.plot(xl,rossby_model_log([sl_mcmc[1][1],to_mcmc[1][1],be_mcmc[1][1]],xl),
'k-',lw=2,label=r'$\beta=\ {0:.1f}$'.format(be_mcmc[1][1]))
ax.set_ylabel(ylabel,fontsize='xx-large')
ax.set_xlabel('R$_o$',fontsize='x-large')
ax.set_xlim(1e-3,2)
ax.tick_params(labelsize='x-large')
#ax.set_xticklabels((0.001,0.01,0.1,1))
handles, labels = ax.get_legend_handles_labels()
new_handles = np.append(handles[-1],handles[0:-1])
new_labels = np.append(labels[-1],labels[0:-1])
if sampleName!=None:
ax.legend(new_handles,new_labels,loc=3, title=sampleName)
else:
ax.legend(new_handles,new_labels,loc=3)
if plotfilename!=None:
plt.savefig(plotfilename)
def print_pdf(cropchain,filename,col_names=["sat_level,turnover,beta"]):
f = open(filename,"w")
f.write("# {}".format(col_names[0]))
for cname in col_names[1:]:
f.write(",{}".format(cname))
f.write("\n")
for i,p in enumerate(cropchain):
#print p
f.write(str(p[0]))
for this_p in p[1:]:
f.write(",{}".format(this_p))
f.write("\n")
f.close()
|
09cc3ca40043f129d237cf29cc5c72b34102c60b | gabriellaec/desoft-analise-exercicios | /backup/user_017/ch19_2020_09_11_01_33_04_265125.py | 178 | 3.734375 | 4 | def classifica_triangulo(a,b,c):
if a == b and a == c:
print("Equilatero")
elif a == b and a != c:
print("Isosceles")
else:
print("Escaleno")
|
2c075c079761d67075f9a24b6ff9158f60f8c7de | Cozoob/Algorithms_and_data_structures | /BIT ALGO/Programowanie Dynamiczne cz1/canConstruct.py | 1,404 | 3.53125 | 4 | # Created by Marcin "Cozoob" Kozub at 20.04.2021 08:45
def can_construct(target, words):
memo = [0 for _ in range(len(target) + 1)]
memo[0] = True
def rec_can_construct(target, words, memo):
if target == "":
return True
if memo[len(target)] != 0:
return memo[len(target)]
for i in range(len(words)):
word = words[i]
flag = True
if word[0] == target[0] and len(word) <= len(target):
for j in range(1, len(word)):
if word[j] != target[j]:
flag = False
if flag == True:
curr_target = rec_can_construct(target[len(word):], words, memo)
if curr_target == True:
memo[len(target)] = True
return True
memo[len(target)] = False
return False
return rec_can_construct(target, words, memo)
if __name__ == '__main__':
# print(can_construct("abcdef", ["ab", "abc", "cd", "def", "abcd"])) # True
# print(can_construct("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"])) # False
# print(can_construct("enterapotentpot", ["a", "p", "ent", "enter", "ot", "o", "t"])) # True
print(can_construct("eeeeeeeeeeeeeeeeeeeeeef", ["e", "ee", "eee", "eeee", "eeeee", "eeeeee"])) # False |
404492ee7b98c9e86d7c140ac5369d58158dfa5c | arthurk/keylogger | /kla_text_input.py | 1,359 | 3.796875 | 4 | """
Reads the generated csv file from the keylogger
and outputs text input that can be entered into
https://patorjk.com/keyboard-layout-analyzer/
Since the KLA cannot process virtual keys such as Shift, Command
or Alt these are omitted from the output.
"""
import csv
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('filename', type=str)
args = parser.parse_args()
shift_map = {
"/": "?",
".": ">",
",": "<",
"[": "{",
"]": "}",
"\\": "|",
"`": "~",
"1": "!",
"2": "@",
"3": "#",
"4": "$",
"5": "%",
"6": "^",
"7": "&",
"8": "*",
"9": "(",
"0": ")",
"-": "_",
"=": "+",
";": ":",
"'": "\"",
}
# translates a key to it's value when shift mod is pressed
def get_shift_value(key):
try:
return shift_map[key]
except KeyError:
return key.upper()
with open(args.filename) as csvfile:
r = csv.reader(csvfile)
word = ""
for key, mod in r:
if len(key) == 1:
if mod == "shift ":
key = get_shift_value(key)
word += key
elif key == "SPACE":
word += " "
else:
if key == "ENTER":
print(word)
else:
# print without newline
print(word, end="")
word = ""
|
7c2bb712bb125c103d7ef57adf3d687246579d4e | kiilkim/book_duck | /pythonPractice/test3.py | 3,524 | 3.84375 | 4 | #반복문 .\
#대량데이터를 많이 처리해야 하므로 for,while 등 사용
#반복되는 부분이 탭만큼 띄워짐
i=1
while i <= 10 :
print(i)
i+=1
#break 반복문 빠져나오기
#continue: 계속
#while 문 안에서도 if 문 쓰고 텝해서 써야 한다.
i = 0
while i<=10:
i+=1
if(i%3==0) :
continue #반복문 맨처음
print(i)
#130p예시 나무 꾼
treeHit = 0
while treeHit < 10:
treeHit +=1
print("나무를 %d번 찍었습니다." % treeHit)
if treeHit == 10:
print("나무가 넘어갑니다.")
#어디서 쓸 수 있나
#어항의 온도,
#for 변수 in 리스트 (튜플,문자열):
#튜플은 수정 불가, 문자열 : 문자를 여러개 모아서 배열에 담았다.
# 반복할 명령1
# 반복할 명령2
li = [85,95,90,80,75]
sum = 0 #합계저장
print(len(li))
for i in li:
sum +=i
print("항목개수:",len(li))
print("점수합계:",sum)
print("점수평균:",sum/len(li))
#138p
test_list=['one', 'two', 'tree']
for i in test_list : #one,two,three순서대로 i에 대입
print(i)
a = [(1,2), (3,4), (5,6)]
for (first,last) in a:
print(first,last)
print(first+last)
#주사위의 합
s="hello"
for a in s:
print(a)
lis=['hello']
for a in lis:
print(a)
#리스트안의 문자열은 하나로 친다.
#1~10출력 range(시작번호, 끝번호,증가값 )
add = 0
for i in range(1,11,1):
print(i)
add+=i
print("총합:",add)
#for응용 139p
scores = [90, 50, 60, 80, 75]
#합격인지 불합격인지
number = 0 # 학생에게 붙여줄 번호
for score in scores :
number +=1
if(score>=60):
print("%d번 학생은 합격입니다" % number)
else:
print("%d번 학생은 불합격입니다" % number)
#물고기어항 5개
fish_tanksC = [25,27,29,22,26]
number =0
for fish_tankC in fish_tanksC:
number+=1
if(fish_tankC >28) :
print("%d번 어항이 %d도 입니다." % (number,fish_tankC))
elif(fish_tankC <26):
print("%d번 어항이 %d도 입니다." % (number,fish_tankC))
else:
print("%d번 어항은 정상온도입니다." % number)
## 2단 출력
#2*1=2
#2*2=4
#..
#2*9=18
for i in range(1,10,1):
#print(2,"*",i,"=",2*i)
print("%d*%d=%d" % (2,i,2*i))
# 구구단
for dan in range(2,10,1):
print("<%d단>" % dan)
for i in range(1,10,1):
print("%d*%d=%d" % (dan,i,dan*i))
#한줄 for 문
#
#[반복실행문 for 변수 in 리스트 ]
#
a = [1,2,3,4]
result= [i*3 for i in a]
print(result)
#for문과 같이 사용되는 rnage
a = range(10) # 0부터 10 '미만' !
sum = 0
for i in range(1,101):
sum+=i
print(sum)
scores = []
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")
# [조건에 만족하는 반복실행문 for 변수 in 리스트 if 조건]
# 2의 배수를 구해서 i*3
result = [i*3 for i in range(0,101) if(i%2==0)]
#for 문 돌리면서도 2의 배수 찾을 수 있음
print(result)
# [반복실행문 for 변수1 in 리스트1 for 변수2 in 리스트2]
# [반복실행문 for 변수1 in 리스트1 if 조건1 for 변수2 in 리스트2 if 조건2]
# 구구단결과
result = [dan*i for dan in range(2,10,1) for i in range(1,10,1)]
print(result) |
5c561e1b2efe09a05724e60b2f667f1cf86e670d | taichisano94/adventofcode2020 | /day12/main.py | 5,408 | 4.21875 | 4 | class Direction:
EAST = 0
NORTH = 1
WEST = 2
SOUTH = 3
@staticmethod
def get_direction_string(value):
if value == Direction.EAST:
return "EAST"
elif value == Direction.NORTH:
return "NORTH"
elif value == Direction.WEST:
return "WEST"
elif value == Direction.SOUTH:
return "SOUTH"
else:
raise Exception(f"Unknown value {value} for direction")
class InstructionCode:
FORWARD = "F"
RIGHT_ROTATE = "R"
LEFT_ROTATE = "L"
NORTH = "N"
SOUTH = "S"
EAST = "E"
WEST = "W"
class Ship:
def __init__(self):
"""
We treat moving east as positive x and north as positive y
"""
self.x = 0
self.y = 0
self.direction = Direction.EAST
def do_instruction(self, code, value):
"""
Process a single instruction
"""
if code == InstructionCode.FORWARD:
self._update_direction_movement(self.direction, value)
elif code == InstructionCode.NORTH:
self._update_direction_movement(Direction.NORTH, value)
elif code == InstructionCode.SOUTH:
self._update_direction_movement(Direction.SOUTH, value)
elif code == InstructionCode.EAST:
self._update_direction_movement(Direction.EAST, value)
elif code == InstructionCode.WEST:
self._update_direction_movement(Direction.WEST, value)
elif code == InstructionCode.LEFT_ROTATE or code == InstructionCode.RIGHT_ROTATE:
self._update_direction_face(code, value)
def _update_direction_movement(self, direction, value):
"""
Updates the coordinate movement according to given direction
"""
if direction == Direction.EAST:
self.x += value
elif direction == Direction.WEST:
self.x -= value
elif direction == Direction.NORTH:
self.y += value
elif direction == Direction.SOUTH:
self.y -= value
else:
raise Exception(f"Unknown direction {direction} given")
def _update_direction_face(self, rotation, value):
"""
Update the way the ship is facing
"""
rotation_amount = value / 90
if rotation == InstructionCode.LEFT_ROTATE:
self.direction = (self.direction + rotation_amount) % 4
elif rotation == InstructionCode.RIGHT_ROTATE:
self.direction = (self.direction - rotation_amount) % 4
else:
raise Exception(f"Unknown rotation direction {rotation}")
def get_manhattan_distance(self):
return abs(self.x) + abs(self.y)
def get_current_location(self):
return (self.x, self.y)
def __str__(self):
return f"{self.get_current_location()}[{Direction.get_direction_string(self.direction)}]"
class Waypoint:
"""
The x and y values are relative to the ship's position and does not mean
the literal position in the grid
"""
def __init__(self):
self.relative_x = 10
self.relative_y = 1
def move(self, direction, value):
"""
Moves the waypoint's relative position
"""
if direction == Direction.EAST:
self.relative_x += value
elif direction == Direction.WEST:
self.relative_x -= value
elif direction == Direction.NORTH:
self.relative_y += value
elif direction == Direction.SOUTH:
self.relative_y -= value
else:
raise Exception(f"Unknown direction {direction}")
def rotate(self, rotation, value):
"""
Rotates the relative position of the waypoint
"""
rotation_amount = int(value / 90)
for i in range(rotation_amount):
if rotation == InstructionCode.LEFT_ROTATE:
self.relative_x, self.relative_y = self.relative_y * -1, self.relative_x
else:
self.relative_x, self.relative_y = self.relative_y, self.relative_x * -1
def __str__(self):
x_str = f"+{self.relative_x}" if self.relative_x > 0 else self.relative_x
y_str = f"+{self.relative_y}" if self.relative_y > 0 else self.relative_y
return f"({x_str}, {y_str})"
class ShipWaypointManager:
"""
Class that manages how the ship and waypoint moves
"""
def __init__(self):
self.ship = Ship()
self.waypoint = Waypoint()
def do_instruction(self, code, value):
if code == InstructionCode.FORWARD:
for i in range(value):
self.ship.x += self.waypoint.relative_x
self.ship.y += self.waypoint.relative_y
elif code == InstructionCode.EAST:
self.waypoint.move(Direction.EAST, value)
elif code == InstructionCode.WEST:
self.waypoint.move(Direction.WEST, value)
elif code == InstructionCode.NORTH:
self.waypoint.move(Direction.NORTH, value)
elif code == InstructionCode.SOUTH:
self.waypoint.move(Direction.SOUTH, value)
elif code == InstructionCode.LEFT_ROTATE or code == InstructionCode.RIGHT_ROTATE:
self.waypoint.rotate(code, value)
else:
raise Exception(f"Unknown instruction {code}")
def __str__(self):
return f"{self.ship}{self.waypoint}"
if __name__ == "__main__":
instructions = list()
with open("input/input.txt", "r") as f:
for line in f:
line = line.strip()
instructions.append(line)
ship = Ship()
for i in instructions:
code = i[0]
value = int(i[1:])
ship.do_instruction(code, value)
print(f"Part 1 solution is {ship.get_manhattan_distance()}")
m = ShipWaypointManager()
for i in instructions:
code = i[0]
value = int(i[1:])
m.do_instruction(code, value)
print(f"Part 2 solution is {m.ship.get_manhattan_distance()}")
|
c72412e26ed2f5148fc8520dd1450149c6c11755 | darshanjoshi16/GTU-Python-PDS | /lab5_7.py | 1,053 | 3.953125 | 4 | class point:
def __init__(self,x=0,y=0):
self.x = float(x)
self.y = float(y)
def translate(self,o,p,q):
self.x = self.x + float(o)
self.y = self.y + float(p)
self.z = self.z + float(q)
def __str__(self) :
print("({:.2f},{:.2f},{:.2f})".format(self.x,self.y,self.z))
class point3D(point):
def __init__(self,x,y,z):
super().__init__(x,y)
self.z = float(z)
def translate(self,o,p,q):
point.translate(self,o,p,q)
def __str__(self) :
print("({:.2f},{:.2f},{:.2f})".format(self.x,self.y,self.z))
print("------------------------------------------------------------------")
x=input("Enter a value of x:")
y=input("Enter a value of y:")
z=input("Enter a value of z:")
obj=point3D(x,y,z)
dx=input("Enter a value of dx:")
dy=input("Enter a value of dy:")
dz=input("Enter a value of dz:")
obj.translate(dx,dy,dz)
print("------------------------------------------------------------------")
obj.__str__() |
1d4b3adf25c7eb35afad94a6eafe1c16e8966807 | anantpad/helloworld | /hello world.py | 360 | 4.3125 | 4 | """Type Hello World
x=("hello world")
print(x)"""
"""input("what is your name?")
print("It's nice to meet you")
"""
"""ask the user fortheir name, print the greeting that includes the name"""
"""x=input("What is your Name ?")
print ("welcome "+x)"""
"""print("Rashmi")"""
y=input("What is your name")
x=input("How are you")
print("what is your name "+x)
|
d2feae638719ce8ac4cd51f209cc78ea91a8bb75 | brian-cai/CS4400 | /Old_Copy/jtest.py | 1,446 | 3.5625 | 4 | import sqlite3
import sys
connection = sqlite3.connect("{}.sqlite3".format("josetest"))
cursor = connection.cursor()
cursor.execute("""DROP TABLE IF EXISTS User""")
cursor.execute("""CREATE TABLE User (email varchar(30),username varchar(30) not null, password varchar(30) not null, primary key(email), unique(username))""")
commandlist = [
"""INSERT INTO User values("rohith@testPotato Left Right DOwn", "brohith", "password")""",
"""INSERT INTO User values("victor@test", "braza", "lol")""",
"""INSERT INTO User values("victor@test", "should fail", "123456")""",
"""INSERT INTO User values("jose@test", "braza", "should fail")""",
"""INSERT INTO User values("victor@test", "braza", "should fail")""",
"""INSERT INTO User values("nullcheck@1", null, "should fail")""",
"""INSERT INTO User values("nullcheck@2", "pooplah", null)"""
]
for command in commandlist:
try:
cursor.execute(command)
print("good")
except:
print(sys.exc_info()[0])
# cursor.execute("""INSERT INTO User values("rohith@test", "brohith", "password")""")
# cursor.execute("""INSERT INTO User values("victor@test", "braza", "lol")""")
# cursor.execute("""INSERT INTO User values("victor@test", "should fail", "123456")""")
# cursor.execute("""INSERT INTO User values("jose@test", "braza", "should fail")""")
# cursor.execute("""INSERT INTO User values("victor@test", "braza", "should fail")""")
# cursor.execute("""_""")
connection.commit() |
dbe920acc8f45bdccf8368af47d92dc851d54567 | RohanKD/IDT-SMF-2021 | /SMF_3.py | 1,856 | 3.84375 | 4 | """
Rohan Dalal
20 January 2021
IDT
1st Period
SMF_3
"""
""" Imported libraries are here, I used the random library to generate pseudo random numbers for the random 8 ball statements
Without these libraries I couldn't have done this"""
import os, sys
import cs50
import random
#Pre-processor directivea to maek sure code is compiled right
def main():
# The description of what my program does
print('This is a smart Magic 8 ball, FOr some questions it will give a random answer. But for Some questions such as Will Rohan Get a 100 it will say it is certain.')
# This list contains all the possible predictions of the magic-8 ball.
Predictions = [ 'As I see it, yes.', ' Don’t count on it.', 'It is certain.', ' It is decidedly so', 'Most likely', 'My sources say no.', 'My reply is no.', ' Outlook not so good.', 'Outlook very good', 'Signs point to yes', 'Very Doubtful', 'Without a doubt', 'yes', 'Definitely yes']
# This generates the random number and sets it equal to x, this will come in to play later
x=random.randint(0,13)
# This is where the user is asked to input a question.
Question = input('Ask your question without a question mark, and make sure it starts with a space')
# Here is where The magic 8 ball gives it's predictions, because it is "smart" for certain questions it will always give the same answer
if (Question== ' Will Rohan get a 100 on SMF_3'):
print('It is certain')
elif(Question== ' Is CMDR Schenk a good teacher'):
print('Undoubtedly So')
#here is where the variable x comes into play, if the question is not one of the two listed above,
else:
#it will respond with a randombly selected option from the Predictions list. x is the random number and that number of the list is called
print(Predictions[x])
if(__name__=='__main__'):
main()
|
7fe380db5ce7c5b9c8e145c33dd763e87ed6998b | pccode21/Data-Structures-and-Algorithms | /List/Delete_duplicate_data.py | 1,654 | 3.796875 | 4 | """只能用于数字"""
List = [1, 3, 6, 3, 2, 2, 3, 4, 5, 4, 6, 7]
if List:
List.sort(reverse=True) # 把 List 重新排序,默认是升序
# list.sort( key=None, reverse=False)
# key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
# reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
last = List[-1]
print(last) # 打印结果是列表中的最后一个数7
print(len(List)) # 打印结果是列表的长度12
for i in range(len(List)-2, -1, -1): # 在这里,len(List)-2是指列表中的倒数第二个数,-1是指列表中的第一个数,步长是-1表示列表从后往前扫描
# range(start, stop[, step])
# start: 计数从 start 开始。默认是从 0 开始。
# stop: 计数到 stop 结束,但不包括 stop
# step:步长,默认为1
if last == List[i]: # 判断扫描到的值是否与最后一个值相同
del List[i] # 如果相同,则将该相同值删除
else:
last = List[i] # 如果列表扫描一遍没有与最后的值相同的值,则将倒数第二的值做为最后的值,重新扫描
print(List)
"""如何从Python列表中删除重复项"""
mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
"""
从列表中删除重复项
使用“列表”项作为键来创建字典。这将自动删除所有重复项,因为字典不能具有重复键
然后,将字典转换回列表
"""
|
2256436f5f656022fdb9021d913fd91ef8407b76 | om-henners/advent_of_code | /2019/day8/solution1.py | 883 | 4.125 | 4 | #!/usr/bin/env python
"""
Solution for day 8 part 1
"""
import io
import numpy as np
def make_image(path: str, cols: int, rows: int) -> np.ndarray:
"""
Use simple reshaping to make the array
"""
img = np.loadtxt(path, delimiter=' ', dtype=np.int)
img = img.reshape(-1, rows, cols)
return img
def checksum(img: np.ndarray) -> int:
"""
Find the layer with the minimum number of digits. Multiply the count of 1s on this layer by the number of 2s
"""
min_zeros_layer = np.argmin(np.sum(img == 0, axis=(1, 2)))
counts = np.bincount(img[min_zeros_layer].ravel())
return counts[1] * counts[2]
def main():
"""
Main runner
"""
img = make_image(
io.StringIO(
' '.join(open('input').read().strip())
),
25,
6
)
print(checksum(img))
if __name__ == '__main__':
main()
|
3627648506f3f7f0b6001bf2d00e0db55baffea3 | ViranderSingh/DataTypes | /main.py | 11,570 | 4.375 | 4 | # 1. Fundamental Data Types
# int
# float
# complex
# str
# bool
# list
# dict
# tuple
# set
# 2. Classes -> Custom Types
# 3. Specialized Data Types
# 4. None
# Let's Start
# 1. Fundamental Data Types
# NUMBERS Data Types -> int and float
print(type(3 + 4))
print(type(3 - 4))
print(type(3 * 4))
print(type(3 / 4)) # o.75 This is a Floating Point Number
print(type(0))
print(type(0.00001))
print('---------------------------')
print('NUMBERS -> int and float')
print(2**2) # ** denotes To the Power of
print(2 // 2) # // denotes Divided by and returns an integer type
print(6 % 4) # % denoted Modulus and returns remainder
# Math Functions
print(round(10.98))
print(abs(-20))
# Operator Precedence
print((20 - 3) + 2 ** 2)
# Order of Operators is as follows
# ()
# **
# * /
# + -
print(bin(5))
print(int('0b101', 2))
# STRING Data Type -> str
print('---------------------------')
print('STRING -> str')
print(type("Hi! How are you doing?"))
username = 'supercoder'
password = 'supersecret'
long_string = '''
Wow
O O
---
'''
print(long_string)
first_name = 'Virander'
last_name = 'Singh'
full_name = first_name + ' ' + last_name
print(full_name)
# String Concatenation
print('Virander ' + 'Singh')
# Type Conversion
# print(type(int(str(100))))
a = str(100)
b = int(a)
c = type(b)
print(c)
# Escape Sequence
weather = "\t It\'s \"kind of\" sunny. \n Hope you have a good day."
print(weather)
# Formatted Strings
name = 'Virander'
age = 29
# print('Hi ' + name + '. You are ' + str(age) + ' years old.')
# print('Hi {0}. You are {1} years old.'.format(name, age)) # A Way to do it in Python 2 and 3
print(f'Hi {name}. You are {age} years old.') # Python 3
print('Hello there! My name is %s and my age is %s' %(name, age)) # Hello there Andrei and Sunny --> you can also use %d, %f, %r for integers, floats, string representations of objects respectively
# String Indexes
selfish = '01234567'
# 01234567
# [start:stop:stepover] # String Slicing
print(selfish[0:8:2])
print(selfish[1:])
print(selfish[:5])
print(selfish[::3])
print(selfish[-1])
print(selfish[::-1]) # Reversing a String
# Immutability
# String in Python are Immutable
selfish = '100'
print(selfish) # You can change the value of the whole string but you cannot reassign a part of an indiviual string
# selfish[0] = '8' # This isn't possible in Python and hence strings are immutable
naam = 'Virander Singh'
print(naam[0:len(naam)])
# Python String Methods
quote = 'to be or not to be'
print(quote.upper())
print(quote.capitalize())
print(quote.find('be'))
quote2 = quote.replace('be', 'see', 2)
print(quote2)
print(quote) # String are immutable and hence quote doesnt change. However, a new string quote2 can be created from quote
q = ' I am alone '
print(q.strip()) # Strips all whitespace characters from both ends.
r = 'On an island'
print(r.strip('d')) # Strips all passed characters from both ends.
s = 'but life is good!'
print(s.split()) # ['but', 'life', 'is', 'good!']
t = 'Need to make fire'
print(t.startswith('Need')) # True
u = 'and cook rice'
print(u.endswith('rice')) # True
v= 'bye bye'
print(v.index('e'))
# BOOLEAN Data Type -> bool
print('---------------------------')
print('BOOLEAN -> bool')
Name = 'Virander Singh'
is_cool = False
is_cool = True
print(bool(1))
print(bool('True'))
# all of the below evaluate to False. Everything else will evaluate to True in Python.
print(bool(None))
print(bool(False))
print(bool(0))
print(bool(0.0))
print(bool([]))
print(bool({}))
print(bool(()))
print(bool(''))
print(bool(range(0)))
print(bool(set()))
# Palindrome check
word = 'reviver'
print(word.find(word[::-1])) # 0
p = bool(word.find(word[::-1]) + 1)
print(p) # True
# Facebook Exercise
User_name = 'Virander Singh'
User_age = 29
relationship_status = 'Single'
relationship_status = 'It\'s Complicated'
print(relationship_status)
# Age Exercise
# birth_year = input('What year were you born?\n')
# Age = 2021 - int(birth_year)
# print(f'Your age is {Age}.')
# LIST Data Type -> list
# List is the first Data Structure in Python
print('---------------------------')
print('LIST -> list')
li = [1, 2, 3, 4]
li2 = ['a', 'b', 'c']
li3 = [1, 2, 'a', True]
# Amazon Example
# List Slicing
amazon_cart = [
'notebooks',
'sunglasses',
'toys',
'grapes'
]
print(amazon_cart[0:2])
print(amazon_cart[0::2])
# Lists are Mutable
# Copying Vs Modifying a list
amazon_cart[0] = 'laptop'
new_cart = amazon_cart[:] # Copying a list
# new_cart = amazon_cart # Modifying a list
new_cart[0] = 'gum'
print(new_cart)
print(amazon_cart)
# Matrix -> 2D list
# Matrix is a multi-dimentional list
matrix = [
[1, 5, 1],
[0, 1, 0],
[1, 0, 1]
]
print(matrix[0][1])
# List functions
basket = [1, 2, 3, 4, 5]
print(len(basket))
# List methods
# ADDING
# basket.append(100) # append just modifys a list and doesn't create a new list
# basket.insert(4, 100) # insert just modifys a list and doesn't create a new list
basket.extend([100, 101, 102]) # extend just modifys a list and doesn't create a new list
new_list = basket
print(basket)
print(new_list)
# REMOVING
basket.pop()
basket.pop(0) # pop removes an object at the given index
print(basket)
New_list = basket.pop(3) # pop method returns a value
print(New_list)
New_list1 = basket.remove(101) # remove method doesn't return any value
print(New_list1)
basket.remove(100) # remove removes the specified object
print(basket)
New_list2 = basket.clear() # clear method doesn't return any value
print(New_list2)
basket.clear() # clear removes the all the objects from the list
print(basket)
Basket = ['a', 'x', 'b', 'c', 'd', 'e', 'd']
# print(Basket.index('d', 0, 2)) # yields an error as 'd' is at index 3
print('d' in Basket)
print('i' in 'Hi my name is Virander Singh')
print(Basket.count('d'))
print(sorted(Basket)) # sorted function creates a copy of Basket and doesn't modify it.
print(Basket)
# new_Basket = Basket[:] # This is same as sorted()
# new_Basket.sort()
# print(new_Basket)
# new_Basket = Basket.copy() # This is same as above
# new_Basket.sort()
# print(new_Basket)
# Sorted reverse list
Basket.sort()
reverse_Basket = Basket.reverse()
print(Basket)
# sorted list
Basket.sort()
print(Basket)
print(Basket[::-1])
# Range is ussed for iteration
print(list(range (1, 100)))
print(list(range(101)))
# .join() is a string method that iterates a value in the given list
# sentence = '!'
# new_sentence = sentence.join(['Hi', 'my', 'name', 'is', 'Virander'])
new_sentence = '!'.join(['Hi', 'my', 'name', 'is', 'Virander']) # This is the short hand way of writing the above code
print(new_sentence)
# List Unpacking
a,b,c, *other, d = [1,2,3,4,5,6,7,8,9]
print(a)
print(b)
print(c)
print(other)
print(d)
# NONE Data Type -> None
# None in Python is same as Null in other langauges
# None represents the absence of value
print('---------------------------')
print('NONE -> None')
weapons = None
print(weapons)
# DICTIONARY Data Type -> dict
# Dictionary is the second Data Structure in Python
# A Dictionary is an unordered key-value pair
print('---------------------------')
print('DICTIONARY -> dict')
Dictionary = {
'a': 1,
'b': 2,
'x': 3
}
print(Dictionary['a'])
print(Dictionary)
Dictionary1 = {
'c': [1,2,3],
'd': 'hello',
'e': True
}
print(Dictionary1['c'][1])
My_list = [
{
'c': [1,2,3],
'd': 'hello',
'e': True
},
{
'c': [4,5,6],
'd': 'hello',
'e': True
}
]
print(My_list[0]['c'][2])
# Keys in Dictionary should be Unique can be anything thats Immutable. It cannot be a list as list is mutable
Dictionary2 = {
123: [1,2,3],
True: 'Hello',
'[100]': True # List is mutable and hence cannot be used as a key in a Dictionary
}
print(Dictionary2[123])
# Dictionary Methods
user = {
'basket': [1,2,3],
'greet': 'Hello',
'age': 20
}
# print(user['age']) # This gives an error if age isn't present in the Dictionary.
# So we use .get() method to avoid the error and to check if a key is present in the Dictionary or not
print(user.get('age')) # Gives None as it isn't present in the Dictionary
print(user.get('age', 55)) # This checks if the key 'age' is present in the Dictionary or not. If not, then it creates this key in the dictionary with the given value
# However, if the key already exists, then it returns the value corresponding to it and ignores the override
# Creating a Dictionary usign a built-in function dict
user1 = dict(name= 'Virander')
print(user1)
# To check if a key or value or an item exists in a Dictionary or not using Dictionary Methods
print('size' in user)
print('age' in user.keys())
print('Hello' in user.values())
print(user.items())
user.clear() # Clears the whole dictionary
print(user)
# After creating a copy of a dictionary and then clearing it, the copy of the Dictionary still exists
user2 = user1.copy()
print(user1.clear())
print(user2)
user3 = {
'basket': [1,2,3],
'greet': 'Hello',
'age': 20
}
print(user3.pop('age'))
print(user3)
print(user3.popitem()) # popitem() removes a random item from the dictionary
print(user3)
print(user3.update({'age': 55})) # adds or updates the dictionary with additional key value pair
print(user3)
# TUPLE Data Type -> tuple
# Tuple is the third Data Structure in Python
# A Tuple is an immutable list. you cannot sort or reverse or modify a tuple unlike list. This makes code safe but less flexible
# Tuple is better than List in terms of Performance
print('---------------------------')
print('TUPLE -> tuple')
my_tuple = (1,2,3,4,5,5)
# my_tuple[0] = 'z' # You cannot do this like list as a tuple is immutable
print(my_tuple)
print(my_tuple[0])
print(5 in my_tuple)
user4 = {
(1,2): [1,2,3],
'greet': 'Hello',
'age': 20
}
print(user4.items())
print(user4[(1,2)])
new_tuple = my_tuple[1:4]
print(new_tuple)
x,y,z, *other = (1,2,3,4,5)
print(x)
print(other)
# Tuple has only two methods and they are count() and index()
print(my_tuple.count(5))
print(my_tuple.index(5))
# Built in function in Tuple
print(len(my_tuple))
# SET Data Type -> set
# Set is the fourth Data Structure in Python
# A Set is unordered collections of unique objects
print('---------------------------')
print('SET -> set')
my_set = {1,2,3,4,5,5}
print(my_set)
# print(my_set[0]) # indexes aren't present in sets
print(1 in my_set)
print(len(my_set))
print(list(my_set))
my_set.add(100)
my_set.add(2) # 2 doesn't get added as a set can contain just unique items
print(my_set)
my_list = [1,2,3,4,5,5]
print(set(my_list))
# Methods in Set
new_set = my_set.copy()
my_set.clear()
print(new_set)
print(my_set)
my_set1 = {1,2,3,4,5}
your_set = {4,5,6,7,8,9,10}
# print(my_set1.difference(your_set)) # it finds difference of my_set1 from your_set
# my_set1.discard(5)
# print(my_set1)
# my_set1.difference_update(your_set) # this updates the my_set1 with the difference between my_set1 and your_set
# print(my_set1)
# print(my_set1.intersection(your_set)) # shows the common items between two sets
# print(my_set1 & your_set) # this is same as the above
#print(my_set1.isdisjoint(your_set)) # validates if there are common items in two sets and returns false if there are common items available
#print(my_set1.union(your_set)) # it unites two sets by eliminating the duplicates
# print(my_set1 | your_set) # this is same as the above
# print(my_set1.issubset(your_set)) # it is True if my_set has only 4 and 5 as items in it. As it vaidates if my_set1 is a part of your_set
# print(your_set.issuperset(my_set1)) # it is True if my_set has 4 and 5 as items in it. As it validates if your_set incorporates my_set1 in it
|
262ce4751f306afbc73e7f6eb21b9ecc1a1eb307 | allenlgy/Django-project | /08_面向对象基础/人狗大战.py | 891 | 3.703125 | 4 | class Dog(object):
role = 'dog'
def __init__(self, name, breed, attack):
self.name = name
self.breed = breed
self.attack = attack
self.life = 100
def bite(self,person): # 这里传进来的是一个对象
person.life -= self.attack
print("狗【%s】咬了人[%s]%s血,人还剩[%s]"%(self.name,person.name,self.attack,person.life))
class Person(object):
role = 'person'
def __init__(self, name,sex,attack ):
self.name = name
self.sex = sex
self.attack = attack
self.life = 10
def attack_d(self,dog): # 这里传进来的是一个对象
dog.life -= self.attack
print('人【%s】攻击了【%s】【%s】血,狗还剩【%s】'%(self.name,dog.name,self.attack,dog.life))
d = Dog('旺财','哈士奇',30)
p = Person('小明','男',500)
d.bite(p)
p.attack_d(d) |
97311b43012688109387a932c9eee73441f9325c | oliverdippel/Codewars | /Pathfinder1.py | 2,710 | 3.5625 | 4 | class Node:
def __init__(self, position, symb):
self.position = position
self.symb = symb
self.neighbours = []
class Graph:
def __init__(self, map):
# parsing
m = map.split('\n')
self.rdim = len(m[0])
self.cdim = len(m)
tupler = lambda i: (i // self.rdim, i % self.rdim)
self.nodes = {tupler(i): Node(tupler(i), symb)
for i, symb in enumerate(map.replace('\n', ''))}
for node in [node for node in self.nodes.values() if node.symb != 'W']:
node.neighbours = [pos for pos in self._find_neighbours(node.position)
if self.nodes[pos].symb != 'W']
# [(node.position, node.neighbours) for node in self.nodes.values()]
self.end = (self.rdim - 1, self.cdim - 1)
self.start = (0, 0)
def connect_path(self, start=(0, 0), path=[], end=None):
"""In a backtracking manner find weather or not their is a path beween start and end"""
path = path + [start]
if start == end:
return path
for neighb in sorted(self.nodes[start].neighbours, key= lambda x: x[0], reverse=True):
if neighb not in path:
newpath = self.connect_path(start=neighb, path=path, end=end)
if newpath:
return newpath
return None
def find_path(self):
return self.connect_path(start=self.end, end=self.start)
def _find_neighbours(self, position):
"""returns the set of horizontal an vertical neighbours"""
r, c = position
cond = lambda r, c: 0 <= r < self.rdim and 0 <= c < self.cdim
kernel = [(-1, 0), (0, -1), (0, 1), (1, 0)]
neighb = set((r + i, c + j) for i, j in kernel
if cond(r + i, c + j) and cond(r + i, c + j))
return neighb
def path_finder(map):
"""https://www.codewars.com/kata/5765870e190b1472ec0022a2"""
return bool(Graph(map).find_path())
if __name__ == '__main__':
# TODO : speed up on mostly empty boards - this is the current bottleneck.
# all test caseses work though
a = "\n".join([
".W.",
".W.",
"..."
])
b = "\n".join([
".W.",
".W.",
"W.."
])
c = "\n".join([
"......",
"......",
"......",
"......",
"......",
"......"
])
d = "\n".join([
"......",
"......",
"......",
"......",
".....W",
"....W."
])
assert (path_finder(a) == True)
assert (path_finder(b) == False)
assert (path_finder(c) == True)
assert (path_finder(d) == False)
|
26b24f17bc07c3efdf8e2669db1ee5b3413bf315 | darup67/algorithms_and_data_structures | /python/sort/qsort_variations/quicksort_median.py | 2,474 | 3.828125 | 4 | import math
count = 0
def quicksort(inputList, lo=0, hi=None):
global count
## Default value for hi (not possible to assign in parameter list)
if hi == None:
hi = len(inputList) ## the hi value for range is exclusive
## Base case: if the subarray inputList[lo:hi] is of length 1 or less, return
if hi - lo < 2:
return
## Median-of-three calculation
mid = math.floor(((hi - 1) - lo) / 2) + lo
## print('{} {} {}'.format(inputList[lo], inputList[mid], inputList[hi - 1]))
if inputList[lo] >= inputList[mid] and inputList[lo] <= inputList[hi - 1]:
pivotChoice = lo
elif inputList[lo] >= inputList[hi - 1] and inputList[lo] <= inputList[mid]:
pivotChoice = lo
elif inputList[mid] >= inputList[lo] and inputList[mid] <= inputList[hi - 1]:
pivotChoice = mid
elif inputList[mid] >= inputList[hi - 1] and inputList[mid] <= inputList[lo]:
pivotChoice = mid
else:
pivotChoice = hi - 1
## Choose pivot as pivotChoice, swap with lo
inputList[pivotChoice], inputList[lo] = inputList[lo], inputList[pivotChoice]
## Naive pivot selection (intentional for this example)
pivot, i = lo, lo ## where i is the index of the last value lower than the pivot
## Partition: swap all values lower than pivot into the partition [lo + 1 ... i]
## i gets pre-incremented to simplify the swap
for j in range(lo + 1, hi):
if inputList[j] < inputList[pivot]:
i = i + 1
inputList[j], inputList[i] = inputList[i], inputList[j]
## Swap pivot into ith position
inputList[pivot], inputList[i] = inputList[i], inputList[pivot]
## Increment comparison count
count += hi - lo - 1;
## Recursively sort subarrays to the left and right of pivot (in-place)
quicksort(inputList, lo, i) ## quicksort inputList[lo, i - 1]
quicksort(inputList, i+1, hi) ## quicksort inputList[i + 1, hi]
def get_list_from_file(filename):
newList, result = list(open(filename)), []
for item in newList:
result.append(int(item.rstrip('\n')))
return result
def validate(inputList):
for x in range(0, len(inputList) - 1):
if inputList[x] > inputList[x + 1]:
return False;
return True
testList = get_list_from_file('../data/QuickSort.txt')
quicksort(testList)
print(validate(testList))
print(count)
|
ab4eaaccd8c6a4de89332947d533de8e17774fb7 | inesjoly/toucan-data-sdk-1 | /toucan_data_sdk/utils/postprocess/math.py | 7,319 | 4.3125 | 4 | import operator as _operator
from typing import List
MATH_CHARACTERS = '()+-/*%.'
def _basic_math_operation(df, new_column, column_1, column_2, op):
"""
Basic mathematical operation to apply operator on `column_1` and `column_2`
Both can be either a number or the name of a column of `df`
Will create a new column named `new_column`
"""
if not isinstance(column_1, (str, int, float)):
raise TypeError(f'column_1 must be a string, an integer or a float')
if not isinstance(column_2, (str, int, float)):
raise TypeError(f'column_2 must be a string, an integer or a float')
if isinstance(column_1, str):
column_1 = df[column_1]
if isinstance(column_2, str):
column_2 = df[column_2]
operator = getattr(_operator, op)
df[new_column] = operator(column_1, column_2)
return df
def add(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='add')
def subtract(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='sub')
def multiply(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='mul')
def divide(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='truediv')
def is_float(x):
try:
float(x)
except ValueError:
return False
else:
return True
class Token(str):
"""
A formula is a string like this '"2018 " - 2017 + (a - b)'
In order to parse it, we split it in different tokens and keep track if it was
quoted or not.
E.g. in the formula above, `2017` is a number whereas `"2018"` is a column name.
even though both are strings.
"""
def __new__(cls, text, quoted=False):
string = super().__new__(cls, text.strip())
string.quoted = quoted
return string
def _parse_formula(formula_str) -> List[Token]:
tokens = []
current_word = ''
quote_to_match = None
for x in formula_str:
if x in ('"', "'") and not quote_to_match:
quote_to_match = x
continue
if x == quote_to_match:
tokens.append(Token(current_word, True))
current_word = ''
quote_to_match = None
continue
if quote_to_match or x not in MATH_CHARACTERS:
current_word += x
else:
tokens.append(Token(current_word))
current_word = ''
tokens.append(Token(x))
tokens.append(Token(current_word))
if quote_to_match is not None:
raise FormulaError('Missing closing quote in formula')
return [t for t in tokens if t]
def formula(df, *, new_column: str, formula: str):
"""
Do mathematic operations on columns (add, subtract, multiply or divide)
---
### Parameters
*mandatory:*
- `new_column` (*str*): name of the output column
- `formula` (*str*): Operation on column. Use name of column and special character:
- `+` for addition
- `-` for subtraction
- `*` for multiplication
- `/` for division
**Note:**
- your column name can contain spaces.
- if your column name is a number, you must use a quote mark : `"` or `'` (cf. example)
---
### Examples
**Input**
| variable | valueA | valueB | My rate |
|:--------:|:--------:|:-----:|:------:|
| toto | 20 | 100 | 10 |
| toto | 30 | 200 | 10 |
| toto | 10 | 300 | 10 |
```cson
formula:
new_column: 'valueD'
formula: '(valueB + valueA ) / My rate'
```
**Output**
| variable | valueA | valueB | My rate | valueD |
|:--------:|:--------:|:------:|:-------:|:-------:|
| toto | 20 | 100 | 10 | 12 |
| toto | 30 | 200 | 10 | 23 |
| toto | 10 | 300 | 10 | 31 |
---
**Input**
| variable | 2018 | 2019 |
|:--------:|:--------:|:-----:|
| toto | 20 | 100 |
| toto | 30 | 200 |
| toto | 10 | 300 |
```cson
formula:
new_column: 'Evolution'
formula: "'2019' - '2018'"
```
**Output**
| variable | 2018 | 2019 | Evolution |
|:--------:|:--------:|:-----:|:-----:|
| toto | 20 | 100 | 80 |
| toto | 30 | 200 | 170 |
| toto | 10 | 300 | 290 |
"""
tokens = _parse_formula(formula)
expression_splitted = []
for t in tokens:
# To use a column name with only digits, it has to be quoted!
# Otherwise it is considered as a regular number
if not t.quoted and (t in MATH_CHARACTERS or is_float(t)):
expression_splitted.append(t)
elif t in df.columns:
expression_splitted.append(f'df["{t}"]')
else:
raise FormulaError(f'"{t}" is not a valid column name')
expression = ''.join(expression_splitted)
df[new_column] = eval(expression)
return df
class FormulaError(Exception):
"""Raised when a formula is not valid"""
def round_values(df, *, column: str, decimals: int, new_column: str = None):
"""
Round each value of a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to round
- `decimals` (*int*): number of decimal to keeep
*optional :*
- `new_column` (*str*): name of the new column to create.
By default, no new column will be created and `column` will be replaced
---
### Example
** Input**
ENTITY|VALUE_1|VALUE_2
:-----:|:-----:|:-----:
A|-1.512|-1.504
A|0.432|0.14
```cson
round_values:
column: 'VALUE_1'
decimals:1
new_column: 'Pika'
```
**Output**
ENTITY|VALUE_1|VALUE_2|Pika
:-----:|:-----:|:-----:|:-----:
A|-1.512|-1.504|-1.5
A|0.432|0.14|0.4
"""
new_column = new_column or column
df[new_column] = df[column].round(decimals)
return df
def absolute_values(df, *, column: str, new_column: str = None):
"""
Get the absolute numeric value of each element of a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column
*optional :*
- `new_column` (*str*): name of the column containing the result.
By default, no new column will be created and `column` will be replaced.
---
### Example
**Input**
| ENTITY | VALUE_1 | VALUE_2 |
|:------:|:-------:|:-------:|
| A | -1.512 | -1.504 |
| A | 0.432 | 0.14 |
```cson
absolute_values:
column: 'VALUE_1'
new_column: 'Pika'
```
**Output**
| ENTITY | VALUE_1 | VALUE_2 | Pika |
|:------:|:-------:|:-------:|:-----:|
| A | -1.512 | -1.504 | 1.512 |
| A | 0.432 | 0.14 | 0.432 |
"""
new_column = new_column or column
df[new_column] = abs(df[column])
return df
|
7466f8c6b3d05b1b251bb8cbe883e40ef5b46230 | MitaliSharma12052001/CS142_2020 | /linkedlist.py | 719 | 4.03125 | 4 | class Item:
def __init__(self, val):
self.val = val
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insertAtBegin(self,val):
# Adds an item to front (head) of the linkedlist
newItem = Item(val) # Creates a new BOX
newItem.next = self.head # Points Box to curr head
self.head = newItem # Makes box new head
def display(self):
curr = self.head
while curr != None:
print(str(curr.val)+"->",end = '')
curr = curr.next
print("None")
# Create an object of class linkedlist
ll1 = Linkedlist()
ll1.insertAtBegin(1)
ll1.insertAtBegin(2)
ll1.insertAtBegin(3)
ll1.display() |
127d4fb8434b66e5830690f56bd165bdd960f2c2 | jinnygym/Prepro-Python | /function.py | 283 | 3.640625 | 4 | """function - DAY3"""
import math
math.ceil() # up
math.floor() # down
math.factorial()
math.sin()
math.cos()
math.tan()
math.radians() # Degrees to radians
math.degrees() # Radians to degrees
math.pi() #3.141592653589793
math.sqrt()
import math
def main():
"""function""" |
9197e6c5c5f5593004094773b1a36f781b8eb5fa | schoobydrew/132LAVA | /ImplentationOf GUI With Input/encryptv3.py | 1,002 | 4.09375 | 4 | ############################################
# ASCII encrypter v3
# Uses ASCII values to encrypt a user
# generated password.
############################################
from random import randint
MIN_VALUE = 65
MAX_VALUE = 122
# dictionary for later use
def encrypt(userPass):
newPass = ''
for char in userPass:
# ASCII value of the character
newCharValue = ord(char)
# gives two options 0 and 1
coinFlip = randint(0, 1)
# if coin lands on 0, set to minimum and add a random
# integer to the ASCII of the character
if (coinFlip == 0):
newCharValue = MIN_VALUE + randint(0, MAX_VALUE - MIN_VALUE)
# if coin lands on 1, set to maximum and subtract a random
# integer to the ASCII of the character
else:
newCharValue = MAX_VALUE - randint(0, MAX_VALUE - MIN_VALUE)
# grabs the character value of the ASCII number
# stores it
newChar = chr(newCharValue)
# adds the new character to the encrypted password
newPass += newChar
return newPass
|
daed03a96935178bde84ad4dbeb745d3d197ac41 | Greek-and-Roman-God/Athena | /codingtest/week08/level9_math2/taxicab_geometry.py | 179 | 3.890625 | 4 | # 택시 기하학
# 문과는 문제 이해부터 힘든 문제 흐윽
import math
r=int(input())
area1=round((r**2)*math.pi,6)
area2=round(r*r*2,6)
print(area1)
print(area2) |
20a1e44c1c10dc2d5088d9f17ea83d1acd3a7b6c | purna-manideep/Python | /Trees/depthFirstSearchBinary.py | 881 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from binaryTreeBetter import *
def depth_first_search_binary(root, fcn):
stack = [root]
while len(stack) > 0:
print("at node " + str(stack[0].get_value()))
if fcn(stack[0]):
return True
else:
temp = stack.pop(0)
if temp.get_right_branch():
stack.insert(0, temp.get_right_branch())
if temp.get_left_branch():
stack.insert(0, temp.get_left_branch())
return False
def find6(obj):
return obj.get_value() == 6
def find1(obj):
return obj.get_value() == 1
def find2(obj):
return obj.get_value() == 2
def find3(obj):
return obj.get_value() == 3
def find10(obj):
return obj.get_value() == 10
depth_first_search_binary(n5, find6)
depth_first_search_binary(n5, find2)
depth_first_search_binary(n5, find10) |
7d21b9c0353937e5756444ff11a521dd58563a3b | PeterCHK/hackerrank | /maxwater2.py | 1,004 | 3.59375 | 4 | def maxWater(height,n):
a = []
for i in range(n):
a.append([height[i],range(n)[i]])
b = sorted(a, key=lambda x : x[0])
minIndSoFar = b[n-1][1]
maxIndSoFar = b[n-1][1]
_max = 0
for i in range(n-2,0,-1):
#Current building paired with the building
#greater in height and on the extreme left
left = 0
if minIndSoFar < b[i][1]:
left = b[i][0] * (b[i][1] - minIndSoFar - 1)
#Current building paired with the building
#greater in height and on the extreme right
right = 0
if maxIndSoFar > b[i][1]:
right = b[i][0] * (maxIndSoFar - b[i][1] - 1)
#Maximum so far
_max = max(left, right, _max)
# Update the maximum and minimum so far
minIndSoFar = min(minIndSoFar,b[i][1])
maxIndSoFar = max(maxIndSoFar,b[i][1])
return _max
if __name__ == "__main__" :
height = [ 2, 1, 3, 4, 6, 5 ];
n = len(height);
print(maxWater(height, n));
|
d7291857b8b2f2d79c8285e175eb2c4e1df148cc | iam-amitkumar/BridgeLabz | /DataStructureProgram/Test.py | 2,968 | 4.21875 | 4 | """This program takes the month and year as user-input
and prints the Calendar of the month. Store the Calendar
in an 2D Array, the first dimension the week of the month
and the second dimension stores the day of the week.
@author Amit Kumar
@version 1.0
@since 09/01/2019
"""
# function to check whether the entered year is a leap year or not
def isleap_year(year2):
if (year2 % 400 == 0) or ((year2 % 4 == 0) and (year2 % 100 != 0)): # checks whether the year is a century
# year or not
return True
return False
def calender(month, year):
day = ['Sun', ' Mon', ' Tue', ' Wed', ' Thu', 'Fri', ' Sat'] # Stores the Month in a list
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # since the index of list starts from 0 and month
# is 1
values = 1
d = 1
m = month
y = year
# determining the day of the first date of any month so we can determine from which day we have to start printing
# the calender, final output of the set of these formulae is 0-6, i.e., Sun - Sat
y0 = y - (14 - m) // 12
x = y0 + y0 // 4 - y0 // 100 + y0 // 400
m0 = m + 12 * ((14 - m) // 12) - 2
d0 = (d + x + 31 * m0 // 12) % 7
print(d0)
if isleap_year(year): # checks if the month entered is February leap year or not
days[month] = 29 # if yes sets the no. of days in February as 29
days[1] = 29
row = 6
column = 7
two_d_array = [[0 for j in range(column)] for i in range(row)] # create empty 2d array
print('Your Calender is\n')
for i in range(0, 6 + 1):
print(day[i], end=' ') # print day's for calender
print()
for i in range(row):
for j in range(column):
if values <= days[m - 1]:
if i == 0 and j < d0: # while d0 is less than j
two_d_array[i][j] = ' ' # it will print blank space
continue
two_d_array[i][j] = values # add days into calender
values += 1 # increment counter
for i in range(row):
for j in range(column):
if two_d_array[i][j] != 0:
x = two_d_array[i][j] # ljust() method returns the string
x1 = str(x).ljust(4) # left justified in a string of length width.
print(x1, end=" ")
print()
print()
###################################################################################################################
def calender_queue_runner():
"""
This method act as runner for calender_queue(month, year) method
:return:This method won't return anything
"""
global month, year
try:
month = int(input('Enter Month:'))
except Exception as e:
print(e)
print("Enter integer only ")
try:
year = int(input('Enter year:'))
except Exception as e:
print(e)
print("Enter integer only")
calender(month, year)
calender_queue_runner()
|
3f2f5bc98eae7aab2700ad4d1c538b16a509c35c | Zelenskiy/informatics_10_prof | /Урок 29, 30. Функції/Функція з параметрами.py | 162 | 3.671875 | 4 | def avg(x):
sum_values = sum(x)
count_values = len(x)
return sum_values / count_values
x1 = [2, 3, 4]
x2 = (2, 3, 4)
print(avg(x1))
print(avg(x2))
|
88879e46f6b01992787566298b60821a3af45e27 | kentxun/PythonBase | /splitSearch/findPos.py | 901 | 3.84375 | 4 | '''
有一个有序数组arr,其中不含有重复元素,请找到满足arr[i]==i条件的最左的位置。
如果所有位置上的数都不满足条件,返回-1。
给定有序数组arr及它的大小n,请返回所求值。
测试样例:
[-1,0,2,3],4
返回:2
'''
# -*- coding:utf-8 -*-
class Find:
def findPos(self, arr, n):
# write code here
# 如果 头 小于 尾,则是逆序,
if arr[0] > n-1 or arr[n-1] < 0:
return -1
left = 0
right = n-1
res = -1
while left <= right:
mid = left + int((right-left)/2)
# 0-mid从左到右 严格递增1 ,数值最小是1
if arr[mid] > mid:
right = mid -1
elif arr[mid] < mid:
left = mid + 1
else:
res = mid
right = mid -1
return res
|
48f9690797784aae42d1d8941f9e6bebb57d2233 | cybernuki/holbertonschool-higher_level_programming | /0x0B-python-input_output/12-student.py | 764 | 3.9375 | 4 | #!/usr/bin/python3
"""This module Defines a Student class"""
class Student():
"""Class that represents a student"""
def __init__(self, first_name, last_name, age):
"""Constructor method"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""Returns a dictionary representation of a
student instance.
If attrs is a list of string, only attributes names
contained in this list are retrieved.
Otherwise, all attributes are retrieved.
"""
if type(attrs) is list and all(type(val) == str for val in attrs):
return {k: getattr(self, k) for k in attrs if hasattr(self, k)}
return self.__dict__
|
67da17f9b9f6a119243821358b753c1fd7868688 | rzhadev/PCsolutions | /projecteuler/projecteuler9.py | 158 | 3.671875 | 4 | def special_triplet(n):
for a in range(3,n):
for b in range(4,n):
c = n - a - b
if c**2 == a**2 + b**2:
return a*b*c
print(special_triplet(1000)) |
94d6639dd29219c37bf1fb8b5d87317da1c33a8a | 5l1v3r1/python-advance | /Thread communication queue in python.py | 1,750 | 4.34375 | 4 | #The queue class of queue module is useful to create a queue that holds the data produced by the producer.
#the data can be taken from the queue and utilized by the consumer.
#we need not use locks since queues are thread safe.
#creating queue object:
# from queue import Queue
# q=Queue()
#Queue mthods:
#1. put() - this method is used by producer to insert item into the queue.
#syntax : queue_object.put(item)
# eg: q.put(i)
#2. get() - This method is used by consumer to retrieve items from the queue.
#syntax:- producer_object.queuue_object.get(item)
# eg:- p.q.get(i)
#3. empty() - This mehtod returns True if queue is Empty else returns False.
#eg: q.empty()
#4. full() - This method returns True if queue is full else returns False.
from threading import Thread
from queue import Queue
from time import sleep
class Producer:
def __init__(self):
self.q=Queue()
def produce(self):
for i in range(1,6):
print("Item produced...",i)
self.q.put(i)
sleep(1)
class consumer:
def __init__(self,prod):
self.prod=prod
def consume(self):
for i in range(1,6):
print("Item recived",self.prod.q.get(i))
p=Producer()
c=consumer(p)
t1=Thread(target=p.produce)
t2=Thread(target=c.consume)
t1.start()
t2.start()
# from threading import Thread
# from queue import Queue
# from time import sleep
# q=Queue()
# def test1():
# for i in range(1,5):
# print("hello friend... ",i)
# q.put(i)
# sleep(1)
# def test2():
# for i in range(1,5):
# print("bye friend....",q.get())
# t1=Thread(target=test1)
# t2=Thread(target=test2)
# t1.start()
# t2.start()
|
308ff933752c75c0c43963a6b058010386285189 | thejaredchapman/JMC_Python | /GeneratorsExample.py | 629 | 4 | 4 | ## GENERATOR EXAMPLES
## Generate numbers from square
def gensquare(N):
for i in range (N):
yield i**2
for x in gensquares(10):
print(x)
## Generate numbers from range
import random
random.randint(1,10)
## Generate lowest and highest numbers in range
def rand-num(low, high, n):
for i in range(n):
yield random.randint(low,high)
for num in rand_num(1,10,25)
print(num)
## User iter() string to convert to an iterator
s = 'Gametime'
s = iter(s)
print(next(s))
## Print everything from item in list
my_list = [1,2,3,4,5]
gencomp = (item for item in my_list if item > 3)
for item in gencomp:
print(item)
|
de79a6536a7ec1eefa64acc907361a338e707f42 | AbhishekDoshi26/python-programs | /Panda/math.py | 395 | 3.78125 | 4 | import pandas as pd
y = pd.read_csv('data.csv', squeeze=True, usecols=['Y-Axis'])
print(y.count()) # Counts number of rows
print(len(y)) # Counts number of rows
print(y.sum()) # Adds all data
print(y.mean()) # Calculates Average
print(y.std()) # Calculates Standard Deviation
print(y.min()) # Prints minimum value
print(y.max()) # Prints maximum value
print(y.median()) # Prints Median
|
0bf9333d263de5079e1b6ca6de9e163c756f6f91 | pdemeulenaer/spark-training | /spark-exercises/spark-ex-aggregations.py | 14,819 | 3.84375 | 4 | # Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC ### Aggregations: GroupBy
# COMMAND ----------
# You have such a df.
df = spark.createDataFrame([("1991-11-15",'a',23),
("1991-11-16",'a',24),
("1991-11-17",'a',32),
("1991-11-25",'b',13),
("1991-11-26",'b',14)], schema=['date', 'customer', 'balance_day'])
# Produce a groupby operation which allows to collect the dates and the values in 2 columns, time_series_dates and time_series_values. During the aggregation, build also a 3rd column which is made of both date and value, like tuples. Show the result without truncating it.
# Expected:
# +--------+------------------------------------+------------------+------------------------------------------------------+
# |customer|time_series_dates |time_series_values|time_series_tuples |
# +--------+------------------------------------+------------------+------------------------------------------------------+
# |a |[1991-11-15, 1991-11-16, 1991-11-17]|[23, 24, 32] |[[1991-11-15, 23], [1991-11-16, 24], [1991-11-17, 32]]|
# |b |[1991-11-25, 1991-11-26] |[13, 14] |[[1991-11-25, 13], [1991-11-26, 14]] |
# +--------+------------------------------------+------------------+------------------------------------------------------+
# Answer
df = df.groupby("customer").agg(F.collect_list('date').alias('time_series_dates'),
F.collect_list('balance_day').alias('time_series_values'),
F.collect_list(F.struct('date','balance_day')).alias('time_series_tuples'))
df.show(truncate=False)
# COMMAND ----------
# MAGIC %md-sandbox
# MAGIC
# MAGIC ### Aggregations: Window functions
# COMMAND ----------
# Import the Window class and the sql functions
from pyspark.sql import Window
import pyspark.sql.functions as F
# COMMAND ----------
# With such a dataframe
df = spark.createDataFrame([(1, 4), (2, 5), (2, 8), (3, 6), (3, 2)], ["A", "B"])
# Group by A and build the average of B, min of B, max of B
# Expected:
# +---+------+------+------+
# | A|avg(B)|min(B)|max(B)|
# +---+------+------+------+
# | 1| 4.0| 4| 4|
# | 2| 6.5| 5| 8|
# | 3| 4.0| 2| 6|
# +---+------+------+------+
# Answer
df.groupBy("A").agg(F.avg("B"), F.min("B"), F.max("B")).show()
# COMMAND ----------
# Using same df as above, group by column A and get the distinct number of rows in column B for each group, called "countB". Then order by that quantity, descending
# Expected:
# +---+------+
# | A|countB|
# +---+------+
# | 2| 2|
# | 3| 2|
# | 1| 1|
# +---+------+
# Answer
df.groupBy('A').agg(F.countDistinct('B').alias('countB')).orderBy('countB',ascending=False).show()
# COMMAND ----------
# now same, but using the approxmative distinct count function instead of the deterministic distinct count function distinctCount
# Expected
# +---+------+
# | A|countB|
# +---+------+
# | 3| 2|
# | 2| 2|
# | 1| 1|
# +---+------+
# Answer
df.groupBy('A').agg(F.approx_count_distinct('B').alias('countB')).orderBy('countB',ascending=False).show()
# COMMAND ----------
# group by A and get the first, last, and sum of colunm B. Rename these columns as "my first", "my last", "my everything"
# Expected:
# +---+--------+-------+-------------+
# | A|my first|my last|my everything|
# +---+--------+-------+-------------+
# | 1| 4| 4| 4|
# | 2| 5| 8| 13|
# | 3| 6| 2| 8|
# +---+--------+-------+-------------+
# Answer
df.groupBy("A").agg(
F.first("B").alias("my first"),
F.last("B").alias("my last"),
F.sum("B").alias("my everything")
).show()
# COMMAND ----------
# from following dataframe, group by A and for each group, give the list of distinct elements
df = spark.createDataFrame([(1, 4), (2, 5), (2, 8), (2, 8), (2, 9), (3, 6), (3, 2)], ["A", "B"])
# Expected:
# +---+---------+
# | A| B|
# +---+---------+
# | 1| [4]|
# | 2|[9, 5, 8]|
# | 3| [2, 6]|
# +---+---------+
# Answer
df.groupBy("A").agg(F.collect_set("B").alias("B")).show()
# COMMAND ----------
# You have the following dataframe.
dfSales= spark.createDataFrame([
['TV',200],
['Headphones',400],
['Phones',300],
['Kitchen',500],
['Office',300]],('itemName','sales_quantity'))
# Create a new column salesDenseRank which is the dense_rank over the sales_quantity (use window function)
# Expected
# +----------+--------------+--------------+
# | itemName|sales_quantity|salesDenseRank|
# +----------+--------------+--------------+
# | TV| 200| 1|
# | Phones| 300| 2|
# | Office| 300| 2|
# |Headphones| 400| 3|
# | Kitchen| 500| 4|
# +----------+--------------+--------------+
# Answer
from pyspark.sql import Window
from pyspark.sql.functions import dense_rank,col
windowSpec = Window.orderBy("sales_quantity")
dfSales.select(
col("itemName"),
col("sales_quantity"),
dense_rank().over(windowSpec).alias("salesDenseRank")
).show()
# COMMAND ----------
# You have such a dataframe
tup = [(1, "a"), (1, "a"), (1, "b"), (2, "a"), (2, "b"), (3, "b")]
df = spark.createDataFrame(tup, ["id", "category"])
df.show()
# Using a window function so that, for each category, ordering each category by the id, compute the sum of each row with the following one.
# Given:
# +---+--------+
# | id|category|
# +---+--------+
# | 1| a|
# | 1| a|
# | 1| b|
# | 2| a|
# | 2| b|
# | 3| b|
# +---+--------+
# Expected:
# +---+--------+---+
# | id|category|sum|
# +---+--------+---+
# | 1| a| 2|
# | 1| a| 3|
# | 1| b| 3|
# | 2| a| 2|
# | 2| b| 5|
# | 3| b| 3|
# +---+--------+---+
# Answer
window = Window.partitionBy("category").orderBy("id").rowsBetween(Window.currentRow, 1)
df.withColumn("sum", F.sum("id").over(window)).sort("id", "category", "sum").show()
# COMMAND ----------
# With this dataframe:
df = spark.createDataFrame([(1, 4), (2, 5), (2, 8), (3, 6), (3, 2)], ["A", "B"])
# Using a window function, for each group within A column, ordered by B, compute the difference of each row of column B with previous row of same column
# Expected:
# +---+---+----+
# | A| B|diff|
# +---+---+----+
# | 1| 4|null|
# | 2| 5| 3|
# | 2| 8|null|
# | 3| 2| 4|
# | 3| 6|null|
# +---+---+----+
# Answer
from pyspark.sql.window import Window
window_over_A = Window.partitionBy("A").orderBy("B")
df.withColumn("diff", F.lead("B").over(window_over_A) - df.B).show()
# COMMAND ----------
# In the following df, produce a column count which counts the number of items in each group of x column. Order the final result by both column
data = [('a', 5), ('a', 8), ('a', 7), ('b', 1),]
df = spark.createDataFrame(data, ["x", "y"])
# Expected:
# +---+---+-----+
# | x| y|count|
# +---+---+-----+
# | a| 5| 3|
# | a| 7| 3|
# | a| 8| 3|
# | b| 1| 1|
# +---+---+-----+
# Answer
w = Window.partitionBy('x')
df.select('x', 'y', F.count('x').over(w).alias('count')).sort('x', 'y').show()
# COMMAND ----------
# Register the dataframe in a temporary view and perform the same operation in pure SQL (using spark.sql)
# Answer
df.createOrReplaceTempView('table')
spark.sql(
'SELECT x, y, COUNT(x) OVER (PARTITION BY x) AS n FROM table ORDER BY x, y'
).show()
# COMMAND ----------
# You have this df. Groupby Product and pivot by Country, and sum by Amount
data = [("Banana",1000,"USA"), ("Carrots",1500,"USA"), ("Beans",1600,"USA"), \
("Orange",2000,"USA"),("Orange",2000,"USA"),("Banana",400,"China"), \
("Carrots",1200,"China"),("Beans",1500,"China"),("Orange",4000,"China"), \
("Banana",2000,"Canada"),("Carrots",2000,"Canada"),("Beans",2000,"Mexico")]
columns= ["Product","Amount","Country"]
df = spark.createDataFrame(data = data, schema = columns)
# Given:
# +-------+------+-------+
# |Product|Amount|Country|
# +-------+------+-------+
# |Banana |1000 |USA |
# |Carrots|1500 |USA |
# |Beans |1600 |USA |
# |Orange |2000 |USA |
# |Orange |2000 |USA |
# |Banana |400 |China |
# |Carrots|1200 |China |
# |Beans |1500 |China |
# |Orange |4000 |China |
# |Banana |2000 |Canada |
# |Carrots|2000 |Canada |
# |Beans |2000 |Mexico |
# +-------+------+-------+
# Expected:
# +-------+------+-----+------+----+
# |Product|Canada|China|Mexico|USA |
# +-------+------+-----+------+----+
# |Orange |null |4000 |null |4000|
# |Beans |null |1500 |2000 |1600|
# |Banana |2000 |400 |null |1000|
# |Carrots|2000 |1200 |null |1500|
# +-------+------+-----+------+----+
# Answer
pivotDF = df.groupBy("Product").pivot("Country").sum("Amount")
pivotDF.show(truncate=False)
# COMMAND ----------
# Do the same as above, but forcing the order of the columns to "USA","China","Canada","Mexico"
# Expected:
# +-------+----+-----+------+------+
# |Product|USA |China|Canada|Mexico|
# +-------+----+-----+------+------+
# |Orange |4000|4000 |null |null |
# |Beans |1600|1500 |null |2000 |
# |Banana |1000|400 |2000 |null |
# |Carrots|1500|1200 |2000 |null |
# +-------+----+-----+------+------+
countries = ["USA","China","Canada","Mexico"]
pivotDF = df.groupBy("Product").pivot("Country", countries).sum("Amount")
pivotDF.show(truncate=False)
# COMMAND ----------
# Unpivot for Canada, China and Mexico
# Expected:
# +-------+------+-------+
# |Product|Amount|Country|
# +-------+------+-------+
# |Orange |4000 |China |
# |Beans |1500 |China |
# |Beans |2000 |Mexico |
# |Banana |2000 |Canada |
# |Banana |400 |China |
# |Carrots|2000 |Canada |
# |Carrots|1200 |China |
# +-------+------+-------+
# Answer
from pyspark.sql.functions import expr
unpivotExpr = "stack(3, 'Canada', Canada, 'China', China, 'Mexico', Mexico) as (Country,Amount)"
unPivotDF = pivotDF.select("Product", expr(unpivotExpr)) \
.where("Amount is not null").select("Product","Amount","Country")
unPivotDF.show(truncate=False)
# COMMAND ----------
# Using a window function, get the ntile of the groups on id: for each id group, give the ntile(2) (category is not important column here)
from pyspark.sql import Window
tup = [(1, "a"), (1, "a"), (2, "a"), (1, "b"), (2, "b"), (3, "b"), (3, "c"), (3, "d"), (3, "e")]
df = spark.createDataFrame(tup, ["id", "category"])
# Expected:
# +---+--------+-----+
# | id|category|ntile|
# +---+--------+-----+
# | 1| a| 1|
# | 1| a| 1|
# | 1| b| 2|
# | 2| a| 1|
# | 2| b| 2|
# | 3| b| 1|
# | 3| c| 1|
# | 3| d| 2|
# | 3| e| 2|
# +---+--------+-----+
# Answer
window = Window.partitionBy("id").orderBy("id")
df.withColumn("ntile", F.ntile(2).over(window)).sort("id", "category").show()
# COMMAND ----------
# CUBE, ROLLUP functions
# COMMAND ----------
# You have such a dataframe, build the cube function with count aggregation on both columns:
data=[("item1",2),("item2",5),("item3",20),("item2",20),("item1",10),("item1",5)]
df=spark.createDataFrame(data,["Item_Name","Quantity"])
# Expected
# +---------+--------+-----+
# |Item_Name|Quantity|count|
# +---------+--------+-----+
# | null| null| 6|
# | null| 2| 1|
# | null| 5| 2|
# | null| 10| 1|
# | null| 20| 2|
# | item1| null| 3|
# | item1| 2| 1|
# | item1| 5| 1|
# | item1| 10| 1|
# | item2| null| 2|
# | item2| 5| 1|
# | item2| 20| 1|
# | item3| null| 1|
# | item3| 20| 1|
# +---------+--------+-----+
# Answer
#COUNT FUNCTION
df.cube(df["Item_Name"],df["Quantity"]).count().sort("Item_Name","Quantity").show()
# COMMAND ----------
# You have such a dataframe, build the sum function with count aggregation on both columns:
data=[("item1",2),("item2",5),("item3",20),("item2",20),("item1",10),("item1",5)]
df=spark.createDataFrame(data,["Item_Name","Quantity"])
# Expected
# +---------+--------+-------------+
# |Item_Name|Quantity|sum(Quantity)|
# +---------+--------+-------------+
# | null| null| 62|
# | null| 2| 2|
# | null| 5| 10|
# | null| 10| 10|
# | null| 20| 40|
# | item1| null| 17|
# | item1| 2| 2|
# | item1| 5| 5|
# | item1| 10| 10|
# | item2| null| 25|
# | item2| 5| 5|
# | item2| 20| 20|
# | item3| null| 20|
# | item3| 20| 20|
# +---------+--------+-------------+
# Answer
df.cube(df["Item_Name"],df["Quantity"]).sum().sort("Item_Name","Quantity").show()
# COMMAND ----------
# build the rollup + count of the same dataframe:
# Expected
# +---------+--------+-----+
# |Item_Name|Quantity|count|
# +---------+--------+-----+
# | null| null| 6|
# | item1| null| 3|
# | item1| 2| 1|
# | item1| 5| 1|
# | item1| 10| 1|
# | item2| null| 2|
# | item2| 5| 1|
# | item2| 20| 1|
# | item3| null| 1|
# | item3| 20| 1|
# +---------+--------+-----+
# Answer
df.rollup("Item_Name","Quantity").count().sort("Item_Name","Quantity").show()
# COMMAND ----------
# You have this dataframe. Produce the rollup of it according to the age. Give the grouping column g of the name, and the sum of the age. Order by the name
df = spark.createDataFrame([("Alice", 2), ("Bob", 5)], ["name", "age"])
# Expected:
# +-----+----+---+---+
# | name| age| g|age|
# +-----+----+---+---+
# | null|null| 1| 7|
# |Alice|null| 1| 2|
# |Alice| 2| 0| 2|
# | Bob| 5| 0| 5|
# | Bob|null| 1| 5|
# +-----+----+---+---+
# Answer
df.rollup("name", "age").agg(F.grouping("age").alias("g"), F.sum("age").alias("age")).orderBy("name").show()
# COMMAND ----------
# Build the cube function of the same dataframe as above, and produce the grouping of the name column, and the sum over age column. Sort by name
# Expected:
# +-----+--------------+--------+
# | name|grouping(name)|sum(age)|
# +-----+--------------+--------+
# | null| 1| 7|
# |Alice| 0| 2|
# | Bob| 0| 5|
# +-----+--------------+--------+
# Answer
df.cube("name").agg(F.grouping("name"), F.sum("age")).orderBy("name").show()
# COMMAND ----------
|
6d757b0b4d5de60e3d772546beb73fe090b92881 | Aasthaengg/IBMdataset | /Python_codes/p00001/s050837870.py | 90 | 3.609375 | 4 | s = [int(input()) for i in range(10)]
s.sort(reverse = True)
for i in s[:3]:
print(i)
|
2c0780bacbc416d53cb21701cf00fc67471c8afe | Salihbayraktar/Patika-Python | /CodeWars/4-Kyu/SumByFactors.py | 1,887 | 3.71875 | 4 | def find_and_sum_prime_numbers(n, resultDict):
rawN = n
n = abs(n)
i = 2
primeSet = set()
while i * i <= n:
if n % i:
i += 1
else:
n //= i
if i not in resultDict:
resultDict[i] = rawN
elif i not in primeSet:
resultDict[i] += rawN
primeSet.add(i)
if n > 1:
if n not in resultDict:
resultDict[n] = rawN
primeSet.add(n)
elif n not in primeSet:
resultDict[n] += rawN
return resultDict
def sum_for_list(lst):
resultDict = {}
for i in lst:
resultDict = find_and_sum_prime_numbers(i, resultDict)
resultList = sorted(resultDict.items(), key=lambda x: x[0]) # Engin hocaya sonucu tuple değil de list olarak elde edip edemeyeceğimizi sor
print(resultList)
resultList2 = sorted([k,v] for k,v in resultDict.items())
print(resultList2)
for i in range(len(resultList)):
resultList[i] = list(resultList[i]) #
print(resultList)
return resultList
list2 = [902357, -968097, -627144, -652087, -429945, 11194, -494131, -506621, -738142, -630425, 808045, -70747, -50136, -441806, -334532]
#list2 = [12, 15]
sum_for_list(list2)
"""
primeNumbers = set()
for i in range(3, maxNumber + 1, 2):
isPrime = True
for j in range(3, i, 2):
if i % j == 0:
isPrime = False
break
if isPrime:
primeNumbers.add(i)
print(i)
return primeNumbers
"""
"""
def sum_for_list(lst):
primeNumbers = find_prime_numbers(964644)
print(primeNumbers)
# primeNumbers = find_prime_numbers(abs(lst[len(lst)-1]))
# primeNumbers = find_prime_numbers(409007)
# print(primeNumbers)
primeDict = {}
sum_for_list([9984194949455489949])
"""
|
4f522dc2fe41a5c71b37d840c7a1309b6d1127c0 | kimjeonghyon/Algorithms | /Python/LG편의점.py | 1,257 | 3.515625 | 4 | # 물품 코드
# 커피 coffee 우유 milk 즉석밥 rice 물 water 휴지 paper 라면 ramen
codes = {'coffee':'커피','milk':'우유','rice':'즉석밥','water':'물', 'paper':'휴지','ramen':'라면'}
records = ['coeeff','COF%#@$eef','mi kl','ter%$^wa','MKIL','Mk%@#l$%i','water','WATER']
# 3-1 위의 판매 기록에서 특수문자 빈칸을 제거하고 소문자로 변경하여 출력하라.
# coeeff, cofeef, mikl, terwa, mkil, mkli, water, water
import re
listItem = []
for before_str in records:
after_str = re.sub("[%|#|@|$|^|' ']", "", before_str)
listItem.append(after_str.lower())
print ("============Answer 3-1=============")
print (','.join(listItem))
print()
# 3-2 각 판매기록의 정확한 물품코드를 출력하라
# coffee, coffee, milk, water, milk, milk, water, water
codesSorted = {}
for key in codes.keys():
codesSorted[''.join(sorted(key))]=key
print ("============Answer 3-2=============")
listItem2 = []
for item in listItem:
listItem2.append(codesSorted[''.join(sorted(item))])
print(','.join(listItem2))
# 3-3 이 날에 판매된 물품을 출력하라
# coffee, milk, water
saled = set(listItem2)
print ("============Answer 3-3=============")
print (','.join(sorted(list(saled))))
|
6821af9f43f71bbe28a105c7cc01379e16ff72fa | kthure01/DevOps20 | /Python/exercises0/string-length/string_length.py | 222 | 3.78125 | 4 | def get_length(name):
return len(name)
length = get_length("Guido van Rossum")
print(length, "(Guido är skaparen av Python)" )
# The correct answer here should be `16`
# Gain some extra score by answering who "Guido van Rossum" is ;)
|
5e6e4499ba4a177e74d5df6dd493630078fb5638 | foleymd/boring-stuff | /debugging/raise_assert.py | 1,380 | 4.1875 | 4 | # the raise and assert statements
import traceback, os
# print a box
def box_print(symbol, width, height):
if len(symbol) != 1:
raise Exception('The input symbol must be a single-character string.')
if (width < 2) or (height < 2) :
raise Exception('Box width and height must be greater than or equal to 2.')
print(symbol * width) #top line
for i in range (height - 2):
print(symbol + (' ' * (width -2)) + symbol) #outer edge + inner space + outer edge
print(symbol * width) #bottom line
print('Printing boxes: \n')
box_print('$', 10, 9)
box_print('#', 15, 4)
print('\nExceptions : \n')
# box_print('!!', 15, 4) # raises single-character exception
# box_print('G', 1, 4) # raises width/height exceptions
# raise Exception('This is the error message.')
try:
raise Exception('This is the error message.')
except:
error_file = open('error_log.txt', 'a')
error_file.write(traceback.format_exc())
error_file.close()
print('The traceback info was written to error_log.txt')
# assertions are checks to make sure nothing weird is happening
# if asserts fail, programs should crash - they help you find problems sooner rather than later
# assertions are for programmer errors and not non-fatal errors
print('\nAssertions: \n')
assert False, 'This is the error message.'
|
e7d2de023d38529bece8d7e4dface47796345c93 | chenyi229/Data-Structure | /chenyi_07_选择排序.py | 246 | 4.03125 | 4 | def selectSort(list):
for i in range(0,len(list)):
for j in range(i+1,len(list)):
if list[i]>list[j]:
list[i], list[j] = list[j], list[i]
print(list)
list=[0,12,2,1,5,1]
selectSort(list) |
b85e38178e74d80b2e59503ff90782f680a26c52 | OBigVee/Toy-projects | /pig Latin/pigLatin.py | 1,358 | 4.25 | 4 | """
this program encodes English-language phrases into pig Latin.
Pig Latin is a form of coded language. There are many different ways to form pig Latin phrases.
this application used the following algorithm:
Tokenize the phrase into words.
To translate each English word into a pig Latin word, place the first
letter of the English word at the end of the word and add the letters “ay.” Thus, the word “jump”
becomes “umpjay,” the word “the” becomes “hetay,” and the word “computer” becomes “omputercay.”
Blanks between words remain as blanks.
Method printLatinWord display each word. Each token is passed to method printLatinWord
to print the pig Latin word.
"""
class PigLatin:
def __init__(self,):
userInput = input("enter phrase here and press enter\n::")
self.phrase = userInput
self.pigLatin = [ ]
self.splitPhrase = self.phrase.split()
def printPigLatin(self):
for eachPhrase in self.splitPhrase:
raw = " "
char_1 = eachPhrase[0]
#[i for i in range(len(eachPhrase)) pass if i== 0 else raw+=eachPhrase[i]]
for i in range(len(eachPhrase)):
if (i ==0) :
pass
else:
raw+=eachPhrase[i]
# pass
# else:
# raw += eachPhrase[i]
self.pigLatin.append(raw+char_1+"ay")
print(self.pigLatin)
return self.pigLatin
pigLatin = PigLatin()
pigLatin.printPigLatin()
|
339a1d48a6489132f726e87dbf39c6486e945448 | sushrut91/ComputerSecurity-Project1 | /Q2-GCD.py | 1,027 | 4.03125 | 4 | #!/usr/bin/python3
from _ctypes import FormatError
def main():
try:
n1 = int(input('Enter an integer: '))
n2 = int(input('Enter an integer: '))
if n1 == 0 or n2 == 0:
print('Enter n1 and n2 both should be greater than 0')
return -1 # Return error
else:
gcd = GCD(n1,n2)
print('\nThe G.C.D of {} and {} is {}'.format(n1, n2, gcd))
return 0
except ValueError:
print('You entered a non integer value. Please try again.')
#Function which returns GCD of both values
def GCD(n1,n2):
# Convert negative values to positive values
if n1 < 0:
n1 = -n1
if n2 < 0:
n2 = -n2
#Ensure that n2 is always greater
if n2 > n1:
temp = n1
n1 = n2
n2 = temp
r=1
#Euclid's algorithm
while r > 0:
r = n1 % n2
if r == 0:
return n2
n1 = n2
n2 = r
if __name__ =='__main__': main() |
880916cf018bf7ae2d23fd09ce23c803ca07b6fb | sgnajar/Wikipedia-web-crawl | /webCrawler.py | 2,349 | 3.59375 | 4 | # By: Sasan Najar
# Email: sasangnajar@gmail.com
# This code is to:
## STEP1: Go to a random Wikipedia page and click the fisrt link
## STEP2: Then on that page click the first link in the main body of the article text
import requests
import time
import urllib
import bs4
startURL = "https://en.wikipedia.org/wiki/Special:Random"
targetURL = "https://en.wikipedia.org/wiki/Philosophy"
def getFirstLink(url):
response = requests.get(url)
html = response.text
soup = bs4.BeautifulSoup(html, 'html.parser') # make soup obj of html
contentdiv = soup.find(id='mw-content-text').find(class_="mw-parser-output") #first link
#if the article contains no links this value will remain None
articleLink = None
# find all the direct children of contentdiv that are paragraghs
for element in contentdiv.find_all("p", recursive=False):
if element.find("a", recursive=False):
articleLink = element.find("a", recursive=False).get('href')
break
if not articleLink:
return
# Build a full url from the relative articleLink url
firstLink = urllib.parse.urljoin('https://en.wikipedia.org/', articleLink)
return firstLink
#continueCrawl function
#continueCrawl should return True or False following these rules:
#if the most recent article in the searchHistory is the target article the search should stop and the function should return False
#If the list is more than 25 urls long, the function should return False
#If the list has a cycle in it, the function should return False
#otherwise the search should continue and the function should return True.
def continueCrawl(searchHistory, targetURL, maxSteps=25):
if searchHistory[-1] == targetURL:
print("target article found")
return False
elif len(searchHistory) > maxSteps:
print("search too long -- aborting search ...")
return False
elif searchHistory[-1] in searchHistory[:-1]:
print("repeated article -- aborting search ...")
return False
else:
return True
articleChain = [startURL]
while continueCrawl(articleChain, targetURL):
#print(articleChain[-1])
firstLink = getFirstLink(articleChain[-1])
if not firstLink:
print("article with no links -- aborting search")
break
articleChain.append(firstLink)
time.sleep(2)
|
12471d763e202b66f334cb53b5369cbe1a9b3167 | Tanavya/ProjectEuler | /EulerP43.py | 488 | 3.53125 | 4 | import itertools
import time
start = time.time()
primes = [2,3,5,7,11,13,17]
num = "0123456789"
perms = [ "".join(x) for x in itertools.permutations(num)]
def subStringDivisible(n):
if int(n[3]) % 2 != 0:
return False
for i in range(1,8):
if int(n[i:i+3]) % primes[i-1] != 0:
return False
return True
SUM = 0
for n in perms:
if subStringDivisible(n):
SUM += int(n)
print "Ans:", SUM, "found in", time.time()-start, "seconds"
|
d3c91d01256cb28d136a2f459925d8ffca5b621f | s5003597/Python-Examples | /session_1/input_and_conditions/02_conditions.py | 230 | 4.09375 | 4 | command = input('Please enter a command: ')
if command == 'print':
print(command)
elif command == 'name':
name = input('Please enter your name: ')
print(name)
else:
print('The command you entered was not valid!')
|
3458c3efde5dc6e23fef3dac35687ddc7f5983f8 | oliviersamin/P7_Resolvez-des-problemes-en-utilisant-des-algorithmes-en-Python | /bruteforce.py | 4,272 | 3.921875 | 4 | # livrable = liste d'actions à acheter du type [{'name': 'action1', 'quantity': x},...]
# constraints : 1. buy only 1 action and only once
# 2. cannot buy a part of action but only a plain number
# 3.maximum money to spend = 500 euros
# 4. Read a file containing shares information -------- OK
# 5. MUST TRY ALL THE POSSIBLE COMBINATIONS AND SELECT THE BEST ONE
# 6. Display only the best result
import csv
import time as t
csv_filename = 'data_bruteforce.csv'
capital_to_invest = 500
def read_csv_file(csv_file: str) -> list:
""" read the csv file and load the list following the format:
[{'name': 'action1', 'price': 100, 'profit': 10}, ...]"""
shares_list = []
with open(csv_file, newline='', encoding='utf-8') as f:
reader = csv.reader(f)
headers = []
for index, row in enumerate(reader):
if index == 0:
headers = row
else:
shares_list.append({headers[0]: row[0], headers[1]: int(row[1]), headers[2]: int(row[2])})
return shares_list
def create_gain_by_share(list_of_shares: list) -> list:
""" get a list of shares and calculate from its 'profit' its 'gain' in euros """
for share in list_of_shares:
share['Gain'] = round(share['profit']*share['price']/100.,3)
return list_of_shares
def brute_force_gain(capital_max, shares, shares_kept=[]):
""" use a recursive function to go faster """
if shares:
gain1, list_share1, capital = brute_force_gain(capital_max, shares[1:], shares_kept)
share = shares[0]
if share['price'] <= capital_max:
gain2, list_share2, capital = brute_force_gain(capital_max - share['price'], shares[1:], shares_kept +
[share])
if gain1 < gain2:
return gain2, list_share2, capital
return gain1, list_share1, capital
else:
return sum([i['Gain'] for i in shares_kept]), shares_kept, capital_max
def brute_force_pourcentage(capital_max, shares, shares_kept=[]):
""" use a recursive function to go faster """
if shares:
p1, list_share1, capital = brute_force_pourcentage(capital_max, shares[1:], shares_kept)
share = shares[0]
if share['price'] <= capital_max:
p2, list_share2, capital = brute_force_pourcentage(capital_max - share['price'], shares[1:],
shares_kept + [share])
if p1 < p2:
return p2, list_share2, capital
return p1, list_share1, capital
else:
return sum([i['profit'] for i in shares_kept]), shares_kept, capital_max
def main():
""" main function """
# print('calcul for {} shares'.format(number))
start = t.time()
shares_list = read_csv_file(csv_filename)
shares_list = create_gain_by_share(shares_list)
max_gain, list_shares, capital_restant = brute_force_gain(capital_to_invest, shares_list)
# total_pourcentage, list_shares2, capital_restant2 = brute_force_pourcentage(capital_to_invest, shares)
# gain = sum([share['Gain'] for share in list_shares2])
# list_shares = sorted_list_result(list_shares)
end = t.time()
print('------ GAIN -------')
print('liste d actions: {}\ncapital restant = {} euros'.format(list_shares, capital_restant))
print("nombre d'actions achetées = ", len(list_shares))
print('gain en euros: {} soit {}%'.format(round(max_gain,2), round(max_gain/capital_to_invest*100.,2)))
print('temps d exécution du programme = {} secondes'.format(round(end-start,2)))
for share in list_shares:
print(share['name'])
# print('------ POURCENTAGE -------')
# print('liste d actions: {}\ncapital restant = {} euros'.format(list_shares2, len(list_shares2), capital_restant2))
# print('gain en euros: {} soit {}%'.format(round(gain,2), round(gain/capital_to_invest*100.,2)))
# print(total_pourcentage)
# print('temps d exécution du programme = {} secondes'.format(round(end-start,2)))
if __name__ == "__main__":
# print(timeit.timeit("main()", number = 5))
main()
|
e4baa866d15fe11ee18110b12c21246fd10ade79 | nathanbaja/Python-Exercises-CursoEmVideo | /ex075.py | 420 | 3.859375 | 4 | a = int(input('Digite um numero '))
b = int(input('Digite um numero '))
c = int(input('Digite um numero '))
d = int(input('Digite um numero '))
ns = (a, b, c, d,)
print(f'Voce digitou {ns.count(9)} vezes o numero 9')
if 3 in ns:
print(f'O primeiro 3 aparece na posicao {ns.index(3)+1}')
x = 0
print(f'Os numeros pares digitados foram: ',end='')
for x in ns:
if x % 2 == 0:
print(x,'', end='') |
4670312b1707a632dcfe9e6101c6558ba276fae1 | CharlesBasham132/com404 | /second-attempt-at-tasks/2-guis/window-layouts/1-place/bot.py | 1,287 | 3.90625 | 4 | from tkinter import *
class Gui(Tk):
# initialise window
def __init__(self):
super().__init__()
#set window attributes
self.title("Newsletter")
self.configure(bg="yellow",
height=500,
width=500)
self.add_heading_label()
self.add_instruction_label()
self.add_advance_button()
def add_heading_label(self):
#create
self.heading_label = Label()
self.heading_label.place(x=0, y=0)
#style
self.heading_label.configure(font = "Arial 24",
text = "Recieve our Newsletter")
def add_instruction_label (self):
self.instruction_label = Label()
self.instruction_label.place(x=0, y=50)
self.instruction_label.configure(font = "Arial 16",
text = "Please enter your detalis")
def add_advance_button(self):
self.advance_button = Button()
self.advance_button.place(x=0, y=100)
self.advance_button.configure(bg="red",
text ="subscribe",
width=50)
gui = Gui()
gui.mainloop() |
1244e619d427faaca90ffabf313b98db4c118e19 | burakunaltr/Project-Euler | /SORULAR/4 - Largest palindrome product.py | 539 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
__author__ = "Burak Ünal"
enBuyuk = 0
for i in range(100,999):
for j in range(100,999):
carpim = i*j
if str(carpim) == str(carpim)[::-1]:
if carpim > enBuyuk:
enBuyuk = carpim
print("En Büyük Palindrom Sayı =", enBuyuk)
|
53d3ef9e55a7a6b6ec985a19798378502aa32fe2 | theianrobertson/movie-trivia | /pull_data.py | 6,580 | 3.734375 | 4 | """
Pull Data - some methods for pulling data out.
Author: Ian Robertson
"""
import datetime
import logging
import os
from bs4 import BeautifulSoup
import requests
def get_site(url, filename):
"""Pulls out the html from a site, and saves it."""
logging.info('getting {}'.format(url))
r = requests.get(url)
t = r.text
logging.debug('First 100: {}'.format(t[0:100]))
with open(filename, 'w') as f:
f.write(t)
logging.info('Written to file!')
def birthday_clue(wp):
"""Gets a birthday clue based on a WikiParse object
Parameters
----------
wp : WikiParse
The wiki parse object
"""
if wp.bday:
day_of_month = int(wp.bday.strftime('%d'))
if day_of_month in (1, 21, 31):
day_suffix = 'st'
elif day_of_month in (2, 22):
day_suffix = 'nd'
elif day_of_month in (3, 23):
day_suffix = 'rd'
else:
day_suffix = 'th'
birthday = '{} {}{}, {}'.format(
wp.bday.strftime('%B'),
day_of_month,
day_suffix,
wp.bday.strftime('%Y'))
return 'Born ' + birthday
else:
return None
class WikiParse():
"""Parses out some info from a wiki page!"""
def __init__(self, filename):
self.filename = filename
with open(filename) as f:
self.soup = BeautifulSoup(f.read(), 'html5lib')
self._get_infobox()
self._get_name()
self._get_image_url()
self._get_bday()
self._get_gender()
self._second_sentence()
self._get_imdb()
def _get_infobox(self):
"""Grabs infobox"""
try:
self.infobox = self.soup.find('table', {'class': 'infobox'})
except:
self.infobox = None
def _get_name(self):
"""Grabs the name and whether it's interesting"""
try:
nn = self.infobox.find('span', {'class': 'nickname'}).text
self.nickname = nn
except AttributeError:
self.nickname = None
try:
self.commonName = self.soup.find(id='firstHeading').text
except:
#No main heading????
self.commonName = None
def _get_image_url(self):
"""Tries to grab an image"""
try:
self.imageURL = self.infobox.find('img')['src']
except:
self.imageURL = None
def _get_bday(self):
"""Tries to grab a birthday"""
try:
bday_string = self.infobox.find('span', {'class': 'bday'}).text
self.bday = datetime.datetime.strptime(bday_string, '%Y-%m-%d')
except:
self.bday = None
def _get_gender(self):
"""Tries to grab a gender based on categories"""
female = ['female', 'actress', 'women']
male = ['male', 'actor', 'men']
full_text = self.soup.get_text().lower()
count_female = full_text.count(' she ') + full_text.count(' her ')
count_male = full_text.count(' he ') + full_text.count(' his ')
try:
#Grabs the text in catlinks id
catlinks = self.soup.find(id='catlinks').text.lower()
if any(s in catlinks for s in female):
self.gender = 'F'
elif any(s in catlinks for s in male):
self.gender = 'M'
else:
try:
ratio_male = float(count_male) / float(count_female)
except:
ratio_male = 1
if ratio_male > 2:
self.gender = 'M'
elif ratio_male < 0.5:
self.gender = 'F'
else:
self.gender = None
except:
self.gender = None
def _second_sentence(self):
"""Second sentence is usually an easy one"""
t = self.soup.find(id='mw-content-text')
#Kills the IPA span because it can have periods
try:
t.find(class_='IPA').decompose()
except:
pass
tt = '\n'.join([p.text for p in t.find_all('p')])
self.second_sentence = tt.split('.')[1].strip()
def _get_imdb(self):
"""
Tries to grab an IMDB link - gets last a href tag matching
www.imdb.com/name.
"""
a_list = self.soup.find_all('a')
self.imdb_url = None
for link in a_list:
try:
href = link['href']
except:
href = ''
if 'www.imdb.com/name' in href:
self.imdb_url = href
if self.imdb_url:
filename = os.path.join('files', 'imdb', self.imdb_url.replace('/',
'_'))
if not os.path.isfile(filename):
get_site(self.imdb_url, filename)
with open(filename) as f:
self.imdb_soup = BeautifulSoup(f.read(), 'html5lib')
def __repr__(self):
return '<Wiki Parse {0}>'.format(self.commonName)
def __str__(self):
attrs = vars(self)
st = 'Parsing:\n'
for at in attrs:
if at not in ['infobox', 'soup', 'imdb_soup']:
st += ' {0}: {1}\n'.format(at, attrs[at])
return st
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
urls = [
'https://en.wikipedia.org/wiki/Michael_Caine',
'https://en.wikipedia.org/wiki/Melissa_McCarthy',
'https://en.wikipedia.org/wiki/Sarah_Jessica_Parker',
'https://en.wikipedia.org/wiki/Jerry_Seinfeld',
'https://en.wikipedia.org/wiki/Leonardo_DiCaprio',
'https://en.wikipedia.org/wiki/Sia_Furler',
'https://en.wikipedia.org/wiki/Matthew_Perry',
'https://en.wikipedia.org/wiki/Diana,_Princess_of_Wales',
'https://en.wikipedia.org/wiki/Elizabeth_II',
'https://en.wikipedia.org/wiki/Donald_Trump',
'https://en.wikipedia.org/wiki/Harrison_Ford',
'https://en.wikipedia.org/wiki/Roman_Polanski',
'https://en.wikipedia.org/wiki/Jack_Nicholson',
'https://en.wikipedia.org/wiki/Arnold_Schwarzenegger',
'https://en.wikipedia.org/wiki/Tina_Fey',
'https://en.wikipedia.org/wiki/Sarah_Palin'
]
for url in urls:
filename = os.path.join('files', url.replace('/', '_'))
if not os.path.isfile(filename):
get_site(url, filename)
p = WikiParse(filename)
print(p)
print(birthday_clue(p))
|
7b167808b27694356410e4a951d5dfabe7a1ab19 | mindnhand/Learning-Python-5th | /Chapter18.Arguments/print3_alt2.py | 631 | 3.53125 | 4 | #!/usr/bin/env python3
#encoding=utf-8
#--------------------------------------------
# Usage:
# Description:
#--------------------------------------------
import sys
def print3(*args, **kargs):
sep = kargs.pop('sep', ' ')
end = kargs.pop('end', '\n')
file = kargs.pop('file', sys.stdout)
if kargs:
raise TypeError('extra keywords: %s' % kargs)
output = ''
first = True
for arg in args:
output += ('' if first else sep) + str(arg)
first = False
file.write(output + end)
print3(99, (1, 2, 3), sep='@')
print3(909, name='bob') # will raise an Exception
|
1f02670973604cf27409388a756d6e878ff5c39b | EduardoSanglard/ProjetoEstudos | /EstruturaSequencial/ex11.py | 385 | 4.09375 | 4 | try:
int1 = int(input('Primeiro Inteiro: '))
int2 = int(input('Segundo Inteiro: '))
real = float(input('Numero Real: '))
print('Dobro do primeiro com metade do segundo: ', (int1*2)+int2)
print('Soma do triplo do primeiro com o terceiro: ', (int1*3)+real)
print('terceiro elevado ao cubo: ', real**3)
except ValueError:
print('Voce nao digitou um numero') |
6068bba4400e2009854af16d019df4738d051903 | sithugirish/march-2018 | /dona.py | 96 | 3.640625 | 4 | print"enter two number"
a=int(raw_input())
b=int(raw_input())
c=a-b
print"difference is"+str(c)
|
52c4f66b1426b8580ed327d1e8e730a54800963e | jditlee/tmdSurprise_leetcode_hot100 | /[139]单词拆分.py | 2,439 | 3.5 | 4 | # 给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
#
# 说明:
#
#
# 拆分时可以重复使用字典中的单词。
# 你可以假设字典中没有重复的单词。
#
#
# 示例 1:
#
# 输入: s = "leetcode", wordDict = ["leet", "code"]
# 输出: true
# 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
#
#
# 示例 2:
#
# 输入: s = "applepenapple", wordDict = ["apple", "pen"]
# 输出: true
# 解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
# 注意你可以重复使用字典中的单词。
#
#
# 示例 3:
#
# 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
# 输出: false
#
# Related Topics 字典树 记忆化搜索 哈希表 字符串 动态规划
# 👍 1049 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
"""
:param s:
:param wordDict:
:return:
"""
import functools
@functools.lru_cache(None)
def back_tack(s):
if not s:
return True
res = False
for i in range(1,len(s)+1):
# print("1:",s[:i],res)
if s[:i] in wordDict:
# print("2:", s[:i], res)
res = res or back_tack(s[i:])
# print("3:", s[:i], res)
return res
return back_tack(s)
def wordBreak1(self, s: str, wordDict: List[str]) -> bool:
"""
动态规划 时间复杂度O(n^2) 空间复杂度O(n)
:param s:
:param wordDict:
:return:
"""
size = len(s)
dp = [True]+[False]*size
for i in range(size):
for j in range(i+1,size+1):
if dp[i] and (s[i:j] in wordDict):
dp[j] = True
return dp[-1]
def fab(n):
if n<2:
return n
return fab(n-1)+fab(n-2)
if __name__ == '__main__':
s = "hello"
wordDict = ["he","llo"]
print(Solution().wordBreak(s,wordDict))
# print(len(s))
# print(s[0:1])
# print(s[0:4])
# print(fab(6))
# leetcode submit region end(Prohibit modification and deletion)
|
93627c8653e8f572b320cf4de701dff5fac5896b | S-Tim/Codewars | /python/deodorant_evaporator.py | 1,064 | 4.15625 | 4 | """
Deodorant Evaporator
This program tests the life of an evaporator containing a gas.
We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold
(threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictly positive.
The program reports the nth day (as an integer) on which the evaporator will be out of use.
Note : Content is in fact not necessary in the body of the function "evaporator", you can use it or not use it, as you wish.
Some people might prefer to reason with content, some other with percentages only. It's up to you but you must keep it as a
parameter because the tests have it as an argument.
"""
def evaporator(content, evap_per_day, threshold):
days = 0
currentContent = content
while currentContent / content * 100 > threshold :
currentContent *= (1.0 - (evap_per_day / 100))
days += 1
#print("Content after one day is " + str(currentContent))
return days
print(evaporator(10, 10, 10))
|
81162f76f77aaed4a5cec6305d7dee545bb26a03 | porigonop/code_v2 | /cours_POO/TP1/Joueur.py | 2,604 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Domino import *
class Joueur:
""" Classe représentant un joueur
:Attribut nom: String, représentant le nom du joueur
:Attibut main: liste, représentant la main du joueur courant,liste
represente l'ensemble des dominos qu'il a à jouer
"""
def __init__(self, nom):
""" Constructeur de la classe
:Param nom: String, servant à initialiser l'attribut nom du joueur
de la classe
"""
self.nom = nom
self.main = []
def ajoute_a_la_main(self, domino):
""" Methode permettant d'ajouter un domino à la main du joueur courant
"""
if isinstance(domino, Domino):
self.main.append(domino)
def __repr__(self):
""" Redéfinition de la méthode __repr__ pour la classe Domino"""
return "Main du joueur " + self.nom + ' : ' + str(self.main)
def est_le_meme_que(self, joueur):
""" Méthode permettant de tester si le nom du joueur courant
(ie de self) et de joueur sont identiques
:Param joueur: Joueur
"""
return self.nom == joueur.nom
def affiche(self):
""" Méthode permettant d'afficher la main du joueur courant """
print(self.__repr__())
def joue(self, domino):
""" Méthode permettant au joueur courant de jouer un domino.
Cela n'est possible que si le domino en question est
effectivement dans la main du joueur.
Lorsque l'action n'est pas possible, la méthode affiche
la main du joueur courant.
:Param domino: Domino
"""
for indice in range(len(self.main)):
if domino.est_le_meme_que(self.main[indice]):
return self.main.pop(indice)
print("COUP IMPOSSIBLE : " + "main de "+ self.nom + " : " +\
str(self.main))
return None
if __name__ == '__main__':
d1 = Domino(3,2)
d2 = Domino(3,4)
d3 = Domino(2,3)
d4 = Domino(4,4)
d5 = Domino(5,4)
joueur = Joueur("toto")
joueur.affiche()
joueur.ajoute_a_la_main(d1)
joueur.affiche()
joueur.ajoute_a_la_main("3")
joueur.affiche()
joueur.ajoute_a_la_main(d2)
joueur.ajoute_a_la_main(d3)
joueur.ajoute_a_la_main(d4)
joueur.ajoute_a_la_main(d5)
joueur.affiche()
joueur.joue(d2)
joueur.affiche()
d6 = Domino(1, 2)
joueur.joue(d6)
joueur_2 = Joueur("titi")
joueur_3 = Joueur("toto")
print(joueur.est_le_meme_que(joueur_2))
print(joueur.est_le_meme_que(joueur_3))
|
e201e45154ed465e225214665630fae33add8735 | layshidani/learning-python | /lista-de-exercicios/Curso Python mundo 1 fundamentos cursoemvideo/Exercício Python #007 Média Aritmética.py | 300 | 3.625 | 4 |
# coding: utf-8
print('Olá! Vamos calcular a média do aluno!')
nota1 = float(input('Qual foi a primeira nota? '))
nota2 = float(input('Qual foi a segunda nota? '))
nota3 = float(input('Qual foi a terceira nota? '))
nf = (nota1 + nota2 + nota3)/3
print('\nA média final é: {:.2f}'.format(nf))
|
ef157729ec3f973f5f9a38183f73cbf3799fdf94 | Wizmann/ACM-ICPC | /Leetcode/Algorithm/python/1000/00232-Implement Queue using Stacks.py | 507 | 3.921875 | 4 | class Queue(object):
def __init__(self):
self.a = []
self.b = []
def push(self, x):
self.a.append(x)
def pop(self):
if not self.b:
self.do_move()
return self.b.pop()
def peek(self):
if not self.b:
self.do_move()
return self.b[-1]
def empty(self):
return not self.a and not self.b
def do_move(self):
while self.a:
self.b.append(self.a.pop())
|
e23df7d253df0c33d7a7a33ac01b49b94cd47c4a | blazarus23/Pandas-tutorial- | /SalesData.py | 5,065 | 3.578125 | 4 | import pandas as pd
import os
df = pd.read_csv("Sales_Data/Sales_April_2019.csv")
pd.options.display.width= None
pd.options.display.max_columns= None
pd.set_option('display.max_rows', 3000)
pd.set_option('display.max_columns', 3000)
files = [file for file in os.listdir("Sales_Data")]
## create empty df to store all new concatinated data
all_months = pd.DataFrame()
for file in files:
df = pd.read_csv("Sales_Data/"+ file)
all_months = pd.concat([all_months, df])
#remove first column in data frame
# what the code is saying df.iloc[row_start:row_end , col_start, col_end]
#all_months = df.iloc[:, 0:]
all_months.to_csv('all_data.csv', index=False)
all_data = pd.read_csv("all_data.csv")
## clean all the data! drop rows of NaN
nan_df = all_data[all_data.isna().any(axis=1)]
all_data = all_data.dropna(how='all')
#print (all_data.head(10))
## augment data with additional columns
# add month column
## find 'or' and delete it
all_data = all_data[all_data['Order Date'].str[0:2] != 'Or']
all_data['Month'] = all_data['Order Date'].str[0:2]
all_data['Month'] == all_data['Month'].astype('int32')
## converting columns to the correct type
all_data['Quantity Ordered'] = pd.to_numeric(all_data['Quantity Ordered'])
all_data['Price Each'] = pd.to_numeric(all_data['Price Each'])
# add another column for total sale values
all_data['Sales'] = all_data['Quantity Ordered'] * all_data['Price Each']
# add a city column using .apply() method
# writing a function that grabs the specific data you want. Example grabbing the City and State information
def get_city (address):
return address.split(',')[1]
def get_state (address):
return address.split(',')[2].split(' ')[1]
all_data['City'] = all_data['Purchase Address'].apply(lambda x: get_city(x) + ' ' + get_state(x))
#rearrange column to fit appropriately
#cols = list(all_data.columns.values)
#all_data = all_data[cols[0:5] + [cols [-1]] + cols [5:]]
## Task 1: what was the best month for sales? how much was earned that month?
results = all_data.groupby('Month').sum()
import matplotlib.pyplot as plt
#gives range for months, always put extra number for exclusiveness e.g. 13 for 12 months
#months = range(1,13)
#plt.bar(months, results['Sales'])
#plt.show()
# customising graphs
"""
plt.xticks(months)
plt.ylabel('Sales in USD ($)')
plt.xlabel('Month number')
plt.show()
"""
#print (month_data)
## Task 2: what city had the highest number of sales?
import matplotlib.pyplot as plt
results = all_data.groupby('City').sum()
# to ensure data aligns use the (df for df) code
cities = [city for city, df in all_data.groupby('City')]
""""
plt.bar(cities, results['Sales'])
plt.xticks(cities, rotation='vertical', size=6)
plt.ylabel('Sales in USD ($)')
plt.xlabel('City name')
plt.show()
"""
## Task 3: what time should we display ads to maximise likelihood of customer buying products?
# convert date/time into date/time object to easily access parts of date (hour, minute etc)
all_data['Order Date'] = pd.to_datetime(all_data['Order Date'])
all_data['Hour'] = all_data['Order Date'].dt.hour
all_data['Minute'] = all_data['Order Date'].dt.minute
# plot the data on a line graph
import matplotlib.pyplot as plt
hours = [hour for hour, df in all_data.groupby('Hour')]
"""
plt.plot(hours, all_data.groupby(['Hour']).count())
plt.xticks(hours)
plt.xlabel('Hour')
plt.ylabel('Number of Orders')
plt.grid()
plt.show()
"""
## Take 4: What products are most often sold together?
# how to identify duplicated data, keep=False makes sure you keep all the duplicates
#df = all_data[all_data['Order ID'].duplicated(keep=False)]
# create new column to combine duplicated data
#df['Grouped'] = df.groupby('Order ID')['Product'].transform(lambda x: ','.join(x))
# drop out instances of the same pair (e.g. rows 2 and 3)
#df = df[['Order ID', 'Grouped']].drop_duplicates()
# using these tools going to count the final number of pairs that exist in df
""""
from itertools import combinations
from collections import Counter
count = Counter()
for row in df['Grouped']:
row_list = row.split(',')
count.update(Counter(combinations(row_list, 2)))
pairs = count.most_common(10)
print (pairs)
"""
## Task 5: what product sold the most? And why?
product_group = all_data.groupby('Product')
quantity_ordered = product_group.sum()['Quantity Ordered']
#print (product_group)
import matplotlib.pyplot as plt
products = [product for product, df in product_group]
""""
plt.bar(products, quantity_ordered)
plt.xticks(products, rotation='vertical', size=8)
plt.ylabel('Quantity Ordered')
plt.xlabel('Product')
plt.show()
"""
## add second y-axis to prove hypothesis of why?
# use subplots
prices = all_data.groupby('Product').mean()['Price Each']
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.bar(products, quantity_ordered, color='b')
ax2.plot(products, prices, 'b-')
ax1.set_xlabel('Product Name')
ax1.set_ylabel('Quantity Ordered', color='g')
ax2.set_ylabel('Price of Product', color='r')
ax1.set_xticklabels(products, rotation='vertical', size=8)
#plt.show()
#print (prices)
|
449ef891ba8c0b0e717a91bbd344fa325736e957 | Nethermaker/school-projects | /intro/code_hints.py | 942 | 4.59375 | 5 | #How do I rotate a letter?????
#I am going to give you two completely different methods.
#Method 1: The ASCII method!
#The ord() function will take a letter and return its ASCII value.
print ord('a')
print ord('J')
#The chr() function takes an ASCII value and returns its character.
print chr(97)
print chr(74)
letter = 'p'
number = 5
rotation = ord('p') + 5
print chr(rotation)
#Your job (if you use this method): if you go past the range that you should be in, you need to
# subtract (or add) 26 until you're back in the correct range.
#Method 2: The Alphabet String Method
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter = 'e'
number = -5
location = alphabet.index(letter)
location = (location + number) % 26
print alphabet[location]
#Your job (if you use this method): this does not currently work for upper case letters
# or non-letters. You have to make it work for any character.
|
f4c608184ed50110919bacf8563aaf8f81eba311 | Kevinkang0211/Advanced-Algorithm | /Minimum Spanning Tree/MST_kruskal.py | 2,326 | 3.703125 | 4 |
import numpy as np
import pandas as pd
# Kruskal's algorithm in Python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
# Search function
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def apply_union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
# Applying Kruskal algorithm
def kruskal_algo(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
# for u, v, weight in result:
# print("%d - %d: %d" % (u, v, weight))
sum_weight = 0
for i in range(len(result)):
sum_weight += result[i][2]
print('The weight of',self.V , 'nodes is' ,sum_weight)
print('------MST with Kruskal algorithm(Upper triangle)------')
for k in range(10,60,10):
g = Graph(k)
data = np.array(pd.read_excel('MSTdata.xlsx'))
data = data[:,1:]
for i in range(k):
for j in range(i+1,k):
g.add_edge(i, j, data[i][j])
g.kruskal_algo()
print('\n------MST with Kruskal algorithm(Lower triangle)------')
for k in range(10,60,10):
g = Graph(k)
data = np.array(pd.read_excel('MSTdata.xlsx'))
data = data[:,1:]
for i in range(k):
for j in range(0,i):
g.add_edge(i, j, data[i][j])
g.kruskal_algo()
|
048f0e42243aa8f5305f60e5bf902e16abaa18bf | puneet4840/Data-Structure-and-Algorithms | /Linked List in Python/2 - Doubly Linked List/10 - Count Total Number of Node.py | 1,864 | 4.15625 | 4 | # Count Total Numer Of Nodes in Doubly Linked List.
print()
class Node():
def __init__(self,data):
self.prev=None
self.data=data
self.next=None
class Linked_list():
def __init__(self):
self.start=None
def Insert_Node(self,data):
temp=Node(data)
if self.start==None:
self.start=temp
else:
p=self.start
while p.next!=None:
p=p.next
p.next=temp
temp.prev=p
def Count_Nodes(self):
if self.start==None:
print('\nLinked List is Empty')
else:
count=1
if self.start.next==None:
print(f'\n{count} Node Present in the Linked List')
else:
ptr=self.start
while ptr.next!=None:
ptr=ptr.next
count+=1
if count==0:
print('\nLinked List is Empty')
else:
print(f'{count} nodes present in the Linked List')
def Display(self):
if self.start==None:
print('\nLinked list is Empty')
else:
x=self.start
while x!=None:
print(x.data,end='->')
x=x.next
if __name__ == "__main__":
LL=Linked_list()
print()
while True:
print('\n=============')
print('1: Insert Node')
print('2: Count Nodes')
print('3: Display')
print('4: Exit')
ch=int(input("Enter Your Choice: "))
if ch==1:
item=int(input("Enter Your Choice: "))
LL.Insert_Node(item)
elif ch==2:
LL.Count_Nodes()
elif ch==3:
LL.Display()
elif ch==4:
quit()
else:
print('\nInvalid Choice') |
5982302f71cb6373cdabc725ff8d2fc6ac4ec4c1 | threedworld-mit/tdw | /Python/tdw/container_data/container_tag.py | 370 | 3.5625 | 4 | from enum import Enum
class ContainerTag(Enum):
"""
A tag for a container shape.
"""
on = 1 # An object on top of a surface, for example a plate on a table.
inside = 2 # An object inside a cavity or basin, for example a toy in a basket or a plate in a sink.
enclosed = 4 # An object inside an enclosed cavity, for example a pan in an oven.
|
abbd1a5905ac4ba4ca80181cc2b58abc5c8cae09 | medhini/ECE544-PatternRecognition | /mp1/train_eval_model_svm.py | 2,784 | 3.640625 | 4 | """
Train model and eval model helpers.
"""
from __future__ import print_function
import numpy as np
import sklearn
from models.support_vector_machine import SupportVectorMachine
import random
from sklearn.utils import shuffle
def train_model(data, model, learning_rate=0.001, batch_size=100,
num_steps=100, shuffle=True):
"""Implements the training loop of stochastic gradient descent.
Performs stochastic gradient descent with the indicated batch_size.
If shuffle is true:
Shuffle data at every epoch, including the 0th epoch.
If the number of example is not divisible by batch_size, the last batch
will simply be the remaining examples.
Args:
data(dict): Data loaded from io_tools
model(LinearModel): Initialized linear model.
learning_rate(float): Learning rate of your choice
batch_size(int): Batch size of your choise.
num_steps(int): Number of steps to run the updated.
shuffle(bool): Whether to shuffle data at every epoch.
Returns:
model(LinearModel): Returns a trained model.
"""
# Perform gradient descent.
batch_epoch_num = data['label'].shape[0] // batch_size
epochs = 1
for i in range(epochs):
if shuffle:
data['image'],data['label'] = sklearn.utils.shuffle(data['image'],data['label'], random_state=0)
print(i)
for j in range(0,data['label'].shape[0],batch_size):
image_batch = data['image'][j:(j+batch_size)]
label_batch = data['label'][j:(j+batch_size)]
print(j)
for k in range(num_steps):
update_step(image_batch, label_batch, model, learning_rate)
return model
def update_step(image_batch, label_batch, model, learning_rate):
"""Performs on single update step, (i.e. forward then backward).
Args:
image_batch(numpy.ndarray): input data of dimension (N, ndims).
label_batch(numpy.ndarray): label data of dimension (N,).
model(LinearModel): Initialized linear model.
"""
f = model.forward(image_batch)
gradient = model.backward(f,label_batch)
model.w = model.w - learning_rate*gradient
def eval_model(data, model):
"""Performs evaluation on a dataset.
Args:
data(dict): Data loaded from io_tools.
model(LinearModel): Initialized linear model.
Returns:
loss(float): model loss on data.
acc(float): model accuracy on data.
"""
f = model.forward(data['image'])
loss = model.loss(f,data['label'])
y_predict = model.predict(f)
count = 0
for i in range(len(data['label'])):
if data['label'][i] == y_predict[i]:
count = count + 1
acc = (count/len(data['label']))*100
return loss, acc
|
862e4140810e770ba062ad1a3bfd17ceee7c2756 | eleisoncruz/myPythonExploration | /deleteCreateContents.py | 649 | 4.21875 | 4 | # This will delete the contents of the file then the program will allow you to create new contents
# of the file.
from sys import argv
script, filename = argv
print "We will erase first the contents of %s file" %filename
print "Press CTRL-C to cancel."
print "Hit ENTER to proceed."
raw_input("? ")
print "Opening the file: "
print "*" * 10;
target = open(filename, "w")
print "Truncating the file contents: Goodbye!"
target.truncate()
print "Enter here the new contents of %r file" %filename
newContent = raw_input();
print "Now saving new contents: "
print "*" * 10
target.write(newContent)
print "Done saving new contents."
target.close()
|
1ec3fc987b6671befb0194698407178c0c82c200 | Beat30/Exercise_CS1 | /1_3.py | 232 | 4 | 4 | #Ex. 1.2
#calculate nth root of a A>0
y=0.0
x=1.0
n=2
A=int(input('A= '))
x=A/2
def nroot(A,x,n):
x=1/n*((n-1)*x+A/x**(n-1))
return x
while x!=y:
y=x
x=nroot(A,x,n)
print(x)
print( 'nth root of A is ', x)
|
615a921bb959c82a186df0ffbb24e16e321750cd | ericksonlopes/PandasV1.2.3 | /10_minutos_para_os_pandas/07_agrupamento.py | 598 | 4.03125 | 4 | import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
"B": ["one", "one", "two", "three", "two", "two", "one", "three"],
"C": np.random.randn(8),
"D": np.random.randn(8),
}
)
print(df, '\n')
# Agrupando e aplicando a sum()função aos grupos resultantes.
print(df.groupby("A").sum())
print(df.groupby("B").sum())
# O agrupamento por várias colunas forma um índice hierárquico e, novamente, podemos aplicar a sum() função.
print(df.groupby(['A', 'B']).sum())
|
061b9add0a375df2d2f319efbc0937c95506cf87 | kmehran1106/HackerRank-Python | /Easy/Save Prisoner/code_save_prisoner.py | 1,725 | 3.53125 | 4 | import pytest
from typing import List
def save_the_prisoner(prisoner_count: int, sweet_count: int, start_chair: int):
"""
[
if sweets > prisoners, then we need to find the remainder sweets after full passes
then, we'll be able to find out the last prisoner
the edge case here however is if sweets > prisoners and sweets is a multiple of prisoners
then, this means in the final pass, the number of sweets remaining will be equal to prisoners
start = 6
prisoners -> 1 2 3 4 5 6 7
here, we subtracted one from start_chair, because the start_chair itself needs to receive
the candy.
]
Args:
prisoner_count (int): [description]
sweet_count (int): [description]
start_chair (int): [description]
Returns:
[type]: [description]
"""
sweet_count = sweet_count % prisoner_count if sweet_count > prisoner_count else sweet_count
if sweet_count == 0:
sweet_count = prisoner_count
start_chair -= 1
diff = prisoner_count - start_chair
if diff >= sweet_count:
return start_chair + sweet_count
else:
return sweet_count - diff
@pytest.fixture
def get_fixtures():
first_input = [5, 2, 1]
first_output = 2
second_input = [5, 2, 2]
second_output = 3
third_input = [7, 19, 2]
third_output = 6
fourth_input = [13, 140874526, 1]
fourth_output = 13
return [
(first_input, first_output),
(second_input, second_output),
(third_input, third_output),
(fourth_input, fourth_output),
]
def test_code(get_fixtures):
for data in get_fixtures:
assert save_the_prisoner(*data[0]) == data[1] |
4968572741bacc457beaa1851c83b38bea14bc06 | FarzanAkhtar/Intro-to-Webd | /Week 1 Practice Problems/1.py | 185 | 4.15625 | 4 | #Fibonacci numbers
n=int(input("Enter an Integer:"))
a=0
b=1
print("First",n,"fibonacci numbers are:")
print(a)
print(b)
for i in range(2,n):
c = a + b
print(c)
a=b
b=c
|
4e13e69478eff7a6e654b37c6e248745929b29a2 | bartoszmaleta/4th-Self-instructed-week | /errors_and_exceptions exercises3.py | 878 | 3.796875 | 4 | print('------------------------------------------------ 1')
person = {}
properties = [
("name", str),
("surname", str),
("age", int),
("height", float),
("weight", float),
]
for property, p_type in properties:
valid_value = None
while valid_value is None:
try:
value = input("Please enter your %s: " % property)
valid_value = p_type(value)
except ValueError as ve: # just added 'as ve'
print("Could not convert %s '%s' to type %s. Please try again." % (property, value, p_type.__name__))
print(ve) # just added this line
person[property] = valid_value
print(person)
print('------------------------------------------------ 2')
try:
age = int(input("Please enter your age: "))
except ValueError as err:
print("You entered incorrect age input: %s" % err)
raise err |
6b22a0d77640e76b2ae9e5390a8dde752e396d94 | andersonvelasco/Programming-2020B | /Entrenamiento Algoritmico/primos.py | 603 | 4.03125 | 4 | '''Script que determina si un numero ingresado por el usuario es primo o compuesto
Teoria:
Que es un número primo:
SOn aquellos no. enteros divisibles unicamente entre 1 y por si mismo. Solo 2 divisores
'''
#Call packages or libraries
import os
os.system("cls") # thsi kine let you clear screen.
counter = 0
i = 1
print(":::VERIFICADOR DE NÚMEROS PRIMOS::::")
num=int(input("Ingrese un número: "))
while i <= num :
if num % i ==0:
counter = counter +1
i = i + 1
if counter <= 2:#counter < 3
print("El No. ",i-1," es PRIMO")
else:
print("El No. ",i-1," es COMPUESTO") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.