blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b22c0155c9290b038e32b97ad013a32e9247689a | grgoswami/Python_202004 | /source/ap9.py | 277 | 4.28125 | 4 |
fruit = 'I like to eat %s'
# The following is called Python 2 style string formatting
print(fruit %('oranges'))
print(fruit)
# This following is Python 3 style string formatting
fruit = 'I like to eat {0} and {1}'
print(fruit.format('oranges', 'strawberry'))
print(fruit)
|
b3c151a939dfe692d5b16931231953f085be78b7 | cdrenteria/blackjack | /blackjack.py | 5,688 | 4.0625 | 4 | from random import shuffle
import time
import ast
class Card:
""" Builds a single card"""
def __init__(self, value, suit):
self.value = value
self.suit = suit
def display_card(self):
"""This displays the value and suit of card, if the card is a face card it assigns a value of 10"""
print(f"{self.value} of {self.suit}")
if self.value == "Jack":
self.value = 10
if self.value == "Queen":
self.value = 10
if self.value == "Ace":
self.value = 10
if self.value == "King":
self.value = 10
class Deck:
"""Builds, shuffles, and displays a deck of cards using the Card class"""
def __init__(self, amount=1):
self.amount = amount
self.cards = []
def build_deck(self):
"""Builds a new deck of 52 cards using the Card Class"""
for d in range(self.amount):
for s in ["Hearts" , "Spades" , "Diamonds" , "Clubs"]:
for v in range(1, 11):
self.cards.append(Card(v, s))
for s in ["Hearts" , "Spades" , "Diamonds" , "Clubs"]:
for v in ["Jack" , "Queen" , "King", "Ace"]:
self.cards.append(Card(v, s))
def display_deck(self):
"""For every card contained in the deck it prints the suit and value"""
for c in self.cards:
c.display_card()
def shuffle_deck(self):
""" Randomly rearranges the cards"""
shuffle(self.cards)
class Player:
def __init__(self):
self.hand = []
self.amount = 0
self.play = True
self.score = 0
def draw_card(self):
""" Draws a card and adds it the players hand and check the player total value of cards to see if is lower, equal
to or higher than 21"""
self.hand.append(d1.cards.pop())
self.hand[-1].display_card()
inc_amount = self.hand[-1].value
self.amount += inc_amount
if self.amount > 21:
print("Bust!")
elif self.amount == 21:
print("You win!")
p1.score += 200
print(p1.score)
elif self.amount < 21:
p1.player_input()
def player_input(self):
"""Allow a player to hit or pass"""
if self.play == True:
p1_input = input(f"You have {self.amount} would you like to hit or pass? [1 - hit / 0 - pass]: ")
if p1_input == "1" or p1_input.lower() == "hit":
p1.draw_card()
elif p1_input == "0" or p1_input.lower() == "pass": # Problem! When I enter "0" it repeats p1_input once.
print("Alright, my turn!")
else:
print("Please hit or pass")
class Dealer(Player):
"""
This is a subclass of Player and inherits it's attributes. This class plays 21 against the Player using 'if' logic
"""
def __init__(self):
super().__init__()
self.hand = []
self.amount = 0
def dealer_draw_car(self):
"""
The dealer draws a card, check's the value of the cards in his and and will either hit if he has less then the player
and stay if he has more while being under 21 total. The dealer looses if his is lower so he will hit
even if he is very close to 21 since it is his only option to win. The dealer will 'push' if he is equal to
the player.
"""
self.hand.append(d1.cards.pop())
self.hand[-1].display_card()
time.sleep(1)
inc_amount = self.hand[-1].value
self.amount += inc_amount
if self.amount > 21: #If the dealer goes over 21 they lose
print("I went over! You win!")
p1.score += 100
print(p1.score)
time.sleep(1)
elif self.amount == 21: #If the dealer hits 21 they lose
print(f" You had {p1.amount} and I have {self.amount} I win!")
time.sleep(1)
elif abs(21-self.amount) < abs(21-p1.amount): #if the dealer gets closer to 21 then the palyer they win
print(f" You had {p1.amount} and I have {self.amount} I win!")
time.sleep(1)
elif self.amount > 18 and (abs(21 - self.amount) == abs(21 - p1.amount)): # if the dealer is over 18 and equal to the player they push
print("Push")
time.sleep(1)
else:
p2.dealer_draw_car()
def play_game():
""""Runs a continous loop that plays blackjack"""
p1.draw_card()
if p1.amount < 21:
p2.dealer_draw_car()
p2.amount = 0
p1.amount = 0
def setup_game():
"""
Creates the new deck and shuffles it
:return:
"""
d1.build_deck()
d1.shuffle_deck()
def end_game():
"""Ends the game, resets the cards, and checks for a high score. If Player has new high score it will allow them to
save their score and name"""
with open("high_score.txt", "r") as high_scores:
high_score_dict = ast.literal_eval(high_scores.read())
print(p1.score)
for k in high_score_dict:
if p1.score > high_score_dict[k]:
print("New High Score!")
high_score_name = input("What is your name? ")
new_high_score = {high_score_name: p1.score}
with open("high_score.txt", "w") as high_scores:
high_scores.truncate(0)
high_scores.write(str(new_high_score))
p1.score = 0
d1.cards = []
setup_game()
print("Shuffling the deck!")
time.sleep(1)
d1 = Deck()
setup_game()
p2 = Dealer()
p1 = Player()
while True:
play_game()
if len(d1.cards) <= (d1.amount * 13):
end_game() |
a9f5409e7cca0213d148273f0313198bd64a9685 | jyang001/Bridge-Card-Game | /Deck.py | 2,955 | 4.125 | 4 | import random
from Card import Card
class Deck(object):
#------------------------------------------------------------
def __init__(self):
""" Theta(n) run-time efficiency
post: Creates a 52 card deck in standard order"""
cards = []
for suit in Card.SUITS:
for rank in Card.RANKS:
cards.append(Card(rank,suit))
self.cards = cards # cards in the deck
self._size = 52 # number of cards initally in a deck
#------------------------------------------------------------
def size(self):
"""Cards left, Theta(1) run-time efficiency
post: Returns the number of cards in self"""
return self._size
#------------------------------------------------------------
def deal(self):
"""Deal a single card, Theta(1) run-time efficiency
pre: self.size() > 0
post: Returns the next card in self, and removes it from self."""
assert self._size > 0
card = self.cards.pop() # removing a card from the deck
self._size -= 1 # update the number of cards in the deck
return card
#------------------------------------------------------------
def shuffle(self):
"""Shuffles the deck, using Python's random module
post: randomizes the order of cards in self"""
random.shuffle(self.cards)
#n = self._size()
#cards = self.cards
#for i,card in enumerate(cards):
# pos = randrange(i,n)
# cards[i] = cards[pos]
# cards[pos] = card
#------------------------------------------------------------
def addTop(self,card):
""" adds a card to the top of the deck, Theta(1) run-time efficiency
pre: card is of type Card
post: card is added back to the top of the deck"""
self.cards.append(card) # putting the card to the top of the deck
self._size += 1 # incrementing the size of the deck
#------------------------------------------------------------
def addRandom(self,card):
""" adds a card to the random place in the deck, Theta(1) run-time efficiency
pre: card is of type Card
post: card is added back to the deck, into random place"""
place = random.randint(0,self._size) # getting a random position for the card to be place into
self.cards.insert(place,card) # putting the card into place position in the deck
self._size += 1 # incrementing the size of the deck
#------------------------------------------------------------
def addBottom(self,card):
""" adds a card to the bottom of the deck, Theta(1) run-time efficiency
pre: card is of type Card
post: card is added back to the bottom of the deck"""
self.cards.insert(0,card) # put the card to the bottom of the deck
self._size += 1 # increment size of the deck
|
4e149b89f795f604fe3de5586046b4163bd2f95e | tristann3/CS-1.2 | /sorting_algorithms/bubble_sort.py | 420 | 4.21875 | 4 | def bubble_sort(lst):
''' This is an implementation of bubble sort '''
n = len(lst)
passes = n - 1
# repeats process n-1 times
for i in range(passes):
for j in range(0, passes, -1):
#If current element is greater than whats next
if lst[j] > lst[j+1]:
# This assigns the two variables at the same time to avoid overriding
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst |
da46d31c38907ae974a06d84f9a22eac50b32878 | Jiezhi/myleetcode | /src/124-BinaryTreeMaximumPathSum.py | 1,291 | 3.515625 | 4 | #!/usr/bin/env python
"""
CREATED AT: 2022/4/24
Des:
https://leetcode.com/problems/binary-tree-maximum-path-sum/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Hard
Tag:
See: 2246
"""
from typing import Optional
from tree_node import TreeNode
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
"""
The number of nodes in the tree is in the range [1, 3 * 10^4].
-1000 <= Node.val <= 1000
"""
ret = root.val
def dfs(node) -> int:
if not node:
return -1000
nonlocal ret
if not node.left and not node.right:
ret = max(ret, node.val)
return node.val
left = dfs(node.left)
right = dfs(node.right)
ret = max(ret, node.val, node.val + left, node.val + right, node.val + left + right, left, right)
return max(node.val, node.val + left, node.val + right)
dfs(root)
return ret
def test():
assert Solution().maxPathSum(TreeNode.from_list([-2, -1])) == -1
assert Solution().maxPathSum(TreeNode.from_list([1, 2, 3])) == 6
assert Solution().maxPathSum(TreeNode.from_list([-10, 9, 20, None, None, 15, 7])) == 42
if __name__ == '__main__':
test()
|
602278dfba2b4012514f74f51b6691d2ce7c1357 | Ryan47Liao/PreySimulator | /Simulator/ball.py | 930 | 3.859375 | 4 | # A Ball is Prey; it updates by moving in a straight
# line and displays as blue circle with a radius
# of 5 (width/height 10).
from prey import Prey
import random
import math
class Ball(Prey):
radius = 5 # used in this class only; never changes
_color = 'blue'
def __init__(self,x,y):
def random_angle():
# between 0 and 2pi
return random.random()*math.pi*2
Prey.__init__(self,x = x,y = y,
width=5,height= 5,angle = random_angle(),speed = 5)
def update(self,model):
self.move()
self.wall_bounce() #model as a nonlocal param
def display(self,canvas): #The object is displayed as a ball
canvas.create_oval(self._x-Ball.radius , self._y-Ball.radius,
self._x+Ball.radius, self._y+Ball.radius,
fill=self._color)
|
42974219c81884c79392abbda9916b4953dee128 | shaklev/mcdonalds_vs_programming | /programming_vs_mcdonalds/mygame.py | 1,262 | 4.03125 | 4 | import sys
import mc_donalds
import programming
global statement
statement ="answer 'yes' or 'no' "
def start():
print "Hello human , do you wanna play a game ? ", statement
answer=raw_input("> ")
if "yes" in answer or "Yes" in answer:
print "Glad you want , to play"
print "Just to warn you , i will be very honest with you"
print "Choose left or right door:"
side=raw_input("> ")
if "left" in side:
print "So you have time to go back to the start, but would you ?" , statement
annswer=raw_input("> ")
if "yes" in annswer or "Yes" in annswer:
start()
elif "no" in annswer or "No" in annswer:
mc_donalds.mcdonalds()
else:
print "Here we go from the start ....."
start()
elif "right" in side:
programming.programming()
else:
print "You didn't choose either side , probably you are just another 'follower' "
print "Too bad..."
elif "no" in answer or "No" in answer:
print "Too bad , i just wanted to play .... :("
sys.exit(0)
else:
print "Wow just answer yes or no !!!"
start()
start()
|
10cf42621f796c4c9558d153ad2e4116978e676b | JazzikPeng/Algorithm-in-Python | /106. Construct Binary Tree from Inorder and Post.py | 1,791 | 3.953125 | 4 | # 106. Construct Binary Tree from Inorder and Postorder Traversal
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
pInorder = 0
pPostorder = 0
class Solution:
def set_pInorder(self,n):
global pInorder # Needed to modify global copy of globvar
pInorder = n
def set_pPostorder(self,n):
global pPostorder
pPostorder = n
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
self.set_pInorder((len(inorder) - 1))
self.set_pPostorder((len(postorder) - 1))
return self.helper(inorder, postorder, None)
def helper(self, inorder, postorder, end):
# print("pInorder: ", pInorder)
# print("pPostorder: ", pPostorder)
# print("Inorder: ", inorder[0:pInorder+1])
# print("postorder: ", postorder[0:pPostorder+1])
# print("end.val: ", end if end==None else end.val)
if(pPostorder < 0):
return None
# The Last element in pPostorder is the root
root = TreeNode(postorder[pPostorder])
# print("root.val: ", root.val)
self.set_pPostorder(pPostorder-1)
if (inorder[pInorder] != root.val):
root.right = self.helper(inorder, postorder, root)
# print("pInorder: ", pInorder)
# print("==========================")
self.set_pInorder(pInorder-1)
if(end==None or inorder[pInorder] != end.val):
root.left = self.helper(inorder, postorder, end)
return root
if __name__ == '__main__':
b = Solution()
print(b.buildTree([9,3,15,20,7], [9,15,7,20,3]).val) |
9591124c97e63b599f1ea9d34b26eb78d190e9b6 | javierlopeza/IIC1103-2014-2 | /Tareas/Tarea 3/tarea3_nroalumno_seccion_n/PRUEBAS/mukt_tupla.py | 540 | 3.734375 | 4 | #MULTIPLICACION DE TUPLAS POR ESCALAR (equivalente a escalar por vector)
def mult_tupla(e,tupla):
t1=int(tupla[0])*e
t2=int(tupla[1])*e
t3=int(tupla[2])*e
r=(t1,t2,t3)
return (r)
#SUMA DE TUPLAS
def suma_tupla(t1,t2):
d1=int(t1[0])+int(t2[0])
d2=int(t1[1])+int(t2[1])
d3=int(t1[2])+int(t2[2])
r=(d1,d2,d3)
return (r)
#TUPLA ELEVADO A POTENCIA
def pot_tupla(e,tupla):
t1=int(tupla[0])**e
t2=int(tupla[1])**e
t3=int(tupla[2])**e
r=(t1,t2,t3)
return (r)
|
47b1dc61f43c82c0bdc7f44240b4907d690a1cba | jbloemker97/Python-Challenges | /missing_num.py | 257 | 4 | 4 | '''
Create a function that takes a list of numbers between 1 and 10 (excluding one number) and returns the missing number.
'''
def missing_nums(lst):
try:
for num in range(1,11):
index = lst.index(num)
except:
return num |
51d6198af17fe7252252a35537cc1ee984766ff5 | mkusman1/progressive-learning | /proglearn/sims/make_XOR.py | 2,751 | 3.53125 | 4 | import itertools
import numpy as np
from sklearn import datasets
from sklearn.utils import check_random_state
def make_XOR(n_samples=100, cluster_center=[0,0], cluster_std=0.25,
dist_from_center=0.5, N_XOR=False, theta_rotation=0,
random_state=None):
"""
Generate 2-dimensional Gaussian XOR distribution.
(Classic XOR problem but each point is the
center of a Gaussian blob distribution)
Parameters
----------
n_samples : int, optional (default=100)
If int, it is the total number of points equally divided among
the four clusters.
cluster_center : array of shape [2,], optional (default=[0,0])
The x1 and x2 coordinates of the center of the four clusters.
cluster_std : float, optional (default=0.25)
The standard deviation of the clusters.
dist_from_center : float, optional (default=0.5)
X value distance of each cluster to the center of the four clusters.
N_XOR : boolean, optional (default=False)
Change to Gaussian N_XOR distribution (inverts the class labels).
theta_rotation : float, optional (default=0)
Number of radians to rotate the distribution by.
random_state : int, RandomState instance, default=None
Determines random number generation for dataset creation. Pass an int
for reproducible output across multiple function calls.
Returns
-------
X : array of shape [n_samples, 2]
The generated samples.
y : array of shape [n_samples]
The integer labels for cluster membership of each sample.
"""
#variable setup
seed = random_state
dist = dist_from_center
std = cluster_std
n = int(n_samples/4)
cluster_centers = np.array(list(itertools.product([dist, -dist], repeat=2)))
cluster_centers = cluster_center - cluster_centers
n_per_cluster = np.full(shape=2, fill_value=n)
#make blobs
X1,_ = datasets.make_blobs(n_samples=n_per_cluster, n_features=2,
centers=cluster_centers[[0,3], :],
cluster_std=std, random_state=seed)
X2,_ = datasets.make_blobs(n_samples=n_per_cluster, n_features=2,
centers=cluster_centers[[1,2], :],
cluster_std=std, random_state=seed)
#assign classe
if N_XOR:
y1, y2 = np.zeros(n*2), np.ones(n*2)
else:
y1, y2 = np.ones(n*2), np.zeros(n*2)
X = np.concatenate((X1, X2))
y = np.concatenate((y1, y2))
#rotation
c, s = np.cos(theta_rotation), np.sin(theta_rotation)
R = np.array([[c, -s], [s, c]])
X = (R @ X.T).T
return X,y
|
97e25b50f6a95fd35fa7843177168a9f8bd10629 | neternefer/Python | /emplyee.py | 229 | 3.53125 | 4 | class Employee():
def __init__(self, first, last, salary):
self.first = first
self.last = last
self.salary = salary
def give_raise(self, praise=5000):
self.salary += praise
print(self.salary)
|
7aff2780496175196ed4156cd001f97582d7d641 | dengdengkai/Python_practise | /10/10-3.py | 225 | 3.515625 | 4 | #!/usr/bin/python
#coding: UTF-8
"""
题目:时间函数举例3。
程序分析:无。
"""
import time
start = time.clock()
for i in range(10000):
print i
end = time.clock()
print 'different is %6.3f' % (end - start)
|
1762d7409f18feaf8e9f7a9ea9eec1dbdb87f445 | endokazuki/algorithm | /algorithm/algorithm_datastructure/5.divide-and-conquer/exhaustive_search.py | 2,607 | 3.984375 | 4 | """"
#再帰関数
def sum(n):
if n <= 0:
return n
return n + sum(n-1)
#10+9+8....+1+0
print(sum(10))
"""
from itertools import product
#list(product([False, True], repeat=3))#2^3通り
#[(False, False, False), (False, False, True), (False, True, False), (False, True, True),
#(True, False, False), (True, False, True), (True, True, False), (True, True, True)]
search_sequence_sum=int(input())
#合計数
search_sequence = list(map(int, input().split()))
#探索する数をまとめて配列に入力(但し、必ず昇順で入力する事)
target_sequence_sum=int(input())
#合計数
target_sequence = list(map(int, input().split()))
#対象の数をまとめて配列に入力
target_sequence_judge=["no"]*target_sequence_sum
#対象の数の結果専用の配列(デフォルトはno(未解決)と置く)
#全パターン検証後は、noは解なしでyesは解ありと判定する
selection_list=list(product(['False','True'], repeat=search_sequence_sum))
#print(selection_list[31])
#print(selection_list[1][4])
#数字を5つ選んだ場合
#section_list[0][0]...[4][4](25パターン)
def result(search_sequence_sum,search_sequence,target_sequence_sum,target_sequence,target_sequence_judge,selection_list):
pattern=0
select=0
select_sequence_sum=0
target_sequence_point=0
while pattern<=2**search_sequence_sum-1:
#組み合わせは2**(配列数)パターン存在する
while select<=search_sequence_sum-1:
judge=selection_list[pattern][select]
if judge=='True':
select_sequence_sum+=search_sequence[select]
else:
pass
select+=1
#各パターン内でTrueであった場合、Trueに属する数を合算する
while target_sequence_point<=target_sequence_sum-1:
if target_sequence[target_sequence_point]==select_sequence_sum:
target_sequence_judge[target_sequence_point]="yes"
else:
pass
target_sequence_point+=1
#各パターンの合算結果と対象の数が同値であるものをyes(解あり)と判定する
target_sequence_point=0
select_sequence_sum=0
select=0
#初期化
pattern+=1
#print(target_sequence_judge)
for output_judge in target_sequence_judge:
print(output_judge)
#結果を出力
result(search_sequence_sum,search_sequence,target_sequence_sum,target_sequence,target_sequence_judge,selection_list)
|
176267c423727b628bf570d77f4aed294f8635a6 | boydperez/reverse-shell | /server.py | 1,763 | 3.546875 | 4 | import socket
HOST = socket.gethostbyname(socket.gethostname())
PORT = 12345
sock = None
def init_socket():
try:
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("[Socket created]")
sock.bind((HOST, PORT))
print("[Socket bound successfully]")
# Listen to only one client
sock.listen()
print(f"Server listening on port {PORT}")
accept_conn()
except socket.error as err:
print(f"[ERROR] Unable to initialize socket \nverbose: {err}")
def accept_conn():
conn, address = sock.accept()
print("Reverse connection will appear here")
print(f"Connected to {address[0]}:{address[1]}")
handle_client(conn, address)
def handle_client(conn, address):
while True:
conn.send(str(len('os.getcwd()')).encode('utf-8'))
conn.send('os.getcwd()'.encode('utf-8'))
print(conn.recv(2048).decode('utf-8'), end='')
cmd = input()
if cmd == '?':
help_menu()
elif cmd == 'exit' or cmd == 'quit':
cmd_length = len(cmd)
conn.send(str(cmd_length).encode('utf-8'))
conn.send(cmd.encode('utf-8'))
conn.close()
break
else:
cmd_length = len(cmd)
conn.send(str(cmd_length).encode('utf-8'))
conn.send(cmd.encode('utf-8'))
data = conn.recv(1024)
if data != '':
print(data.decode('utf-8'))
def help_menu():
print("""Help Menu
\nAll kinds of system shell commands are supported based on the OS connected to
\nto quit type 'quit' or 'exit'""")
print("Reverse Shell by B0yd\n")
print("?: help\n")
print("Server is starting...")
init_socket()
|
8e9ffce74ffc74f0fdfaf3ee24442062ed097d9b | rtagliaviaz/python-guess-number | /app.py | 360 | 4 | 4 | import random
x = random.randint(1, 20)
print(x)
while True:
guess = input('what is the number\n')
if int(guess) == x:
print('you guessed successfully, your number is', guess,'and the random number is', x)
break
elif int(guess) > x:(
print('your number is greater try again')
elif int(guess) < x:
print('your number is lower try again') |
0dc08dab87449d13edf34bb8a6a9537491985909 | singhamandeep-kgp/Hackerrank | /Counting_sort_2.py | 302 | 3.71875 | 4 | def countingSort(arr):
my_dict = {}
for i in range(0,100):
my_dict[i] = 0
for i in arr:
my_dict[i] += 1
final = []
for i in my_dict:
j = 0
while j < my_dict[i]:
final.append(i)
j += 1
return final
|
12ae880fb83d55fadb8b2cdcc0714caeccc62fcd | kyamaguchi/nlp100 | /python/q39.py | 680 | 3.625 | 4 | #!/usr/bin/env python
def question():
print("39. Zipfの法則")
print("単語の出現頻度順位を横軸,その出現頻度を縦軸として,両対数グラフをプロットせよ.")
import common
groups = common.extract_groups_from_mecab('neko.txt.mecab')
counts = common.word_counts(groups)
# print(counts)
freq = list(counts.values())
freq.sort(reverse=True)
freq_rank = []
for v in freq:
freq_rank.append(freq.index(v)+1)
# print(list(zip(freq, freq_rank)))
import matplotlib.pyplot as plt
def main():
plt.plot(freq_rank, freq)
plt.xscale('log')
plt.yscale('log')
plt.show()
if __name__ == '__main__':
question()
main()
|
ab9ee9f5bb2e6734bb7a12bd0fee1a9636da880a | gladdduck/PythonStudyRecored | /Chapter2-4.py | 1,298 | 4 | 4 | #Python编程从入门到实践
#Eric Matthes
'''
字符串方法:
单引号双引号无区别
.title() 首字母大写
.upper()/.lower() 全大写/全小写
+直接拼接 在print中输出用+ str(target)
.rstrip()/.lstrip()/strip() 去除左右两边空白字符串
列表方法:
列表可以修改元素 元组元素不能修改 元组性能更高 不会轻易被垃圾回收
★ 切片 ★
append(value)
insert(index,value)
del 列表名称[index]
pop()#返回弹出的元素值
remove(value)
sort()#排序改变原列表顺序
sorted()#返回顺序列表
reverse()#逆序
len()
'''
LIST=[]
if not LIST:
print("空")
LIST=[1,'33',0.3,"hello",[1,2,3,4]]
#for遍历列表
for item in LIST:
print(item)
#产生随机数组
LIST=list(range(1,10,2))
#简单的创建数组
LIST=[value**2 for value in range(1,11)]
print(max(LIST))
print(sum(LIST))
#测试for循环与range(left,right,step) [left,right)
ans=0
for value in range(1,1000001):
ans=value+ans
print(ans)
#数组的赋值操作
newList=LIST #给LIST地址 对newList的操作也会影响LIST
# newList=LIST[:] #返回的LIST引用
LIST.append('hhh')
newList.append(11111)
print(LIST)
print(newList)
#元组用()列表用[] 只能修改元组的引用 |
d73b3166b884291180733ebbce95614f900fd208 | dsouzadyn/Coding-Interview | /data-structures/ctci-balanced-brackets/solution.py | 677 | 3.796875 | 4 | def isMirror(x, y):
if x == '(' and y == ')':
return True
elif x == '[' and y == ']':
return True
elif x == '{' and y == '}':
return True
else:
return False
def is_matched(s):
is_balanced = True
stack = []
def push(data):
stack.append(data)
def pop():
if len(stack) > 0:
return stack.pop()
for x in s:
if x in ['(', '{', '[']:
push(x)
elif x in [')', '}', ']']:
if isMirror(pop(), x) == False:
is_balanced = False
break
if len(stack) == 0:
return is_balanced
else:
return False
t = int(input().strip())
for a0 in range(t):
expression = input().strip()
if is_matched(expression) == True:
print("YES")
else:
print("NO")
|
5fb62b17706b5a2775aca3530222f2289cbfe851 | kaushikamaravadi/Python_Practice | /Warmup/prime_factors.py | 445 | 3.90625 | 4 | """What is the largest prime factor of the number 600851475143"""
number = int(input("entger any integer"))
factors = []
largest = []
for i in range(1 , number + 1):
if number % i == 0:
factors.append(i)
#print(i)
print(factors)
maximum = max(factors)
print(maximum)
for fact in factors:
for i in range(2, fact):
if (fact % i) == 0:
break
else:
largest.append(fact)
print(max(largest))
|
e4bdbd1413a902cac5ac40d5c1ea9ae1488ead50 | DeanFlint/PythonProjects | /ToBeConverted/median_num.py | 1,687 | 4.4375 | 4 | """
median
Great work! You've covered a lot in these exercises.
Last but not least, let's write a function to find
the median of a list.
The median is the middle number in a sorted sequence
of numbers.
Finding the median of [7, 12, 3, 1, 6] would first
consist of sorting the sequence into [1, 3, 6, 7, 12]
and then locating the middle value, which would be 6.
If you are given a sequence with an even number of
elements, you must average the two elements
surrounding the middle.
For example, the median of the sequence [7, 3, 1, 4]
is 3.5, since the middle elements after sorting the
list are 3 and 4 and (3 + 4) / (2.0) is 3.5.
You can sort the sequence using the sorted()
function, like so:
sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
"""
entry = [4, 5, 5, 4]
def median(entry):
new_list = []
for num in entry: #add each num into the new_list
new_list.append(num)
new_list.sort() #sort the list numerically
div = len(new_list) #assign the length of the list
if div == 1: #if only one item in list, the median would be 1
return 1
elif div % 2 != 0: #if the list isn't even, divide the length by 2
mid_index = new_list[div / 2] #since indexes start at 0, you don't need to =1
return mid_index #for example [2,4,6,8,10]. 5 numbers, 5 / 2 = 2 (int). new_list[2] would return 3rd value
else: #if list has an even number, use same method as odd (but minus 1) to find out first number
frst = new_list[(div / 2)-1] #then use the odd method to find the second number
scnd = new_list[div / 2]
avg = float(frst + scnd) / 2.0 #add the two values together then divide by 2 to work out median
return avg
print median(entry) |
3514cb0a21c3537501ad1b9c91c0521805d8d270 | alxhghs/python_tests | /animals_class.py | 1,096 | 3.875 | 4 | class Animal(object):
def __init__(self, size, color):
self.size = size
self.color = color
def inputAnimal(self):
self.size = raw_input("What is the size? ")
self.color = raw_input("What is the color? ")
def dispAnimal(self):
print "The animal is %s." % self.size
print "The animal is %s." % self.color
class Canine(Animal):
def __init__(self, trick):
Animal.__init__(self, "size", "color")
self.trick = trick
def trickInput(self):
self.trick = raw_input("What is the canine's favorite trick? ")
def dispTrick(self):
print "The canine's favorite trick is %s." % self.trick
class Dog(Canine):
def __init__(self, owner):
Canine.__init__(self, "trick")
self.owner = owner
def dogOwner(self):
self.owner = raw_input("Who owns the dog? ").title()
def dispOwner(self):
print "The dog's owner is %s." % self.owner
spot = Dog("owner")
spot.inputAnimal()
spot.dispAnimal()
spot.trickInput()
spot.dispTrick()
spot.dogOwner()
spot.dispOwner()
|
aa1f42ecf1825398ccb9dd3dfec7b01dc1a254d3 | jmcnamara44/pythonadventures | /chapter2/shapes.py | 271 | 4.21875 | 4 | import turtle
sides = int(input("How many sides will your shape have? "))
angle = 360 / sides
length = 400 / sides
turtle.fillcolor("blue")
turtle.begin_fill()
for side in range(sides):
turtle.forward(length)
turtle.right(angle)
turtle.end_fill()
turtle.done() |
32fcfb4e26e7584d95346a939a61366f42a617a2 | iamagoodman/ProjectFor2018 | /python/test1.py | 804 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# fo = open('foo.txt','r+')
# fo = open('title1.docx',mode='ab+')
# filecontent = fo.read()
# fo.write('fdajfkasjkfldjaskfsjaklfjsdklajfkls')
# print(filecontent)
# fo.close()
# os.rename('title.docx','title1.docx')
# os.mkdir('newdir1')
# os.rmdir('newdir')
# os.remove('foo.txt')
print(os.getcwd())
# 条件控制 / if嵌套也行,注意缩进
a = 1
if (a<5):
print('a<5')
elif (a==5):
print('a==5')
else:
print('a>5')
# 循环语句 for , while
count = 0
while count < 5:
print(count)
count += 1
else:
print(count)
for x in range(6,10):
if x>8:
break
else:
print(x*2)
for x in range(0,10,3):
print(x)
list1 = ['google','baidu','taobao','ali','huawei']
for i in range(len(list1)):
print(i,list1[i])
print(list(range(1,5)))
|
ca6dbe3200b6688129d0424b8fa7687d2ec41803 | kwshi/knotch | /knotch/__init__.py | 1,640 | 3.609375 | 4 | #!/usr/bin/env python3
from . import language as lang
def split(n): # Split into chunks of three
# Negative numbers
negative = False
if n < 0:
negative = True
n *= -1
text = str(int(n))
kilos = len(text)//3 + 1 # Powers of thousand
zfill = text.zfill(kilos * 3)
chunks = [zfill[i:i+3] for i in range(0, len(zfill), 3)]
if chunks and chunks[0] == '000': # Remedy custom zerofill
del chunks[0]
kilos -= 1
return kilos, chunks, negative
def knot(n):
kilos, chunks, negative = split(n)
groups = [] # Word groups
# Per chunk
for chunk in chunks: # Per 3-digit chunk
group = [] # Initiate current word group
# Hundreds place
if chunk[0] != '0':
group.append(lang.ones[int(chunk[0]) - 1])
group.append(lang.hundred)
# And
if chunk[1:3] != '00' and (group or groups): # Something after 'and' (in this group) & something before 'and'
group.append(lang._and)
# Tens & teens
if chunk[1] == '1': # Teens
group.append(lang.teens[int(chunk[2])])
else: # Regular tens
if chunk[1] != '0': group.append(lang.tens[int(chunk[1]) - 2])
# Ones place
if chunk[1] != '0' and chunk[2] != '0': # Case for hyphens
group[-1] += '-'
group[-1] += lang.ones[int(chunk[2]) - 1]
elif chunk[2] != '0': # No hyphens
group.append(lang.ones[int(chunk[2]) - 1])
# Power of thousands suffix
if chunk != '000':
if kilos > 1: group.append(lang.kilo(kilos - 2))
kilos -= 1 # Decrement thousands
if group: groups.append(' '.join(group)) # Append group to groups
if groups:
y = ', '.join(groups)
if negative: y = lang.negative + ' ' + y
return y
else: return lang.zero # Zero!
|
cd26575527821e2b52e069d0e1f87bcd8f25e82f | gdh756462786/Leetcode_by_python | /Dynamic Programming/Largest Divisible Subset.py | 1,101 | 3.9375 | 4 | # coding: utf-8
'''
Given a set of distinct positive integers, find the largest subset
such that every pair (Si, Sj) of elements
in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
nums: [1,2,3]
Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8]
Result: [1,2,4,8]
'''
class Solution(object):
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if nums is None or len(nums) == 0:
return []
nums = sorted(nums)
size = len(nums)
dp = [1] * size
pre = [None] * size
for x in range(size):
for y in range(x):
if nums[x] % nums[y] == 0 and dp[y] + 1 > dp[x]:
dp[x] = dp[y] + 1
pre[x] = y
idx = dp.index(max(dp))
ans = []
while idx is not None:
ans += nums[idx],
idx = pre[idx]
return ans
solution = Solution()
print solution.largestDivisibleSubset([]) |
f11b320bac86b8419e33a9937e126035fd6c92a2 | lxconfig/BlockChainDemo | /Python_Workspace/Algorithm/栈和队列/04-Stack.py | 804 | 3.84375 | 4 | # -*- coding:utf-8 -*-
# time: 2019/8/21 15:05
# File: 04-Stack.py
class Stack:
def __init__(self):
self.__item = []
def is_empty(self):
return self.__item == []
def size(self):
return len(self.__item)
def push(self, item):
self.__item.insert(0, item)
def pop(self):
if not self.is_empty():
return self.__item.pop(0)
else:
return None
def peek(self):
if not self.is_empty():
return self.__item[0]
else:
return None
if __name__ == '__main__':
stack = Stack()
print(stack.is_empty())
print(stack.size())
stack.push(1)
stack.push(2)
print(stack.size())
print(stack.pop())
print(stack.peek())
|
699feaf8efbb8c188f4231fce0788fb39a92c6a8 | vrbloke-minor/minor-old | /Python/CodeBat/Excercise20.py | 113 | 3.546875 | 4 | #array123
def array123(nums):
temp = ""
for number in nums:
temp += str(number)
return "123" in temp
|
ab2acce4ed6e4ff762195821f21088e87ecfdb17 | juliodantas/calculadora | /calculadora.py | 1,315 | 4.21875 | 4 | print("********** Python Calculator **********\n")
print("Selecione uma das seguintes opções\n")
print("1 - Soma")
print("2 - Subtração")
print("3 - Divisão")
print("4 - Multiplicação")
opcao = int(input("Digite sua opção (1,2,3,4): "))
#x = int(input("Digite o primeiro número: "))
#y = int(input("Digite o segundo número: "))
def somar():
x = int(input("Digite o primeiro número: "))
y = int(input("Digite o segundo número: "))
print("O resultado é:",x + y)
def subtrair(x,y):
return x - y
def multplicar(x,y):
return x * y
def dividir(x,y):
return x / y
if opcao == 1:
#x = int(input("Digite o primeiro número: "))
#y = int(input("Digite o segundo número: "))
somar()
#z = x + y
#print("O resultado é:",z)
elif opcao == 2:
x = int(input("Digite o primeiro número: "))
y = int(input("Digite o segundo número: "))
z = x - y
print("O resultado é:",z)
elif opcao == 3:
x = int(input("Digite o primeiro número: "))
y = int(input("Digite o segundo número: "))
z = x / y
print("O resultado é:",z)
elif opcao == 4:
x = int(input("Digite o primeiro número: "))
y = int(input("Digite o segundo número: "))
z = x * y
print("O resultado é:",int(z))
else:
print("Essa opção não existe")
|
4d358ddd8f797837117558aa47e53b408bf5b2aa | tharlysdias/estudos-python | /aula_7.py | 652 | 4.03125 | 4 | # Operadores de atribuição
a = 10
# Python possibilita a declaração de várias variaveis na mesma atribuição, utilizando atribuições diferentes (ao mesmo tempo)
maisIgual, menosIgual, vezesIgual, divididoIgual, moduloIgual = 5,6,7,8,9
print(str(maisIgual) + "-" + str(moduloIgual))
# Operadores de atribuições classicas
maisIgual += 1 #resultado 6
menosIgual -= 1 #resultado 5
vezesIgual *= 1 #resultado 7
divididoIgual /= 1 #resultado 8.0
moduloIgual %= 2 #resultado 1
print(maisIgual, menosIgual, vezesIgual, divididoIgual, moduloIgual)
# Atribuição e calculo ao mesmo tempo
a, b, c = 2,4,8
a, b, c = a*2, a+b+c, a*b*c
print(a,b,c) |
921d5b29e602c042788ee670cce202f73540e0b1 | IvanmgmSoftwareEngineering/DAA_Python | /AlgortimosGrafoPROPIOS/Recorridos/bfs_iterativo.py | 2,623 | 3.765625 | 4 | #Recorrido Primero en Anchura (BFS=Breadth First Search)
#Versión Iterativa
#Primero en Anchura=> Lista de tipo COLA (FIFO)
from collections import deque
#----------------------------------------------------
#VERSIÓN PROPIA UTILIZANDO DICCIONARIO
#----------------------------------------------------
#VERSIÓN PROFESOR UTILIZANDO LISTA DE ADYACENCIA
def bfsAux(grafo,visited,vertice):
#Implementamos una Lista de tipo FIFO = COLA
pila=deque() #Bicola: es una cola que se pueden hacer insercciones y borrados por el principio y por el final
#Marcamos el nodo como visitado
visited[vertice]=True
print(vertice,end=" ")
#Metemos el Nodo en la cola
pila.append(vertice)
while pila:
aux=pila.pop()#saco de la cola el Nodo 1
for vertice_adyacente in grafo[vertice]:
if not visited[vertice]:
visited[vertice_adyacente] = True
print(vertice_adyacente, end =" ")
pila.append(vertice_adyacente)
def bfs_iterativo (grafo):
n=len(grafo)
visited = [False] * n
for vertice in range (1,n):#Límite inferior siempre inclusivo y el límite superior se excluye
if not visited[vertice]:
bfsAux(grafo,visited,vertice)
#Hemos utilzado una Pila FIFO
#Lo implementamos de forma iterativa
#Paso 1: Definimos el Grafo
#Una lista de listas se indexa como un array
#grafo[0]=[] lista vacía
#grafo[3]=[2,4,5]
#grafo[4][2]=3
grafo=[
[],
[2,4,8],# El vertice 1 está conectado a los vértices 2, 4 y 8
[1,3,4],# El vertice 2 está conectado a los vértices 1, 3 y 4
[2,4,5],# El vertice 3 está conectado a los vértices 2, 4 y 5
[1,2,3,7],# El vertice 4 está conectado a los vértices 1, 2, 3 y 7
[3,6],# El vertice 5 está conectado a los vértices 3 y 6
[5,7],# El vertice 6 está conectado a los vértices 5 y 7
[4,6,9],# El vertice 7 está conectado a los vértices 4, 6 y 9
[1,9],# El vertice 8 está conectado a los vértices 1 y 9
[7,8] # El vertice 9 está conectado a los vértices 7 y 8
]
#Probamos
bfs_iterativo(grafo)
#En este mismo código si cambiamos la Cola por una Pila, cambiamos donde pone encolar por desapilar y donde pone desencolar ponemos apilar,
#este mismo algorimo nos srive para generar una versión iterativa del recorrido primero en profundidad
#Para nodos dirigidos se debe utilizar el recorrido Priemro en Anchura y no se puede utilizar un
#recorrido Primero en Profundidad ya que este segundo recorrido no nos asegura visitar todos los nodos en el caso de tener el Grafo Nodos Trampa. |
374eea17ccd5a4c1fb52a4f5a7d918a7e51cbc55 | jcallahan4/image_segmentation | /image_segmentation.py | 6,262 | 3.765625 | 4 | # image_segmentation.py
"""Image Segmentation
Jake Callahan
Graph theory has a variety of applications. A graph (or network) can be
represented in many ways on a computer. In this program, I implement a common
matrix representation for graphs and show how certain properties of the matrix
representation correspond to inherent properties of the original graph. I also
show an application of using graphs and linear algebra to segment images.
"""
import numpy as np
from scipy import linalg as la
from imageio import imread
from matplotlib import pyplot as plt
from scipy import sparse
from scipy.sparse import linalg
def laplacian(A):
"""Compute the Laplacian matrix of the graph G that has adjacency matrix A.
Parameters:
A ((N,N) ndarray): The adjacency matrix of an undirected graph G.
Returns:
L ((N,N) ndarray): The Laplacian matrix of G.
"""
m,n = np.shape(A)
D = np.zeros(n**2).reshape((n,n))
A_sums = A.sum(axis=1)
for i in range(n):
D[i,i] = A_sums[i]
return D - A
def connectivity(A, tol=1e-8):
"""Compute the number of connected components in the graph G and its
algebraic connectivity, given the adjacency matrix A of G.
Parameters:
A ((N,N) ndarray): The adjacency matrix of an undirected graph G.
tol (float): Eigenvalues that are less than this tolerance are
considered zero.
Returns:
(int): The number of connected components in G.
(float): the algebraic connectivity of G.
"""
lap = laplacian(A)
eigs = la.eig(lap)
real_eigvals = np.real(eigs[0])
count = 0
for i in range(len(np.real(eigs[0]))):
if abs(np.real(eigs[0])[i]) < tol:
count += 1
return count
def get_neighbors(index, radius, height, width):
"""Calculate the flattened indices of the pixels that are within the given
distance of a central pixel, and their distances from the central pixel.
Parameters:
index (int): The index of a central pixel in a flattened image array
with original shape (radius, height).
radius (float): Radius of the neighborhood around the central pixel.
height (int): The height of the original image in pixels.
width (int): The width of the original image in pixels.
Returns:
(1-D ndarray): the indices of the pixels that are within the specified
radius of the central pixel, with respect to the flattened image.
(1-D ndarray): the euclidean distances from the neighborhood pixels to
the central pixel.
"""
# Calculate the original 2-D coordinates of the central pixel.
row, col = index // width, index % width
# Get a grid of possible candidates that are close to the central pixel.
r = int(radius)
x = np.arange(max(col - r, 0), min(col + r + 1, width))
y = np.arange(max(row - r, 0), min(row + r + 1, height))
X, Y = np.meshgrid(x, y)
# Determine which candidates are within the given radius of the pixel.
R = np.sqrt(((X - col)**2 + (Y - row)**2))
mask = R < radius
return (X[mask] + Y[mask]*width).astype(np.int), R[mask]
class ImageSegmenter:
"""Class for storing and segmenting images."""
def __init__(self, filename):
"""Read the image file. Store its brightness values as a flat array."""
#Read image and scale for matplotlib
self.image = imread(filename)
self.scaled = self.image / 255
#Check if color, if so change to grayscale
if self.scaled.ndim == 3:
self.brightness = self.scaled.mean(axis = 2)
self.color = True
else:
self.brightness = self.scaled
self.color = False
#Unravel brightness into 1-D array
self.M,self.N = self.brightness.shape
self.flat_brightness = np.ravel(self.brightness)
#Ensure flat brightness is correct shape, store as attribute
if self.flat_brightness.size != self.M*self.N:
raise ValueError("Flat brightness incorrect shape!")
def show_original(self):
"""Display the original image."""
if self.color == True:
plt.imshow(self.image)
elif self.color == False:
plt.imshow(self.image, cmap="gray")
plt.axis("off")
plt.show()
def adjacency(self, r=5., sigma_B2=.02, sigma_X2=3.):
"""Compute the Adjacency and Degree matrices for the image graph."""
A = sparse.lil_matrix((self.M*self.N, self.M*self.N))
for i in range(self.M*self.N):
neighbors, distances = get_neighbors(i, r, self.M, self.N)
W = [np.exp(-1*abs(self.flat_brightness[i]-self.flat_brightness[neighbors[j]])/sigma_B2-abs(distances[j])/sigma_X2) for j in range(len(neighbors))]
A[i, neighbors] = W
D = np.array(A.sum(axis = 0))[0]
return A.tocsc(), D
def cut(self, A, D):
"""Compute the boolean mask that segments the image."""
lap = sparse.csgraph.laplacian(A)
D_12 = sparse.diags(1/np.sqrt(D))
DLD = D_12 @ lap @ D_12
eig_vals, eig_vecs = sparse.linalg.eigsh(DLD, which="SM", k=2)
X = eig_vecs[:,1].reshape(self.M,self.N)
mask = X > 0
return mask
def segment(self, r=5., sigma_B=.02, sigma_X=3.):
"""Display the original image and its segments."""
A, D = self.adjacency(r, sigma_B, sigma_X)
mask = self.cut(A,D)
if self.color:
mask = np.dstack((mask, mask, mask))
pos_image = self.image*mask
neg_image = self.image*~mask
ax1 = plt.subplot(131)
if self.color == False:
ax1.imshow(self.image, cmap = "gray")
plt.axis("off")
ax2 = plt.subplot(132)
ax2.imshow(pos_image, cmap = "gray")
plt.axis("off")
ax3 = plt.subplot(133)
ax3.imshow(neg_image, cmap = "gray")
plt.axis("off")
else:
ax1.imshow(self.image)
plt.axis("off")
ax2 = plt.subplot(132)
ax2.imshow(pos_image)
plt.axis("off")
ax3 = plt.subplot(133)
ax3.imshow(neg_image)
plt.axis("off")
plt.show()
|
db423a261bc85ce8a72d47119e1d7192add468d5 | starlight2100/Hello_World | /Notas01.py | 837 | 3.828125 | 4 | def help():
print("É necessário informar o valor da nota.")
print("Sintaxe: {0} <valor>".format(sys.argv[0]))
def nota(valor):
if 9.0 < valor <= 10.0:
return "A"
elif 8.0 < valor <= 9.0:
return "A-"
elif 7.0 < valor <= 8.0:
return "B"
elif 6.0 < valor <= 7.0:
return "B-"
elif 5.0 < valor <= 6.0:
return "C"
elif 4.0 < valor <= 5.0:
return "C-"
elif 3.0 < valor <= 4.0:
return "D"
elif 2.0 < valor <= 3.0:
return "D-"
elif 1.0 < valor <= 2.0:
return "E"
elif 0.0 < valor <= 1.0:
return "E-"
else:
return "Nota inválida"
if __name__ == '__main__':
if len(sys.argv) < 2:
help()
sys.exit(errno.EPERM)
else:
valor = float(sys.argv[1])
print(nota(valor))
|
acb135ee15d342ea5ebae556b7997e0ac4e530f8 | jaeehooon/data_structure_and_algorithm_python | /PART 1/ch05/5_class_and_static_decorator.py | 516 | 3.890625 | 4 | # 5.3.1 데코레이터 패턴
class A(object):
_hello = True # 클래스 변수
def foo(self, x):
print("foo ({0}, {1}) 실행".format(self, x))
@classmethod
def class_foo(cls, x):
print("class foo ({0}, {1}) 실행: {2}".format(cls, x, cls._hello))
@staticmethod
def static_foo(x):
print("static_foo ({0}) 실행".format(x))
if __name__ == '__main__':
a = A()
a.foo(1)
a.class_foo(2)
A.class_foo(2)
a.static_foo(3)
A.static_foo(3)
|
d596067cbecff2facf1035f6ab7cf3ac1113417b | juanprog97/Uva-Problems-Resolved | /UvaProblemResolved/chimp.py | 1,057 | 3.65625 | 4 | from sys import stdin
#Problem 10611 - The Playboy Chimp
def bSearchMax(Array, x):
N = len(Array)
ans = False
if N >= 1:
low, hi = 0, N
while Array[low]!= x and low + 1 != hi:
mid = low + ((hi-low)>>1)
if Array[mid] < x:
low = mid
else:
hi = mid
ans = Array[low]
return ans
def binSearchMin(Array,x):
N = len(Array)
ans = False
if N >= 1 :
low, hi = 0, N
while low + 1 != hi:
mid = low + ((hi-low)>>1)
if Array[mid] > x:
hi = mid
else:
low = mid
ans = Array[hi]
return ans
def solve(ladies, x):
ansMax, ansMin = 'X', 'X'
if ladies[0]<x and ladies[len(ladies)-1] > x:
ansMax = bSearchMax(ladies,x)
ansMin = binSearchMin(ladies,x)
elif ladies[0]<x:
ansMax = bSearchMax(ladies,x)
elif ladies[len(ladies)-1] > x:
ansMin = binSearchMin(ladies,x)
print(ansMax,ansMin)
def main():
inp = stdin
inp.readline()
ladies = [ int(x) for x in inp.readline().split() ]
inp.readline()
queries = [ int(x) for x in inp.readline().split() ]
for x in queries:
solve(ladies, x)
main()
|
3489367f57847471fb4e99c6f4b49d825fd78e41 | joshianshul2/Python | /classintro2.py | 212 | 3.5 | 4 | class Test:
def __init__(self,a,b):
self.a=a
self.b=b
def add(self,a,b):
c=self.a+self.b
return c
p=Test(10,20)
print(p.a)
print(p.b)
q=p.add(p.a,p.b)
print("sum =" ,q)
|
348d3e35c06cdfafd3d08a1f3501ca0fd91ee6f4 | jixinfeng/leetcode-soln | /python/057_insert_interval.py | 1,688 | 4 | 4 | """
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
"""
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
if intervals is None or intervals == []:
return [newInterval]
s = newInterval.start
e = newInterval.end
left = [interval for interval in intervals if interval.end < s]
right = [interval for interval in intervals if interval.start > e]
if len(left) + len(right) < len(intervals):
s = min(s, intervals[len(left)].start)
e = max(e, intervals[-1 - len(right)].end)
return left + [Interval(s, e)] + right
intervals = [Interval(*item) for item in [[1, 3], [6, 9]]]
assert [[interval.start, interval.end] for interval in Solution().insert(intervals, Interval(2, 5))] == [[1, 5], [6, 9]]
intervals = [Interval(*item) for item in [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]]
assert [[interval.start, interval.end] for interval in Solution().insert(intervals, Interval(4, 9))] == [[1, 2], [3, 10], [12, 16]]
|
428bcadd9fa328ea1156bdfe085fe131619ceb64 | mubaskid/new | /DAY1/MultiplicationTable.py | 109 | 3.78125 | 4 |
num = int(input('enter the number='))
i = 1
while i<=10:
print(num, 'x', i, '=', num / i)
i = i+1
|
5b6637dddd575bfb9f395456ac2fd6db8b75e9c4 | zakiay/hw | /ex29.py | 394 | 3.71875 | 4 | people = 20
cats = 30
dogs = 15
print "p: ", people
print "c: ", cats
print "d: ", dogs
if people < cats:
print "p < c"
if people > cats:
print "p > c."
if people < dogs:
print "p < d"
if people > dogs:
print "p > d"
dogs += 5
print
print "d: ", dogs
if people >= dogs:
print "p >= d"
if people <= dogs:
print "p <= d"
if people == dogs:
print "p == d"
if True:
print "\nTrue\n" |
99827ddcd65765ad558052f21f426ba05b86fece | James-Bedford/Python | /Real_Python_Part1/read_write.py | 3,426 | 4.5625 | 5 |
#opens and existing or creates a new file and writes text and closes it.
'''commneted out or just keeps rewriting all output
my_output_file = open("hello.txt","w")
my_output_file.writelines("This is file one")
my_output_file.close()
'''
#to just read the file
my_read_file = open("hello.txt","r")
print(my_read_file.readlines())
my_read_file.close()
#to add text to a an exisiting file - on a new line
my_output_file = open("hello.txt","a")
text_To_Add = ["\nNew line, new text"]
my_output_file.writelines(text_To_Add)
my_output_file.close()
#reads files and output each new line to a new line - , after print statement
#does this.
my_read_file = open("hello.txt","r")
for n in my_read_file.readlines():
print(n),
my_read_file.close()
#end function can be used to control end of line
#Here a double ne line is added
my_read_file = open("hello.txt","r")
for n in my_read_file.readlines():
print(n,end="\n\n")
my_read_file.close()
#Using with allows you not to have to use close()
#New file created and written to.
with open("hello.txt","r") as my_input, open("hi.txt","w") as my_output:
for n in my_input.readlines():
my_output.write(n)
#using seek()
my_input_file = open("hello.txt","r")
print ("Line 0(first line):",my_input_file.readline())
my_input_file.seek(0)
print ("Line 0 again:", my_input_file.readline())
print("Line 1:", my_input_file.readline())
my_input_file.seek(8) #jump to char at index 8
print("Line 0(starting at 9th character):",my_input_file.readline())
my_input_file.seek(10,0)
print("Line 0(starting at 11th character):",my_input_file.readline())
my_input_file.close()
#to change file paths and use fun like rmdir mkdir need to import os module
import os
path = "C:/Users/jbedford/Gazprom/Win_Python/WinPython-64bit-3.5.3.1Qt5/notebooks/work/Refresh"
win_Style_Path = r"C:\Users\jbedford\Gazprom\Win_Python\WinPython-64bit-3.5.3.1Qt5\notebooks\work\Refresh\doc_folder"
my_Input_File = os.path.join(path,"hello.txt")
with open(my_Input_File,"r")as file_reader:
for n in file_reader.readlines():
print(n)
import os
import shutil, os
#images file contains a number of different files formats and a set of sub folders
#program finds files and copies formats to crrect subdirectories
image_Path = "C:/Users/jbedford/Gazprom/Win_Python/WinPython-64bit-3.5.3.1Qt5/notebooks/work/Refresh/images/"
tiff_Path = "C:/Users/jbedford/Gazprom/Win_Python/WinPython-64bit-3.5.3.1Qt5/notebooks/work/Refresh/images/tiff/"
jpeg_Path = "C:/Users/jbedford/Gazprom/Win_Python/WinPython-64bit-3.5.3.1Qt5/notebooks/work/Refresh/images/jpeg/"
png_Path = "C:/Users/jbedford/Gazprom/Win_Python/WinPython-64bit-3.5.3.1Qt5/notebooks/work/Refresh/images/png"
#get list of images
file_Name_List = os.listdir(image_Path)
new_Name = "test_File.txt"
#loop over the files
for n in file_Name_List:
if n.lower().endswith(".tif"):
#How large is the file?
file_Size = os.path.getsize(image_Path+n)
print("File {0} is {1} bytes long".format(n,file_Size))
#need a method to copy/move
#shutil.copy(image_Path+n,jpeg_Path)5
#shutil.move(image_Path+n,jpeg_Path)
#now rename and chnage file type
#shutil.copy(image_Path+n,image_Path+new_Name)
#Delete file
#os.unlink(image_Path+new_Name)
|
37601fda113c8ebdcd1c305becfe95f714c48778 | v4s1levzy/practicum_1 | /50.py | 387 | 3.640625 | 4 | import random
import numpy
N = int(input("Количество элементов в массиве "))
A = [random.randint(-5, 5) for i in range(0, N)]
print(A)
S = 0
K = 0
L = 0
for i in range(N):
if A[i]%3 == 0:
S = S + 1
if A[i]%2 == 0:
K = K + 1
L = L + A[i]
F = L/K
A.append(F)
A.insert(0,S)
print(F)
print(S)
print(A)
|
7e3f66dd22574785a9a3a28e002f0bb547815231 | johnbomba/giz_db_lecture | /sql/select.py | 961 | 4.375 | 4 | import sqlite3
with sqlite3.connect('Ferrall.db') as connection: # REQUIRED
connection.row_factory = sqlite3.Row # this line gives you rows as dictionary like objects
cursor = connection.cursor() # REQUIRED
cursor.execute("SELECT * FROM william;") # for select you execute and then fetch
rows = cursor.fetchall()
for row in rows:
pass
#print(dict(row))
def get_movie(id):
with sqlite3.connect('Ferral.db') as connection:
cursor.execute("SELECT * FROM william WHERE id=?", (id,)) # (x,) is a single element tuple
return tuple(cursor.fetchone())
def get_by_info(movie, year):
with sqlite3.connect('Ferral.db') as connection:
query_data = {"movie": movie, "year": year}
cursor.execute("SELECT * FROM william WHERE movie=:movie AND year=:year", query_data) # (x,) is a single element tuple
return tuple(cursor.fetchone())
if __name__ == "__main__":
print(get_movie(8)) |
47ed80d511a6ff41f76919e78e61a819311c4db9 | stupidchen/leetcode | /src/leetcode/P3309.py | 1,781 | 3.515625 | 4 | class ListNode:
def __init__(self, key, val, next=None, last=None):
self.key = key
self.val = val
self.next = next
self.last = last
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.map = {}
self.capacity = capacity
self.head = ListNode(-1, -1)
self.tail = self.head
def _set_next_node(self, node, target):
if target.next == node:
return
tn = target.next
if tn:
tn.last = node
target.next = node
nn = node.next
if nn:
nn.last = node.last
else:
self.tail = node.last
node.last.next = nn
node.last = target
node.next = tn
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.map:
self._set_next_node(self.map[key], self.head)
return self.map[key].val
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self.map:
self._set_next_node(self.map[key], self.head)
self.map[key].val = value
else:
if self.capacity == 0:
self.capacity = 1
self.tail.last.next = None
del self.map[self.tail.key]
tmp = self.tail
self.tail = self.tail.last
del tmp
node = ListNode(key, value, last=self.tail)
self.map[key] = node
self.tail.next = node
self.tail = node
self._set_next_node(node, self.head)
self.capacity -= 1
|
8ce36154199991ce9581d06e7fb6c3d2875f81bd | VladimirNikel/Optimization-and-decision-making-methods | /laba7/decorators.py | 5,307 | 3.671875 | 4 | from time import sleep, time
from random import random
import string
def calc_duration(func):
"""
a decorator that outputs the execution time of a function
"""
def decorated(*args, **kwargs):
time_to_start = time()
result_func = func(*args, **kwargs)
time_to_finish = time()
print(f"elapsed time is about {time_to_finish-time_to_start} seconds")
return result_func
return decorated
@calc_duration
def long_executing_task(): # func(*args, **kwargs) ==== long_executing_task
for index in range(3):
print(f'Iteration {index + 1}')
sleep(random())
def suppress_errors(list_errors):
"""
a decorator that displays a message instead of an exception
"""
def decorator(func):
def decorated(*args, **kwargs):
try:
return func(*args, **kwargs)
except list_errors as err:
print(f"error: {err}")
return decorated
return decorator
@suppress_errors((
KeyError,
ValueError,
))
def potentially_unsafe_func(key: str):
print(f'Get data by the key {key}')
data = {'name': 'test', 'age': 30}
return data[key]
def result_between(value_min, value_max):
"""
decorator validating by minimum and maximum value
"""
def decorator(func):
def decorated(*args, **kwargs):
result = func(*args, **kwargs)
if value_min <= result <= value_max:
return result
else:
return ValueError
return decorated
return decorator
def len_more_than(s_len):
"""
decorator validating by length string
"""
def decorator(func):
def decorated(*args, **kwargs):
result_func = func(*args, **kwargs)
if len(result_func) >= s_len:
return result_func
else:
return ValueError
return decorated
return decorator
@result_between(0, 10)
def sum_of_values(numbers):
return sum(numbers)
@len_more_than(100)
def show_message(message: str) -> str:
return f'Hi, you sent: {message}'
def replace_commas(func):
"""
decorator that replaces punctuation marks with spaces
"""
def decorated(*args, **kwargs):
result_func = func(*args, **kwargs)
for i in list(string.punctuation):
result_func = result_func.replace(i, ' ')
return result_func
return decorated
def words_title(func):
"""
the decorator, in each word (a sequence of characters on both sides surrounded by a space),
makes the first and last letter uppercase
"""
def decorated(*args, **kwargs):
result_func = func(*args, **kwargs)
whitespace_positions = []
n = 0
for i in result_func:
if i == ' ':
whitespace_positions.append(n)
n += 1
list_result = list(result_func)
for i in range(whitespace_positions.__len__()):
if i == 0:
list_result[whitespace_positions[0] + 1] = str(list_result[whitespace_positions[0] + 1]).upper()
elif i == whitespace_positions.__len__() - 1:
list_result[whitespace_positions[whitespace_positions.__len__() - 1] - 1] = \
str(list_result[whitespace_positions[whitespace_positions.__len__() - 1] - 1]).upper()
else:
list_result[whitespace_positions[i] - 1] = str(list_result[whitespace_positions[i] - 1]).upper()
list_result[whitespace_positions[i] + 1] = str(list_result[whitespace_positions[i] + 1]).upper()
return ''.join(list_result)
return decorated
@words_title
@replace_commas
def process_text(text: str) -> str:
return text.replace(':', ',')
@replace_commas
@words_title
def another_process(text: str) -> str:
return text.replace(':', ',')
def cache_result():
"""
decorator-cache that stores the result of executing a function for the specified arguments and returns it
if the function is called again with a certain set of arguments.
"""
_cache_result = {}
def decorator(func):
def decorated(*args, **kwargs):
if args not in _cache_result:
_cache_result[args] = func(*args, **kwargs)
return _cache_result[args]
return decorated
return decorator
@cache_result()
def some_func(last_name, first_name, age):
return f'Hi {last_name} {first_name}, you are {age} years old'
if __name__ == '__main__':
long_executing_task() # print "elapsed time is about <> seconds"
print('\n')
print(potentially_unsafe_func('name')) # everything is ok
print(potentially_unsafe_func('last_name')) # error is silented
print('\n')
print(sum_of_values((1, 3, 5, 7))) # ValueError
print(show_message('Howdy, howdy my little friend')) # ValueError
print('\n')
print(process_text('the French revolution resulted in 3 concepts: freedom,equality,fraternity'))
print(another_process('the French revolution resulted in 3 concepts: freedom,equality,fraternity'))
print('\n')
print(some_func('shulyak', 'dmitry', 30)) # call
print(some_func('ivanov', 'ivan', 25)) # call
print(some_func('shulyak', 'dmitry', 30)) # cache
|
2871b26dbee59c0c3a6a1665f99bee381275d958 | yangbaoxi/dataProcessing | /python/字符串/监测字符串由什么字符组成/istitle.py | 357 | 3.828125 | 4 | # 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
# str.istitle()
# 返回值: 如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False.
str = "Hello World"
str2 = "Hello world"
print(str.istitle()) # True
print(str2.istitle()) # False |
5b5abcedc32f9fe5486ef99f4a895ae9992a3307 | ShalakaPawar/PPL-Assignment | /PPLAssign_Exception.py | 593 | 3.921875 | 4 | #Name: Shalaka Pawar
#Mis: 111903095
# Division: 2
# Program to raise an exception and handle it
# This program can be used to take integer input only
import sys
List1 = [ 'a', 0, 2 ]
for i in List1:
try:
print("Entered value = ", i)
reciprocal = 1/int(i)
except:
print("Error found - ", sys.exc_info()[0])
print("\nNext entry")
print("Reciprocal of number = ", reciprocal)
try:
integer = int(input("Enter a number : ")) # If user enters a non-integer value then this line will give ValueError
except:
print("Please enter an integer number only")
|
b26f65ec3a60d233e0eef93b56e7f0a9f472764a | kevin-fang/leetcode | /0130 Surrounded Regions.py | 1,042 | 3.53125 | 4 | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
bfs = deque()
for y in range(len(board)):
for x in range(len(board[0])):
if (y == 0 or y == len(board)-1 or x == 0 or x == len(board[0])-1) and board[y][x]=='O':
board[y][x] = 'M'
bfs.append([y,x])
while bfs:
y,x = bfs.popleft()
for dy, dx in [[1,0],[0,1],[-1,0],[0,-1]]:
ny, nx = y+dy, x+dx
if ny >= 0 and ny < len(board) and nx >= 0 and nx < len(board[0]) and board[ny][nx] == 'O':
board[ny][nx] = 'M'
bfs.append([ny,nx])
for y in range(len(board)):
for x in range(len(board[0])):
if board[y][x] == 'O': board[y][x] = 'X'
if board[y][x] == 'M': board[y][x] = 'O'
|
001e74da46c97baa79cb05928faac8e381aa75a7 | finnrj/python-proj | /py-euler/problem_045.py | 714 | 3.515625 | 4 | '''
Triangle, pentagonal, and hexagonal numbers are generated by the following
formulae:
Triangle : Tn=n(n+1)/2
1, 3, 6, 10, 15, ...
Pentagonal
Pn=n(3n−1)/2
1, 5, 12, 22, 35, ...
Hexagonal
Hn=n(2n−1)
1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
'''
from utilities.specialNumbers import generateFromLambda
if __name__ == '__main__':
pentas = set(list(generateFromLambda(lambda n: n * (3 * n - 1) // 2, 100000)))
hexas = set(list(generateFromLambda(lambda n: n * (2 * n - 1), 100000)))
print([i for i in pentas if i in hexas])
# pentas = set(list(generateFromLambda(lambda n: n*(3n-1)//2))
|
2730d5fea239ac8706092356d0fc21a4ec3e6f11 | ZheyuWalker/Leetcode-in-python | /Greedy/P452_minArrowShots.py | 1,416 | 3.84375 | 4 | # here are some spherical balloons taped onto a flat wall that represents the XY-plane.
# The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon
# whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.
#
# Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis.
# A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend.
# There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely,
# bursting any balloons in its path.
#
# Given the array points, return the minimum number of arrows that must be shot to burst all balloons.
from typing import List
def findMinArrowShots(points: List[List[int]]) -> int:
points.sort()
n = len(points)
if n == 1:
return 1
i = 1
left_bound, right_bound = points[0]
cnt = 0
while i < n:
if points[i][0] <= right_bound:
left_bound = points[i][0]
right_bound = min(right_bound, points[i][1])
i += 1
else:
cnt += 1
left_bound, right_bound = points[i]
return cnt + 1
if __name__ == '__main__':
points = [[9, 12], [1, 10], [4, 11], [8, 12], [3, 9], [6, 9], [6, 7]]
res = findMinArrowShots(points)
print(res)
|
5ab03380508fea09b83c24097b72a661d04b06d6 | POSYDON-code/POSYDON | /posydon/utils/configfile.py | 10,436 | 3.765625 | 4 | """Module for providing support for configuration files.
The ConfigClass loads, edits and saves configuration files in JSON format. The
data are encapsulated in a single dictionary mapping the variable names (keys)
to their values.
ConfigFile is an alternative to the `configparse` module in Python's standard
libray. While `configparser` can handle only string values and requires using
sections (as in .ini files), `ConfigFile` is simpler and faster to use, while
permits keys and values of any type that a Python dictionary permits.
As it relies on the Python `json` module, an internal function is called when
a values is not known to `json`, e.g. numpy arrays.
Finally, the function `parse_inifile` is defined to help reading .ini files.
Examples
--------
(1) Saving a dictionary:
D = {"username": "konstantinos",
"nodes": [1, 5, 3],
"memory": 1024,
"code": 42,
"std.out": "/data/output/std.out"}
config_file = ConfigFile("tmp.cfg")
config_file.update(D)
config_file.save()
OR
my_config_file = ConfigFile()
my_config_file.update(D)
my_config_file.save(filename)
(2) Loading and printing configuration:
config = ConfigFile(filename)
print("Loaded a config file with {} entries.".format(len(config)))
print("The code is", config["code"])
print(config)
(4) Altering entries (and creating if non-existing):
config["machine"] = "supercomputer"
config["code"] = 24
config["H0 and error"] = (67.8, 0.9)
(3) Loading configuration from multiple files:
config = CongfigFile("config1.json")
config.load("config2.json")
OR
config.load("config1.json")
config.load("config2.json")
If the two loaded configuration files have common keys, then an Exception
will occur. To allow updates, e.g. in the case of default configuration
and user configuration overriding the former, then:
config = ConfigFile("default.cfg")
config.load("user.cfg", can_update=True)
(5) Iterating entries:
config = ConfigFile("my_conf.json")
print("All configuration items:")
for key in config:
print(" {}: {}".format(key, config[key]))
print("Ok, I'll repeat that...:")
for key, value in config.items():
print(" {}: {}".format(key, value))
"""
__authors__ = [
"Konstantinos Kovlakas <Konstantinos.Kovlakas@unige.ch>",
"Scott Coughlin <scottcoughlin2014@u.northwestern.edu>",
"Jeffrey Andrews <jeffrey.andrews@northwestern.edu>",
]
import os
import copy
import numpy as np
import json
import ast
import configparser
import operator
class ConfigFile:
"""Class handling input, process and output of configurations."""
def __init__(self, path=None):
"""Initialize a ConfigFile with or without a path."""
self.entries = {}
self.path = path
if self.path is not None:
if os.path.exists(self.path):
self.load(path)
def deepcopy(self):
"""Make a deep copy of the object."""
newobj = ConfigFile()
newobj.path = copy.deepcopy(self.path)
newobj.entries = copy.deepcopy(self.entries)
return newobj
@staticmethod
def _serialize(data):
"""Serialize data of types unknown to Python's `json` module."""
if isinstance(data, np.ndarray):
return data.tolist()
def save(self, path=None, overwrite=True):
"""Save the configuration entries into a JSON file.
Parameters
----------
path : str or None
Where to save. If None, save to the path from the initialization.
overwrite : bool
If True, it will overwrite if the path exists.
"""
if path is None:
if self.path is None:
raise Exception("No path passed.")
path = self.path
if os.path.exists(path) and not overwrite:
raise Exception("JSON file not saved: overwrite not permitted.")
with open(path, "wt") as f:
json.dump(self.entries, f, sort_keys=True, indent=4,
ensure_ascii=True, default=self._serialize)
def load(self, path=None, can_update=False):
"""Load the entries from a JSON file containing a dictionary.
Parameters
----------
path : str or None
The path of the JSON file. If `None` it will use the path which
which the ConfigFile instance was initialized.
can_update : bool
If True, if a key already exists, it will get the new value.
If False, an Exception is thrown.
"""
if path is None:
if self.path is None:
raise Exception("No path passed.")
path = self.path
with open(path, "rt") as f:
new_entries = json.load(f)
if not can_update:
current_keys = set(self.entries.keys())
new_keys = set(new_entries.keys())
common = list(current_keys & new_keys)
if len(common) != 0:
raise Exception("Not allowed to update the entries {}".
format(common))
self.entries.update(new_entries)
def __getattr__(self, key):
"""Return the value of an entry."""
return self.entries[key]
def __getitem__(self, key):
"""Return the value of an entry."""
return self.entries[key]
def __setitem__(self, key, value):
"""Create new or updates an entry."""
self.entries[key] = value
def __delitem__(self, key):
"""Delete an entry by it's key."""
del self.entries[key]
def __iter__(self):
"""Allow the iteration of entries."""
return iter(self.entries)
def update(self, dictionary):
"""Create new or update entries from an external dictionary."""
self.entries.update(dictionary)
def keys(self):
"""Return the keys of the configuration dictionary."""
return self.entries.keys()
def values(self):
"""Return the values of the configuration dictionary."""
return self.entries.values()
def items(self):
"""Return (key, value) tuples of the configuration dictionary."""
return self.entries.items()
def __repr__(self):
"""Represent the configuration dictionary as a string."""
output_str = ''
for key, value in self.entries.items():
output_str = output_str + key + ": " + str(value) + "\n"
return output_str
def __contains__(self, item):
"""Search if a specific entry exists in the configuration."""
return item in self.entries
def __len__(self):
"""Return the number of configuration entries."""
return len(self.entries)
def parse_inifile(inifile):
"""Parse an inifile and return dicts of each section."""
binOps = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Mod: operator.mod
}
def arithmetic_eval(s):
"""Control how the strings from the inifile get parsed."""
node = ast.parse(s, mode='eval')
def _eval(node):
"""Different strings receive different evaluation."""
if isinstance(node, ast.Expression):
return _eval(node.body)
elif isinstance(node, ast.Str):
if ',' in node.s:
return node.s.replace(' ', '').split(',')
else:
return node.s
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.BinOp):
return binOps[type(node.op)](_eval(node.left),
_eval(node.right))
elif isinstance(node, ast.List):
return [_eval(x) for x in node.elts]
elif isinstance(node, ast.Name):
result = VariableKey(item=node)
constants_lookup = {
'True': True,
'False': False,
'None': None,
}
value = constants_lookup.get(result.name, result,)
if type(value) == VariableKey:
# return regular string
return value.name
else:
# return special string like True or False
return value
elif isinstance(node, ast.NameConstant):
# None, True, False are nameconstants in python3 but names in 2
return node.value
else:
raise Exception('Unsupported type {}'.format(node))
return _eval(node.body)
# ---- Create configuration-file-parser object and read parameters file.
cp = configparser.ConfigParser(
{'MESA_DIR': os.environ['MESA_DIR']},
interpolation=configparser.ExtendedInterpolation()
)
cp.read(inifile)
# ---- Read needed variables from the inifile
dictionary = {}
for section in cp.sections():
dictionary[section] = {}
for option in cp.options(section):
opt = cp.get(section, option)
try:
try:
dictionary[section][option] = arithmetic_eval(opt)
except Exception:
dictionary[section][option] = json.loads(opt)
except Exception:
if ',' in opt:
dictionary[section][option] = opt.replace(
' ', '').split(',')
else:
dictionary[section][option] = opt
run_parameters = dictionary['run_parameters']
mesa_inlists = dictionary['mesa_inlists']
mesa_extras = dictionary['mesa_extras']
slurm = dictionary['slurm']
return run_parameters, slurm, mesa_inlists, mesa_extras
class VariableKey(object):
"""A dictionary key which is a variable.
@ivar item: The variable AST object.
"""
def __init__(self, item):
"""Construct the object by giving a `name` to it."""
self.name = item.id
def __eq__(self, compare):
"""Equality if the names are the same."""
return (
compare.__class__ == self.__class__
and compare.name == self.name
)
def __hash__(self):
"""Allow hashing using the name of the variable."""
return hash(self.name)
|
eb7b37d089415c0132787510a0ff8cd33942e87c | vikashvishnu1508/algo | /Revision/Recursion/productSum.py | 632 | 4.21875 | 4 | # Tip: You can use the type(element) function to check whether an item
# is a list or an integer.
def productSum(array):
# Write your code here.
return getSum(array, 1)
def getSum(array, depth):
print(f"array = {array}")
productSum = 0
for curItem in array:
print(f"curItem = {curItem}, productSum = {productSum}")
if isinstance(curItem, list):
productSum += getSum(curItem, depth + 1)
print(f"is a list productSum = {productSum}")
else:
productSum += (depth * curItem)
print(f"else productSum = {productSum}")
return productSum
array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
print(productSum(array)) |
cd5569da7cdd8b25c6df07b59bf1e9b77ff32976 | avinnshrestha/csci102-week12-labAB | /csci102-week12-git.py | 1,679 | 3.546875 | 4 | #Avinn Shrestha
#CSCI 102 Section A
#Week 12 Part B
#1. PrintOutPut
def PrintOutput(statement):
print('OUTPUT', statement)
return statement
#PrintOutput('Hello World')
#2. LoadFile
def LoadFile(file):
f = open(file, 'r')
read_lines = f.readlines()
read_lines = list(map(lambda x:x.strip(),read_lines))
return read_lines
#3. UpdateString
def UpdateString(string1, string2, index):
list1 = []
for char in string1:
list1 += char
list1[index] = string2
print('OUTPUT', ''.join(list1))
#UpdateString('Hello World', 'a', 3)
#4. FindWordCount
def FindWordCount(list1, string1):
count = 0
list1 = (''.join(list1))
for string in list1:
if string == string1:
count += 1
print(count)
return count
FindWordCount(['cat', 'dogcat', 'caccacc'],'c')
'''Global Variables to test'''
players = ["Mary", "Cody", "Joe", "Jill", "Xai", "Bodo"]
players2 = ["Melvin", "Martian", "Baka", "Xai", "Cody"]
scores = [5, 8, 10, 6, 10, 4]
''''''
#5. ScoreFinder
def ScoreFinder(list1, list2, string1): #players, scores, name
if string1 in list1:
place = list1.index(string1)
score = list2[place]
print('OUTPUT ', string1, 'got a score of ', score)
else:
print('OUTPUT player not found')
#ScoreFinder(players,scores,'Jill')
#6. Union
def Union(list1,list2):
list3 = list1 + list2
print('OUTPUT', list3)
return list3
#Union(scores,players2)
#7. Intersection
def Intersection(list1, list2):
list3 = []
for string in list1:
if string in list2:
list3.append(string)
return list3
#print('OUTPUT', Intersection(players,players2))
|
19c9aa976a103e09239da3b1887b52bda3528377 | AmPoulami/Rock-Paper-Scissors | /game.py | 1,148 | 4.21875 | 4 | import random
user_wins=0
computer_wins=0
options=["rock","paper","scissors"]
while True:
user_input=input("Type rock/paper/scissors or Q/q to quit:")
if user_input=='q' or user_input=='Q':
break
if user_input not in options:
continue
random_num=random.randint(0,2)
computer_guess=options[random_num]
print("Computer picked",computer_guess)
if user_input=="rock" and computer_guess=="scissors":
print("You won!")
user_wins+=1
elif user_input=="paper" and computer_guess=="scissors":
print("You won!")
user_wins+=1
elif user_input=="scissors" and computer_guess=="paper":
print("You won!")
user_wins+=1
elif user_input==computer_guess:
print("Draw")
else:
print("Computer won!")
computer_wins+=1
if user_wins>computer_wins:
print("WINNER --> YOU !!")
print("Scoreboard")
print("YOU COMPUTER")
print(user_wins," ",computer_wins)
else:
print("WINNER --> COMPUTER !!")
print("Scoreboard")
print("YOU COMPUTER")
print(user_wins," ",computer_wins)
print("Goodbye!") |
c09d5b979322dc5048316f78cf219c62f2c4026c | urstkj/Python | /data_type/set.py | 1,218 | 3.828125 | 4 | #!/usr/local/bin/python
#-*- coding: utf-8 -*-
import random as random
Days = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
Months = {"Jan", "Feb", "Mar"}
Dates = {21, 22, 17}
print(Days)
print(Months)
print(Dates)
Days = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
for d in Days:
print(d)
Days = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"])
Days.add("Sun")
print(Days)
Days = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"])
Days.discard("Sun")
print(Days)
DaysA = set(["Mon", "Tue", "Wed"])
DaysB = set(["Wed", "Thu", "Fri", "Sat", "Sun"])
AllDays = DaysA | DaysB
print(AllDays)
DaysA = set(["Mon", "Tue", "Wed"])
DaysB = set(["Wed", "Thu", "Fri", "Sat", "Sun"])
AllDays = DaysA & DaysB
print(AllDays)
DaysA = set(["Mon", "Tue", "Wed"])
DaysB = set(["Wed", "Thu", "Fri", "Sat", "Sun"])
AllDays = DaysA - DaysB
print(AllDays)
DaysA = set(["Mon", "Tue", "Wed"])
DaysB = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)
a = set()
b = set()
for i in range(10):
a.add(random.randint(1, 10))
b.add(random.randint(1, 10))
print(a)
print(b)
print(a | b)
print(a - b)
print(a ^ b) |
22b1f4aa2fff7f309da8413da23fb2f4fe52d157 | kirankilva/Python_Games | /Number_Guessing_Game/guessNumber.py | 5,838 | 3.78125 | 4 | #Importing libraries
from tkinter import *
import random
from tkinter import messagebox as msg
#Code goes from here
class NumberGuess:
def __init__(self, root):
self.root = root
self.root.geometry('400x400+500+100')
self.root.title('Number Guessing Game')
#All variables
val = 0
self.num_var = IntVar()
self.chance_var = IntVar()
self.from_var = IntVar()
self.to_var = IntVar()
self.res_var = StringVar()
self.chance_var.set(5)
self.res_var.set('Hello User!..')
#Title
Label(self.root, text='NUMBER GUESSING GAME', width=30, height=1, font=('Times New Roman',15,'bold')).place(x=10, y=10)
#Enter the number label
num_lbl = Label(self.root, text='Enter the number : ', width=15, height=1, font=('Times New Roman',11))
num_lbl.place(x=25, y=100)
num_entry = Entry(self.root, width=10, background='white', bd=1, textvariable=self.num_var)
num_entry.place(x=145, y=103)
#Chances label
chance_lbl = Label(self.root, text='Chances left : ', width=15, height=1, font=('Times New Roman',11))
chance_lbl.place(x=35, y=160)
chance_entry = Entry(self.root, width=10, background='white', bd=1, textvariable=self.chance_var)
chance_entry.place(x=145, y=163)
#Result label
res_lbl = Label(self.root, text='Result will appear here : ', width=20, height=1, font=('Times New Roman',11))
res_lbl.place(x=20, y=220)
res_entry = Entry(self.root, width=55, background='white', bd=1, textvariable=self.res_var)
res_entry.place(x=30, y=245)
#Range from
from_lbl = Label(self.root, text='From : ', width=5, height=1, font=('Times New Roman',11))
from_lbl.place(x=250, y=100)
from_entry = Entry(self.root, width=10, background='white', bd=1, textvariable=self.from_var)
from_entry.place(x=300, y=103)
#Range to
to_lbl = Label(self.root, text='To : ', width=5, height=1, font=('Times New Roman',11))
to_lbl.place(x=255, y=160)
to_entry = Entry(self.root, width=10, background='white', bd=1, textvariable=self.to_var)
to_entry.place(x=300, y=163)
#Designer
Label(self.root, text="designed by", fg="grey").place(x=170, y=360)
Label(self.root, text="KIRAN KILVA", font="Helvetica 10").place(x=165, y=378)
#buttons
#Start button
start_btn = Button(self.root, text='S T A R T', width=10, bd=1, bg='orange', activebackground='orange', fg='white', activeforeground='black', font=('',9,'bold'), cursor='hand2', command=self.start_func)
start_btn.place(x=30, y=300)
#Reset button
reset_btn = Button(self.root, text='R E S E T', width=10, bd=1, bg='blue', activebackground='blue', fg='white', activeforeground='black', font=('',9,'bold'), cursor='hand2', command=self.reset_func)
reset_btn.place(x=115, y=300)
#Guess button
guess_btn = Button(self.root, text='G U E S S', width=10, bd=1, bg='green', activebackground='green', fg='white', activeforeground='black', font=('',9,'bold'), cursor='hand2', command=self.guess_func)
guess_btn.place(x=200, y=300)
#Clear button
clear_btn = Button(self.root, text='E X I T', width=10, bd=1, bg='grey', activebackground='grey', fg='white', activeforeground='black', font=('',9,'bold'), cursor='hand2', command=self.exit_func)
clear_btn.place(x=285, y=300)
#Start button function
def start_func(self):
try:
if (self.from_var.get() == 0 and self.to_var.get() == 0) or (self.from_var.get() == '' and self.to_var.get() == ''):
msg.showwarning('Warning', 'Please select the range.')
else:
self.res_var.set(f'Guess the Number between {self.from_var.get()} and {self.to_var.get()}')
global val
num = random.randint(self.from_var.get(), self.to_var.get())
val = num
except:
msg.showerror('ERROR', 'Invalid Entries. Please try again')
#Reset button function
def reset_func(self):
self.num_var.set(0)
self.chance_var.set(5)
self.from_var.set(0)
self.to_var.set(0)
self.res_var.set('Hello User!..')
#Guess button function
def guess_func(self):
if self.res_var.get() == 'Hello User!..':
msg.showwarning('WARNING', 'Please click the START button')
else:
if self.num_var.get() > val:
self.res_var.set(f'Wrong!. {self.num_var.get()} is Greater than the Number')
elif self.num_var.get() < val:
self.res_var.set(f'Wrong!. {self.num_var.get()} is Less than the Number')
else:
self.res_var.set('Congragulations!.. You WON the game')
ans = msg.askquestion('Congragulations', 'You Won the game!!\nDo you want to play again?')
if ans == 'yes':
self.reset_func()
self.chance_var.set(self.chance_var.get()+1)
else:
self.root.destroy()
self.chance_var.set(self.chance_var.get()-1)
if self.chance_var.get() == 0:
msg.showinfo('BETTER LUCK NEXT TIME', 'Sorry!! You Lost The Game')
self.reset_func()
#Exit button function
def exit_func(self):
ask = msg.askquestion('EXIT', 'Do you really want to exit the game?')
if ask == 'yes':
self.root.destroy()
root = Tk()
obj = NumberGuess(root)
root.mainloop()
|
318713915501e20b9b3873caf4caa93835b7f328 | utopfish/LeetCodeCamp | /python/sword2offer/o45minNumber.py | 736 | 3.65625 | 4 | #@Time:2020/9/9 16:56
#@Author:liuAmon
#@e-mail:utopfish@163.com
#@File:o45minNumber.py
__author__ = "liuAmon"
from typing import List
class Solution:
def minNumber(self, nums: List[int]) -> str:
def sort(arr):
if len(arr)<2:
return arr
pivot=arr[0]
less=[]
greater=[]
for i in arr[1:]:
if (i+pivot)<(pivot+i):
less.append(i)
else:
greater.append(i)
return sort(less)+[pivot]+sort(greater)
nums=[str(i) for i in nums]
res=sort(nums)
return "".join(res)
if __name__=="__main__":
input=[3,30,34,5,9]
s=Solution()
print(s.minNumber(input)) |
d2da49ec9de7a0808fe061df66391a1c203265ae | anjaligr05/TechInterviews | /grokking_algorithms/bfs.py | 630 | 3.515625 | 4 | from collections import deque
graph = {}
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['bob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jonny']
graph['anuj'] = []
graph['peggy'] = []
graph['thom'] = []
graph['jonny'] = []
def personIsSeller(person):
if person[-1]=='m':
return True
else:
return False
search_queue = []
search_queue += graph['you']
flag = 0
while search_queue:
person = search_queue.pop()
if personIsSeller(person):
flag = 1
print(('person {} is seller').format(person))
else:
search_queue += graph[person]
if flag == 0:
print 'Not a mango seller'
|
7e1a5bbc5d7f5ba29e6a8cd10ba3622e4ac5ed3d | samirettali/project-euler | /64.py | 529 | 3.5625 | 4 | #!/usr/bin/env python3
from math import sqrt, floor
def get_period(n):
limit = sqrt(n)
a = int(limit)
period = 0.0
if a * a != n:
d = 1.0
m = 0.0
while a != 2 * int(limit):
m = d * a - m
d = (n - m * m) / d
a = int((limit + m) / d)
period += 1
return period
def main():
result = 0
for n in range(2, 10000):
if get_period(n) % 2 == 1:
result += 1
print(result)
if __name__ == '__main__':
main()
|
263ed37a2ea79d4ef6f363e5d4a020bcc7be9272 | Ekaterina-sol/Python_Basics | /hw4/hw4_7.py | 193 | 3.96875 | 4 | import math
n = int(input("Введите число n: "))
def fact(n):
for number in range (1, n+1):
yield number
for el in fact(n):
print(f"{el}! = {math.factorial(el)}")
|
cad95f5afa5ad52c030c25e320aad47c66f8c758 | akshay-591/ML-Code | /Python/Unsupervised-ML/K_mean/InitCentroids.py | 1,853 | 3.828125 | 4 | # this file contain method which will initialize centroids randomly
from random import random
import numpy as mat
def getCentroids(X, numCentroids):
"""
This Method Returns Centroids by choosing them Randomly from The Given data.
:param X: Unlabelled Data.
:param numCentroids: Number of Centroids user wants.
:return: randomly chosen Centroids.
"""
centroids = mat.zeros((numCentroids, X.shape[1]))
ind = mat.arange(X.shape[0])
mat.random.shuffle(ind)
centroids = X[ind[0:numCentroids],:]
return centroids
def calibrate(X, indexes, numCentroids):
"""
This Methods Calibrate the Centroids and find the new ones.
:param X: Unlabelled Data
:param indexes: indexes of Centroids which each Data example belongs to, They can be found using findNearest()
Method.
:param numCentroids: Number of Centroids.
:return: new Updated Centroids
"""
centroids = mat.zeros((numCentroids, X.shape[1]))
for i in range(numCentroids):
ind = mat.where(indexes == i)[0]
centroids[i, :] = mat.mean(X[mat.ix_(ind)], axis=0)
return centroids
def findNearest(X, centroids):
"""
This methods find the minimum distance and Indexes for each Data example w.r.t Centroids and
:param X: Unlabeled Data Example
:param centroids: Centroids/
:return: Array of Minimum Distance and Array of centroids Index.
"""
temp = mat.zeros((X.shape[0], centroids.shape[0]))
for i in range(centroids.shape[0]):
distance = mat.subtract(X, centroids[i, :])
square_distance = mat.power(distance, 2)
square_distance = mat.sum(square_distance, axis=1)
temp[:, i] = square_distance
min_distance = mat.min(temp, axis=1)
min_distance_index = mat.argmin(temp, axis=1)
return min_distance, min_distance_index
|
7664a81254409ca3b6b2e2c11a4c39b99e6cfa3d | Protectorofcode/GeekBrains | /Python. Basics/7_ООП. Продвинутый уровень/task_1.py | 1,190 | 4.09375 | 4 | # Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод __init__()),
# который должен принимать данные (список списков) для формирования матрицы.
class Matrix:
def __init__(self, input_data):
self.input = input_data
def __str__(self):
return str('\n'.join([' '.join(map(str, line)) for line in self.input])) + '\n'
def __add__(self, other):
result = ''
if len(self.input) == len(other.input):
for line_1,line_2 in zip(self.input, other.input):
if len(line_1) == len(line_2):
sum = [i + j for i, j in zip(line_1, line_2)]
result += ' '.join(map(str, sum)) + '\n'
else:
return 'Проблемы с размерностями'
else:
return 'Проблемы с размерностями'
return result
matrix_1 = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_2 = Matrix([[9, 8, 7], [6, 5, 84], [3, 21, 1]])
print(matrix_1)
print(matrix_1 + matrix_2) |
99841b5ed0e69f80891b7ca773cbc3b7e94171e5 | ShashiMogalla/zyx | /assignment2.py | 1,190 | 3.90625 | 4 | # assignment-2 on pandas
#Import Python Libraries
import numpy as np
import pandas as pd
# reading a file
#import the data by Reading from csv file
df = pd.read_csv("C:/Users/user/Desktop/python learning/JNTUK/50_Startups.csv")
df.head()
df.columns
df.shape
# slicing first 15 rows into data1
data1=df[:15]
data1.shape
#administration column only
admin=df['Administration']
admin.head()
# c) Finding min, max, head, tail, dtypes values of Administration column.
admin.min()
admin.max()
admin.head()
admin.tail()
# Slicing 2 & 3 columns of the data frame and store it into another variable.
data2=df.iloc[:, 2:4]
data2.head()
data2.tail()
'''
Find out the aggregations like mean, median,variance and standard deviation
for first 20 rows of profit column
'''
profit_col=df.iloc[:20,4:5]
profit_col.head()
profit_col.tail()
profit_col.median()
profit_col.mean()
profit_col.std()
#Find out the profit median for different states.Use groupby function
df_state = df.groupby(['State'])
df_state['Profit'].median()
#Filter out the rows from dataframe where R&D Spend is more than 50,000
sel_rows=df[df['R&D Spend']>50000]
sel_rows.shape
sel_rows.head()
|
c734c6eadbeac58df1232bd36b19c647fce1e0d0 | uclaacmai/tensorflow-examples | /tensorboard.py | 3,655 | 3.859375 | 4 | '''
Tensorboard visualization for a basic MNIST classifier
from https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/4_Utils/tensorboard_basic.py
'''
from __future__ import print_function
import tensorflow as tf
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Parameters
learning_rate = 0.01
training_epochs = 1
batch_size = 100
display_step = 1
logs_path = '/tmp/tensorflow_logs/example'
x = tf.placeholder(tf.float32, [None, 784], name='x-data')
# 0-9 digits recognition => 10 classes
y = tf.placeholder(tf.float32, [None, 10], name='y-data')
# Set model weights
def weight_variable(shape, name = 'weights'):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name = name)
def bias_variable(shape, name = 'bias'):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial, name = name)
W, b = weight_variable([784, 10]), bias_variable([10])
with tf.name_scope('Model'):
W_1, b_1 = weight_variable([784, 100], name = 'weights-1'), bias_variable([100], name = 'bias-1')
with tf.name_scope('FC-layer-1'):
act_fc_1 = tf.nn.relu(tf.matmul(x, W_1) + b_1, name = 'hidden-layer-activations')
with tf.name_scope('Softmax-layer'):
W_2, b_2 = weight_variable([100, 10], name = 'weights-2'), bias_variable([10], name = 'bias-2')
pred = tf.nn.softmax(tf.matmul(act_fc_1, W_2) + b_2, name = 'softmax-predictions')
with tf.name_scope('Loss'):
# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
with tf.name_scope('SGD'):
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
with tf.name_scope('Accuracy'):
# Accuracy
acc = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
acc = tf.reduce_mean(tf.cast(acc, tf.float32))
# Initializing the variables
init = tf.global_variables_initializer()
# Create a summary to monitor cost tensor
tf.summary.scalar("loss", cost)
# Create a summary to monitor accuracy tensor
tf.summary.scalar("accuracy", acc)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# op to write logs to Tensorboard
summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop), cost op (to get loss value)
# and summary nodes
_, c, summary = sess.run([optimizer, cost, merged_summary_op],
feed_dict={x: batch_xs, y: batch_ys})
# Write logs at every iteration
summary_writer.add_summary(summary, epoch * total_batch + i)
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model
# Calculate accuracy
print("Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels}))
print("Run the command line:\n" \
"--> tensorboard --logdir=/tmp/tensorflow_logs/examples " \
"\nThen open up localhost:6006")
|
c4fcd9c37ab80636ea66e77cd824ce19c1073bf9 | Natacha7/Python | /Funcion/Operacion_funciones.py | 617 | 4 | 4 | # Función que realiza la suma de dos números
def sumar(a, b):
s = a + b
return s
def resta(a, b):
r = a - b
return r
def multiplica(a, b):
m= a * b
return m
def division(a, b):
d= a / b
return d
# Aquí inicia la aplicación
numero1 = int(input("Digite el primer numero: "))
numero2 = int(input("Digite el segunfo numero: "))
suma = sumar(numero1, numero2)
restar = resta(numero1, numero2)
multiplicar = multiplica(numero1, numero2)
dividir = division(numero1, numero2)
print("a + b =" , suma)
print("a - b=", restar)
print("a * b=", multiplicar)
print("a / b=", dividir)
|
c13b90590644cff93e6c7887d71aea9520ca3d45 | akimi-yano/algorithm-practice | /lc/152.MaximumProductSubarray.py | 2,516 | 3.828125 | 4 | # 152. Maximum Product Subarray
# Medium
# 4898
# 172
# Add to List
# Share
# Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
# Example 1:
# Input: [2,3,-2,4]
# Output: 6
# Explanation: [2,3] has the largest product 6.
# Example 2:
# Input: [-2,0,-1]
# Output: 0
# Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
class Solution:
# def maxProduct(self, nums: List[int]) -> int:
# min_so_far = max_so_far = best = nums[0]
# for num in nums[1:]:
# min_so_far, max_so_far = min(num, min_so_far * num, max_so_far * num), max(num, min_so_far * num, max_so_far * num)
# best = max(best, max_so_far)
# return best
def maxProduct(self, nums: List[int]) -> int:
minprod = maxprod = best = nums[0]
for i in range(1,len(nums)):
if nums[i]<0:
minprod,maxprod = maxprod,minprod
maxprod = max(maxprod*nums[i],nums[i])
minprod = min(minprod*nums[i],nums[i])
best = max(best,maxprod)
return best
class Solution:
def maxProduct(self, nums: List[int]) -> int:
# initialize the max,min,best to as the first elem in the arr
max_prod = min_prod = best = nums[0]
# skip the first elem as we already checked in the prevous step
for i in range(1,len(nums)):
# compare and get the global max and min - could be previous one * cur_num or just cur_num
max_prod, min_prod = max(max_prod*nums[i], nums[i],min_prod*nums[i]), min(min_prod*nums[i], nums[i],max_prod*nums[i])
# compare best with max
best = max(best, max_prod)
return best
# More intuitive way
class Solution:
def maxProduct(self, nums: List[int]) -> int:
'''
2 paths solution
reset cur to 1 if I get 0
if its negative, keep going
there are only 2 patterns and 1 generic one:
[xxxooo]
[oooxxx]
[oooooo] (generic one)
'''
best = nums[0]
cur = 1
for i in range(len(nums)):
cur *= nums[i]
best = max(best, cur)
if cur == 0:
cur = 1
cur = 1
for k in range(len(nums)-1,-1,-1):
cur*=nums[k]
best = max(best,cur)
if cur == 0:
cur = 1
return best
|
82b64c5827c8897683f46a34a84305a292461a1a | roganovich/mypython | /index.py | 1,940 | 4.15625 | 4 | # пример создания строки
string = 'My first pynhon string'
print(string) #выводим на экран
# 0 элемент массива. строка это массив
first_e = string[0]
print(first_e) #выводим на экран
# c 3 по 7 элемент массива.
first_e = string[3:7]
print(first_e)
# выполняем сложение
a=1
b=6
print(a+b)
# выполняем разбор строки на элементы массива
spisok = list('spisok')
print(spisok)
#обновление элемента массива по его индексу
arr = [111, 222, '333', '444', 555, 666]
print(arr[5])
arr[5]=777
print(arr[5])
#развернуть массив в обратном порядке
print(arr)
arr.reverse()
print(arr)
#сортировка массива.... только один тип в массиве!!!!!!
arr=[5,6,2,3,6,8,9]
print(arr)
arr.sort()
print(arr)
#сортировка массива.... только один тип в массиве!!!!!!
arr=['55','124','88','99','1']
print(arr)
arr.sort()
print(arr)
#найти индекс элемента массива по значению
a = arr.index('55')
print(a)
#очистить значение переменной
#a.clear()
#print(a)
#добавить элемент в список
arr=['55','124','88','99','1']
arr.append(99999999)
print(arr)
#добавить элемент из списка по значению
arr.remove('124')
print(arr)
#ассоциативные массивы
pre = {'name':'ira','lasetame':'pleshakova'}
print(pre)
#добавляем элементы по имени ключа
pre['age']=[1988]
pre['sex']='female'
print(pre)
#сравнить размер списка и массива
list=(1,2,3)
array=[1,2,3]
print(list.__sizeof__())
print(array.__sizeof__())
#полностью удалить из памяти переменную
del list |
23daef9e54bb04c88432bfffd470c7bf2b57562c | mottaquikarim/pydev-psets | /pset_functions/data_manipulation/p2.py | 410 | 3.984375 | 4 | """
Clean Pairs
"""
# Below is a list of common food pairings. Write a function called "cleaner" that cleans the data such that each list item is a tuple (e.g. ('Milk', 'Cookies')). Assign the results to a variable called "clean_pairs".
pairs = [('Milk', 'Cookies'), ('Peanut Butter - Jelly'), ('Spaghetti & Meatballs'), ('Eggs', 'Bacon'), ('Pancakes & Syrup'), ('Chicken - Waffles'), ('Peas', 'Carrots')]
|
3089ad1a5c03fa77d7c54a84748a35e24c5e6db3 | awesome-liuxiao/leetcodesolution | /53_maxSubarr.py | 481 | 3.578125 | 4 | from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) == 0:
return
res = float('-inf')
out = res
for num in nums:
out = max(out+num, num)
res = max(out, res)
# print(res)
return res
x = Solution()
nums = [-2,1,-3,4,-1,2,1,-5,4]
x.maxSubArray(nums)
nums = []
x.maxSubArray(nums)
nums = [1]
x.maxSubArray(nums)
nums = [1,2]
x.maxSubArray(nums) |
81c1d992a9edc275c0c8aa3784fcfbc5ea928190 | farzinnasiri/network-assignments | /p4/heartbeat.py | 3,410 | 3.578125 | 4 | import sys
import time
import random
from socket import *
'''
run the command: "python heartbeat.py server" to run the server
run the command: "python heartbeat.py client" to run the client
default port number is 8000
'''
def main():
arg = sys.argv[1]
if arg == "server":
server = Server(8000, 'localhost')
server.run()
elif arg == "client":
client = Client(8000, 'localhost')
client.run()
else:
print("Command not found...")
class Client:
def __init__(self, port, host):
self.port = port
self.host = host
def run(self):
client_socket = socket(AF_INET, SOCK_DGRAM)
print("Client is running on", self.host, ":", self.port)
seq_num = 0
while True:
chance = random.randint(0, 10)
# dropping packets with 30 percent chance
if chance > 3:
# creating and sending heart beat messages
message = "BOOM" + " " + str(seq_num) + " " + str(time.time())
client_socket.sendto(message.encode('utf-8'), (self.host, self.port))
print(message)
# increasing sequence numbers
seq_num += 1
time.sleep(0.5)
class Server:
def __init__(self, port, host):
self.port = port
self.host = host
def run(self):
server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind((self.host, self.port))
# if no heartbeat came for 2 seconds then the client is dead!
server_socket.settimeout(2)
server_seq_num = 0
print("Server is running on", self.host, ":", self.port)
# listening for heartbeats
while True:
try:
message, addr = server_socket.recvfrom(1024)
# parsing the payload
_, seq_num, time_stamp = message.decode().split()
seq_num = int(seq_num)
# calculating trip time
delta = round(time.time() * 1000000) - round(float(time_stamp) * 1000000)
# deciding packet loss has happen or not
if server_seq_num == 0:
server_seq_num = seq_num
elif server_seq_num != seq_num:
# packet or packets are lost
diff = seq_num - server_seq_num
if diff == 1:
print("Packet number", server_seq_num, " is lost")
else:
print("Packets with numbers: ",
" ".join([str(packet) for packet in range(server_seq_num, seq_num)]), "are lost")
# increasing server side sequence number to be the same as the client
server_seq_num = seq_num + 1
print("Packet number", server_seq_num - 1, "was delivered in", delta, "\u03BCs")
continue
if server_seq_num == seq_num:
# no packet loss
print("Packet number", server_seq_num, "was delivered in", delta, "\u03BCs")
server_seq_num += 1
except timeout:
# client might not have started yet or is dead
if server_seq_num == 0:
continue
print("Client has stopped working")
if __name__ == '__main__':
main()
|
f4f01f61e2a2f174117ceafc7b7ee13a05fe1f0f | HOJIN-LIM/Capston-design7-LOL | /checkbox.py | 414 | 3.5 | 4 | from tkinter import *
root =Tk()
root.title("nadu coding")
chkvar=IntVar()
chkbox=Checkbutton(root,text="오늘하루보지않기", variable=chkvar)
chkbox.pack()
chkvar2=IntVar()
chkbox2=Checkbutton(root,text="일주일동안 보지않기", variable=chkvar2)
chkbox2.pack()
def btncmd():
print(chkvar.get())
btn=Button(root, text="클릭", command=btncmd)
btn.pack()
root.mainloop()
|
649a0c09c58e07dd63a40d2d8527d328e63c6f18 | alonana/top | /python/2020/iterate_over_cube.py | 986 | 3.546875 | 4 | from python.test_utils import test_solution, assert_equals, get_ints
def increment(position, located_sum):
non_zero = 0
for i in range(2, -1, -1):
if position[i] != 0:
non_zero = i
break
def find_cell(n, index):
total_cubes = 0
located_sum = 0
prev_total = 0
for s in range(3 * n):
a = (s + 1) * (s + 2) // 2
prev_total = total_cubes
total_cubes += a
if total_cubes > index:
located_sum = s
break
offset = index - prev_total
print("located sum", located_sum, "offset", offset)
position = [0, 0, located_sum]
for i in range(offset):
increment(position, located_sum)
return located_sum
def run_line(match):
n = int(match.group(1))
index = int(match.group(2))
expected = get_ints(match.group(3))
actual = find_cell(n, index)
assert_equals(actual, expected)
test_solution(__file__, '(\\d+), (\\d+)\\s+{(.*)}', run_line)
|
941ae20e99ba7d133cd26ea6b92c795d6d21530e | LeBron-Jian/BasicAlgorithmPractice | /剑指offer/PythonVersion/30_包含 min函数的栈.py | 2,500 | 4.03125 | 4 | #_*_coding:utf-8_*_
'''
题目:
剑指offer 30 包含 min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,
调用 min, push以pop的时间复杂度都是O(1)
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
'''
class MinStack:
'''
普通栈的push() 和 pop() 函数的复杂度为O(1) 而获取栈最小值 min()
函数需要遍历整个栈,复杂度为O(n)
难点: 将 min() 函数复杂度降为O(1),可通过建立辅助栈实现
复杂度分析:
时间复杂度O(1)
空间复杂度O(n)
'''
def __init__(self):
"""
initialize your data structure here.
"""
self.main_stack = []
self.aux_stack = []
def push(self, x: int) -> None:
'''
push(x) 终点为保持辅助栈的元素是非严格降序
将x压入栈A
若1栈B为空 或2 x 小于等于栈B的栈顶元素,则将x 压入栈B
'''
if len(self.main_stack) == 0:
self.main_stack.append(x)
self.aux_stack.append(x)
else:
self.main_stack.append(x)
last_value = self.aux_stack[-1]
if last_value > x:
self.aux_stack.append(x)
else:
self.aux_stack.append(last_value)
def pop(self) -> None:
'''
重点为保持栈A,B元素一致性
即同时保持栈A,栈B出栈
'''
if not self.main_stack:
return None
self.aux_stack.pop()
self.main_stack.pop()
def top(self) -> int:
'''
直接返回主栈或者辅栈的栈顶元素
'''
if not self.main_stack:
return None
return self.main_stack[-1]
def min(self) -> int:
'''
直接返回辅助栈的栈顶元素
'''
if not self.aux_stack:
return None
return self.aux_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
|
ed6a720fe9665f556760b68af4d22cef3a8e5d6d | wwg377655460/DataStructureToLeetCode | /problem_203.py | 1,273 | 3.890625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def createLinkedList(arr, n):
if n == 0:
return None
head = ListNode(arr[0])
cur = head
for num in arr[1:]:
cur.next = ListNode(num)
cur = cur.next
return head
def printLinkedList(head):
cur = head
while cur is not None:
print(str(cur.val) + "->", end='')
cur = cur.next
print("NULL")
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummyHead = ListNode(0)
dummyHead.next = head
cur = dummyHead
while cur.next is not None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummyHead.next
# solution = Solution()
# nums1 = [1,2,2,1]
# nums2 = [2,2]
# res = solution.intersect(nums1, nums2)
# print(res)
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5]
n = len(arr)
head = createLinkedList(arr, n)
printLinkedList(head)
solution = Solution()
head = solution.removeElements(head, 3)
printLinkedList(head)
|
d29b72dea2e974850eb926a74a2a26d89ae2332b | Hoshitter1/Python | /Class/magic_methods/boolean_object.py | 728 | 3.921875 | 4 | class MyList:
def __init__(self, length):
self.length = length
def __len__(self):
"""
if bool is not implemented when bool is called,
python will look for len instead.
"""
print('len called')
return self.length
def __bool__(self):
print('bool called')
return self.length > 0
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __bool__(self):
return bool(self.x or self.y)
if __name__ == '__main__':
ml = MyList(1)
print(bool(ml))
p1 = Point(0, 0)
print(f'p1: {bool(p1)}')
p2 = Point(1, 1)
print(f'p2: {bool(p2)}')
p3 = Point(0, 1)
print(f'p3: {bool(p3)}')
|
e037486dbeaf6785a1ad0931131c134922de2b66 | pawarspeaks/HacktoberFest_2021 | /python/url_shortener.py | 124 | 3.53125 | 4 | import pyshorteners
url=input("Enter URL :\n")
print("URL after Shortening:",pyshorteners.Shortener().tinyurl.short(url))
|
0dda15b0eccfe4b005240fefed9dd50e30788588 | prasannamadina/sum-of-two-numbers | /sum of two numbers.py | 181 | 4.25 | 4 | # To add two numbers and find their sum
number1 = int(input('Number1: '))
number2 = int(input('Number2: '))
sum = (number1 + number2)
print('The sum of the numbers is: ', sum)
|
60c9df0da60cf86274b48c3a54c5919b0f676529 | k018c1052/kadai | /Exam08/Exam-8_2.py | 111 | 3.609375 | 4 | num = int(input('入力>'))
if num % 2 == 0:
print('偶数')
pass
else:
print('奇数')
pass |
24e42846f773b83edf4be28b3816767b443360eb | alamaison/gander | /gander/test/uk/ac/ic/doc/gander/flowinference/python_test_code/type_engine/inherited_method.py | 317 | 3.65625 | 4 | class A:
def n(self):
pass
class B(A):
def m(self):
pass
class C(B):
def __init__(self):
print "I inherit m from my parent"
class D(C):
def __init__(self):
print "I inherit m from my grandparent"
c = C()
print c.m # what_am_i_parent
d = D()
print d.m # what_am_i_grandparent
|
6737c267ce505cb319f262baf86cd0a939e17b13 | elif-tr/Python-Work | /Kaya_Elif_PA_3.py | 5,514 | 4.0625 | 4 | '''
Created on Feb 15, 2020
@author: Elif_Kaya_HW12 Kaya
Create an order summary matrix to calculate the number of orders for each day in the given interval amount from the user
'''
#Import necessary libraries
import orderlog
import datetime
#Define constants
STARTMIN = 60*6
ORDERS = orderlog.orderlst
CLOSING_MIN = 22 * 60
WEEK_DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
#Define the function for interval labels
def labelString(interval, startmin, duration):
'''
produces a string label with begin-end times of an interval
:param interval: will calculate the interval where the order summary falls on,
:param startmin: is the opening hour in minutes
:param duration: is the interval minutes entered by the user
:return: returns interval as string
'''
#Calculate the start time of the interval
interval_start = startmin + (duration * interval)
interval_end = interval_start + duration -1
#Get the start time in hours and minutes
start_hour = interval_start // 60
start_min = interval_start % 60
int_beginning = str(start_hour) + ":" + str(start_min).zfill(2)
#Get the end time in hours and minutes
end_hour = interval_end // 60
end_min = interval_end % 60
int_end = str(end_hour) + ":" + str(end_min).zfill(2)
return int_beginning + "-" + int_end
def composeWeeklyOrdersMatrix(duration = 60):
'''
produces a matrix for weekly orders
:param duration: interval duration defaulting to 60 when nothing specified
:return: returns summary matrix as 2 dimensional list
'''
#calculating the opening and closing hours of the shop in minutes
global STARTMIN
global ORDERS
global CLOSING_MIN
total_mins_open = CLOSING_MIN - STARTMIN #total mins the business open in one day
#Calculate the total number of intervals based in duration
total_intervals = total_mins_open // duration
#Starting the 2d array - initializing the 2d array to 0
summary_matrix = [[0]*total_intervals for i in range (7)]
#go through the order list excluding the first row to find the minutes and split them with : to calculate the total mins
for order in ORDERS[1:]:
minutes = order[1].split(":")
tot_minutes_per_order = int(minutes[0]) * 60 + int(minutes[1])
occurence = (tot_minutes_per_order - STARTMIN) // duration
dates = order[0].split("-")
day = datetime.datetime(int(dates[0]), int(dates[1]), int(dates[2])).weekday()
#increase summary matrix of the dimensions of number of days and number of interval
summary_matrix[day][occurence] +=1
return summary_matrix
def printOrderSummaryMatrix(summary_matrix, duration):
'''
prints order summary matrix
:param summary_matrix: the matrix we created in our previous function
:param duration: the interval in minutes
'''
global CLOSING_MIN
global STARTMIN
global WEEK_DAYS
#Assign the variable in our header that will be the same in every output
header_output = "DAY\TIME | "
total_mins_open = CLOSING_MIN - STARTMIN
#Calculate the total number of intervals in a day
total_intervals = total_mins_open // duration
#doing a for loop to find each interval and print it all in the same line
for i in range(total_intervals):
header_output += labelString(i, STARTMIN, duration) + "|"
print()
print("WEEKLY ORDER SUMMARY")
print()
print(header_output)
print("-"*57) #crates the dashes after the label
#create a for loop to print the corresponding weekdays in our matrix
for r in range(len(summary_matrix)):
day_label = WEEK_DAYS[r]
print(day_label.ljust(9), end = "") #fill with spaces to the right
row = summary_matrix[r]
for column in row:
print(str(column).rjust(11), end = " ") #fill with spaces to the left with 11 spaces
print()
print("-"*57)
def main():
'''
asks user for input, creates matrix, prints matrix and then asks user again to enter a day to calculate the
max order interval on that day
'''
global STARTMIN
global WEEK_DAYS
#Ask the user to specify the length (in minutes) of the time interval used to aggregate the orders
user_interval = eval(input("Please specify the length of the time interval in minutes: "))
# produce summary matrix
summary_matrix = composeWeeklyOrdersMatrix(user_interval)
# print matrix
printOrderSummaryMatrix(summary_matrix, user_interval)
#Create a while loop to get day information from user to display the peak interval of that day until they only press enter
peak_interval = None
while peak_interval is not "":
peak_interval = input("Enter day to see peak interval, or press enter to stop: ").lower().title()
#Check to see if what user entered is in our week_day list
if peak_interval in WEEK_DAYS:
index_row = WEEK_DAYS.index(peak_interval)
row = summary_matrix[index_row]
row_max = max(row)
interval_row = row.index(row_max)
final_output = labelString(interval_row, STARTMIN, user_interval)
print(final_output + ",", row_max, "orders")
print("Bye!") #final print when they hit enter
main()
|
c5a19ca26f0d44d209915d43f501c03b44516f94 | tomhaoye/LetsPython | /practice/practice28.py | 151 | 3.640625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def age(n):
if n == 1:
c = 10
else:
c = age(n - 1) + 2
return c
print age(5)
|
b80c9997a4cd89d2d9efc878feb3fe5d4a9a51a9 | jay940059/algorithm | /Leetcode/9_Palindrome Number_06170221.py | 306 | 3.640625 | 4 | class Solution:
def isPalindrome(self,x):
if x<0: #如果是負數就不會是倒數
return(False)
else:
if str(x) == str(x)[::-1]: #如果是正數倒數就會跟自己相等
return(True)
else:
return(False)
|
e55f1fac8219e910cbff52dfa58538cc34829b98 | volodymyr1213/python-for-system-administration | /function_bmi.py | 228 | 3.796875 | 4 | #!/usr/bin/env python
import time
def gather_info():
height = float(input("Please enter your height: "))
weight = float(input("Please enter your weight: "))
total = weight / height
print(total)
gather_info()
|
ac1678001905103aa798e9892b2e72c2ec9f8a72 | SantiagoHerreG/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 168 | 3.75 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
new_set = {elem for elem in my_list}
count = 0
for elem in new_set:
count += elem
return (count)
|
157479252f15888057dd6d4029db990e59483658 | Aden-Q/LeetCode | /code/917.Reverse-Only-Letters.py | 335 | 3.609375 | 4 | class Solution:
def reverseOnlyLetters(self, s: str) -> str:
# first collect all the letters
letters = [c for c in s if c.isalpha()]
res = []
for c in s:
if c.isalpha():
res.append(letters.pop())
else:
res.append(c)
return ''.join(res) |
273dd5c9dddf424a76931223385b2f8a53893fc2 | dangor/advent-of-code-2020 | /day16/p1.py | 689 | 3.5625 | 4 | import re
def run(inputfile):
file = open(inputfile)
data = list(x.strip('\n') for x in file.readlines())
file.close()
valid = set()
for line in data:
if line == '':
break
match = re.search('(\d+)-(\d+) or (\d+)-(\d+)', line)
valid.update(range(int(match.group(1)), int(match.group(2)) + 1))
valid.update(range(int(match.group(3)), int(match.group(4)) + 1))
sum = 0
nearby = False
for line in data:
if line == "nearby tickets:":
nearby = True
continue
if not nearby:
continue
nums = line.split(',')
for num in nums:
i = int(num)
if i not in valid:
sum += i
print(f"Answer: {sum}")
|
4e47c4b8812a318148d2d8150922db0de43a68a3 | Josenildo-Souza/projeto | /elementos.py | 4,859 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 14 15:25:59 2018
@jls2
"""
#import Criptografia as cp
dic_elementos = {}
def cadastrar_elementos(dic_elementos):
cpf = input("Digite o CPF do Tripulante: ")
if cpf in dic_elementos:
print("Esse CPF ja esta Cadastrado!")
else:
nome = input("Digite o nome do tripulante: ")
funcao = input("Digite o cargo(Função) do tirpulante: ")
data_de_nascimento = input("Digite a data de nascimento do tripulante: ")
data_de_embarque = input("Digite a data de embarque: ")
porto_de_referencia = input("Digite o porto de Referencia do tripulante: ")
passaporte = input("Digite o nº do passaporte: ")
matricula = input("Digite o nº da matricula: ")
print("Tripulante Cadastrado com Sucesso!")
dic_elementos[cpf]=(nome, funcao, data_de_nascimento, data_de_embarque, porto_de_referencia, passaporte, matricula)
def buscar_elementos(dic_elementos):
continua = True
while continua == True:
elemento_buscado = input("Digite o cpf do tripulante: ")
if elemento_buscado in dic_elementos:
print(dic_elementos[elemento_buscado])
# loog = login + str(data()) + 'Busca de tripulante efetuada'
# log(loog)
escolha = input("Deseja outro Tripulante? (s/n) ")
if escolha == "s":
continua = True
else:
continua = False
else:
print("Tripulante nao encontrado em nosso banco de dados!")
escolha1 = input("Deseja buscar outro Tripulante? s/n ")
if escolha1 == "s":
continua = True
else:
continua = False
def buscar_cargo(dic_elementos):
continua = True
while continua == True:
resultados = []
cargo_buscado = input("Digite o cargo do tripulante: ")
continua = False
for cpf in dic_elementos:
if dic_elementos[cpf][1] == cargo_buscado:
resultados.append(dic_elementos[cpf])
if len(resultados)== 0:
print("Nenhum Tripulante com esse cargo")
entrada = input("Deseja buscar outro Tripulante? (s/n) ")
if entrada == "s":
continua = True
else:
continua = False
else:
for i in resultados:
print(i)
def remover_elementos(dic_elementos):
continua = True
while continua == True:
cpf = input("Digite o cpf que deseja para remover o Tripulante: ")
if cpf in dic_elementos:
dic_elementos.pop(cpf)
print("Tripulante Removido com Sucesso!")
continua = False
else:
entrada=input("Tripulante nao encontrado, deseja buscar outro?(s/n) ")
if entrada=="s":
continua=True
elif entrada=="n":
continua=False
def atualizar_elementos(dic_elementos):
continua = True
while continua == True:
cpf = input("Digite o cpf do Tripulante que vc quer atualizar: ")
if cpf in dic_elementos:
dic_elementos.pop(cpf)
cadastrar_elementos(dic_elementos)
print("Tripulante Atualizado com Sucesso!")
continua = False
else:
continuar=input("Tripulante nao encontrado, deseja buscar outro?(s/n) ")
if continuar=="s":
continua=True
elif continuar=="n":
continua=False
def mostrar_todos_os_elementos(dic_elementos):
if len(dic_elementos)==0:
print("O dicionario de Tripulantes está vazio!")
else:
for chave in dic_elementos:
print(dic_elementos[chave])
###########################################
def ordenar_elementos(dic_elementos):
lista = []
for chave in dic_elementos:
lista.append(chave)
lista.sort()
return lista
def impressao_ordenada(dic_elementos):
arq = open("impressao.txt", "w")
lista = ordenar_elementos(dic_elementos)
for chave in lista:
arq.write(chave+':\n')
arq.write("Nome: "+ dic_elementos[chave][0]+"\n")
arq.write("Função: "+ dic_elementos[chave][1]+"\n")
arq.write("Data de Nascimento: "+ dic_elementos[chave][2]+"\n")
arq.write("Data de Embarque: "+ dic_elementos[chave][3]+"\n")
arq.write("Porto de Referencia: "+ dic_elementos[chave][4]+"\n")
arq.write("Passaporte: "+ dic_elementos[chave][5]+"\n")
arq.write("Matricula: "+ dic_elementos[chave][6]+"\n\n")
arq.close()
|
22440e61a075a89deecddff6fcf088b461cc14f6 | jamesjholee/python100 | /basics/d1/main.py | 1,012 | 4.4375 | 4 | # Lesson 1
print("Hello world!")
# Coding Exercise 1
print("Day 1 - Python Print Function")
print("The function is decalred like this:")
print("print('what to print')")
# Lesson 2
print("Hello World!\nHello World!\nHello World")
print("Hello" + " James")
# Coding Exercise 2
print("Day 1 - String Manipulation")
print("String Concatenation is done with the '+' sign.")
print("e.g. print('Hello ' + 'world')")
print("New lines can be created with a backslash and n.")
# Lesson 3
input('What is your name?')
print("Hello " + input("What is your name?") + "!")
# Coding Exercise 3
print(len(input("What is your name?")))
# Lesson 4
name = input("What is your name? ")
print(name)
# Coding Exercise 4
a = input("a:")
b = input("b:")
c = a
a = b
b = c
print("a = " + a)
print("b = " + b)
#Day 1 Project
print('Welcome to the Band Name Generator!!!')
city = input("What city did you grow up in?\n")
pet = input("What was the name of your first pet?\n")
print("Your band name is " + city + " " + pet + "!")
|
8223d7f1b180425c39df86595d386464cfc77ab5 | sankket/Python_Examples | /While_loop.py | 326 | 4.21875 | 4 | # Working of the while loop.
#loop will keep on running until the condition is satisfied.
num = 0
while num < 10:
print ('number is currently: ',num)
print (' number is still less than 10, adding 1 to num')
num+=1
#With the while loop we can execute a set of statements as long as a condition is true.
|
3a0db3541b40f13b08be4f146fa99b590063e4be | naguiluz/from-the-beginning | /writing files.py | 620 | 4.1875 | 4 | #set as a variable so that the open function can be used easier
new_file = open("new file test", "w") #w will overwrite what is in a file
# adding a new file name will instead create a new file with the following contents
new_file.write("This is a file") #instead of adding to the print out in python it overwrites to the actual file (REPEATS IF RUN MULTIPLE TIMES BE CAREFUL)
new_file.write("\nnot too sure why i wouldn't just make a separate on my own") #\n adds a new line after the last existing line in the file
new_file.close() #good practice to close file after opening it |
b34b9a5e2a50b9dd9aaf6ccb23acf4012029e02b | SwatiTParshuramkar/File_python | /que4.py | 441 | 3.703125 | 4 | # my_file = open("question1.txt")
# file_data = my_file.read()
# content = []
# Counter = 0
# # Reading from file
# # Content = file.read()
# CoList = content.split("\n")
# while Counter < coList:
# if delhi in my_file:
# my_file = open("delhi.txt", "w")
# content.append(my_file)
# elif shimla in my_file:
# my_file3 = open("shimla.txt", "w")
# content.append(my_file)
# Counter+=1
|
4d83dcc85b5dcfa3cb088f1d7b5ac9bde368e6bc | AhmadQmairah/Python | /conditions_task.py | 736 | 4.125 | 4 | import operator
ops = { "+": operator.add, "-": operator.sub ,"*" :operator.mul,"/": operator.truediv}
while (True):
operand_1= input("Enter the first number: ").strip()
if ( not operand_1.isdigit()):
print("Please enter a valid number")
continue
break
while (True):
operand_2= input("Enter the second number: ").strip()
if ( not operand_2.isdigit()):
print("Please enter a valid number")
continue
break
while(True):
operation= input("Choose the operation (+, -, /, *): ").strip()
if operation not in ops :
print("Please enter a valid operation")
continue
break
print("The answer is",ops[operation](int(operand_1),int(operand_2)))
|
bfcc2907d5c35e025304e5f5669b026bf13012d4 | dongheelee1/LeetCode | /15_3Sum.py | 2,013 | 3.78125 | 4 | '''
15. 3Sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
'''
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
'''
IDEA:
find the combinations of 3 numbers, iterate through the list with the first pointer, and then trying to find two extra numbers to sum to 0
'''
# Sort the elements
nums.sort()
res = []
# Now fix the first element
# one by one and find the
# other two elements
for i in range(0, len(nums)-2): #need to have space for left and right pointers
if i > 0 and A[i] == A[i-1]:
continue
# To find the other two elements,
# start two index variables from
# two corners of the array and
# move them toward each other
l = i + 1
r = len(nums)-1
while l < r:
if( A[i] + A[l] + A[r] == 0): #sum of 3 elements == 0
res.append([A[i], A[l], A[r]]) #append results to res
#move the left and right pointers to the next different numbers, so we do not get repeating result
while l < r and A[l] == A[l+1]:
l += 1
while l < r and A[r] == A[r-1]:
r -= 1
l += 1
r -= 1
elif A[i] + A[l] + A[r] < 0:
l += 1
else: # A[i] + A[l] + A[r] > sum
r -= 1
# If we reach here, then
# no triplet was found
return res
|
8fcc0425bdeb46f02dd4dd20bf4bba03d1bd0a86 | ShallowDream-97/39-prp-landscape_history_game | /client_user_register_and_login.py | 1,466 | 3.8125 | 4 | #The file is used for user to register or login to server.
#The file provided that the client send their name and ip to server
import socket
import client_get_host
def get_usr_id(): #得到用户名,返回两行数据,第一行数据是学号,第二行是用户所用客户端ip,以此标识用户
usr_id = input("Please input your student id:") #输入学号
usr_name=input("Please input your usr name:")#输入名字
usr_ip = client_get_host.get_host_ip()#获取用户IP
print("Hi,%s!Welcome to run this program",usr_name)
usr_msg = usr_id+'\n'+usr_ip #用ip和学号标识用户
return usr_msg
#In our program, register equals login,so we use server_register_host to receiver all msg.
def register_and_login():
usr_msg = get_usr_id() #得到用户的信息
server_register_ip = "59.78.44.125" #服务器IP
server_register_port = 3344 #注册端口
udp_socket_send_usr_msg = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #创建套接字
#绑定信息
udp_socket_send_usr_msg.bind(("",4455)) #绑定端口 绑定地址(host,port)到套接字, 在 AF_INET下,以元组(host,port)的形式表示地址。
udp_socket_send_usr_msg.sendto(usr_msg.encode("utf-8"),(str(server_register_ip),server_register_port)) #发送 UDP 数据,将数据发送到套接字,address 是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。
|
b3f2cf989f24e2189be3c0d883c2f90c3989f875 | andrewp-as-is/recursion-detect.py | /tests/recursion-detect/examples/depth.py | 184 | 3.890625 | 4 | #!/usr/bin/env python
import recursion_detect
def recur():
depth = recursion_detect.depth()
print("depth = %s" % depth)
if depth==10:
return
recur()
recur()
|
5e59b1f88eea228d4e111b3402dc772556eba939 | zabojnikp/study | /Python_Projects/python3_selfstudy/lekce_6/practice_2_objekty.py | 1,830 | 4.21875 | 4 | import math
class Point:
name = ''
z = -2
def __init__(self, x, y=0):
self.x = x
self.y = y
def add_point(self, other_point):
self.x = self.x + other_point.x
self.y = self.y + other_point.y
def print_me(self):
print("bod {2}: [{0};{1};{3}]".format(self.x,self.y, self.name, self.z))
# def get_x(self):
# return self.x
@property
def distance_from_origin(self):
return math.sqrt(self.x**2 + self.y**2)
#instance objektu typu point predepsany tridou point
point_1 = Point(2,3)
point_1.print_me()
point_2 = Point(4,2)
point_2.print_me()
point_1.add_point(point_2)
point_1.print_me()
class MujPoint(Point):
def sub_point(self, other_point):
self.x = self.x - other_point.x
self.y = self.y - other_point.y
point_3 = MujPoint(3,3)
point_3.name = "muj super point"
point_3.print_me()
point_3.sub_point(Point(1,1))
point_3.print_me()
print(point_3.distance_from_origin)
class Person:
first_name = 'Jana'
last_name = 'Fana'
@property
def full_name(self):
return "{0} {1}".format(self.first_name, self.last_name)
@full_name.setter
def full_name(self, full_name_to_set):
self.first_name = full_name_to_set.split()[0]
self.last_name = full_name_to_set.split()[1]
def print_me(self):
print("F:{0} L:{1}".format(self.first_name, self.last_name))
ja = Person()
ja.print_me()
print(ja.full_name)
ja.full_name = "Sandra Novak"
ja.print_me()
class Ctverec:
def __init__(self, strana):
self.strana = strana
@property
def obsah(self):
return self.strana**2
@obsah.setter
def obsah(self, obsah):
self.strana = math.sqrt(obsah)
ctverec1 = Ctverec(5)
print(ctverec1.obsah)
ctverec1.obsah = 81
print(ctverec1.strana)
|
9851d468404b5f0174f7f3f36dfcb04a5b6034b2 | YulitaGap/BattleShip | /battleship.py | 6,878 | 3.78125 | 4 | import random
from random import randint
class Game:
def __init__(self):
"""
Initialization of class Game
(fields : list of fields)
(players: list of players)
"""
self.__fields = []
self.__players = []
self.__current_player = 0
@staticmethod
def shoot_at(cell, field_given):
"""
Return True if there is a ship in a cell, false if it's empty cell.
Changes cell position in grid(list) and board(dict).
(tuple, class) - > boolean
"""
line = 'abcdefghijklmnopqrstuvwxyz'.index(cell[0].lower())
field_given.grid[line][cell[1] - 1] = 'X'
if field_given.board[cell] == 0:
print('You missed!')
print(field_given.field_with_ships())
return False
elif field_given.board[cell] == 1:
field_given.grid[line][cell[1] - 1] = '*'
print('You shoot at ship!')
field_given.field_with_ships()
return True
elif field_given.board[cell] == 'X':
field_given.field_with_ships()
return False
field_given.board[cell] = 'X'
def board_dict(self):
"""
Converts a grid to a dictionary type.
Initializes board attribute.
(class) -> None
"""
board_dict = {}
line_number = 1
for x in self.grid:
board_dict[line_number] = [cell.replace('_', '0') for cell in x]
line_number += 1
cells = dict()
letters = [chr(x) for x in range(65, 75)]
for key, value in board_dict.items():
for x in range(0, 10):
cells[letters[x], key] = value[x]
self.board = cells
def field_without_ships(self):
grid = []
for row in range(10):
row = []
for col in range(10):
row.append('_')
grid.append(row)
self.grid = grid
class Field(Game):
def __init__(self):
self._ships = []
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
def random_field(self):
decks = []
ships = [(1, 4), (2, 3), (3, 2), (4, 1)]
for ship in ships:
for k in range(ship[0]):
a = random.randint(0, 9)
x = chr(65+a)
y = random.randint(1, 10 - ship[1])
horizontal = random.randint(0, 1)
deck = Ship((x, y), horizontal)
if horizontal:
deck.length = (1, ship[1])
else:
deck.length = (ship[1], 1)
decks.append(deck)
self._ships = decks
for ship in decks:
self.board[ship.bow] = 1
if horizontal:
for i in range(1, max(ship.length)):
self.board[ship.bow[0], ship.bow[1]+i] = 1
else:
for i in range(max(ship.length)):
self.board[chr(65+i), ship.bow[1]] = 1
def field_with_ships(self):
numbers = '123456789'
print(' | ' + ' | '.join(numbers) + ' |'+' 10 |')
for number, row in enumerate(self.grid):
print(chr(65+number), '| ' + ' | '.join(row) + ' |')
return '\n'
class Ship(Field):
def __init__(self, bow, horizontal):
self.bow = bow
self.horizontal = horizontal
self.length = ()
self.hit = []
class Player(Game):
def __init__(self):
"""
Initialization of Player class
"""
self.__name = ''
def get_name(self):
self.name = str(input('> Enter your name of nickname: '))
return self.name
@staticmethod
def read_position():
"""
Get coordinates of cell and return in tuple format
-> tuple
"""
try:
guess_row = str(input(" > Enter Row Letter:")).upper()
guess_col = int(input(" > Enter Col Number:"))
cell = (guess_row, guess_col)
return cell
except ValueError:
print('Enter only upper letters and int!')
except TypeError:
print('Enter only upper letters and int!')
if __name__ == '__main__':
print('Game Battleship')
print('Hello, Player 1!')
player1 = Player()
player1.get_name()
print(player1.name + "'s" ' starting field:')
game = Game()
game.current_player = 1
field1 = Field()
field1.field_without_ships()
field1.board_dict()
field1.field_with_ships()
print('Now adding ships to your field...')
field1.random_field()
print('\n')
print('Hello, Player 2!')
player2 = Player()
player2.get_name()
print(player2.name + "'s" ' field:')
game.current_player = 2
field2 = Field()
field2.field_without_ships()
field2.board_dict()
field2.field_with_ships()
print('Now adding ships to your field...')
field2.random_field()
game._players = [player1, player2]
game._fields = [field1, field2]
game.current_player = 0
field = field2
def count_unhit(fields):
"""
Return amount of cells, which are not hit.
(class Field) - > int
"""
un_hit = 0
for key, value in fields.board:
if type(value) == int:
un_hit += value
return un_hit
while count_unhit(field1) and count_unhit(field2):
miss = True
while miss:
print(game._players[game.current_player].name, ' your turn!')
point = game._players[game.current_player].read_position()
if game.shoot_at(point, field) is True:
game.current_player = 0
print(game._players[game.current_player].name, ' try again!')
miss = True
continue
else:
field = field1
field2.field_with_ships()
game.current_player = 1
print(game._players[game.current_player].name, ' your turn!')
point = game._players[game.current_player].read_position()
if game.shoot_at(point, field) is True:
game.current_player = 1
print(game._players[game.current_player].name, ' try again!')
# print(game._players[game.current_player].name, ' your turn!')
field = field1
game.current_player = 1
continue
else:
field1.field_with_ships()
game.current_player = 0
miss = False
field = field2
continue
winner = game.current_player
print('Congratulations, {}, you won!'.format(winner)) |
82cdc7c7da86629d91cba34fb6bbff83310c3b39 | BloodiestChapel/Personal-Projects | /Python/GuessingGame.py | 832 | 4.0625 | 4 | # Guessing game
# Create a random number between 1 & 99
# If user is below the number, let them know
# If user is above the number, let them know
# If user is correct, they win
import random
secretNumber = random.randint(1, 99)
# You only get 7 guesses
for guessesTaken in range(1, 7):
# Begin for statement
print('What number am I thinking of..?')
guess = int(input())
if guess < secretNumber:
print('Too low. Try again.')
elif guess > secretNumber:
print('Too high. Try again.')
else:
break
# End for statement
if guess == secretNumber:
print('Correct. You won in ' + str(guessesTaken) + ' moves.')
else:
print('You have failed. The number I was thinking of was ' + str(secretNumber))
print('You were ' + str(secretNumber - guess) + ' away from the answer.') |
9ad46f9d700b4bb8ee1e1fb2ff9777f258bda6e3 | leztien/utilities | /datasets/make_swiss_roll.py | 2,845 | 3.6875 | 4 |
def make_swiss_roll(n_revolutions=3, radius_to_width_ratio=1, major_minor_axis_ratio=1, density=300):
"""makes Swiss Roll"""
import numpy as np
from pandas import factorize
from math import pi as π
n_points = density # relative data density
t = np.linspace(0, n_revolutions * π, n_points)
x = np.cos(t) * np.exp(0.1 * t) * major_minor_axis_ratio
y = np.sin(t) * np.exp(0.1 * t)
# calculate how many points to skip because of the exponential distance growth to make the distances equal
M = np.c_[x, y]
distances_between_points = ((M[1:, :] - M[:-1, :]) ** 2).sum(axis=1) ** 0.5
length = len(distances_between_points)
mult = length / np.max(distances_between_points - np.min(distances_between_points))
nx = (distances_between_points - np.min(distances_between_points)) * mult
nx = [int(n) for n in nx[::3]]
x = x[::-1][nx][::-1]
y = y[::-1][nx][::-1]
t = t[::-1][nx][::-1]
# calculate the step (for the distance between points) along the width of the roll
M = np.c_[x, y]
step = np.mean(((M[1:, :] - M[:-1, :]) ** 2).sum(axis=1) ** 0.5) * 1.5
mn, mx = np.min(np.c_[x, y]), np.max(np.c_[x, y])
z = np.arange(mn, mx * radius_to_width_ratio, step=step, dtype=np.float32)
# assemble the matrix
pl = np.zeros(shape=(len(z), len(x), 3), dtype=np.float64)
pl[:, :, 0] = x
pl[:, :, 1] = y
pl = np.rot90(pl, axes=(0, 1), k=1)
pl[:, :, -1] = z
pl = np.rot90(pl, axes=(0, 1), k=-1)
X = pl.reshape(pl.shape[0] * pl.shape[1], pl.shape[-1])
# rotate and scale
n = 1 / (2 ** 0.5)
T = [[n, -n, -n],
[n, n, -n],
[n, 0, n]]
X = np.matmul(T, X.T).T
X += np.abs(X.min(axis=0))
y = factorize(list(t) * len(z))[0].tolist()
return X ,y
def main():
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
X, y = make_swiss_roll(density=220, n_revolutions=3)
fig = plt.figure(figsize=(10, 5))
sp = fig.add_subplot(121, projection='3d')
sp.axis('equal')
sp.set(xlabel="x-axis", ylabel="y-axis", zlabel="z-axis")
sp.scatter(*X.T, c=y, cmap='viridis', s=5)
# plot different manifold results
from sklearn.manifold import Isomap, LocallyLinearEmbedding, TSNE, MDS
model_list = (Isomap, LocallyLinearEmbedding, TSNE, MDS)
for i, spNumber in enumerate([3, 4, 7, 8]):
X_2D = model_list[i](n_components=2).fit_transform(X, y)
sp = fig.add_subplot(2, 4, spNumber)
sp.scatter(*X_2D.T, c=y, cmap='viridis', s=10)
sp.set_xticks([]);
sp.set_yticks([])
sp.set_title(model_list[i].__name__, fontsize=10)
plt.subplots_adjust(left=0.01, wspace=0.2)
plt.show()
if __name__ == "__main__": main() |
35a3707610816e371ee89133c293174d556ec82a | chenzhao2020/dsci-532_group-20 | /src/data_wrangling.py | 10,069 | 3.84375 | 4 | import pandas as pd
import numpy as np
months_short = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
def select_type(hotel_type="All"):
"""Reads the "data/processed/clean_hotels.csv" source file and returns
a data frame filtered by hotel type
Parameters
----------
hotel_type : string, either "City", "Resort", or "Both
Returns
-------
dataframe with hotel data filtered by hotel type
"""
hotels = pd.read_csv("data/processed/clean_hotels.csv")
# filter based on hotel type selection
if hotel_type == "Resort":
hotels = hotels[hotels["Hotel type"] == "Resort"]
if hotel_type == "City":
hotels = hotels[hotels["Hotel type"] == "City"]
return hotels
def get_year_stats(data, scope="all_time", ycol="Reservations", year=2016):
"""creates a string with summary stats from the selected year
Parameters
----------
data : dataframe produced by `get_year_data()`
scope: should the stats be for "all_time" or the "current" year?
y_col: the variable selected from "y-axis-dropdown"
year: the year selected from "year-dropdown"
Returns
-------
string: ex) "Year 2016: Ave=4726, Max=6203(Oct), Min=2248(Jan)"
"""
if scope == "all_time":
max_ind = data[data["Line"] == "Average"][ycol].argmax()
min_ind = data[data["Line"] == "Average"][ycol].argmin()
ave = round(data[data["Line"] == "Average"][ycol].mean())
string = f"Historical "
else:
max_ind = data[data["Line"] != "Average"][ycol].argmax() + 12
min_ind = data[data["Line"] != "Average"][ycol].argmin() + 12
ave = round(data[data["Line"] != "Average"][ycol].mean())
string = f"Year {year} "
maxi = round(data.iloc[max_ind, 2])
mini = round(data.iloc[min_ind, 2])
max_month = months_short[data.iloc[max_ind, 0] - 1]
min_month = months_short[data.iloc[min_ind, 0] - 1]
string += f"Ave : {ave}, Max : {maxi}({max_month}), Min : {mini}({min_month})"
return string
def get_month_stats(data, scope="all_time", ycol="Reservations", year=2016, month=1):
"""creates a string with summary stats from the selected month and year
Parameters
----------
data : dataframe produced by `get_year_data()`
scope: should the stats be for "all_time" or the "current" year
y_col: the variable selected from "y-axis-dropdown"
year: the year selected from "year-dropdown"
month: the month selected from "month-dropdown"
Returns
-------
string: ex) "Jan 2016 Ave : 73, Max : 183(Jan 2), Min : 33(Jan 31)"
"""
short_month = months_short[month - 1] # convert numeric month to abbreviated text
if scope == "all_time":
max_ind = data[data["Line"] == "Average"][ycol].argmax()
min_ind = data[data["Line"] == "Average"][ycol].argmin()
ave = round(data[data["Line"] == "Average"][ycol].mean())
string = f"Historical "
else:
if (year < 2016 and month < 7) or (
year > 2016 and month > 8
): # if out of data range return message
return "No data for this month"
max_ind = data[data["Line"] != "Average"][ycol].argmax() + len(
data[data["Line"] == "Average"]
)
min_ind = data[data["Line"] != "Average"][ycol].argmin() + len(
data[data["Line"] == "Average"]
)
ave = round(data[data["Line"] != "Average"][ycol].mean(skipna=True))
string = f" {short_month} {year} "
maxi = round(data.iloc[max_ind, 2])
mini = round(data.iloc[min_ind, 2])
max_date = data.iloc[max_ind, 0]
min_date = data.iloc[min_ind, 0]
string += f"Ave : {ave}, Max : {maxi}({short_month} {max_date}), Min : {mini}({short_month} {min_date})"
return string
def get_year_data(hotel_type, y_col, year):
"""returns a data frame containing monthly summaries of one variable for
the selected hotel type, for the selected year and for all-time
Parameters
----------
hotel_type : string, either "City", "Resort", or "Both
y_col: the variable selected from "y-axis-dropdown"
year: the year selected from "year-dropdown"
Returns
-------
dataframe: monthly summaries of selected variable for the selected time period
"""
hotels = select_type(hotel_type)
data = pd.DataFrame()
if y_col == "Reservations": # count number of "Reservations"
data["Average"] = (
hotels.groupby("Arrival month")["Hotel type"].count()
/ hotels.groupby("Arrival month")["Arrival year"].nunique()
)
data[str(year)] = (
hotels[hotels["Arrival year"] == year]
.groupby("Arrival month")["Hotel type"]
.count()
)
elif y_col == "Average daily rate": # average the "Average daily rate"
data["Average"] = hotels.groupby("Arrival month")[y_col].mean()
data[str(year)] = (
hotels[hotels["Arrival year"] == year]
.groupby("Arrival month")[y_col]
.mean()
)
else: # sum the other variables
data["Average"] = (
hotels.groupby("Arrival month")[y_col].sum()
/ hotels.groupby("Arrival month")["Arrival year"].nunique()
)
data[str(year)] = (
hotels[hotels["Arrival year"] == year].groupby("Arrival month")[y_col].sum()
)
# make the month_no a column
data = data.reset_index()
data = pd.melt(data, "Arrival month").rename(
columns={"variable": "Line", "value": y_col}
)
return data
def get_month_data(
hotel_type="All",
y_col="Reservations",
year=2016,
month=1,
):
"""returns a data frame containing monthly summaries of one variable for
the selected hotel type, for the selected year and for all-time
Parameters
----------
hotel_type : string, either "City", "Resort", or "Both
y_col: the variable selected from "y-axis-dropdown"
year: the year selected from "year-dropdown"
month: the month selected from "month-dropdown"
Returns
-------
dataframe: daily summaries of selected variable for the selected time period
"""
hotels = select_type(hotel_type)
hotels = hotels[hotels["Arrival month"] == month]
data = pd.DataFrame()
if y_col == "Reservations": # count number of "Reservations"
data["Average"] = (
hotels.groupby("Arrival day")["Hotel type"].count()
/ hotels.groupby("Arrival day")["Arrival year"].nunique()
)
data[str(year)] = (
hotels[hotels["Arrival year"] == year]
.groupby("Arrival day")["Hotel type"]
.count()
)
elif y_col == "Average daily rate": # average the "Average daily rate"
data["Average"] = hotels.groupby("Arrival day")[y_col].mean()
data[str(year)] = (
hotels[hotels["Arrival year"] == year].groupby("Arrival day")[y_col].mean()
)
else: # sum the other variables
data["Average"] = (
hotels.groupby("Arrival day")[y_col].sum()
/ hotels.groupby("Arrival day")["Arrival year"].nunique()
)
data[str(year)] = (
hotels[hotels["Arrival year"] == year].groupby("Arrival day")[y_col].sum()
)
data = data.reset_index()
data = pd.melt(data, "Arrival day").rename(
columns={"variable": "Line", "value": y_col}
)
# filter out feb 29 for non-leap years
if (year % 4 != 0) and month == 2:
data = data[data["Arrival day"] != 29]
# get the day of the week for the selected year
data["Arrival day of week"] = pd.to_datetime(
year * 10000 + month * 100 + data["Arrival day"], format="%Y%m%d"
)
data["Arrival day of week"] = data["Arrival day of week"].dt.dayofweek
data["Arrival day of week"] = data["Arrival day of week"].replace(
[0, 1, 2, 3, 4, 5, 6], ["Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun"]
)
return data
def left_hist_data(hotel_type="All", year=2016, month=1):
"""returns a data frame containing binned counts of hotel guests' country of origin
for the selected hotel type and time period
Parameters
----------
hotel_type : string, either "City", "Resort", or "Both
year: the year selected from "year-dropdown"
month: the month selected from "month-dropdown"
Returns
-------
dataframe: containing binned counts of hotel guests' country of origin
"""
df = select_type(hotel_type)
df = df[df["Arrival year"] == year]
df = df[df["Arrival month"] == month]
df = (
df.groupby("Country of origin")
.size()
.reset_index(name="counts")
.sort_values(by="counts", ascending=False)[:10]
)
return df
def right_hist_data(hotel_type="All", year=2016, month=1):
"""returns a data frame containing binned counts of the duration of guests' stay
for the selected hotel type and time period
Parameters
----------
hotel_type : string, either "City", "Resort", or "Both
year: the year selected from "year-dropdown"
month: the month selected from "month-dropdown"
Returns
-------
dataframe: containing binned counts of duration of guests' stay
"""
df = select_type(hotel_type)
# select relevant columns then filter by year and month
df = df[["Arrival year", "Arrival month", "Total nights"]]
df = df[df["Arrival year"] == year]
df = df[df["Arrival month"] == month]
# calculate counts for total nights
df = (
df.groupby("Total nights").count()
/ df.groupby("Total nights").count().sum()
* 100
)
df = df.reset_index().drop(columns="Arrival year")
df.columns = ["Total nights", "Percent of Reservations"]
return df
if __name__ == "__main__":
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.