blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0356949de94e8f3f2ee4df73b5061ac4ac2ff373 | conejo1995/pythonLabs | /join.py | 98 | 3.8125 | 4 | print("Enter two strings.")
string1 = input()
string2 = input()
print(str.join(string1, string2))
|
502ec7abbd3d176e3d2b4747c94f62f10a044948 | caul1flower/alg | /sorting_algorithms.py | 1,833 | 4.09375 | 4 | def selection_sort(arr):
comparisons = 1
for i in range(len(arr)):
comparisons += 1
min_idx = i
comparisons += 1
for j in range(i + 1, len(arr)):
comparisons += 2
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return comparisons
def insertion_sort(arr):
comparisons = 1
for i in range(1, len(arr)):
comparisons += 1
key = arr[i]
j = i - 1
comparisons += 1
while j >= 0 and key < arr[j]:
comparisons += 2
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return comparisons
def merge_sort(lst):
comparisons = 0
if len(lst) > 1:
middle = len(lst) // 2
left = lst[:middle]
right = lst[middle:]
merge_sort(left)
merge_sort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
lst[k] = left[i]
i += 1
else:
lst[k] = right[j]
j += 1
k += 1
comparisons += 1
while i < len(left):
lst[k] = left[i]
i += 1
k += 1
while j < len(right):
lst[k] = right[j]
j += 1
k += 1
return comparisons
def shell_sort(lst):
length = len(lst)
h = 1
comparisons = 0
while (h < (length//3)):
h = 3*h + 1
while (h >= 1):
for i in range(h, length):
for j in range(i, h-1, -h):
comparisons += 1
if (lst[j] < lst[j-h]):
lst[j], lst[j-h] = lst[j-h], lst[j]
else:
break
h = h//3
return comparisons
|
6a826557463d4d9561317d308f8e3aa0eb751884 | rodrigoContreras/git-hello-world | /udemy/19_herencia.py | 802 | 3.953125 | 4 | class Operacion():
def __init__(self):
self.valor1=0
self.valor2=0
self.resultado=0
def cargar(self):
self.valor1=int(input("VAlor 1: "))
self.valor2=int(input("VAlor 2: "))
def mostrarResultado(self):
return self.resultado
class Suma(Operacion): # OBtiENE HERENCI DE Operacion
def operar(self):
self.resultado=self.valor1 + self.valor2
class Resta(Operacion):
def resta(self):
self.resultado=self.valor1 - self.valor2
suma1 = Suma()
suma1.cargar()
suma1.operar()
sumaValores = suma1.mostrarResultado()
print("La suma de los valores e : ", str(sumaValores))
resta1 = Resta()
resta1.cargar()
resta1.resta()
restaValores = resta1.mostrarResultado()
print("La resta de los valores e : ", str(restaValores)) |
81f056fb61a2e7816b2fc2138f8ed70de8378b87 | odinfor/leetcode | /pythonCode/No251-300/no334.py | 1,039 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/1/12 4:10 下午
# @Site :
# @File : no334.py
# @desc : 给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。
# 如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false 。
class Solution:
def increasingTriplet(self, nums: list) -> bool:
if len(nums) < 3:
return False
dealNum = {}
for i in range(1, len(nums) - 1):
if nums[i] in dealNum:
continue
leftMin = min(nums[:i])
rightMax = max(nums[i + 1:])
if leftMin < nums[i] < rightMax:
return True
dealNum[nums[i]] = ""
return False
if __name__ == "__main__":
s = Solution()
print(s.increasingTriplet([1, 2, 3, 4, 5]))
print(s.increasingTriplet([2, 1, 5, 0, 4, 6]))
print(s.increasingTriplet([20, 100, 10, 12, 5, 13])) |
c613da93863e17c4aa8f709724f26919fc7670af | alex-dukhno/python-tdd-katas | /persistent_list_kata/day_1.py | 2,423 | 3.703125 | 4 | import unittest
class List(object):
def append(self, item):
return Node(item, self)
def head(self):
pass
def tail(self):
pass
def __repr__(self):
return ''
def __add__(self, other):
return other
class EmptyList(List):
def head(self):
return None
def tail(self):
return None
def __repr__(self):
return ''
class Node(List):
def __init__(self, item, _next):
self._item = item
self._next = _next
def head(self):
return self._item
def tail(self):
return self._next
def __repr__(self):
next_str = repr(self._next)
if next_str is '':
return repr(self._item)
else:
return repr(self._item) + ', ' + next_str
def __add__(self, other):
if other.head() is None:
return self
else:
return (self.tail() + other).append(self.head())
class PersistentListTest(unittest.TestCase):
def testAppendToList(self):
persistent_list = List().append(1)
self.assertEqual('1', repr(persistent_list))
def testAppendManyItemsToList(self):
persistent_list = List().append(1).append(2).append(3)
self.assertEqual('3, 2, 1', repr(persistent_list))
def testHeadOfEmptyList_isNone(self):
self.assertIsNone(List().head())
def testHeadOfList_isTheFirstItem(self):
persistent_list = List().append(1).append(2)
self.assertEqual(2, persistent_list.head())
def testTailOfEmptyList_isNone(self):
self.assertIsNone(List().tail())
def testTailOfList_isTheRestOfList_exceptTheFirstItem(self):
persistent_list = List().append(1).append(2)
self.assertEqual(persistent_list, persistent_list.append(3).tail())
def testConcatenationOfTwoEmptyLists(self):
self.assertEqual('', repr(List() + List()))
def testConcatenationEmpty_andNonemptyList(self):
self.assertEqual('3, 2, 1', repr(List() + List().append(1).append(2).append(3)))
self.assertEqual('3, 2, 1', repr(List().append(1).append(2).append(3) + List()))
def testConcatenationOfTwoNonemptyLists(self):
the_nonempty = List().append(4).append(5).append(6)
the_other_nonempty = List().append(1).append(2).append(3)
self.assertEqual('6, 5, 4, 3, 2, 1', repr(the_nonempty + the_other_nonempty))
|
a432b8ddf376f5afcc1507c72e3582c758fe2f13 | mejasiu/Python | /RocketGame12_3/rocketgame.py | 1,993 | 3.8125 | 4 | import sys
import pygame
from rocket import Rocket
from actions import update
def run_game():
"""This will start the game play"""
pygame.init()
screen = pygame.display.set_mode((600,800))
pygame.display.set_caption("Rocket game")
bg_color = (255, 255, 255)
rocket = Rocket(screen)
while True:
#Creating the main loop of the game
# for event in pygame.event.get():
# if event.type == pygame.QUIT: sys.exit()
#sending to the action function to do what i did below
update(rocket)
# if event.type == pygame.KEYDOWN:
# if event.key == pygame.K_LEFT:
# #Make the ship go to the left
# print("LEFT")
# elif event.key == pygame.K_RIGHT:
# #Make the ship go to the right
# print("RIGHT")
# elif event.key == pygame.K_UP:
# #Make the ship go fly up
# print("UP")
# elif event.key == pygame.K_DOWN:
# #Make the ship go down
# print("DOWN")
#
# if event.type == pygame.KEYUP:
# if event.key == pygame.K_LEFT:
# #Make the ship go to the left
# print("LEFT")
# elif event.key == pygame.K_RIGHT:
# #Make the ship go to the right
# print("RIGHT")
# elif event.key == pygame.K_UP:
# #Make the ship go fly up
# print("UP")
# elif event.key == pygame.K_DOWN:
# #Make the ship go down
# print("DOWN")
#Color the screen
screen.fill(bg_color)
# rocket.blitme()
#
# #this is to make the drawing visable
# pygame.display.flip()
#
run_game()
|
683acabef95365418ab031237fe57588a1c243ec | Hoverbear/SPARCS | /week8/sequence.py | 453 | 4.03125 | 4 | # Number sequences
so_far = [1, 1]
while len(so_far) < 20:
next_number = so_far[-1] + so_far[-2] # Last two numbers added together.
so_far.append(next_number) # Add to the last spot of the list.
print(so_far)
# Can you make a function that returns a list with a size the user specifies?
# For example:
# sequence(20)
# Would return the first 20 items of the sequence.
# Tip:
# def sequence(number_of_items):
# ** Your stuff goes here **
|
c0252f78d998566ab38dc90915c9fa5a45ffc1d2 | Thalisson01/Python | /Exercício Python #068 - Jogo do Par ou Ímpar.py | 697 | 3.75 | 4 | import random
vezes = 0
while True:
n = int(input('Diga um valor: '))
es = str(input('Você que PAR ou ÍMPAR? [P/I]: '))
while es not in 'PpIi':
print('Escolha inválida.')
es = str(input('Você que PAR ou ÍMPAR? [P/I]: '))
sorteio = random.randint(1, 10)
es.upper()
print(sorteio)
if (es == 'P' and (n + sorteio) % 2 == 0):
print('Você venceu, parabéns!')
vezes += 1
elif (es == 'I' and (n + sorteio) % 2 == 1):
print('Você venceu, parabéns!')
vezes += 1
else:
print('Você perdeu, seu lixo!')
print(sorteio)
print(f'Você conseguiu ganhar {vezes} vezes de mim')
break |
d0139a5b99917a8c950197293a309b3d70349460 | rumitpatel9/rolling_dice_task | /game.py | 540 | 3.5 | 4 | import tkinter as tk
from PIL import ImageTk, Image
import random
app = tk.Tk()
app.title("Dice Rolling.")
app.geometry("500x500")
img = ImageTk.PhotoImage(Image.open(f"die{random.randint(1,6)}.PNG"))
panel = tk.Label(image = img)
panel.pack(side = "top", fill = "both", expand = "yes")
def rolling_dice():
img = ImageTk.PhotoImage(Image.open(f"die{random.randint(1,6)}.PNG"))
panel.configure(image =img)
panel.image = img
btn = tk.Button(app, text = 'click me.!',command =rolling_dice)
btn.place(x=200, y=400)
app.mainloop()
|
0ce0c53118ac3807f7b00c1f3145038671cd9a6e | LouisPerrott/Bright-Networks-Internship-Google-Software-challenge | /Bright Internship Software Development/google-code-sample-main/google-code-sample-main/python/src/video_player.py | 11,630 | 3.84375 | 4 | """A video player class."""
from .video_library import VideoLibrary
"""There is something wrong with the module loading I was unable to fix this problem."""
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
def number_of_videos(self):
num_videos = len(self._video_library.get_all_videos())
print(f"{num_videos} videos in the library")
def show_all_videos(self):
"""Returns all videos."""
print("Here's a list of all avaliable videos:")
print("")
for video in self._video_library:
print(video)
print("")
def play_video(self, video_id):
"""Plays the respective video.
Args:
video_id: The video_id to be played.
"""
if video_id == amazing_cats_video_id:
if video_playing != null:
print("Stopping video: {video_playing}")
print("Playing video: Amazing cats")
else:
print("Playing video: Amazing cats")
video_playing = Amazing cats
elif video_id == another_cat_video_id:
if video_playing != null:
print("Stopping video: {video_playing}")
print("Playing video: Another cat video")
else:
print("Playing video: Another cat video")
video_playing = Another cat video
elif video_id == funny_dogs_video_id:
if video_playing != null:
print("Stopping video: {video_playing}")
print("Playing video: Funny dogs")
else:
print("Playing video: Funny dogs")
video_playing = Funny dogs
elif video_id == life_at_google_video_id:
if video_playing != null:
print("Stopping video: {video_playing}")
print("Playing video: Life at Google")
else:
print("Playing video: Life at Google")
video_playing = Life at Google
elif video_id == nothing_video_id:
if video_playing != null:
print("Stopping video: {video_playing}")
print("Playing video: Video about nothing")
else:
print("Playing video: Video about nothing")
video_playing = Video about nothing
else:
print("Cannot play video: Video does not exist")
def stop_video(self):
"""Stops the current video."""
if video_playing == Amazing cats:
print("Stopping video: Amazing cats")
elif video_playing == Another cat video:
print("Stopping video: Another cat video")
elif video_playing == Funny dogs:
print("Stopping video: Funny dogs")
elif video_playing == Life at Google:
print("Stopping video: Life at Google")
elif video_playing == Video about nothing:
print("Stopping video: Video about nothing")
else:
print("Cannot stop video: No video is currently playing")
def play_random_video(self):
"""Plays a random video from the video library."""
import random
random_number = random.randrange(1, 6)
if random_number == 1:
print("Stopping video: {video_playing}")
print("Playing video: Amazing cats")
video_playing = Amazing cats
elif random_number == 2:
print("Stopping video: {video_playing}")
print("Playing video: Another cat video")
video_playing = Another cat video
elif random_number == 3:
print("Stopping video: {video_playing}")
print("Playing video: Funny dogs")
video_playing = Funny dogs
elif random number == 4:
print("Stopping video: {video_playing}")
print("Playing video: Life at Google")
video_playing = Life at Google
elif random number == 5:
print("Stopping video: {video_playing}")
print("Playing video: Video about nothing")
video_playing = Video about nothing
def pause_video(self):
"""Pauses the current video."""
if video_playing == Amazing cats:
print("Pausing video: Amazing cats")
video_paused = Amazing cats
elif video_paused == Amazing cats:
print("Video already paused: Amazing cats")
video_playing = Amazing cats
elif video_playing == Another cat video:
print("Pausing video: Another cat video")
video_paused = Another cat video
elif video_paused == Another cat video:
print("Video already paused: Another cat video")
video_playing = Another cat video
elif video_playing == Funny dogs:
print("Pausing video: Funny dogs")
video_paused = Funny dogs
elif video_paused == Funny dogs:
print("Video already paused: Funny dogs")
video_playing = Funny dogs
elif video_playing == Life at Google:
print("Pausing video: Life at Google")
video_paused = Life at Google
elif video_paused == Life at Google:
print("Video already paused: Life at Google")
video_playing = Life at Google
elif video_playing == Video about nothing:
print("Pausing video: Video about nothing")
video_paused = Video about nothing
elif video_paused == Video about nothing:
print("Video already paused: Video about nothing")
video_playing = Video about nothing
else:
print("Cannot pause video: No video is currently playing")
def continue_video(self):
"""Resumes playing the current video."""
if video_paused == Amazing cats:
print("Continuing video: Amazing cats")
video_playing = Amazing cats
elif video_paused == Another cat video:
print("Continuing video: Another cat video")
video_playing = Another cat video
elif video_paused == Funny dogs:
print("Continuing video: Funny dogs")
video_playing = Funny dogs
elif video_paused == Life at Google:
print("Continuing video: Life at Google")
video_playing = Life at Google
elif video_paused == Video about nothing:
print("Continuing video: Video about nothing")
video_playing = Video about nothing
else:
print("Cannot continue video: Video is not paused")
def show_playing(self):
"""Displays video currently playing."""
if video_playing == Amazing cats:
print("Currently playing: Amazing cats {}")
if video_paused == Amazing cats:
print(" - PAUSED")
if video_playing == Another cat video:
print("Currently playing: Another cat video {}")
if video_paused == Another cat video:
print(" - PAUSED")
if video_playing == Funny dogs:
print("Currently playing: Funny dogs {}")
if video_paused == Funny dogs:
print(" - PAUSED")
if video_playing == Life at Google:
print("Currently playing: Life at Google {}")
if video_paused == Life at Google:
print(" - PAUSED")
if video_playing == Video about nothing:
print("Currently playing: Video about nothing {}")
if video_paused == Video about nothing:
print(" - PAUSED")
else:
print("No video is currently playing")
def create_playlist(self, playlist_name):
"""Creates a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
playlist_list = []
if playlist_name != playlist:
print("Successfully created new playlist: {playlist_name}")
playlist = playlist_name
playlist_list.append(playlist)
else:
print("Cannot create playlist: A playlist with the same name already exists")
def add_to_playlist(self, playlist_name, video_id):
"""Adds a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be added.
"""
if video_id == amazing_cats_video_id:
print("Added video to {playlist_name}: Amazing cats")
elif video_id == another_cat_video_id:
print("Added video to {playlist_name}: Another cat video")
elif video_id == funny_dogs_video_id:
print("Added video to {playlist_name}: Funny dogs")
elif video_id == life_at_google_video_id:
print("Added video to {playlist_name}: Life at Google")
elif video_id == nothing_video_id:
print("Added video to {playlist_name}: Video about nothing")
elif playlist_list.count(playlist_name) == 0:
print("Cannot add video to {playlist_name}: Playlist does not exist")
else:
print("Cannot add video to {playlist_name}: Video does not exist")
def show_all_playlists(self):
"""Display all playlists."""
if playlist_list[0] != null
print("Showing all playlists:)
print(playlist_list)
else:
print("No playlists exist yet")
def show_playlist(self, playlist_name):
"""Display all videos in a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
print("show_playlist needs implementation")
def remove_from_playlist(self, playlist_name, video_id):
"""Removes a video to a playlist with a given name.
Args:
playlist_name: The playlist name.
video_id: The video_id to be removed.
"""
print("remove_from_playlist needs implementation")
def clear_playlist(self, playlist_name):
"""Removes all videos from a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
print("clears_playlist needs implementation")
def delete_playlist(self, playlist_name):
"""Deletes a playlist with a given name.
Args:
playlist_name: The playlist name.
"""
print("deletes_playlist needs implementation")
def search_videos(self, search_term):
"""Display all the videos whose titles contain the search_term.
Args:
search_term: The query to be used in search.
"""
print("search_videos needs implementation")
def search_videos_tag(self, video_tag):
"""Display all videos whose tags contains the provided tag.
Args:
video_tag: The video tag to be used in search.
"""
print("search_videos_tag needs implementation")
def flag_video(self, video_id, flag_reason=""):
"""Mark a video as flagged.
Args:
video_id: The video_id to be flagged.
flag_reason: Reason for flagging the video.
"""
print("flag_video needs implementation")
def allow_video(self, video_id):
"""Removes a flag from a video.
Args:
video_id: The video_id to be allowed again.
"""
print("allow_video needs implementation")
|
1244ed54d5cfcc0774047a7d6f0cdc56c68dc3de | pmduc2012/test | /BT4 - Mutiplication Table.py | 591 | 3.71875 | 4 | '''print('\t\t\t\tMultipication Table')
for i in range(1,10):
print('%5d' % i,end="")
print()
print('-'*45)
for j in range(1,10):
for k in range(1,10):
print ('%5d' % (j*k),end='')
print()
'''
def table(rows, columns):
print('\t\tMultiplication Table')
i = ''
for column in range(1,columns + 1):
i = i + str(column) + '\t'
print('\t' + i)
print('-'*38)
for row in range(1,rows + 1):
i = ''
for column in range(1,columns + 1):
i = i + str(row*column) + '\t'
print(str(row) + '|' + '\t' + i)
table(9,9)
|
91f4f7258f9d434be751346a40d6af88cc7c1ff7 | CoderWZW/leetcode | /排序算法/插入排序.py | 952 | 3.671875 | 4 | # -*- coding: utf-8 -*-
l = [2, 15, 5, 9, 7, 6, 4, 12, 5, 4, 2, 64, 5, 6, 4, 2, 3, 54, 45, 4, 44]
l_out = [2, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 9, 12, 15, 44, 45, 54, 64]
'''
思想:
升序
不断的按顺序遍历,将当前值与前面的值依次比较,插入该值所在位置
'''
# 直接插入排序
# 思路:依次遍历,倒序遍历已经排好序的list,比较后如果目标值大于遍历值,则插入在该遍历值index+1的位置
def insert_sort(l):
l_new = [l[0]]
for i in range(1,len(l)):
temp = l[i]
flag = 0
for j in range(len(l_new)-1, -1, -1):
if temp >= l_new[j]:
l_new.insert(j+1, temp)
flag = 1
break # break 很关键,否则就会每次都遍历所有的排序好的数字
if flag == 0:
l_new.insert(0, temp)
return l_new
print(insert_sort(l))
|
675e26fb1c3e9b504a22d4e825f7ef3e95c7a5fe | Aasthaengg/IBMdataset | /Python_codes/p03738/s573451867.py | 215 | 3.828125 | 4 | import math
def calc(A, B) :
a = math.log(A)
b = math.log(B)
if a > b :
print('GREATER')
elif b > a :
print('LESS')
else :
print('EQUAL')
A = int(input())
B = int(input())
calc(A, B) |
2756c37078f1ad2f3e3de281133e38ea47d6f4da | Ivanpaun/qa_first_group | /my_notepad/mainWindow.py | 1,820 | 3.578125 | 4 | import tkinter as tk
import tkinter.scrolledtext as tkst
import tkinter.font as tkFont
from tkinter import messagebox
class App:
def __init__(self):
self.win = tk.Tk()
self.customFont = tkFont.Font(
family="Helvetica", size=14
)
frame1 = tk.Frame(
master=self.win,
# background = 'maroon'
)
frame1.pack(fill='both', expand='yes')
editArea = tkst.ScrolledText(
master=frame1,
wrap=tk.WORD,
font=self.customFont,
)
editArea.pack(padx=3, pady=3, fill=tk.BOTH, expand=True)
editArea.focus_set()
menubar = tk.Menu(self.win)
# create a pulldown menu, and add it to the menu bar
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Open",)
filemenu.add_command(label="Save",)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.Exit)
menubar.add_cascade(label="File", menu=filemenu)
fontMenu=tk.Menu(menubar, tearoff=1)
fontMenu.add_command(label="IncreaseFont", command=self.IncreaseFont)
fontMenu.add_command(label="DecreaseFont", command=self.DecreaseFont)
menubar.add_cascade(label="Font", menu=fontMenu)
self.win.config(menu=menubar)
self.win.mainloop()
def IncreaseFont(self):
size = self.customFont['size']
self.customFont.configure(size=size + 2)
def DecreaseFont(self):
size = self.customFont['size']
if size-2>0:
self.customFont.configure(size=size - 2)
def Exit(self):
result = messagebox.askokcancel("Python","Would you like to save the data?")
if result:
self.win.destroy()
else:
pass
app=App() |
3cf88f244b057415c6fdd409999c97f7cef857c5 | icculp/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 214 | 3.609375 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new_matrix = [None] * len(matrix)
for i in range(len(matrix)):
new_matrix[i] = list(map(lambda x: (x ** 2), matrix[i]))
return new_matrix
|
0219e70ccc08682ce0b54675c2b4d96b3d5a5ea7 | hustqb/NNLearningLog | /example/LearnCNN/cifar_10_cnn.py | 3,707 | 3.625 | 4 | # coding=utf-8
"""
Train a simple deep CNN on the CIFAR10 small images dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dense, Dropout, Flatten, Input
from keras.models import Model
from keras.preprocessing.image import ImageDataGenerator
from utils.datasets import load_cifar10
input_shape = (32, 32, 3)
batch_size = 32
num_classes = 10
epochs = 200
data_augmentation = True
def load_data():
# The data, shuffled and split between train and test sets:
(x_train, y_train), (x_test, y_test) = load_cifar10()
print('x_train shape:', x_train.shape) # (n, 32, 32, 3)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
return (x_train, y_train), (x_test, y_test)
def cnn():
input_data = Input(input_shape)
x = Conv2D(32, (3, 3), padding='same', activation='relu')(input_data)
x = Conv2D(32, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Dropout(0.25)(x)
x = Conv2D(64, (3, 3), padding='same', activation='relu')(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Dropout(0.25)(x)
x = Flatten()(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(num_classes, activation='softmax')(x)
model = Model(input_data, x)
return model
def main():
(x_train, y_train), (x_test, y_test) = load_data()
model = cnn()
'''
SGD优化器的参数:
lr: 学习率
decay: 每次更新后的学习率衰减值
momentum: 动量参数
nesterov: 是否使用Nesterov动量
'''
# initiate sgd optimizer
sgd = keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
# # initiate RMSprop optimizer
# opt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)
# Let's train the model using sgd
model.compile(sgd, 'categorical_crossentropy', metrics=['accuracy'])
if not data_augmentation:
print('Not using data augmentation.')
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test))
else:
print('Using real-time data augmentation.')
# This will do preprocessing and realtime data augmentation:
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
# Compute quantities required for feature-wise normalization
# (std, mean, and principal components if ZCA whitening is applied).
datagen.fit(x_train)
# Fit the model on the batches generated by datagen.flow().
model.fit_generator(datagen.flow(x_train, y_train,
batch_size=batch_size),
steps_per_epoch=x_train.shape[0] // batch_size,
epochs=epochs,
validation_data=(x_test, y_test))
if __name__ == '__main__':
main()
|
91fadbb3415fa9af79b647fa70f9d1aba3321a15 | Esmaaa/cis024c_springi2021 | /classwork/test_cmdline.py | 387 | 3.765625 | 4 |
import sys
if len(sys.argv) != 3:
print("Please use the following syntax:")
print("python test_cmdline.py <number1> <number2>")
sys.exit(-1)
try:
n1 = float(sys.argv[1])
n2 = float(sys.argv[2])
except ValueError as error:
print("Please enter numerical values for the numbers")
sys.exit(-1)
result = n1 + n2
print("Addition result:", result)
|
cda5b08e7f04e2bbf9427b0287b7a577fb1b172e | Samkiroko/python_100_days | /.history/3_of_100_20210409165424.py | 1,786 | 4.5 | 4 |
# Write a program that works out whether if a given year is a leap year.
# A normal year has 365 days, leap years have 366, with an extra day in February.
# The reason why we have leap years is really fascinating,
# this video does it more justice:
# 🚨 Don't change the code below 👇
year = int(input("Which year do you want to check? "))
# 🚨 Don't change the code above 👆
# Write your code below this line 👇
# if (year % 4) == 0:
# if (year % 100) == 0:
# if (year % 400) == 0:
# print("{0} is a leap year".format(year))
# else:
# print("{0} is not a leap year".format(year))
# else:
# print("{0} is a leap year".format(year))
# else:
# print("{0} is not a leap year".format(year))
# if year % 4 == 0:
# if year % 100 == 0:
# if year % 400 == 0:
# print("leap year")
# else:
# print("not leap year")
# else:
# print("leap year")
# else:
# print("not leap year")
# if/ elif /else
# Ticket code
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
bill = 0
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age < 12:
bill = 5
print("Child tickets are $5.")
elif age <= 18:
bill = 7
print("Youth tickets are $7.")
elif age >= 45 and age <= 55:
print("Everything is going to be ok. Have a free ride on us!")
else:
bill = 12
print("Adult tickets are $12.")
wants_photo = input("Do you want a photo taken? Y or N. ")
if wants_photo == "Y":
bill += 3
print(f"Your final bill is ${bill}")
else:
print("Sorry, you have to grow taller before you can ride.")
|
4100a4db6fe04d9305f0d559716d929c25243782 | KU-ALPS-15/minhyeok | /4949_균형잡힌세상.py | 1,319 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
class stack:
def __init__(self):
self.items = []
def empty(self):
return not self.items
def push(self, item):
self.items.append(item)
def pop(self):
if not self.items:
return -1
else:
return self.items.pop()
def size(self):
return len(self.items)
def top(self):
if not self.items:
return -1
else:
return self.items[-1]
str = []
answer = []
for i in range(100):
str.append(input())
if str[i] == '.':
break
num = len(str)
for i in range(num-1):
answer.append('yes')
for i in range(num-1):
stk = stack()
#if not str[i][-1] == '.':
# answer[i] = 'no'
# continue
for k in range(len(str[i])):
if str[i][k] == '(':
stk.push('(')
elif str[i][k] == '[':
stk.push('[')
elif str[i][k] == ')':
if not stk.pop() == '(':
answer[i] = 'no'
elif str[i][k] == ']':
if not stk.pop() == '[':
answer[i] = 'no'
if not stk.empty():
answer[i] = 'no'
for i in range(num-1):
print(answer[i])
# In[ ]:
|
f4b146857e56224c068844105b3848dca70bc6d5 | rajeshsvv/Lenovo_Back | /1 PYTHON/7 PROGRAMMING KNOWLEDGE/38_Raising_Exceptions.py | 461 | 3.984375 | 4 | class CoffeeCup:
def __init__(self,temperature):
self.__temperature=temperature
def DrinkCoffe(self):
if self.__temperature>85:
# print("Coffee is too hot")
raise Exception("Coffee is too hot")
elif self.__temperature<65:
# print("Coffee is too cold")
raise ValueError("Coffee is too cold")
else:
print("Coffee 0k to drink")
cup=CoffeeCup(80)
cup.DrinkCoffe()
|
17d74cc432607277ee74ed8d60ad00810e8d2e2a | Gp32Prog66/Python-Projects | /Python Projects/Starting Out With Python Projects/Chapter 2/Mass And Weight/Mass_And_Weight.py | 446 | 4.3125 | 4 | print('This Program Calculates Weight and Mass')
#Ask For
mass = int(input('What is the mass of the object?'))
#Calculate Mass of The Object
weight = mass * 9.8
#Determining The Weight of the Object
if weight >= 500:
print('This Object is too Heavy')
print(weight)
elif weight <= 100:
print('This Object is too Light')
print(weight)
else:
print('Here is the Weight of the Object')
print(weight)
|
7ccb3ddd02966ab7a2735be1705e66bd0ef56bdb | Davidxswang/leetcode | /medium/150-Evaluate Reverse Polish Notation.py | 1,992 | 4.03125 | 4 | """
https://leetcode.com/problems/evaluate-reverse-polish-notation/
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
"""
# time complexity: O(n), space complexity: O(n)
# the key is to use a stack to store the operands and result of the operation, when we meed the operator, we take out two operands to operate on. When we finish the operation, we store the result in the stack.
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
i = 0
while i < len(tokens):
op = tokens[i]
if op in ('+','-','*','/'):
op2 = int(stack.pop())
op1 = int(stack.pop())
if op == '+':
stack.append(op1 + op2)
elif op == '-':
stack.append(op1 - op2)
elif op == '*':
stack.append(op1 * op2)
else:
if op2 * op1 < 0 and op1 % op2 != 0:
stack.append(op1 // op2 + 1)
else:
stack.append(op1 // op2)
else:
stack.append(op)
i += 1
return stack[-1] if stack else 0
|
dff19684d6e91cf2d431b675df9160b678b58c18 | DanJamRod/assignment-1-DanJamRod | /q5.py | 2,177 | 4.09375 | 4 | def awesome_word(word):
""" Finds if word is an awesome word (at least one identical non-overlapping word couplet and one xyx type substring)
"""
flag = False # Sets flag initially to False
for i in range (len(word)-2): # Runs the program for every letter except the last two (last two letters have no pairs to compare it to after)
for j in range (len(word)-3-i): # Runs the program for every letter after letter[i]&[i+1], except the last two (last two letters have no pairs to compare it to after)
if word[i:i+2] == word[j+i+2:j+i+4]: # Checks whether a specific letter pair is equal to a specific later pair
flag = True # If there is an identical non-overlapping word couplet, flag changes to True
if flag == False: # If the flag is not True, there is no identical non-overlapping word couplet, word is not awesome and returns False. If flag is True, word continues to the next check
return False
flag = False # Resets flag to False
for i in range(len(word)-2): # Runs the program for every letter except the last two (last two letters have no letters to compare it to after)
if word[i] == word [i+2]: # Checks whether the letter is the same as the second letter after (i.e. whether xyx, y can be any value(including x))
flag = True # If there is an identical xyx type substring, flag changes to True
return flag # If flag is False, no identical xyx type substring, word returns False. If identical xyx type substring, word is awesome so returns True
def find_awesome_words():
"""
return the number of awesome words in the text file
"""
f = open("drunkard_words.txt") # makes f notate the file "drunkard_words.txt"
count = 0 # Start count at 0
for word in f: # Runs program for every word in the list
if awesome_word(word) == True: # Checks whether the word is an awesome word
print(word) # Prints the word if it is an awesome word
count += 1 # Adds 1 to the count if the word is an awesome word
return count # After checking all of the words, returns the count of how many are good words
print(find_awesome_words()) |
4772d38c27610f6d84564b74c3403dbff9b09a3d | DurbekRaxmonqulovich/begin | /13-пример.py | 135 | 3.703125 | 4 | pi=3.14
r1=int(input())
r2=int(input())
s1=pi*r1**2
s2=pi*r2**2
s3=pi*(s1-s2)
print('S1=',s1)
print('S2=',s2)
print('S3=',s3)
|
faeff6ef2cd57af785bf24ceb1a2e93ff3e6a9ef | deladan/moocpython | /corriges2rst/fichiers/toc_convertRST.py | 2,672 | 3.609375 | 4 | #!/usr/bin/env python3
#!python3
"""
Script adapté à partir d'un modèle mis à dispo sur le Mooc Python 3
Script de départ à compléter et à optimiser...
Commentaires sur le script en cours et toutes suggestions bienvenues ;)
Permet de regrouper les fichiers txt des corrigés par semaine sur un seul fichier rst
Hypothèse de départ : tous les fichiers y compris le script sont dans le même dossier
"""
import os # module suivant platforme
print(os)
import glob
print(glob) # manipuation de fichier ?
import re # formatage des données
# mettre tout les fichiers .txt dans une liste
corriges_list = glob.glob("*.txt")
#corriges_list = [nom for nom in corriges_list]
corriges_list.sort()
print(corriges_list)
# ouvre en lecture et ferme en"context manager" chaque fichier corriges.txt
# récupération des données par fichier, regroupement et mise en forme des données
def read():
full_contents = ""
for i, titre_semaine in enumerate(corriges_list):
with open(titre_semaine, encoding='utf-8') as entree:
contents = [line for line in entree.readlines()]
for i, line in enumerate(contents):
#suppression des ### et autres lignes inutiles
line = re.sub(r"^#*[\n]", "\n", line)
line = re.sub(r"(\# -\*- coding: utf-8 -\*-)", '', line)
line = re.sub(r"^(#*\s{1})$", '', line)
# titre 2
if re.search(r"\w*(Corrigés de la semaine \d)\n", line):
titre2 = re.search(r"\w*(Corrigés de la semaine \d)\n", line)[0]
line = "\n\n" + titre2 + ("-" * len(titre2)) + "\n\n"
# titre 3
if re.search(r"\w*(Semaine \d Séquence \d\n)", line):
titre3 = "\n" + re.search(r"\w*(Semaine \d Séquence \d\n)", line)[0]
line = titre3 + ("~" * len(titre3)) + "\n\n" + ".. code:: ipython3" + "\n\n"
# regroupement de tous les corrges dans un seul objet
full_contents += f"{line}"
# lance l'écriture dans le fichier de regroupement rst
write(full_contents)
# ouvre en écriture et ferme en"context manager" le fichier de regroupement rst
# regroupant tous les corrigés
def write(full_contents):
titre = "Corrigés"
titre = titre + "\n" + ("=" * len(titre))
with open('corriges-all.rst', "w", encoding='utf-8') as sortie:
sortie.write(titre)
sortie.write(f"{full_contents}")
# lance la lecture et le regroupement des données
read()
|
04a18ec873f60d8fd8a971a6c3c248ef1a40da71 | manas3789/Hacktoberfest | /Beginner/03. Python/LensSlice.py | 722 | 4.5 | 4 | """
Len's Slice
You work at Len’s Slice, a new pizza joint in the neighborhood. You are going to use your knowledge of Python lists to organize some of your sales data.
Concepts tested here are List SLicing,Sorting and Zipping.
"""
toppings=['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms']
prices= [2, 6, 1, 3, 2, 7, 2]
num_pizzas=len(toppings)
print("We sell "+str(num_pizzas)+" different kinds of pizza!")
pizzas=list(zip(prices,toppings))
pizzas.sort()
print(pizzas)
cheapest_pizza=pizzas[0]
priciest_pizza=pizzas[-1]
print(cheapest_pizza)
print(priciest_pizza)
three_cheapest=pizzas[:3]
print(three_cheapest)
num_two_dollar_slices=prices.count(2)
print(num_two_dollar_slices)
|
3498c21480ac6ef46e8a096edfb52566364454f6 | JaD33Z/ExercismIO-solutions | /python/word-count/word_count.py | 195 | 3.859375 | 4 | import re
def count_words(sentence):
str = re.findall(r"[a-zA-Z0-9]+(?:'\w+)?", sentence.lower())
freq = [str.count(word) for word in str]
return dict(zip(str, freq))
return str
|
e8dbc16833a37225f5ad7361efecff3c09c10209 | Gumbeat/test_tasks | /9/main.py | 829 | 3.875 | 4 | def biggest_substr(s1, s2):
if len(s1) > len(s2):
s1, s2 = s2, s1
i = 0
max_substr = ''
while i < len(s1):
i2 = 0
while i2 < len(s2):
if s1[i] == s2[i2]:
j = i
substr = ''
while j < len(s1) and i2 < len(s2) and s1[j] == s2[i2]:
substr += s1[j]
j += 1
i2 += 1
if len(substr) > len(max_substr):
max_substr = substr
else:
i2 += 1
i += 1
return max_substr
s1 = input('Введите первую строку: ')
s2 = input('Введите вторую строку: ')
s3 = biggest_substr(s1, s2)
print(f'Наибольшая подстрока: {s3}')
# abcd abd abcdef
# abcdefabcx xd cgxddd |
d5ff290c9445ddcea0f68ad9df67fe49fa23b642 | isakss/Forritun1_Python | /employee.py | 1,240 | 3.78125 | 4 |
class Employee(object):
def __init__(self, employee_name = ""):
self._employee_name = employee_name
def get_name(self):
return self._employee_name
class HourlyEmployee(Employee):
EXCESS_RATE = 1.5
def __init__(self, employee_name = "", hourly_wages = 0.0):
super().__init__(employee_name)
self.hourly_wages = hourly_wages
def weekly_pay(self, hours):
if hours > 40:
return (self.hourly_wages * 40) + ((self.hourly_wages * self.EXCESS_RATE) * (hours - 40))
else:
return self.hourly_wages * 40
class SalariedEmployee(Employee):
WEEKS_IN_YEAR = 52
def __init__(self, employee_name = "", annual_salary = 0.0):
super().__init__(employee_name)
self.annual_salary = annual_salary
def weekly_pay(self, hours):
return self.annual_salary / self.WEEKS_IN_YEAR
class Manager(SalariedEmployee):
def __init__(self, employee_name = "", annual_salary = 0.0, weekly_bonus = 0.0):
super().__init__(employee_name, annual_salary)
self.weekly_bonus = weekly_bonus
def weekly_pay(self, hours):
return (self.annual_salary / self.WEEKS_IN_YEAR) + self.weekly_bonus
|
89988b28733a7ddb21a5ecc19fc3d59c7279cb32 | GuiRodriguero/pythonFIAP | /2 Semestre/Aula17/Assassinato.py | 1,215 | 4.09375 | 4 | #Lista de Perguntas
perguntas = ["Telefonou para a vítima? ", "Esteve no local do crime? ", "Mora perto da vítima? ",
"Devia para a vítima? ", "Já trabalhou com a vítima? "]
def perguntar(perguntas):
respostas_positivas = 0
#Passa por todas as perguntas
for x in range(len(perguntas)):
#Inicializa a variável de resposta atual
resposta_atual = ""
#Validação para aceitar somente S ou N
while resposta_atual != "N" or resposta_atual !="S":
print(perguntas[x] + "Responda com S/N") #Mostra a pergunta
resposta_atual = input("").upper() #Recebe a resposta
# Se a resposta for S ou N ele sai do laço While
if resposta_atual == "S" or resposta_atual == "N":
break
#Soma as respostas positivas
if resposta_atual == "S":
respostas_positivas += 1
return respostas_positivas
resultado = perguntar(perguntas) #Recebe como retorno o número de respostas positivas
print("\n:::RESULTADO:::")
if resultado == 2:
print("SUSPEITO")
elif resultado == 3 or 4:
print("CÚMPLICE")
elif resultado == 5:
print("ASSASSINO")
else:
print("INOCENTE")
|
b5fb13c1999c5cb6546c35e9a5b99a5cf21ffe89 | toroleyson/data-prework | /1.-Python/6.-Rock–Paper–Scissors/Problem 6 - Arnoldo Leyson.py | 4,826 | 4.6875 | 5 | Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> ##1. Import the choice function of the random module.
>>> import random
>>>
>>> ##2. Create a list that includes the 3 possible gesture options of the game: 'rock', 'paper' or 'scissors'. Store the list in a variable called gestures.
>>> gestures = ['rock', 'paper', 'scissors']
>>>
>>> ##3. Create a variable called n_rounds to store the maximum number of rounds to play in a game.
>>> n_rounds = 5
>>>
>>> ##4. Create a variable called rounds_to_win to store the number of rounds that a player must win to win the game.
>>> rounds_to_win = round((n_rounds+0.5)/2)
>>> print("Rounds to win:", rounds_to_win)
Rounds to win: 3
>>> ##5. Create two variables to store the number of rounds that the computer and the player have won. Call these variables cpu_score and player_score.
>>> cpu_score = 0
>>> player_score = 0
>>> tie_score = 0
>>>
>>> ##6. Define a function that randomly returns one of the 3 gesture options.
>>> random.choice(gestures)
'paper'
>>>
>>> ##7. Define a function that asks the player which is the gesture he or she wants to show: 'rock', 'paper' or 'scissors'.
>>> player_choice = input ('Choose: rock, paper or scissors (write in lowercase):')
Choose: rock, paper or scissors (write in lowercase):rock
>>> while (player_choice != "rock") & (player_choice != "paper") & (player_choice != "scissors"):
player_choice = input ('Choose: rock, paper or scissors:')
>>> ##8. Define a function that checks who won a round.
>>> ##9. Define a function that prints the choice of the computer, the choice of the player and a message that announces who won the current round.
>>> ##10. Now it's time to code the execution of the game using the functions and variables you defined above.
>>> ##11. Print the winner of the game based on who won more rounds.
>>>
>>> round_number = 0
>>>
>>> while True:
print ("Round:", round_number+1)
player_choice = input ("What is your choice: rock, paper or scissors?")
cpu_choice = random.choice(gestures)
print ("Player choice:", player_choice)
print ("CPU choice:", cpu_choice)
if player_choice == cpu_choice:
print ("Result: Draw, Let's repeat this round:")
tie_score = tie_score + 1
round_number = round_number
elif (player_choice == "rock") and (cpu_choice == "paper"):
print ("Result: CPU wins")
cpu_score = cpu_score + 1
round_number = round_number + 1
if cpu_score >= rounds_to_win:
print("CPU won the game")
break
elif (player_choice == "rock") and (cpu_choice == "scissors"):
print ("Result: You win")
player_score = player_score + 1
round_number = round_number + 1
if player_score >= rounds_to_win:
print("You won the game")
break
elif (player_choice == "paper") and (cpu_choice == "scissors"):
print ("Result: CPU wins")
cpu_score = cpu_score + 1
round_number = round_number + 1
if cpu_score >= rounds_to_win:
print("CPU won the game")
break
elif (player_choice == "paper") and (cpu_choice == "rock"):
print ("Result: You win")
player_score = player_score + 1
round_number = round_number + 1
if player_score >= rounds_to_win:
print("You won the game")
break
elif (player_choice == "scissors") and (cpu_choice == "rock"):
print ("Result: CPU wins")
cpu_score = cpu_score + 1
round_number = round_number + 1
if cpu_score >= rounds_to_win:
print("CPU won the game")
break
elif (player_choice == "scissors") and (cpu_choice == "paper"):
print ("Result: You win")
player_score = player_score + 1
round_number = round_number + 1
if player_score >= rounds_to_win:
print("You won the game")
break
else:
print ("Invalid choice, Let's try again!")
round_number = round_number
if round_number >= n_rounds:
break
Round: 1
What is your choice: rock, paper or scissors?rock
Player choice: rock
CPU choice: scissors
Result: You win
Round: 2
What is your choice: rock, paper or scissors?rock
Player choice: rock
CPU choice: paper
Result: CPU wins
Round: 3
What is your choice: rock, paper or scissors?rock
Player choice: rock
CPU choice: rock
Result: Draw, Let's repeat this round:
Round: 3
What is your choice: rock, paper or scissors?rock
Player choice: rock
CPU choice: scissors
Result: You win
Round: 4
What is your choice: rock, paper or scissors?rock
Player choice: rock
CPU choice: scissors
Result: You win
You won the game
>>>
|
b6381e04f959ffcbe3d9b6db904e868bf12d376f | raoulsuli/Computer-Architecture | /Python-Parallel-Marketplace/tema/marketplace.py | 5,599 | 4.21875 | 4 | """
This module represents the Marketplace.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Lock, currentThread
class Marketplace:
"""
Class that represents the Marketplace. It's the central part of the implementation.
The producers and consumers use its methods concurrently.
"""
def __init__(self, queue_size_per_producer):
"""
Constructor
:type queue_size_per_producer: Int
:param queue_size_per_producer: the maximum size of a queue associated with each producer
"""
self.queue_size_per_producer = queue_size_per_producer #size for every producer in buffer
self.last_producer = -1 #keep track of producers ids
self.last_cart = -1 #keep track of carts ids
self.carts = {} #dictionary of carts, each containing items and their quantity
self.storage = {} #dictionary of slots available for every buffer
self.products = {} #dictionary of (product, producer_id), quantity
self.lock_producer = Lock() #lock for producer actions
self.lock_consumer = Lock() #lock for consumer actions
def register_producer(self):
"""
Returns an id for the producer that calls this.
"""
with self.lock_producer: #access storage only with a thread
self.last_producer += 1 #add another producer
self.storage[self.last_producer] = self.queue_size_per_producer #initialize its slots
return self.last_producer #return its id
def publish(self, producer_id, product):#
"""
Adds the product provided by the producer to the marketplace
:type producer_id: String
:param producer_id: producer id
:type product: Product
:param product: the Product that will be published in the Marketplace
:returns True or False. If the caller receives False, it should wait and then try again.
"""
space_available = False #return value
with self.lock_producer: #access products and storage only with a thread
if self.storage[producer_id] > 0: #if the producer has space
self.storage[producer_id] -= 1 #occupy it
if (product, producer_id) in list(self.products.keys()): #add product to dictionary
self.products[(product, producer_id)] += 1
else:
self.products[(product, producer_id)] = 1
space_available = True
return space_available
def new_cart(self):
"""
Creates a new cart for the consumer
:returns an int representing the cart_id
"""
with self.lock_consumer: #access carts only with a thread
self.last_cart += 1 #add another cart
self.carts[self.last_cart] = {} #assign it a dictionary
return self.last_cart
def add_to_cart(self, cart_id, product):#
"""
Adds a product to the given cart. The method returns
:type cart_id: Int
:param cart_id: id cart
:type product: Product
:param product: the product to add to cart
:returns True or False. If the caller receives False, it should wait and then try again
"""
product_exists = False #return value
with self.lock_consumer: #access carts, products and storage only with a thread
for (prod, producer_id) in list(self.products.keys()): #if the product exists
if prod == product and self.products[(prod, producer_id)] > 0:
self.products[(prod, producer_id)] -= 1 #remove it from products
self.storage[producer_id] += 1 #release the space used
if prod in self.carts[cart_id]: #add it to cart
self.carts[cart_id][prod] += 1
else:
self.carts[cart_id][prod] = 1
product_exists = True
break
return product_exists
def remove_from_cart(self, cart_id, product):#
"""
Removes a product from cart.
:type cart_id: Int
:param cart_id: id cart
:type product: Product
:param product: the product to remove from cart
"""
product_exists = True
with self.lock_consumer: #verify cart only with a thread
if product not in self.carts[cart_id]: #if the product is not in cart
product_exists = False
if product_exists is False:
return
with self.lock_consumer: #modify carts only with a thread
if self.carts[cart_id][product] == 1: #remove the product
del self.carts[cart_id][product]
else:
self.carts[cart_id][product] -= 1
for (prod, producer_id) in list(self.products.keys()):
if prod == product: #add it back in products dictionary
self.storage[producer_id] -= 1
self.products[(prod, producer_id)] += 1
break
def place_order(self, cart_id):#
"""
Return a list with all the products in the cart.
:type cart_id: Int
:param cart_id: id cart
"""
with self.lock_consumer: #access carts only with a cart and preserve order
for product, quantity in self.carts[cart_id].items(): #print the contents of the cart
for _ in range(quantity):
print(currentThread().getName() + " bought ", end='')
print(product)
|
4972e1b64a19b150ed65d258151bf76a96e3eac0 | daniel-reich/ubiquitous-fiesta | /p94KFBXAzJ3ZxmFmw_19.py | 106 | 3.71875 | 4 |
def ascii_capitalize(txt):
return ''.join(i.upper() if ord(i) % 2 == 0 else i.lower() for i in txt)
|
a9d862d5a0de13bd4c4b9eb5550afa8ec9ab88b3 | imji0319/myProject | /pro1/course1/for_ex01.py | 744 | 3.90625 | 4 | '''
Created on 2017. 9. 29.
@author: jihye
'''
# 별 그리기
# -*-coding : utf-8 -*-
import turtle
def draw_star(x,y,size=50, pencolor='black'):
mypen=turtle.Turtle()
mypen.showturtle()
mypen.color(pencolor)
mypen.penup()
mypen.goto(x,y)
mypen.pendown()
mypen.begin_fill()
for n in range(5):
mypen.forward(size)
mypen.right(144)
mypen.end_fill()
mypen.hideturtle()
def main():
w=520 ; h=500
turtle.setup(w,h)
start=-250
size=100
for n in range(5):
if n%2 == 0 :
draw_star(start,0,size,'blue')
else:
draw_star(start,0,size,'red')
start+=size
turtle.done()
main()
|
c85ebc0cf242d3b61b75f621eb328f394ef18152 | analaura09/pythongame | /p8.py | 171 | 3.859375 | 4 | medida = float(input(' Digite uma distancia em metros: '))
cm = medida * 100
mm = medida * 1000
print(' A medida de {}m corresponde a {}cm e {}mm'.format(medida,cm,mm))
|
70654e9efc3f9c4b8ac55b45657c4d145cb6815f | nivethida/TextMining | /RegularExperssions/regularexp.py | 7,238 | 4.40625 | 4 | # -*- coding: utf-8 -*-
'''
Identifiers:
\d = any number
\D = anything but a number
\s = space
\S = anything but a space
\w = any letter
\W = anything but a letter
. = any character, except for a new line
\b = space around whole words
\. = period. must use backslash, because . normally means any character.
Modifiers:
{1,3} = for digits, u expect 1-3 counts of digits, or "places"
+ = match 1 or more
? = match 0 or 1 repetitions.
* = match 0 or MORE repetitions
$ = matches at the end of string
^ = matches start of a string
| = matches either/or. Example x|y = will match either x or y
[] = range, or "variance"
{x} = expect to see this amount of the preceding code.
{x,y} = expect to see this x-y amounts of the precedng code
'''
import re
text = "100 MAT Math 102 COM Computer 104 ENG English"
#split
result = re.split('\s', text) #returns list
print(result)
#split with one or more spaces
result = re.split('\s+', text) #returns list
print(result)
#findall mostly used method
result = re.findall("\d",text)
print(result)
#['1', '0', '0', '1', '0', '2', '1', '0', '4']
#find out all chunks of text
result = re.findall("\d{3}",text)
print(result)
#['100', '102', '104']
res = re.findall('\d+', text)
print(res)
#['100', '102', '104']
res = re.findall('\d*', text)
print(res)
#['100', '', '', '', '', '', '', '', '', '', '', '', '', '102', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '104', '', '', '', '', '', '', '', '', '', '', '', '', '']
res = re.findall('\d?', text)
print(res)
#['1', '0', '0', '', '', '', '', '', '', '', '', '', '', '', '', '1', '0', '2', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '1', '0', '4', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = "100 MAT Math 102023 COM Computer 104 ENG English"
res = re.findall('\d{1,5}', text)
print(res)
#['100', '10202', '3', '104']
#extract all single digit and single letters
text = "100 MAT Math 102 COM Computer 104 ENG English"
result = re.findall('\w',text)
print(result)
#['1', '0', '0', 'M', 'A', 'T', 'M', 'a', 't', 'h', '1', '0', '2', '0', '2', '3', 'C', 'O', 'M', 'C', 'o', 'm', 'p', 'u', 't', 'e', 'r', '1', '0', '4', 'E', 'N', 'G', 'E', 'n', 'g', 'l', 'i', 's', 'h']
#extract chunks of all letters and all numbers
result = re.findall('\w+',text)
print(result)
#['100', 'MAT', 'Math', '102023', 'COM', 'Computer', '104', 'ENG', 'English']
result = re.findall('[a-z0-9]+',text)
print(result)
#['100', 'ath', '102023', 'omputer', '104', 'nglish']
result = re.findall('[a-zA-Z0-9]+',text)
print(result)
#[A-Za-z0-9]
#['100', 'MAT', 'Math', '102023', 'COM', 'Computer', '104', 'ENG', 'English']
result = re.findall('[A-z]+',text)
print(result)
#['MAT', 'Math', 'COM', 'Computer', 'ENG', 'English']
#extract course name
result = re.findall('[A-Z][a-z]+', text)
print(result)
#['Math', 'Computer', 'English']
# + modifies ony the symbol immediately before it !!!!!!!!!!!!!!!! important
#extract course with abbrevation
result = re.findall('[A-Z]+', text)
print(result)
#['MAT', 'M', 'COM', 'C', 'ENG', 'E']
result = re.findall('[A-Z]{3}', text)
print(result)
result = re.findall('[A-Z]{2,}', text)
print(result)
result = re.findall('^([A-Z]+)\s$', text)# ???????
print(result)
#['MAT', 'COM', 'ENG']
#CAPTURING
# what is the course abbrevation for the course 100
text = "100 MAT Math 102023 COM Computer 104 ENG English"
result = re.findall('100 [A-Z]+', text)
print(result)
#['100 MAT']
result = re.findall('100 ([A-Z]+)', text)
print(result)
#['MAT']
#to capture everything in between A and B
# version 1: .*, diligent version of everything
#version 2: .*? lazy version
text= 'I took flight UA400 today and flight UA500 today'
# extract the flight taken today !!!!!!!!!!!!!!! important
res = re.findall('flight (.*) today', text)
print(res)
#['UA400 today and flight UA500']
res2 = re.findall('flight (.*?) today', text)
print(res2)
#['UA400', 'UA500']
#GROUPING
text = 'MgMt 100, MkTg 200, AcTg 300'
result = re.findall('([A-Z][a-z])+', text)
print(result)
#['Mt', 'Tg', 'Tg']
result = re.findall('(?:[A-Z][a-z])+', text)
print(result)
#['MgMt', 'MkTg', 'AcTg']
import re
text = 'my phone number is (510)421-3123'
# a literal predecessor ( :\(
res = re.findall('\(\d+\)\d+-\d+', text)[0]
print(res)
# to extract the area code
res = re.findall('\((\d+)\)\d+-\d+', text)
print(res)
ß
# using regular exp gor stemming
import re
def stem(text):
suffix = re.findall('^.*(ing|ly|ed|ious|ies|ive|es|s|ment)$', text)[0]
print(re.findall('^.*(ing|ly|ed|ious|ies|ive|es|s|ment)$', text))
#suffix = re.findall('^.*[ing|ment|es|ive|tion|ed|ly]$', text)[0]
return text[:-len(suffix)]
print(stem('management'))
# do something but return stem and suffix at the same time
def stem(text):
suffix = re.findall('^(.+)([ing|ment|es|ive|tion|ed|ly]$)', text)[0]
#suffix = re.findall('^.*[ing|ment|es|ive|tion|ed|ly]$', text)[0]
return text[:-len(suffix)]
print(stem('management'))
def stem(text):
group = re.findall('^(.+)([ing|ment|es|ive|tion|ed|ly]$)', text)[0]
#suffix = re.findall('^.*[ing|ment|es|ive|tion|ed|ly]$', text)[0]
stem,suffix=group
return (stem,suffix)
print(stem('management'))
# match and search
# match: trys to match the pattern from the very first char in the text
# search trys to match the pattern from anywhere
text = '1010 Math 102 Com 103 Mus'
pattern = '\d{3}\s\w+'
if re.search(pattern, text):
x = re.search(pattern, text)
print('found, start from {}, ends at {}'.format(x.start(), x.end()))
else:
print('not found')
text = '1010 Math 102 Com 103 Mus'
pattern = '\d{3}\s\w+'
if re.match(pattern, text):
x = re.search(pattern, text)
print('found, start from {}, ends at {}'.format(x.start(), x.end()))
else:
print('not found')
# remake re.match using re.findall
pattern_match='^\d{3}\s\w+'
pattern_search='\d{3}\s\w+'
print(re.findall(pattern_match, text))
print(re.findall(pattern_search, text))
import re
import nltk
chat = nltk.corpus.nps_chat.posts()
#asion’ or ‘ation’
result = re.findall('^.*(asion|ation)$', chat)
print(result)
print(chat[:3])
words = nltk.corpus.nps_chat.words()
print(words[:100])
words = list(dict.fromkeys(words))# remove duplicates
# whats is the expressions for "ah", including "ahhhh", "aHahah" but not Haha
print([w for w in words if re.search('^[Aa][HhAa]+$', w)])
#extract all decimal numbers used in the chat: 0.1,0.12,.12
print([w for w in words if re.search('^\d*\.\d+$', w)])
print([w for w in words if re.search('^\d+(?:\.\d+)?$', w)])
# search for dash connected values daughter-in-law
print([w for w in words if re.search('^[a-zA-Z]+(-\w+)$', w)])
# abbrevations like U.S.A.
print([w for w in words if re.search('^(?:[A-Z]\.)+$', w)])
#currency: $13. $12.5
print([w for w in words if re.search('^\$\d+(?:\.\d+)?$', w)])
#tokenize with re, goal is to remove the punctuation , and . in the result also tonenize with tabs and multiple places
text = '''here are some spaces , here are some \t\t\t\t\t\t, here are
some new line symbols \n\n\n
'''
wordlist = re.split('[\s\t\n,\.]+', text)
print(wordlist)
import nltk
wordlist2 = nltk.word_tokenize(text)
print(wordlist2)
|
9aebfa0aba8a6b2c519f7ebb5bfefb8fe0a6d8dc | raytwelve/LeetCode | /Medium/Find the Duplicate Number.py | 1,201 | 3.859375 | 4 | '''
https://leetcode.com/problems/find-the-duplicate-number/
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.
'''
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
return self.checkSet(nums)
def checkSet(self, nums):
visited = set()
for x in nums:
if x not in visited:
visited.add(x)
else:
return x
def pythonic(self, nums):
return next(filter(lambda x: nums.count(x) > 1, nums))
def floydsCycle(self, nums):
length = len(nums)
t = 0
h = 1
v = set()
v.add((t,h))
while nums[t] != nums[h]:
t = (t +1) % length
h = (h+2) % length
if t == h:
t = (t +1) % length
h = (h+2) % length
if (t,h) in v:
t = (t+1) % length
h = (h+1) % length
v.add((t,h))
return nums[t] |
c2481e4b9f73ba61ba32518f359ac12e551fb82b | jakebaz/Python-Library-Sytem | /source_code.py | 15,824 | 3.921875 | 4 | import random
class Books():
#Initialize - create book details
def __init__(self, title, author, year, copies, publisher, pub_date):
try: #error handling to ensure the user enters the correct details and data types
self.title = title
self.author = author
self.year = year
self.copies = copies
self.publisher = publisher
self.pub_date = pub_date
self.book_id = 0
self.total_stock = 0
except: #if fails user can call the method and again to retry
print('Could not create book, please try again')
#set/overwrite book details
def set_title(self, new_title):
self.title = new_title
def set_author(self, new_author):
self.author = new_author
def set_year(self, new_year):
self.year = new_year
def set_copies(self, new_copies):
self.copies = new_copies
def set_publisher(self, new_publisher):
self.publisher = new_publisher
def set_pub_date(self, new_pub_date):
self.pub_date = new_pub_date
#return book details
def return_title(self):
return self.title
def return_author(self):
return self.author
def return_year(self):
return self.year
def return_copies(self):
return self.copies
def return_publisher(self):
return self.publisher
def return_pub_date(self):
return self.pub_date
#=====================================================================================#
class BookList(Books): #Inherit from Books class
def __init__(self): #Initialize
self.library = {}
self.total_stock = 0
#store book created in Books()
def store_book(self, bk):
try:
self.bk = bk
except:
print('Books instance not found')
self.bk.book_id = random.randint(1, 100000)
self.library[self.bk.title.lower()] = {
"Title": self.bk.title.lower(), #use of .lower() to ensure search results are found even when user enters an uppercase letter
"Author": self.bk.author.lower(),
"Year": self.bk.year,
"Availability": self.bk.copies,
"Publisher": self.bk.publisher.lower(),
"Publication Date": self.bk.pub_date,
"ID": self.bk.book_id}
self.total_stock += self.bk.copies #add the number of copies to total stock so that returning the total number of books is accurate
return self.library
def search(self, keyword):
try: #if user enters a number system won't crash
for i in self.library: #find book in dictionary and print out to the user
if keyword.lower() in self.library[i].values():
print(self.library[i])
break
else:
print('No Books Found') #Error handling: if book not found, print 'No Books found'
break
except:
print('Please search for a Title, Author, Publisher or Publication Date')
def delete_book(self, book_title):
self.book_title = book_title
try: #system won't crash if user enters a number or makes spelling mistake
if self.book_title.lower() in self.library:
c = self.library[self.book_title.lower()].get('Availability')
self.total_stock -= c
del self.library[book_title.lower()]
print('This book has been successfully deleted')
else:
print('Book not found, please ensure you have typed correctly')
except:
print('Book not found, please ensure you have typed correctly')
#return number of books in collection
def num_of_books(self):
print('There is currently', self.total_stock, 'books in your database')
return self.total_stock
#=====================================================================================#
class Users():
#Initialize - create user details
def __init__(self, username, first_name, surname, house_num, street, postcode, email, dob):
try: #error handling
self.username = username
self.first_name = first_name
self.surname = surname
self.house_num = house_num
self.street = street
self.postcode = postcode
self.email = email
self.dob = dob
except: #if fails user can call the method and again to retry
print('Could not create user, please try again')
#return user details
def return_username(self):
return self.username
def return_first_name(self):
return self.first_name
def return_surname(self):
return self.surname
def return_house_num(self):
return self.house_num
def return_street(self):
return self.street
def return_postcode(self):
return self.postcode
def return_email(self):
return self.email
def return_dob(self):
return self.dob
#change user details
def change_username(self, new_un):
self.username = new_un
def change_first_name(self, new_fn):
self.first_name = new_fn
def change_surname(self, new_sn):
self.surname = new_sn
def change_house_num(self, new_hn):
self.house_num = new_hn
def change_street(self, new_street_name):
self.street = new_street_name
def change_postcode(self, new_pc):
self.postcode = new_pc
def change_email(self, new_email):
self.email = new_email
def change_dob(self, new_dob):
self.dob = new_dob
#=====================================================================================#
class UserList(Users): #Inherit from UserList class
#Initialize
def __init__(self):
self.user_db = {}
#Store users
def store_user(self, user):
try: #error handling for if the user is not in user_db
self.user = user
except:
print('User not found')
if self.user.username in self.user_db: #no two users can have the same username
print('Username already taken, please try again with a different username.')
else:
self.user_db[self.user.username.lower()] = { #use lower() on strings so that they match user inputs
'First name': self.user.first_name.lower(),
'Surname': self.user.surname.lower(),
'House Number': self.user.house_num,
'Street name': self.user.street.lower(),
'Postcode': self.user.postcode.lower(),
'Email address': self.user.email.lower(),
'Date of birth': self.user.dob.lower()}
return self.user_db
#Remove a user
def remove_user(self, name): #add more than one user with the same name functionality
self.name = name
try:
for i in self.user_db: #Loop through dictionary to find user
if self.name.lower() in self.user_db[i].values(): #if user with given name is present, delete
del self.user_db[i]
print('This user has been successfully deleted')
break
else:
print('There is no user with this name')
break
except:
print(name, 'not found, please ensure you have typed correctly')
#Count total number of users
def count_users(self):
count = len(self.user_db)
print('There are currently', count, 'users in your database')
return count
#return a users details
def return_user_details(self, un):
u_details = []
try:
if un.lower() in self.user_db:
print(self.user_db[un])
u_details.append(self.user_db[un])
else:
print('User not Found')
except: #catch error from .lower() if user enters a number
print('User not found')
return u_details
#=====================================================================================#
class Loans(BookList, UserList): #Multiple Inheritence from BookList and UserList classes
def __init__(self, bk_inst, user_inst): #Initialize
self.bk_inst = bk_inst
self.user_inst = user_inst
self.user_loans = {}
self.book_loan = []
self.overdue_books = {}
super().__init__()
def borrow_book(self, book_title, username):
try:
if username.lower() not in self.user_inst.user_db: #error checking: if user name is 'user not found' is printed.
print('User not found')
return
except: #if an int is entered rather than a string print 'User not found'
print('User not Found')
try:
if book_title.lower() in self.bk_inst.library:
c = self.bk_inst.library[book_title.lower()].get('Availability')
c -= 1
self.bk_inst.library[book_title.lower()].update({'Availability': c}) #update library when book is taken out
self.bk_inst.total_stock -= 1 #update total stock when book is taken out
self.user_loans.setdefault(username.lower(), []).append(book_title.lower()) #append item to list in dictionary rather than replace it
if c == 0:
del self.bk_inst.library[book_title.lower()]
self.book_loan.append([username.lower(), book_title.lower()]) #for later use in function 'return_borrower_details'
print(username, 'is now borrowing', book_title)
except:
print('Book is not currently available')
def return_loan(self, book_title, username):
try: #error check: if user spells incorrectly or enters number print 'User not found'
if username.lower() not in self.user_inst.user_db: #error checking: if user name is 'user not found' is printed.
print('User not found')
return
except:
print('User not found')
return
try:
for i in self.user_loans.values():
if book_title.lower() in i:
i.remove(book_title.lower()) #update user loans dictionary when book is returned
c = self.bk_inst.library[book_title.lower()].get('Availability')
c += 1
self.bk_inst.library[book_title.lower()].update({'Availability': c}) #update library when book is returned
self.bk_inst.total_stock += 1 #update total stock when book is returned
print(book_title, 'has been returned')
if len(self.user_loans[username.lower()]) == 0:
del self.user_loans[username.lower()] #if user returns their only book, they get removed from the loans dictionary
except:
print('Book could not be returned')
def return_num_of_loans(self, username): #count and return the total number of books a user is borrowing
try:
if username.lower() in self.user_loans:
l = len(self.user_loans[username.lower()])
if l > 1:
print(username, 'is currently borrowing', l, 'books')
elif l == 1:
print(username, 'is currently borrowing 1 book')
else:
print(username, 'is not currently borrowing any books')
return l
except:
print('Could not find specified user')
def return_overdue_books(self, book_title, username):
try:
if username.lower() not in self.user_inst.user_db: #error checking: if user name is 'user not found' is printed.
print('User not found')
return
except:
print('Could not find user')
try:
for i in self.user_loans.values():
if book_title.lower() in i:
i.remove(book_title.lower()) #update user loans dictionary when book is returned
c = self.bk_inst.library[book_title.lower()].get('Availability')
c += 1
self.bk_inst.library[book_title.lower()].update({'Availability': c}) #update library when book is returned
self.bk_inst.total_stock += 1 #update total stock when book is returned
print(book_title, 'has been returned')
if len(self.user_loans[username.lower()]) == 0:
print('There are currently no overdue books for this user.')
del self.user_loans[username.lower()] #if user returns their only book, they get removed from the loans dictionary
except:
print('Book could not be returned')
def return_borrower_details(self, book):
try:
for sublist in self.book_loan: #loop list to find if book is in the dictionary
for element in sublist:
if element == book.lower():
sub = sublist #get sublist so that we can get the username of the user
usr = sub[0]
except:
print('Book not found')
if usr in self.user_inst.user_db:
print(self.user_inst.user_db[usr]) #print details of borrower of a given book
details = []
details.append(self.user_inst.return_first_name)
details.append(self.user_inst.return_surname)
details.append(self.user_inst.return_email)
return details #return first name, surname and email of borrower of a given book
#=====================================================================================#
def system_test():
#instances of users
user1 = Users('jk_baz16', 'Jake', 'Bazin', 17, 'Rosemary Avenue', 'NE14 4YA', 'jk.bazin@hotmail.co.uk', '16/05/1997')
user2 = Users('elliewantcookie', 'Ellie', 'Victoria', 5, 'Grey St', 'NE1 5AH', 'ellie@gmail.com', '23/08/1995')
user3 = Users('johnnyboy22', 'John', 'Witherham', 25, 'Hammersmith Lane', 'DH14BY', 'johnnyw22@yahoo.co.uk', '07/02/1987')
user4 = Users('TigerBoy88', 'Mike', 'Tyson', 13, 'Beverly Hills', '90035', 'miketyson@hotmail.com', '30/06/1966')
user5 = Users('jakeyboii', 'Jake', 'Manson', 12, 'Grey St', 'NE1 6BR', 'jakeymanson@googlemail.co.uk', '23/11/1993')
#Store users created in Users class
ul = UserList()
ul.store_user(user1)
ul.store_user(user2)
ul.store_user(user3)
ul.store_user(user4)
ul.store_user(user5)
#Create book instances
bk1 = Books('The Two Towers', 'J J R Tolkien', 1954, 7, 'George Allen & Unwin', '11/11/1954')
bk2 = Books('The Hunger Games', 'Suzanne Collins', 2008, 11, 'Scholastic Press', '14/09/2008')
bk3 = Books('Harry Potter And The Order Of The Pheonix', 'J K Rowling', 2003, 2, 'Bloomsbury', '21/07/2003')
bk4 = Books('The Da Vinci Code', 'Dan Brown', 2003, 5, 'Transworld and Bantom Books', '13/04/2003')
bk5 = Books('Of Mice And Men', 'John Steinbeck', 1937, 1, 'Covici Friede', '1937')
#Store Books previously created
bl = BookList()
bl.store_book(bk1)
bl.store_book(bk2)
bl.store_book(bk3)
bl.store_book(bk4)
bl.store_book(bk5)
#Loan instance with atleast one loan
loans = Loans(bl, ul)
loans.borrow_book('The Hunger Games', 'jk_baz16')
loans.borrow_book('Harry Potter And The Order Of The Pheonix', 'elliewantcookie')
loans.borrow_book('The Two Towers', 'johnnyboy22')
loans.borrow_book('The Da Vinci Code', 'jk_baz16')
system_test() |
c33e7e341130d67149fa86c7c66d0aa5c1d2fa58 | zingzheng/LeetCode_py | /26Remove Duplicates from Sorted Array.py | 658 | 3.59375 | 4 | ##Remove Duplicates from Sorted Array
##Given a sorted array, remove the duplicates in place such that
##each element appear only once and return the new length.
##Do not allocate extra space for another array,
##you must do this in place with constant memory.
##
##2015年6月30日 AC
##zss
class Solution:
# @param {integer[]} nums
# @return {integer}
def removeDuplicates(self, nums):
if not nums:
return 0
lenth = i = 1
while i < len(nums):
if nums[i-1] != nums[i]:
lenth += 1
i += 1
else:
nums.remove(nums[i])
return lenth
|
f7e2042c9fe30af15948a609d10d06b56dcd1bff | 40205331/algorithmsCW | /pythonCW.py | 28,085 | 3.640625 | 4 | import sys
# set colours for pieces
Black = '\033[94m'
Red = '\033[91m'
End = '\033[0m'
# create classes for pieces on the board
class hashtag(object):
def __repr__(self):
return hashtag()
def __str__(self):
return Black + "| # |" + End
class atsign(object):
def __repr__(self):
return atsign()
def __str__(self):
return Red + "| @ |" + End
class emptySpace(object):
def __repr__(self):
return emptySpace()
def __str__(self):
return "| |"
class hashtagKing(object):
def __repr__(self):
return hashtagKing()
def __str__(self):
return Black + "| King# " + End
class atsignKing(object):
def __repr__(self):
return atsignKing()
def __str__(self):
return Red + "| King@ |" + End
# create lists for items to be removed if pieces are taken
hashPieces = [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
atPieces = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
noPieces = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#method to remove a hashtag item from the list if a piece is taken
def hashPieceTaken(hashPieces, noPieces):
#remove first item in the list
hashPieces.pop(0)
#reset the stalemate list
noPieces = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# if list is empty other team wins
if not hashPieces:
print "Player 1 wins!"
sys.exit()
#method to remove a atsign item from the list if a piece is taken
def atPiecesTaken(atPieces, noPieces):
#remove first item in the list
atPieces.pop(0)
#reset stalemate list
noPieces = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# if list is empty player 2 wins
if not atPieces:
print "Player 2 wins!"
sys.exit()
# method for if there cant be a winner
def noPiecesLeft(noPieces):
# remove first item in the list
noPieces.pop(0)
# if list is empty its a stalemate
if not noPieces:
print "Piece has not been taken in 40 turns. It's a stalemate"
sys.exit()
# create board
board =[[" "," 1 ", " 2 "," 3 "," 4 "," 5 ", " 6 "," 7 "," 8 "],
['----------------------------------------------------------------------------------'],
[" 2 " , emptySpace(), hashtag(), emptySpace(), hashtag(), emptySpace(), hashtag(), emptySpace(), hashtag()],
['----------------------------------------------------------------------------------'],
[" 4 " , hashtag(), emptySpace(), hashtag(), emptySpace(), hashtag(), emptySpace(), hashtag(), emptySpace()],
['----------------------------------------------------------------------------------'],
[" 6 " , emptySpace(), hashtag(), emptySpace(), hashtag(), emptySpace(), hashtag(), emptySpace(), hashtag()],
['----------------------------------------------------------------------------------'],
[" 8 " , emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace()],
['----------------------------------------------------------------------------------'],
[" 10 " , emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace(), emptySpace()],
['----------------------------------------------------------------------------------'],
[" 12 " , atsign(), emptySpace(), atsign(), emptySpace(), atsign(), emptySpace(), atsign(), emptySpace()],
['----------------------------------------------------------------------------------'],
[" 14 " , emptySpace(), atsign(), emptySpace(), atsign(), emptySpace(), atsign(), emptySpace(), atsign()],
['----------------------------------------------------------------------------------'],
[" 16 " , atsign(), emptySpace(), atsign(), emptySpace(), atsign(), emptySpace(), atsign(), emptySpace()]]
#print board
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
#team 1 logic
def team1(board):
print "team 1 turn"
while True:
# validation for movement
while True:
# validation to make sure only numbers are entered
RowCoordinate = raw_input ("enter row number: ")
try:
RowCoordinateInt = int(RowCoordinate)
except SyntaxError:
print "Please enter (only) a number: "
continue
except ValueError:
print "Please enter (only) a number: "
continue
# if a number non even number from 2-16 is entered throw error
if RowCoordinateInt not in [2, 4, 6, 8, 10, 12, 14, 16]:
print "row coordinate out of range"
continue
else:
RowCoordinateInt = int(RowCoordinate)
break
# validation to make sure only numbers are entered
while True:
ColCoordinate = raw_input ("enter column number: ")
try:
ColCoordinateInt = int(ColCoordinate)
except SyntaxError:
print "Please enter (only) a number: "
continue
except ValueError:
print "Please enter (only) a number: "
continue
# if a number out with 1-8 is entered throw error
if ColCoordinateInt not in [1, 2, 3, 4, 5, 6, 7, 8]:
print "column coordinate out of range"
continue
else:
ColCoordinateInt = int(ColCoordinate)
break
# validation to make sure only numbers are entered
while True:
RowDestination = raw_input ("enter row number to move to: ")
try:
RowDestinationInt = int(RowDestination)
except SyntaxError:
print "Please enter a number: "
continue
except ValueError:
print "Please enter a number: "
continue
# if a number non even number from 2-16 is entered throw error
if RowDestinationInt not in [2, 4, 6, 8, 10, 12, 14, 16]:
print "row coordinate out of range"
continue
else:
RowDestinationInt = int(RowDestination)
break
# validation to make sure only numbers are entered
while True:
ColDestination = raw_input ("enter column number to move to: ")
try:
ColDestinationInt = int(ColDestination)
except SyntaxError:
print "Please enter a number: "
continue
except ValueError:
print "please enter a number: "
continue
# if a number out with 1-8 is entered throw error
if ColDestinationInt not in [1, 2, 3, 4, 5, 6, 7, 8]:
print "Column coordinate out of range"
continue
else:
ColDestinationInt = int(ColDestination)
break
# Movement validations
# if piece to move is an atsign
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsign()):
# make sure piece cant move more than one column either way
if type(board[RowCoordinateInt-2][ColCoordinateInt+1]) == type(emptySpace()) and type(board[RowCoordinateInt-2][ColCoordinateInt-1]) == type(emptySpace()):
# make sure piece cant move more than one row forward
if RowDestinationInt is not RowCoordinateInt - 2:
print "error can only move one row forward"
continue
# validation to make sure the piece moves forward
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsign()):
if RowDestinationInt >= RowCoordinateInt:
print "Invalid move. Must move diagonally forward"
continue
# validation to make sure king moves forward or backwards only one space
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsignKing()):
if type(board[RowCoordinateInt-2][ColCoordinateInt+1]) == type(emptySpace()) and type(board[RowCoordinateInt-2][ColCoordinateInt-1]) == type(emptySpace()):
if RowDestinationInt is not RowCoordinateInt - 2 or RowDestinationInt is not RowCoordinateInt + 2:
print "Invalid move. Must move diagonally forward or backwards"
continue
# validation to make sure piece moves left or right
if ColDestinationInt == ColCoordinateInt:
print "Invalid move. Must move left or right"
continue
# validation to move on top of an enemy piece
if type(board[RowDestinationInt][ColDestinationInt]) == type(hashtag()):
print "Invalid move. Already a counter here"
continue
# validation to try move an opponents piece
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtag()):
print "Invalid move. this is an enemy"
continue
# validation to move on top of your own piece
if type(board[RowDestinationInt][ColDestinationInt]) == type(atsign()):
print "Invalid move. Already a counter here"
continue
# validation to move an empty space
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(emptySpace()):
print "Invalid move. Can't move empty space"
continue
# movement logic for a regular atsign to move the correct spaces to take enemy pieces forward and to the left and reprint board
if RowCoordinateInt > 4:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsign()):
if RowCoordinateInt > 4 and ColCoordinateInt > 2:
if type(board[RowCoordinateInt - 4][ColCoordinateInt - 2]) == type(emptySpace()):
if type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(hashtag()) or type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(hashtagKing()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt - 2][ColCoordinateInt - 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsign()
hashPieceTaken(hashPieces, noPieces)
if RowDestinationInt == 2:
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a regular atsign to move the correct spaces to take enemy pieces forward and to the right and reprint board
if RowCoordinateInt > 4:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsign()):
if RowCoordinateInt > 4 and ColCoordinateInt < 7:
if type(board[RowCoordinateInt - 4][ColCoordinateInt + 2]) == type(emptySpace()):
if type(board[RowCoordinateInt - 2][ColCoordinateInt + 1]) == type(hashtag()) or type(board[RowCoordinateInt - 2][ColCoordinateInt + 1]) == type(hashtagKing()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt - 2][ColCoordinateInt + 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsign()
hashPieceTaken(hashPieces, noPieces)
if RowDestinationInt == 2:
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a king atsign to move the correct spaces to take enemy pieces forward and to the right and reprint board
if RowCoordinateInt > 4:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsignKing()):
if RowCoordinateInt > 4 and ColCoordinateInt < 7 :
if type(board[RowCoordinateInt - 4][ColCoordinateInt + 2]) == type(emptySpace()):
if type(board[RowCoordinateInt - 2][ColCoordinateInt + 1]) == type(hashtag()) or type(board[RowCoordinateInt - 2][ColCoordinateInt + 1]) == type(hashtagKing()):
if RowDestinationInt < RowCoordinateInt:
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt - 2][ColCoordinateInt + 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsignKing()
hashPieceTaken(hashPieces, noPieces)
if RowDestinationInt == 2:
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a king atsign to move the correct spaces to take enemy pieces forward and to the left and reprint board
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsignKing()):
if RowCoordinateInt > 4 and ColCoordinateInt > 2:
if type(board[RowCoordinateInt - 4][ColCoordinateInt - 2]) == type(emptySpace()):
if type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(hashtag()) or type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(hashtagKing()):
if RowDestinationInt < RowCoordinateInt:
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt - 2][ColCoordinateInt - 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsignKing()
hashPieceTaken(hashPieces, noPieces)
if RowDestinationInt == 2:
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a regular atsign to move the correct spaces to take enemy pieces backwards and to the right and reprint board
if RowCoordinateInt < 14:
if RowCoordinateInt < 14 and ColCoordinateInt < 7:
if type(board[RowCoordinateInt + 4][ColCoordinateInt + 2]) == type(emptySpace()):
if type(board[RowCoordinateInt + 2][ColCoordinateInt + 1]) == type(hashtag()) or type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(hashtagKing()):
if RowDestinationInt < RowCoordinateInt:
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt + 2][ColCoordinateInt + 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsignKing()
hashPieceTaken(hashPieces, noPieces)
if RowDestinationInt == 2:
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a regular atsign to move the correct spaces to take enemy pieces backwards and to the left and reprint board
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsignKing()):
if RowCoordinateInt < 14 and ColCoordinateInt > 2:
if type(board[RowCoordinateInt + 4][ColCoordinateInt - 2]) == type(emptySpace()):
if type(board[RowCoordinateInt + 2][ColCoordinateInt - 1]) == type(hashtag()) or type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(hashtagKing()):
if RowDestinationInt < RowCoordinateInt:
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt + 2][ColCoordinateInt - 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsignKing()
hashPieceTaken(hashPieces, noPieces)
print "219"
if RowDestinationInt == 2:
print "lllll"
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for regular piece to move to an empty space
if RowDestinationInt >= 2:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsign()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsign()
noPiecesLeft(noPieces)
if RowDestinationInt == 2:
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# # movement logic for king piece to move to an empty space
if RowDestinationInt >= 2:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsignKing()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = atsignKing()
noPiecesLeft(noPieces)
if RowDestinationInt == 2:
board[RowDestinationInt][ColDestinationInt] = atsignKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# team 2 logic
def team2(board):
print "team 2 turn"
while True:
# validation for movement
while True:
# make sure only numbers are entered
RowCoordinate = raw_input ("enter row number: ")
try:
RowCoordinateInt = int(RowCoordinate)
except SyntaxError:
print "Please enter a number: "
continue
except ValueError:
print "Please enter a number: "
continue
# throw error if any non even number between 2 - 16 is entered
if RowCoordinateInt not in [2, 4, 6, 8, 10, 12, 14, 16]:
print "row coordinate out of range"
continue
else:
RowCoordinateInt = int(RowCoordinate)
break
while True:
# make sure only numbers are entered
ColCoordinate = raw_input ("enter column number: ")
try:
ColCoordinateInt = int(ColCoordinate)
except SyntaxError:
print "Please enter a number: "
continue
except ValueError:
print "Please enter a number: "
continue
# throw error if number out with 1-8 is entered
if ColCoordinateInt not in [1, 2, 3, 4, 5, 6, 7, 8]:
print " Column coordinate out of range"
continue
else:
ColCoordinateInt = int(ColCoordinate)
break
while True:
# make sure only numbers are entered
RowDestination = raw_input ("enter row number to move to: ")
try:
RowDestinationInt = int(RowDestination)
except SyntaxError:
print "Please enter a number: "
continue
except ValueError:
print "Please enter a number: "
continue
# throw error if non even number between 2-16 is enetered
if RowDestinationInt not in [2, 4, 6, 8, 10, 12, 14, 16]:
print "row coordinate out of range"
continue
else:
RowDestinationInt = int(RowDestination)
break
while True:
# make sure only number is entered
ColDestination = raw_input ("enter column number to move to: ")
try:
ColDestinationInt = int(ColDestination)
except SyntaxError:
print "Please enter a number: "
continue
except ValueError:
print "please enter a number: "
continue
# throw error if number outwith 1-8 is entered
if ColDestinationInt not in [1, 2, 3, 4, 5, 6, 7, 8]:
print "Column coordinate out of range"
else:
ColDestinationInt = int(ColDestination)
break
# Movement validations
# if piece to move is an atsign
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtag()):
# # make sure piece cant move more than one column either way
if RowCoordinateInt < 16 and ColCoordinateInt < 8:
if type(board[RowCoordinateInt + 2][ColCoordinateInt+1]) == type(emptySpace()) and type(board[RowCoordinateInt + 2][ColCoordinateInt-1]) == type(emptySpace()):
# make sure piece cant move more than one row
if RowDestinationInt is not RowCoordinateInt + 2:
print "Invalid move. Must move forward"
continue
# validation to make the piece go forward
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtag()):
if RowDestinationInt <= RowCoordinateInt:
print "Invalid move must move forward"
continue
# validation to make sure king moves forward or backwards only one space
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtagKing()):
if type(board[RowCoordinateInt + 2][ColCoordinateInt+1]) == type(emptySpace()) and type(board[RowCoordinateInt + 2][ColCoordinateInt-1]) == type(emptySpace()):
if RowDestinationInt is not RowCoordinateInt - 2 or RowDestinationInt is not RowCoordinateInt + 2:
print "Invalid move. Must move diagonally forward or backwards"
continue
# validation so that the piece must move left or righ
if ColDestinationInt == ColCoordinateInt:
print "Invalid move. Must move left or right"
continue
# validation so the piece cant move on top of your own piece
if type(board[RowDestinationInt][ColDestinationInt]) == type(hashtag()):
print "Invalid move. Already a counter here"
continue
# validation so you cant move an empty space
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(emptySpace()):
print "Invalid move. Can't move empty space"
continue
# validation so you cant land on an enemy counter
if type(board[RowDestinationInt][ColDestinationInt]) == type(atsign()):
print "Invalid move. Already a counter here"
continue
# validation so you cant move an enemy
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(atsign()):
print "Invalid move. this is an enemy"
continue
# movement logic for a regular hashtag to move the correct spaces to take enemy pieces forward and to the left and reprint board
if RowCoordinateInt < 14:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtag()):
if RowCoordinateInt < 14 and ColCoordinateInt > 2:
if type(board[RowCoordinateInt + 4][ColCoordinateInt - 2]) == type(emptySpace()):
if type(board[RowCoordinateInt + 2][ColCoordinateInt - 1]) == type(atsign()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt + 2][ColCoordinateInt - 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtag()
atPiecesTaken(atPieces, noPieces)
if RowDestinationInt == 16:
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a regular hashtag to move the correct spaces to take enemy pieces forward and to the right and reprint board
if RowCoordinateInt > 4:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtag()):
if RowCoordinateInt < 14 and ColCoordinateInt < 7:
if type(board[RowCoordinateInt + 4][ColCoordinateInt + 2]) == type(emptySpace()):
if type(board[RowCoordinateInt + 2][ColCoordinateInt + 1]) == type(atsign()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt + 2][ColCoordinateInt + 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtag()
hashPieceTaken(hashPieces, noPieces)
if RowDestinationInt == 16:
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a king hashtag to move the correct spaces to take enemy pieces forward and to the right and reprint board
if RowCoordinateInt < 14:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtagKing()):
if RowCoordinateInt < 14 and ColCoordinateInt < 7:
if type(board[RowCoordinateInt + 4][ColCoordinateInt + 2]) == type(emptySpace()):
if RowDestinationInt > RowCoordinateInt:
if type(board[RowCoordinateInt + 2][ColCoordinateInt + 1]) == type(atsign()) or type(board[RowCoordinateInt + 2][ColCoordinateInt + 1]) == type(atsignKing()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt + 2][ColCoordinateInt + 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
atPiecesTaken(atPieces, noPieces)
if RowDestinationInt == 16:
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a hashtag king to move the correct spaces to take enemy pieces forward and to the left and reprint board
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtagKing()):
if RowCoordinateInt < 14 and ColCoordinateInt > 2:
if type(board[RowCoordinateInt + 4][ColCoordinateInt - 2]) == type(emptySpace()):
if type(board[RowCoordinateInt + 2][ColCoordinateInt - 1]) == type(atsign()) or type(board[RowCoordinateInt + 2][ColCoordinateInt - 1]) == type(atsignKing()):
if RowDestinationInt > RowCoordinateInt:
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt + 2][ColCoordinateInt - 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
atPiecesTaken(atPieces, noPieces)
if RowDestinationInt == 16:
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a king hashtag to move the correct spaces to take enemy pieces backward and to the right and reprint board
if RowCoordinateInt > 4:
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtagKing()):
if RowCoordinateInt > 4 and ColCoordinateInt < 7:
if type(board[RowCoordinateInt - 4][ColCoordinateInt + 2]) == type(emptySpace()):
if type(board[RowCoordinateInt - 2][ColCoordinateInt + 1]) == type(atsign()) or type(board[RowCoordinateInt - 2][ColCoordinateInt + 1]) == type(atsignKing()):
if RowDestinationInt > RowCoordinateInt:
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt - 2][ColCoordinateInt + 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
atPiecesTaken(atPieces, noPieces)
if RowDestinationInt == 16:
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic for a king hashtag to move the correct spaces to take enemy pieces backward and to the left and reprint board
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtagKing()):
if RowCoordinateInt > 4 and ColCoordinateInt > 2:
if type(board[RowCoordinateInt - 4][ColCoordinateInt - 2]) == type(emptySpace()):
if type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(atsign()) or type(board[RowCoordinateInt - 2][ColCoordinateInt - 1]) == type(atsignKing()):
if RowDestinationInt > RowCoordinateInt:
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowCoordinateInt - 2][ColCoordinateInt - 1] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
atPiecesTaken(atPieces, noPieces)
if RowDestinationInt == 16:
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic if regular piece moves to an empty space
if RowDestinationInt < 16:
print "1"
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtag()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtag()
noPiecesLeft(noPieces)
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# movement logic if king piece moves to an empty space
if type(board[RowCoordinateInt][ColCoordinateInt]) == type(hashtagKing()):
board[RowCoordinateInt][ColCoordinateInt] = emptySpace()
board[RowDestinationInt][ColDestinationInt] = hashtagKing()
noPiecesLeft(noPieces)
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in board]))
break
# loop team 1 then team 2
while True:
team1(board)
team2(board) |
024a53ff5f24fc6c59229372e343f8b98d0eafc3 | forstupidityonly/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 933 | 4.21875 | 4 | #!/usr/bin/python3
"""my square mod"""
class Square:
"""define a square"""
def __init__(self, size=0):
"""
make a square
make a area
use propery to get size
use setter to set value
raise int and 0 check
"""
self.__size = size
def area(self):
return self.__size**2
@property
def size(self):
return self.__size
@size.setter
def size(self, value):
self.__size = value
if type(value) is not int:
raise TypeError("size must be in integer")
if value < 0:
raise ValueError("size must be >= 0")
def my_print(self):
"""to print"""
if self.__size == 0:
print("")
else:
for x in range(self.__size):
for y in range(self.__size):
print("#", end="")
print("")
|
1c3cd2ea993d898ad7732b9104dec906516b9b44 | UX404/Leetcode-Exercises | /#762 Prime Number of Set Bits in Binary Representation.py | 1,367 | 3.96875 | 4 | '''
Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)
Example 1:
Input: L = 6, R = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
9 -> 1001 (2 set bits , 2 is prime)
10->1010 (2 set bits , 2 is prime)
Example 2:
Input: L = 10, R = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
Note:
L, R will be integers L <= R in the range [1, 10^6].
R - L will be at most 10000.
'''
class Solution:
def countPrimeSetBits(self, L: int, R: int) -> int:
prime = {1: False, 2: True, 3: True, 4: False, 5: True, 6: False, 7: True, 8: False, 9: False, 10: False, 11: True, 12: False, 13: True, 14: False, 15: False, 16: False, 17: True, 18: False, 19: True, 20: False}
result = 0
for n in range(L, R+1):
result += prime[bin(n).count('1')]
return result |
368797e4e617ab2275bd6f2c318557e4e9a8f194 | RionelxSlovesky/learning-python | /CODE/Loops/ForLoopWithMultipleLists.py | 122 | 3.765625 | 4 | names = ["Ahmed","Omar","Salim","Adnan"]
email = ["gmail","hotmail","yahoo"]
for i,j in zip(names,email):
print(i,j)
|
5fdc0a7346ce727d9be9fa85f23f3ea624a9a674 | zsmountain/lintcode | /python/dfs/1637_tree_problem.py | 2,328 | 3.828125 | 4 | '''
Given a tree of n nodes. The ith node's father is fa[i-1] and the value of the ith node is val[i-1]. Especially, 1 represents the root, 2 represents the second node and so on. We gurantee that -1 is the father of root(the first node) which means that fa[0] = -1.
The average value of a subtree is the result of the sum of all nodes in the subtree divide by the number of nodes in it.
Find the maximum average value of the subtrees in the given tree, return the number which represents the root of the subtree.
the number of nodes do not exceed 100000
If there are more than one subtree meeting the requirement, return the minimum number.
Have you met this question in a real interview?
Example
Given fa=[-1,1,1,2,2,2,3,3], representing the father node of each point, and val=[100,120,80,40,50,60,50,70] , representing the value of each node, return 1.
Sample diagram:
-1 ------No.1
/ \
No.2 ----1 1---------No.3
/ | \ / \
2 2 2 3 3
No.1 node is (100+120+80+40+50+60+50+70) / 8 = 71.25
No.2 node are (120 + 40 + 50 + 60) / 4 = 67.5
No.3 node are (80+50+70) / 3 = 66.6667
So return 1.
'''
class Tree_Node:
def __init__(self, nodeID, val):
self.nodeID = nodeID
self.parentID = -1
self.childrens = []
self.val = val
self.numDecendents = 1
self.total = val
class Solution:
"""
@param fa: the father
@param val: the val
@return: the biggest node
"""
def treeProblem(self, fa, val):
self.maxAverage = 0.0
self.maxAvgNode = None
nodeArray = [Tree_Node(i + 1, val[i]) for i in range(len(fa))]
root = nodeArray[0]
for i in range(1, len(nodeArray)):
parent = nodeArray[fa[i] - 1]
nodeArray[i].parentID = parent.nodeID
parent.childrens.append(nodeArray[i])
self.dfs(root)
return self.maxAvgNode
def dfs(self, root):
for child in root.childrens:
self.dfs(child)
root.numDecendents += child.numDecendents
root.total += child.total
average = root.total / root.numDecendents
if self.maxAverage < average:
self.maxAverage = average
self.maxAvgNode = root.nodeID
|
f9a7cca7c091edfe1231db8026b104c55657a574 | dpaklin/Python_basic | /lesson05/dz02.py | 562 | 4.125 | 4 | # 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк,
# количества слов в каждой строке.
with open('txt/file5_2.txt') as f:
text = f.read().splitlines()
for index, value in enumerate(text):
number_of_words = len(value.split())
print('В строке {} есть {} слова.'.format(index + 1, number_of_words))
print('всего', len(text), 'строк(и)')
|
8a64c9f59aa787fa15f2aa526651a4c78eede862 | febel/Python | /transposition_cipher_encryption.py | 381 | 3.71875 | 4 | def main():
monMessage= 'Bienvenue en CDAISI'
maCle=8
ciphertext = encryptMessage(maCle,monMessage)
print ciphertext + '|'
def encryptMessage(key, message):
ciphertext = ['']*key
for col in range(key):
pointer = col
while pointer < len(message):
ciphertext[col] += message[pointer]
pointer += key
return ''.join(ciphertext)
if __name__ == '__main__':
main()
|
7e739ca99b41bf2097499ee6715009062e816013 | tatiaris/random-python-scripts | /free_folk.py | 1,467 | 3.703125 | 4 | import time
from math import factorial
def print_grid(g):
for r in g:
print(r)
print()
def to_tuple(g):
return tuple([tuple(r) for r in g])
def flip(g):
temp = [['']*len(g[0]) for i in range(len(g))]
temp2 = [['']*len(g[0]) for i in range(len(g))]
temp3 = [['']*len(g[0]) for i in range(len(g))]
for i in range(len(g)):
for j in range(len(g[i])):
temp[i][j] = g[i][len(g[i]) - j - 1]
temp2[i][j] = g[len(g) - i - 1][j]
temp3[i][j] = g[len(g) - i - 1][len(g[0]) - j - 1]
return [to_tuple(temp), to_tuple(temp2), to_tuple(temp3)]
def add_unit(g):
global g_list, unique_gs
if (g in unique_gs):
return 0
if (is_full(g)):
g_list.update([g] + flip(g))
unique_gs.update([g] + flip(g))
return 1
unique_gs.update([g] + flip(g))
for i in range(len(g)):
for j in range(len(g[i])):
add_unit(insert_element(get_grid(g), 3, army[3]))
add_unit(insert_element(get_grid(g), 2, army[2]))
add_unit(insert_element(get_grid(g), 1, army[1]))
# l = int(input('Enter length: '))
l = 3
w = int(input('Enter width: '))
start_time = time.time()
grid = to_tuple([['']*w for i in range(l)])
army = {3:'m', 2:'g', 1:'h'}
g_list = set()
unique_gs = set()
get_combos(grid)
print('possible combinations:', len(set(g_list)))
print('time taken:', time.time() - start_time, 'seconds')
# 1, 3, 6, 13, 28, 60
|
7960f64d9be277e07ba5bec60e33cd2dffb5c3da | brianchiang-tw/HackerRank | /Python/Regex and Parsing/Validate Hex Color Code/validate_hex_color_code.py | 788 | 3.640625 | 4 | import re
def print_color_code( line_str ):
if '{' in line_str or '}' in line_str:
return
regex = r'#(?:[0-9a-fA-F]{3}){1,2}'
pattern = re.compile(regex)
colors = re.findall( pattern, line_str )
if colors is not None:
for color_code in colors:
print( str(color_code) )
return
if __name__ == '__main__':
n = int( input() )
search_flag = False
for _ in range(n):
try:
input_str = input()
if '{' in input_str:
search_flag = True
if '}' in input_str:
search_flag = False
except EOFError:
#print( input_str )
continue
if search_flag:
print_color_code( input_str )
|
58058d47558c9154b8a2633258e2f7f85ed03ee5 | XinyiF/Algorithms | /Python/Math/Reverse_Integer.py | 385 | 3.6875 | 4 | class Solution(object):
def reverse(self, x):
flag=False
if x<0:
flag=True
x=str(x)
if flag:
x=x[1:]
res=x[::-1]
if flag:
res=-int(res)
else:
res=int(res)
if -2 ** 31 < res < 2 ** 31 - 1:
return res
return 0
res=Solution()
print(res.reverse(-230)) |
9f9aa4b4aa4cc6b293043e036b2a8a73ab2ec07b | qzhou0/SoftDevSpr19WS | /temp/util/dbOperator.py | 1,237 | 3.859375 | 4 | import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
#==========================================================
DB_FILE="./data/<intended_name>" #<SUBSTITUTE FILE NAME>
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
#==========================================================
#INSERT YOUR POPULATE CODE IN THIS ZONE
cmd = "CREATE TABLE table_name(name TEXT, age INTEGER, id INTEGER)"
"""INSERT"""
#cmd = "INSERT INTO [{}] VALUES(?,?)".format(user)
"""SELECT"""
#cmd = "SELECT name FROM sqlite_master WHERE name = '{}'".format(storyName)
"""how to extract table names"""
#cmd = "SELECT * FROM '{}' WHERE authors = '{}'".format(storyname, username)
# 'SELECT name FROM sqlite_master WHERE type = "table" '
#result = c.execute(cmd).fetchall() #listyfy
"""
if result:#list is not empty
return True
# Otherwise, the user has not contributed. (Return false).
return False
"""
#build SQL stmt, save as string
c.execute(cmd) #run SQL statement
#==========================================================
db.commit() #save changes
db.close() #close database
|
44aaacbaee50704a22c757f4a4f7935f7ecbe477 | hasnain-khan1/pandas_project | /most_freq_words.py | 1,078 | 3.765625 | 4 | from collections import Counter
while True:
print("Available Years and Registrar Name \n1974,1976,1980,1983,1987,1991 \nschmidt , kohl\n")
x = input("Enter the Registrar Name or Year: ")
years = ['1974', '1976', '1980', '1983', '1987', '1991']
registrar_name = ['schmidt', 'kohl']
if x in registrar_name:
if x == 'kohl':
print('kohl')
elif x == 'schmidt':
print('schmidt')
elif x in years:
if x == '1974':
file = open('1974-Schmidt-SPD.nostop', 'r', )
string = file.read()
li = list(string.split(" "))
c = Counter(li)
c.most_common(10)
print(c)
print("1974")
elif x == '1976':
print("1976")
elif x == '1980':
print("1980")
elif x == '1983':
print("1983")
elif x == '1987':
print("1987")
elif x == '1991':
print("1991")
else:
print("Incorrect Registrar Name or Year ")
|
05fc706f408b218e160ebd840369c6b62a1ff89b | yoliskdeveloper/basic_python | /if_statement.py | 1,444 | 4.0625 | 4 | a = 33
b = 209
if b > a:
print('b lebih besar dari a')
a = 33
b = 33
if b > a:
print('b lebih besar dari a')
elif a == b:
print('a dan b nilainya sama')
a = 200
b = 33
if b > a:
print('b lebih besar dari a')
elif a == b:
print('a dan b nilainya sama')
else:
print('a lebih besar dari b')
a = 200
b = 33
if b > a :
print('b lebih besar dari a')
else:
print('a lebih besar dari b')
# satu baris statement
# if
if a > b: print('a lebih besar dari b')
# if ... else
print('a lebih besar dari b') if a < b else print('b lebih besar dari a')
# multiple condition di satu baris
a = 230
b = 235
print('A') if a > b else print('==') if a == b else print('b')
# logical operator
# 'and' akan menampilkan nilai true jika kedua kondisi itu benar, jika satu kondisi itu false, maka kondisi tersebut
# itu false
a = 200
b = 33
c = 400
if a > b and c > a:
print('kedua kondisi itu benar')
# 'or' akan menampilkan nilai true jika hanya satu kondisi yang benar, kondisi akan menjadi false jika kedua kondisi
# adalah salah
if a < b or c > a:
print('hanya satu kondisi saja yang benar')
# nested if
a = 9
if a > 10:
print('nilai a diatas 10')
if a > 20:
print('nilai a ada diatas 20')
else:
print('nilai a bukan diatas 20')
else:
print('nilai a dibawah 10 dan 20')
# pass statement untuk sebagai pedoman, jika nanti kita akan kembali ke blok code tersebtu
if a > b:
pass
|
6e6a4b8b275ab90703cbff6d2154c695c59c3259 | 136772/MyPython | /Mycode/learn/2.py | 1,506 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@author:JaNG
@email:136772@163.com
'''
# def show(*args,**kwargs):
# print(args,type(args))
# print(kwargs,type(kwargs))
#
# l = [11,22,33,44]
# d = {'k1':'v1','k2':'v2'}
#
# show(*l,**d)
# s1 = '{} is {}'
# l = ['alex','sb']
# result = s1.format(*l) #如果传入列表那么就要制定为 * 的参数
#
# print(result)
#
# s2 = '{name} is {acter}' #指定key
# d = {'name':'alex','acter':'2b'}
# result = s2.format(**d) #如果传入字典那么就要制定为 ** 的参数
#
# print(result)
# lambda===========================如果要写简单的函数 可以使用它
#
# def a(i):
# i += 1
# return i
# a = lambda i: i+1 #i 为行参, 可多个 然后加:
# # 创建形式参数i
# # 函数内容, a+1 并把结果return
#
# print(a(99))
# class Foo:
# def __repr__(self):
# return 'bbbbbb'
#
# f = Foo()
# ret = ascii(f)
# print(f)
# print(ret)
l1 = [11,22,33,44]
# new_li = map(lambda x: x+100,l1)
# for i in new_li:
# print(i)
# l = list(new_li)
# print(l)
#
# def a(num):
# return num+100
#
# new_li = map(a,l1)
# print(new_li)
#
# def func(x):
# if x>33:
# return True
# else:
# return False
#
# # n = filter(func,l1)
# n = filter(lambda x:x>33,l1)
# print(list(n))
f = open('test.log','r+')
'''
f.tell() #查看当前指针
f.read()
# print(f.tell())
f.seek(1) #设置当前指针位置
f.close()
'''
f.seek(5)
# print(f.read())
f.truncate()
f.close() |
662fac9793b71fd687f22af38c31aa40eb6b0873 | nileshmahale03/Python | /Python/PythonProject/6 TypeConversion.py | 569 | 3.875 | 4 |
"""
Type conversion is Python:
Implicit
boolean automatically upgrades to integer
integer automatically upgrades to float
Explicit
"""
#1.
a = True
b = 1
c = a + b
print(c)
#2.
a = 135
b = 10.5
c = a + b
print(c)
print(type(c))
#3.
a = "123"
b = 5
c = int(a) + b
print(c)
#4.
str = "NILESH MAHALE"
l = list(str)
t = tuple(str)
s = set(str)
print(str)
print(l)
print(t)
print(s)
#5.
a = 20
b = bin(a)
h = hex(a)
o = oct(a)
print(b)
print(h)
print(o)
#6.
b = "10100"
i = int(b, 2)
print(i)
h = "14"
i = int(h, 16)
print(i)
o = "24"
i = int(o, 8)
print(i)
|
b8bdaa29b675f40f8b8bf9d74247fcc92e6ff664 | fvargaso174/CEvidenciasICCSO | /linear_reg.py | 579 | 3.578125 | 4 | import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression
import Matplotlib.pyplot as plt
dataset = pd.read_csv(’Salary_Data.csv’)
X = dataset.iloc[:,:-1].values
Y = dataset.iloc[’:,1].values
X_train, X_test, y_train, y_test = train test split(x, y, test_size = 1/3, random_state �= 0)
Regressor = LinearRegression()
Regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
plt.scatter(X_train, y_train, color = color)
plt.plot(X_train, regressor.predict(X_train), color =‘blue’)
plt.show() |
20d2d1e869e663722c1c34d430de0fa019b174d8 | Waynezhai/03_python_hm | /03_循环语句/hm_11_printFunction_littleStar.py | 429 | 3.796875 | 4 | #!/usr/bin/python
#coding=utf-8
"""
1、输入十行小星星,第一行一个,第二行2个,第三行三个……
2、小星星居中显示
3、使用循环嵌套处理
4、python2的print后不换行不空格的方法参考:https://segmentfault.com/q/1010000000095970
"""
from __future__ import print_function
row = 1
while row <= 10:
col = 1
while col <= row:
print("*", end = "")
col += 1
print()
row += 1
|
561d244f9473d7801c52ee4116ea32c9c2211d94 | da-ferreira/uri-online-judge | /uri/1221.py | 356 | 3.921875 | 4 |
from math import sqrt, floor
casos = int(input())
for i in range(casos):
numero = int(input())
piso_sqrt = floor(sqrt(numero))
divisores = 0
for j in range(1, piso_sqrt+1):
if numero % j == 0:
divisores += 1
if divisores == 1:
print('Prime')
else:
print('Not Prime')
|
296883e22e1b1112a8942cb64b654fab9120ac13 | jack-mars/selemium_webdriver | /stringmethodspart1.py | 361 | 4.28125 | 4 | """
Accessing characters in a string
Index starts from zero
"""
first = "nyc"[0]
print(first)
city = "sfo"
ft = city[0]
print(ft)
"""
len()
lower()
upper()
str()
"""
print("***********")
stri = "This is a Mixed CASE"
print(stri.lower())
print(stri.upper())
print(len(stri))
print(stri + "2")
print(stri + str(2))
#Concatenation
print("Hello" + " " + "World!!") |
d5f0ff064265d39cf182dad2dbaeadc2e4b3fe7a | Nikita-bsu/Something | /Python/Book Projects/Square_for_turtle.py | 460 | 3.65625 | 4 | import turtle
bob = turtle.Turtle()
#
# def square(t, length):
# for i in range(4):
# t.fd(length)
# t.lt(90)
# print(square(bob, 100))
# def polygon(t, length, n):
# for i in range(4):
# t.fd(length)
# t.lt(360 / n)
#
# print(polygon(bob, 100, 4))
def polygon(t, length, n):
for i in range(4):
t.fd(length * n)
t.lt(360 / n)
def circle(t, r):
polygon(t, r, 360)
print(circle(bob, 10))
|
bf5b896f0ae198a4f78f6a1199596f437922e3a8 | nemzutkovic/Carleton-University-CS-Guide | /COMP 1405/Assignment 3 (100)/prime.py | 171 | 3.796875 | 4 | def isprime(x):
if x == 1: return False
for i in range(2, x):
if x % i == 0: return False
return True
for p in range(1,101):
if isprime(p) == True:
print(p) |
9c9558a86c63ec6c01a986c2a69464d05c559603 | VishalDeoPrasad/HackerRank-Python | /Mini-Max Sum.py | 131 | 3.59375 | 4 | def miniMaxSum(arr):
arr.sort()
#print(arr)
print(sum(arr[:4]), sum(arr[-4:]))
arr = [1,5, 10, 3,5,7,9]
miniMaxSum(arr) |
f92820421da56840a10094e0b2615b3a74f9301e | emmy-kech/Day-4--Home | /binary_search.py | 1,054 | 3.640625 | 4 | class BinarySearch(list):
def __init__(self, a, b, *args):
list.__init__(self, *args)
self.list_length = a
self.step = b
end = self.list_length * self.step
for i in range(self.step, end+1, self.step):
self.append(i)
@property
def length(self):
return len(self)
def search(self, value, start=0, end=None, count=0):
if not end:
end = self.length - 1
if value == self[start]:
return {'index': start, 'count': count}
elif value == self[end]:
return {'index': end, 'count': count}
mid = (start + end) // 2
if value == self[mid]:
return {'index': mid, 'count': count}
elif value > self[mid]:
start = mid + 1
elif value < self[mid]:
end = mid - 1
if start >= end:
return {'index': -1, 'count': count}
count += 1
return self.search(value, start, end, count) |
455cb39957e4298eff5cff30196fabbd54d4c6b8 | astral-sh/ruff | /crates/ruff/resources/test/fixtures/flake8_future_annotations/no_future_import_uses_union_inner.py | 184 | 3.5 | 4 | def main() -> None:
a_list: list[str | None] = []
a_list.append("hello")
def hello(y: dict[str | None, int]) -> None:
z: tuple[str, str | None, str] = tuple(y)
del z
|
654cdb68d7728faaf52e4e903e96f92eab947d3f | llwsykll/leetCode | /palindromeNumber/paNu.py | 300 | 3.5625 | 4 | class Solution:
def isPalindrome(self, x: 'int') -> 'bool':
if x<0:
return False
re = 0
num = x
while(num>0):
re = re*10 + num%10
num = int(num/10)
if re==x:
return True
else:
return False |
885e8d1b693ff90a11425c1e5eb2c23bc3e144f8 | Evaldo-comp/Python_Teoria-e-Pratica | /Livros_Cursos/Udemy/funcoes/funcoes_parametros.py | 3,153 | 4.0625 | 4 | # Algumas funções precisam de dados para executar as operações presentes no seu corpo
# Esses dados são fornecidos pelo usuário quando chamamos essa função e são chamados de argumentos
#Exemplo de função com processamento fixo
def impar_par():
for i in range (1, 11):
if i %2 == 0 :
print(f' O número {i} é par')
else:
print(f' O número {i} é impar')
impar_par()
#Exemplo de função com processamento dinâmico com parâmetros enviados pelo usuário
def impar_par(n):
if n % 2 == 0:
print(f' O número {n} é par')
else:
print(f' O número {n} é impar')
num= int(input('Digite um número\n'))
impar_par(num)
# AS funções podem receber de 1 a n parâmetros, divididos por vírgula.
# O exemplo seguinte recebe três parâmetros para realizar uma operação escolhida pelo usuário
def calc(op,n1, n2):
if op == 1:
return n1 + n2
else op == 2:
return n1 -n2
op = int(input("""
Escolha a operação que deseja realizar'
Digite:
1: SOMA
2: SUBTRAÇÃO
"""))
n1 = int(input('Digite o primeiro número '))
n2 = int(input('Digite o segundo número '))
print(f' O resultado da operação escolhida é {calc(op, n1, n2)}')
#Prática: Insira na função as operações de divisão e multiplicação além de outra opção para tratar
# a inserção de um caractere qualquer como erro.
def calc(op,n1, n2):
if op == 1:
return n1 + n2
elif op == 2:
return n1 -n2
elif op == 3:
return n1 * n2
elif op == 4:
return n1 // n2
else:
return 'entrada inválida'
op = int(input("""
Escolha a operação que deseja realizar'
Digite:
1: SOMA
2: SUBTRAÇÃO
3: MULTIPLICAÇÃO
4: DIVISÃP"""))
n1 = int(input('Digite o primeiro número '))
n2 = int(input('Digite o primeiro número '))
print(f' O resultado da operação escolhida é {calc(op,n1,n2)}')
# OBS: Há uma diferença entre parâmetros e Argumentos:
# Parâmetros são declarados na definição da função, já os argumentos
# são chamados durante a execução da mesma
# Argumentos nomeados:
# A ordem com que os argumentos são passados, pode alterar na execução da função,
# mas podemos nomear Argumentos, dessa forma , não importa a ordem em que os argumentos são passados
#Exemplo de uma função sem argumentos nomeados:
def ficha(nome, sobrenome, idade):
print(f'Olá {nome}, {sobrenome}, você tem {idade} anos')
ficha(12, 'Pereira', 'Evaldo')
# Execução da mesma função com argumentos nomeados:
def ficha(nome, sobrenome, idade):
print(f'Olá {nome} {sobrenome}, você tem {idade} anos')
ficha(idade = 12, sobrenome = 'Pereira', nome = 'Evaldo')
# Você pode escolher colocar um parâmetro default que torna a passagem de
# argumento para esse parâmetro como opcinal;
def exponencial(num, pot = 2): # Se nenhum número for enviado para o segundo parâmetro ele assumira o vaor dois
return num ** pot
print(exponencial(3,3))
#OBS: Esses parâmetros default devem sempre estar no final da declaração
#def exponencial(pot=2, num) -- errado
|
89a8b976b36d6690ee320128f0f4360a0731260a | Terry-Xiang/XZY | /exchange rate.py | 957 | 3.546875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
编者:XZY
日期:2020.2.15
功能:实现美元与人民币汇率转换
"""
#提示用户输入基本信息
print('美元货币单位是USD,人民币的货币单位是CNY')
print('汇率为直接标价法,CNY/USD,其含义为 1 美元 = ?人民币')
print('汇率查询参考网站:https://www.boc.cn/sourcedb/whpj/')
print('请注意大小写')
exchange_rate = input('请输入今日汇率:') #汇率标价为 CNY/USD
currency = input('请输入带有货币单位的金额:')
#转换汇率
if currency[-3:] == 'CNY':
Dollar = eval(currency[:3]) / eval(exchange_rate)
print(currency[:3] + '人民币' + '相当于' + str(Dollar) + '美元')
elif currency[-3:] == 'USD':
RMB = eval(currency[:3]) * eval(exchange_rate)
print(currency[:3] + '美元' + '相当于' + str(RMB) + '人民币')
else:
print('输入格式错误,请重新输入')
|
6a4afa47685b85557c463c988beeedd7d87606f0 | tauCourses/ML_hw4 | /network.py | 8,094 | 3.796875 | 4 | """
network.py
"""
import random
import numpy as np
import math
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import os
import sys
dir_path = repr(os.path.dirname(os.path.realpath(sys.argv[0]))).strip("'")
class Network(object):
def __init__(self, sizes):
"""The list ``sizes`` contains the number of neurons in the
respective layers of the network. For example, if the list
was [2, 3, 1] then it would be a three-layer network, with the
first layer containing 2 neurons, the second layer 3 neurons,
and the third layer 1 neuron. The biases and weights for the
network are initialized randomly, using a Gaussian
distribution with mean 0, and variance 1. Note that the first
layer is assumed to be an input layer, and by convention we
won't set any biases for those neurons, since biases are only
ever used in computing the outputs from later layers."""
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
def SGD(self, training_data, epochs, mini_batch_size, learning_rate,
test_data, plot_graphs = False, calc_gradient_norms = False):
"""Train the neural network using mini-batch stochastic
gradient descent. The ``training_data`` is a list of tuples
``(x, y)`` representing the training inputs and the desired
outputs. """
print("Initial test accuracy: {0}".format(self.one_label_accuracy(test_data)))
n = len(training_data)
training_accuracy = []
training_loss = []
test_accuracy = []
gradient_norms = [[] for i in self.biases]
epochs = [i for i in range(epochs)]
for epoch in epochs:
nabla_b = [np.zeros(b.shape) for b in self.biases]
random.shuffle(list(training_data))
mini_batches = [
training_data[k:k+mini_batch_size]
for k in range(0, n, mini_batch_size)]
for mini_batch in mini_batches:
delta_nabla_b = self.update_mini_batch(mini_batch, learning_rate)
if calc_gradient_norms:
nabla_b = [nb + dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
if plot_graphs:
training_accuracy.append(self.one_hot_accuracy(training_data))
training_loss.append(self.loss(training_data))
test_accuracy.append(self.one_label_accuracy(test_data))
if calc_gradient_norms:
for i, b in enumerate(nabla_b):
gradient_norms[i].append(np.linalg.norm(b)/ float(n))
print ("Epoch {0} test accuracy: {1}".format(epoch, self.one_label_accuracy(test_data)))
if plot_graphs:
self.plot_graph(epochs, training_accuracy, 'training accuracy', 'epcohs', 'training accuracy', '2_b_training_accuracy.png')
self.plot_graph(epochs, training_loss, 'training loss', 'epcohs', 'training loss', '2_b_training_loss.png')
self.plot_graph(epochs, test_accuracy, 'test accuracy', 'epcohs', 'test accuracy', '2_b_test_accuracy.png')
if calc_gradient_norms:
self.plot_gradient_norms(epochs, gradient_norms)
def plot_graph(self, x, y, label, xlabel, ylabel,name):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, label=label)
plt.xlabel(xlabel, fontsize=18)
plt.ylabel(ylabel, fontsize=16)
fig.savefig(os.path.join(dir_path, name))
fig.clf()
def plot_gradient_norms(self, epochs, gradient_norms):
fig = plt.figure()
ax = fig.add_subplot(111)
for i, b in enumerate(gradient_norms):
ax.plot(epochs, b, label="b"+str(i+1))
plt.xlabel('epcohs', fontsize=18)
plt.ylabel('gradient norm', fontsize=16)
plt.legend()
fig.savefig(os.path.join(dir_path, 'gradient_norms.png'))
fig.clf()
def update_mini_batch(self, mini_batch, learning_rate):
"""Update the network's weights and biases by applying
stochastic gradient descent using backpropagation to a single mini batch.
The ``mini_batch`` is a list of tuples ``(x, y)``."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [w - (learning_rate / len(mini_batch)) * nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b - (learning_rate / len(mini_batch)) * nb
for b, nb in zip(self.biases, nabla_b)]
return nabla_b
def backprop(self, x, y):
vs = []
zs = [x]
for b, w in zip(self.biases, self.weights): #forward:
temp = np.dot(w, zs[-1]) + b
vs.append(temp)
zs.append(sigmoid(temp))
zs[-1] = self.output_softmax(vs[-1])
db = [np.zeros(b.shape) for b in self.biases]
dw = [np.zeros(w.shape) for w in self.weights]
db[-1] = self.loss_derivative_wr_output_activations(vs[-1], y) # last layer -delta
dw[-1] = np.dot(db[-1], zs[-2].transpose())
for i in range(self.num_layers-3,-1,-1): #backward:
db[i] = np.dot(self.weights[i+1].transpose(), db[i+1]) * sigmoid_derivative(vs[i]) # delta
dw[i] = np.dot(db[i], zs[i].transpose())
return db, dw
def one_label_accuracy(self, data):
"""Return accuracy of network on data with numeric labels"""
output_results = [(np.argmax(self.network_output_before_softmax(x)), y)
for (x, y) in data]
return sum(int(x == y) for (x, y) in output_results)/float(len(data))
def one_hot_accuracy(self,data):
"""Return accuracy of network on data with one-hot labels"""
output_results = [(np.argmax(self.network_output_before_softmax(x)), np.argmax(y))
for (x, y) in data]
return sum(int(x == y) for (x, y) in output_results) / float(len(data))
def network_output_before_softmax(self, x):
"""Return the output of the network before softmax if ``x`` is input."""
layer = 0
for b, w in zip(self.biases, self.weights):
if layer == len(self.weights) - 1:
x = np.dot(w, x) + b
else:
x = sigmoid(np.dot(w, x)+b)
layer += 1
return x
def loss(self, data):
"""Return the loss of the network on the data"""
loss_list = []
for (x, y) in data:
net_output_before_softmax = self.network_output_before_softmax(x)
net_output_after_softmax = self.output_softmax(net_output_before_softmax)
loss_list.append(np.dot(-np.log(net_output_after_softmax).transpose(),y).flatten()[0])
return sum(loss_list) / float(len(data))
def output_softmax(self, output_activations):
"""Return output after softmax given output before softmax"""
output_exp = np.exp(output_activations)
return output_exp/output_exp.sum()
def loss_derivative_wr_output_activations(self, output_activations, y):
"""Return derivative of loss with respect to the output activations before softmax"""
return self.output_softmax(output_activations) - y
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z))
def sigmoid_derivative(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))
|
3a0a91539adce320648554b196702283b186c937 | AlexeyZavar/informatics_solutions | /4 раздел/Задача I.py | 793 | 3.859375 | 4 | # Напишите программу, которая по данному числу n от 1 до 9 выводит на экран n флагов. Изображение одного флага
# имеет размер 4×4 символов, между двумя соседними флагами также имеется пустой (из пробелов) столбец. Разрешается
# вывести пустой столбец после последнего флага. Внутри каждого флага должен быть записан его номер — число от 1 до n.
#
n = int(input())
a = '+___ '
b = '|__\\ '
c = '| '
print(a * n)
for i in range(1, n + 1):
print('|', i, ' / ', sep='', end='')
print()
print(b * n)
print(c * n)
|
d6ae9bb82f577c0a4235f2fbffdb082f79f5b98c | MasterSlavein/Test_task | /Advanced_6.py | 2,878 | 3.921875 | 4 | # К реализованному классу Matrix в Домашнем задании 3 добавить следующее:
# 1. __add__ принимающий второй экземпляр класса Matrix и возвращающий сумму матриц, если передалась на вход матрица
# другого размера - поднимать исключение MatrixSizeError (по желанию реализовать так, чтобы текст ошибки содержал
# размерность 1 и 2 матриц - пример: "Matrices have different sizes - Matrix(x1, y1) and Matrix(x2, y2)")
# 2. __mul__ принимающий число типа int или float и возвращающий матрицу, умноженную на скаляр/
# 3. __str__ переводящий матрицу в строку. Столбцы разделены между собой табуляцией, а строки — переносами
# строк (символ новой строки). При этом после каждой строки не должно быть символа табуляции и в конце не должно быть
# переноса строки.
import copy
class Matrix:
def __init__(self, list_of_lists):
self.matrix = copy.deepcopy(list_of_lists)
def size(self):
number_of_rows = len(self.matrix)
number_of_columns = len(self.matrix[0])
size_of_matrix = (number_of_rows, number_of_columns)
return size_of_matrix
def transpose(self):
trans_matrix = list(zip(*self.matrix))
self.matrix = trans_matrix
return self
@classmethod
def create_transposed(cls, list_of_lists):
instance = cls(list_of_lists)
return instance.transpose()
def __add__(self, other):
if self.size() == other.size():
resulted_matrix = []
for new_list in zip(self.matrix, other.matrix):
rows = []
for elements in zip(new_list[0], new_list[1]):
rows.append(sum(elements))
resulted_matrix.append(rows)
return resulted_matrix
else:
raise ValueError(f"Matrices have different sizes - Matrix #1 {self.size()} and Matrix #2 {other.size()}")
def __mul__(self, scalar):
resulted_matrix = []
for row in self.matrix:
rows = []
for column in row:
rows.append(column * scalar)
resulted_matrix.append(rows)
return resulted_matrix
def __str__(self):
return '\n'.join([''.join(['%d\t' % column for column in row]) for row in self.matrix])
a = Matrix([[1, 2, 3], [4, 5, 6]])
b = Matrix([[1, 2, 3], [4, 5, 6]])
print(a + b, a * 2)
print(a.__add__(b))
print(a.__mul__(2))
print(a.__str__())
|
f0dcf08ab9eac3c3353aaaf60b66148701208be6 | doga44/Group-Project-Python | /pythongroupproject.py | 10,349 | 3.765625 | 4 | #In this program, we use yahoo finance. To run yahoo finance,
#you need to install the tool in terminal/command.
#Install fix_yahoo_finance using pip:
# $ pip install fix_yahoo_finance --upgrade --no-cache-dir
import pandas as pd
from pandas_datareader import data as pdr
import fix_yahoo_finance as yf
yf.pdr_override()
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#first, we define the functions needed
#function to calculate the cumulative daily returns of a stock or index
def cum_daily_returns(a):
adj_daily_close= a['Adj Close']
adj_daily_returns = adj_daily_close / adj_daily_close.shift(1) -1
cum_adj_daily_returns = (1+adj_daily_returns).cumprod()
#return a dataframe
cum_adj_daily_returns = pd.DataFrame(cum_adj_daily_returns)
return cum_adj_daily_returns
#loop to multiply the stock price with the quantity entered
def add_quantity(ticker_company):
portfolio_value = pd.Series()
#change quantity variable for each loop
y = 0
#loop to multiply the stock price with the right quantity
for i in ticker_company:
#get the financial data for the portfolio
port_data = pdr.get_data_yahoo(i, start_date, end_date)
e = pd.DataFrame(port_data)
#get the number in the serie named quantity
quant_num = int(diff_quant.iloc[y])
#multiply the adj close from everyday with the quantity
e = e['Adj Close'].mul(quant_num)
#fill the Nan values with 0 to be able to add the series
portfolio_value = portfolio_value.add(e, fill_value = 0)
#increase y, to get the next row in the serie with the quantities
y = y + 1
#create a dataframe with the portfolio value
portfolio_value = pd.DataFrame(portfolio_value, columns = ['Adj Close'])
return portfolio_value
#function to get the highest return stock
def highest_return(stocks):
port_data = pdr.get_data_yahoo(stocks, start_date, end_date)
port_data = pd.DataFrame(port_data)
#drop companies that were not listed on the stock market at the start date
port_data = port_data.dropna(axis = 1)
port_data = (port_data['Adj Close'].iloc[-1] /
port_data['Adj Close'].iloc[0] -1) * 100
#get the highest number in the serie
high_return_comp = port_data.idxmax()
per_return = port_data.get(high_return_comp)
return "The stock with the highest return during this "\
"period is %s with %.2f%%" % (high_return_comp,per_return)
def lowest_return(stocks): #to get the lowest return stock
port_data = pdr.get_data_yahoo(stocks, start_date, end_date)
port_data = pd.DataFrame(port_data)
#drop companies that were not listed on the stock market at the start date
port_data = port_data.dropna(axis = 1)
port_data = (port_data['Adj Close'].iloc[-1] /
port_data['Adj Close'].iloc[0] -1) * 100
high_return_comp = port_data.idxmin()
per_return = port_data.get(high_return_comp)
return "The stock with the lowest return during this "\
"period is %s with %.2f%%" % (high_return_comp,per_return)
#step 1: onboarding
print ("This program lets you choose a portfolio consisting of stocks\
from Yahoo Finance to evaluate the hypothetical performance over \
an ex post time period of choice and compares it to the performance \
of the S&P500 market index. You can select, which stocks in which \
quantity you want to include in your portfolio.")
#step 2: insert transactions into program
#we create a dataframe with ticker and quantity as column names
col_names = ['ticker', 'quantity']
portfolio = pd.DataFrame(columns = col_names)
#after you finish the program, you can start to build another portfolio
#using a while loop
run_again = ("yes")
while run_again == ("yes"):
question2 = ("no")
while question2 == ("no"):
print ("First you need to enter your portfolio.")
portfolio = portfolio [0:0]
question = ("yes")
#try if the ticker entered exist in yahoo finance and try if
#you entered a number for the quantity
while True:
portfolio = portfolio.append(pd.Series(
[input("What's the ticker of the first stock? "),
input("How many of those stocks do you have in your portfolio? ")],
index=portfolio.columns ), ignore_index=True)
a = portfolio['ticker'].tolist()
b = portfolio['quantity'].tolist()
a = a[-1]
b = b[-1]
try:
w = pdr.get_data_yahoo(a, start = "1950-01-01",
end = "2018-01-01")
b = int(b)
break
except ValueError:
portfolio = portfolio.drop(portfolio.index[-1])
print("Error! The ticker you entered does "\
"not exist or you did not enter a number "\
"for the quantity; please try again.")
continue
while question != ("no"):
question = input("Do you want to add another stock? (yes/no)")
if question == "yes":
#try if the ticker entered exist in yahoo finance and try if
#you entered a number for the quantity
while True:
portfolio = portfolio.append(pd.Series(
[input("What's the ticker of this stock? "),
input("How many of those stocks do you have " \
"in your portfolio? ")],
index=portfolio.columns ), ignore_index=True)
a = portfolio['ticker'].tolist()
b = portfolio['quantity'].tolist()
a = a[-1]
b = b[-1]
try:
w = pdr.get_data_yahoo(a, start = "1950-01-01",
end = "2018-01-01")
b = int(b)
break
except ValueError:
portfolio = portfolio.drop(portfolio.index[-1])
print("Error! The ticker you entered does not exist "\
"or you did not enter a number for the quantity; "\
"please try again.")
continue
elif question == "no":
print ("Alright, please check if the following table " \
"of your transactions is correct.")
print (portfolio)
question2 = input ("Is this portfolio table correct? (yes/no) ")
if question2 == ("yes"):
print ("Perfect, let's go on!")
elif question2 == ("no"):
print ("Alright, we'll have to start over!")
else:
print ("You didn't type yes or no, please revise.")
#step 3: insert performance time period dates into program
print ("Now define the time period you want to " \
"calculate your portfolio performance for.")
start_date = input("What’s the start date? (YYYY-MM-DD) ")
end_date = input("What’s the end date? (YYYY-MM-DD) ")
#step 4: program provides information about users portfolio
#create a list with the different tickers of the companies
num_stocks = portfolio['ticker'].tolist()
#create a list out of column quantity
diff_quant= portfolio['quantity'].tolist()
#create a serie based on the quantities
diff_quant = pd.Series(diff_quant)
#rename the column
diff_quant.columns = ['quantity']
#portfolio is based at 100 to be compared with the index
#extract the financial data of S&P500
sp500 = pdr.get_data_yahoo('^GSPC',start_date,end_date)
sp500 = sp500['Adj Close']
sp500 = pd.DataFrame(sp500)
#the cumulative daily returns of portfolio are calculated
#and compared to the return of the index
z = add_quantity(num_stocks)
#call the function to calculate cumulative daily returns
cum_index = cum_daily_returns(sp500)
cum_port = cum_daily_returns(z)
#plot the graph and change the legend, labs and title
plt.figure(figsize =(13.5,9))
plt.plot(cum_index, color = 'orange')
plt.plot(cum_port, color = 'blue')
plt.legend(['S&P500','Portfolio'], fontsize = 15)
plt.xlabel('Time Period', fontsize = 15)
plt.ylabel('Cumulative returns', fontsize = 15)
plt.title("Ex post stock portfolio/market index comparison",
fontsize = 20)
plt.show()
#if user enters only one stock then there will be no distinction between the
#highest and lowest returns; if user entered multiple stocks then the code
#computes the highest and lowest return of the time period
if len(num_stocks) == 1:
port_data = pdr.get_data_yahoo(num_stocks, start_date, end_date)
port_data = pd.DataFrame(port_data)
port_data = (port_data['Adj Close'].iloc[-1] /
port_data['Adj Close'].iloc[0] -1) * 100
#convert stocks into a string to avoid having brackets in the result
stock = ''.join(num_stocks)
print("You only entered one stock. During this "\
"period %s had %.2f%% return" % (stock,port_data))
else:
print(highest_return(num_stocks))
print(lowest_return(num_stocks))
#compute the returns for the S&P 500 over the time period
sp500_returns = (sp500['Adj Close'].iloc[-1] /
sp500['Adj Close'].iloc[0] -1) * 100
print('During this period, S&P 500 had %.2f%% return' % sp500_returns)
#compute the returns for stock portfolio over the time period
portfolio_returns = (z['Adj Close'].iloc[-1] /
z['Adj Close'].iloc[0] - 1) * 100
print('During this period, your portfolio had %.2f%% return' % portfolio_returns)
#question if the user wants to repeat the whole construction process again
run_again = input("Would you like to start over? (yes/no)")
if run_again == ("yes"):
print ("Alright, let´s start over!")
elif run_again == ("no"):
print ("Hope you enjoyed our program. Goodbye.") |
b29d367d152aa069e86a80d403972672b2dd518c | amreyesp/ProgrammingExercises | /sorting/bubbleSort.py | 1,706 | 4.28125 | 4 | """Sorting: Bubble Sort"""
"""
Considering the Bubble sort algorithm, given an array of integers, sort the array
in ascending order using it. Once sorted, print the following three lines:
1.Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place.
2.First Element: firstElement, where firstElement is the first element in the sorted array.
3.Last Element: lastElement, where lastElement is the last element in the sorted array.
Credits: www.hackerrank.com
"""
class NewSort:
def __init__(self):
self.array = []
self.minswaps = 0
def bubble_algorithm(self,array):
n = len(array)
for i in range(n):
for j in range(n-1):
if (array[j] > array[j + 1]):
a1 = array[j]
a2 = array[j + 1]
array[j] = a2
array[j+1] = a1
self.array = array
def calc_minswaps(self,array):
n = len(array)
for i in range(n):
for j in range(n-1):
if (array[j] > array[j + 1]):
a1 = array[j]
a2 = array[j + 1]
array[j] = a2
array[j+1] = a1
self.minswaps += 1
self.array = array
def print_result(self):
first = self.array[0]
last = self.array[-1]
return [first,last]
def main():
my_sort = NewSort()
input = [6,4,1,2]
my_sort.calc_minswaps(input)
print('Array is sorted in',my_sort.minswaps,'swaps.')
print('First element:',my_sort.print_result()[0])
print('Last element:',my_sort.print_result()[1])
if __name__=='__main__':
main()
|
594ce006134ac13b65b5dd65b4a410a7c652e06d | DidiMilikina/DataCamp | /Data Scientist with Python - Career Track /24. Machine Learning with Tree-Based Models in Python/03. Bagging and Random Forests 0%/02. Evaluate Bagging performance.py | 911 | 3.640625 | 4 | '''
Evaluate Bagging performance
Now that you instantiated the bagging classifier, it's time to train it and evaluate its test set accuracy.
The Indian Liver Patient dataset is processed for you and split into 80% train and 20% test. The feature matrices X_train and X_test, as well as the arrays of labels y_train and y_test are available in your workspace. In addition, we have also loaded the bagging classifier bc that you instantiated in the previous exercise and the function accuracy_score() from sklearn.metrics.
Instructions
100 XP
Fit bc to the training set.
Predict the test set labels and assign the result to y_pred.
Determine bc's test set accuracy.
'''
SOLUTION
# Fit bc to the training set
bc.fit(X_train, y_train)
# Predict test set labels
y_pred = bc.predict(X_test)
# Evaluate acc_test
acc_test = accuracy_score(y_test, y_pred)
print('Test set accuracy of bc: {:.2f}'.format(acc_test)) |
7164bbff0d08adc744d5fb0ce166ec1885b122cc | jorzel/codefights | /arcade/intro/absoluteValuesSumMinimalization.py | 542 | 3.671875 | 4 | """
Given a sorted array of integers a, find an integer x from a such that the value of
abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.
Example
For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.
"""
def absoluteValuesSumMinimization(a):
even = (len(a) % 2 == 0)
if even:
index = len(a) / 2 - 1
else:
index = len(a) / 2
return a[index]
|
b8fa2494b1e3e057110b4b96bf0beca1a233a1a9 | rahulyhg/MultilingualSourceCode | /猜你心中字母/demo.py | 1,603 | 3.671875 | 4 | #使用python语言来开发 猜你心中字母
print('Content-type: text/html\n')
import cgi
def showSelectHtml(zm,action):
s1="";s2="";s3="";sData="";c="";
for i in range(0,len(zm)):
s=zm[i:i+1]
if (i+1)%3==1:
s1=s1 + s;
elif (i+1)%3==2:
s2=s2 + s;
else:
s3=s3 + s;
sData="&s1="+s1+"&s2="+s2+"&s3="+s3;
c='第'+ str(action) +'步:选择你心里那个字母在哪一组<hr>';
c=c+"第一组:" + s1 + " <a href='?action="+ str(action) +"&index=1"+sData+"'>在这里</a><hr>";
c+="第二组:" + s2 + " <a href='?action="+ str(action) +"&index=2"+sData+"'>在这里</a><hr>";
c+="第三组:" + s3 + " <a href='?action="+ str(action) +"&index=3"+sData+"'>在这里</a><hr>";
return c;
form=cgi.FieldStorage()
zm=form.getvalue('zm','')
action=form.getvalue('action','')
nIndex=form.getvalue('index','')
s1=form.getvalue('s1','')
s2=form.getvalue('s2','')
s3=form.getvalue('s3','')
sData=""
if zm=="":
zm="ABCDEFGHIJKLMNOPQRSTU";
print("菜单:<a href='?'>重置</a><br>");
if action=="1":
print(showSelectHtml(zm,2));
elif action=="2" or action=="3" or action=="4":
nIndex=int(nIndex);
if nIndex==1:
sData=s2+s1+s3;
elif nIndex==2:
sData=s1+s2+s3;
elif nIndex==3:
sData=s1+s3+s2;
if action=="4":
s=sData[10:11];
print("猜你心中记住的字母是不是 <b><font color=red>"+ s +"</font></b>");
else:
print(showSelectHtml(sData,int(action)+1));
else:
print("第1步:请心里记住一个字母:<a href='?action=1'>点击进入下一步</a><div style='letter-spacing:10px;font-size:16px'>" + zm + "</div>");
|
1ab91a728501ce8e6d43c16caf7fbbc5b1cfb563 | DheerajMandvi9/Python-programs-new | /menu driven readfile.py | 1,113 | 3.875 | 4 | ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : count words:")
print("Enter 2 : count line:")
print("Enter 3 : count alphabets:")
print("Enter 4 : exit:")
opt=int(input('enter your choice:'))
if opt==1:
f=open("Atoms.txt","r")
linesList=f.readlines()
count=0
for line in linesList:
wordsList=line.split()
count = count+ len(wordsList)
print("The number of words in this file are : ",count)
f.close()
elif opt==2:
c=0
f=open("Atoms.txt" , "r")
line=f.readline( )
while line:
c=c+1
line=f.readline( )
print('no. of lines:',c)
f.close( )
elif opt==3:
F=open('Atoms.txt','r')
c=0
for line in F:
words=line.split( )
for i in words:
for letter in i:
if(letter.isalpha( )):
c=c+1
print('Total no. of alphabets are:',c)
elif opt==4:
break
else:
print('invalid choice')
ch=(input('want to continue?'))
|
7dd3b0b494e5d769c9412f0c595527e9fa7b86d5 | psssolo/Python | /2.py | 494 | 3.875 | 4 | """
This program takes a Tic-Tac-Toe game pattern (9 chars of [xo.]), and checks if there is a winner.
"""
import re
def is_winner(game_pattern):
return (re.search(r'^(.{3})*(x{3}|o{3})', game_pattern) or
re.search(r'^.{0,2}([xo])..\1..\1', game_pattern) or
re.search(r'^([xo])...\1...\1|..([xo]).\2.\2..', game_pattern))
if is_winner(input("Please enter the game pattern")):
print("Yay! There is a winner!")
else:
print("Oops, no winner this time :(")
|
2707d1df73ddc2d26832fe1b5065edecb900cbf1 | FreedomFrog/pdxcodeguild | /python/guess_the_number.py | 3,134 | 3.734375 | 4 | import random
def get_user_guess():
while True:
guess = input('guess the number: ')
if guess.isdigit():
break
return guess
def towards_target(cor_num, usr_num, last_guess):
guess_diff = abs(cor_num - usr_num)
last_guess_diff = abs(cor_num - last_guess)
if guess_diff >= last_guess_diff:
towards = False
else:
towards = True
return towards
def gen_response(cor_num, usr_num, last_guess, guess_count):
win = False
result = ''
if cor_num == usr_num:
result = 'Correct! You guessed {} times.'.format(guess_count)
win = True
else:
if guess_count > 0:
if towards_target(cor_num, usr_num, last_guess):
result = 'Warmer...'
else:
result = 'Colder...'
result += 'try again'
return result, win
def game1():
last_time = 0
count = 0
x = random.randint(1,10)
active = True
while active:
guess = int(get_user_guess())
response, win = gen_response(x, guess, last_time, count)
print(response)
count += 1
last_time = guess
if win == True:
break
def am_i_right():
correct = ''
while correct != 'y' and correct != 'n':
correct = input('Did I guess your number? (y/n)' ).lower()
if correct == 'y':
result = True
else:
result = False
return result
def user_input():
user_in = ''
while user_in != 'w' and user_in != 'c':
user_in = input('Am I (w)armer or (c)older? ')
if user_in == 'c':
warmer = False
else:
warmer = True
return warmer
def what_to_guess(guess_count, last_guess=0, warm_or_cold=0):
if guess_count < 1:
guess = 7
elif last_guess == 7:
guess = 3
elif last_guess == 3 and warm_or_cold:
guess = 2
elif last_guess == 2 and warm_or_cold:
guess = 1
elif last_guess == 2 and not warm_or_cold:
guess = 5
elif last_guess == 5:
guess = 4
elif last_guess == 3 and not warm_or_cold:
guess = 9
elif last_guess == 9 and warm_or_cold:
guess = 10
elif last_guess == 10 and not warm_or_cold:
guess = 8
elif last_guess == 8 and warm_or_cold:
guess = 6
elif last_guess == 9 and not warm_or_cold:
guess = 6
return guess
def game2():
print('Choose a number between 1 and 10, and I will try to guess it.')
guess_count = 0
last_guess = 0
warm = False
win = False
while not win:
my_guess = what_to_guess(guess_count, last_guess, warm)
print(my_guess)
win = am_i_right()
if win:
print('I Win!')
break
if guess_count > 0:
warm = user_input()
last_guess = my_guess
guess_count += 1
def main():
game = ''
while game != 'c' and game != 'y':
game = input('Would (y)ou like to choose a number, or should the (c)omputer? ')
if game == 'c':
game1()
elif game == 'y':
game2()
if __name__=='__main__':
main() |
60b311d139d10942596baf9c9c067d50453bbab0 | vsdrun/lc_public | /co_fb/844_Backspace_String_Compare.py | 1,398 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/backspace-string-compare/
Given two strings S and T,
return if they are equal when both are typed into empty text editors.
# means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and '#' characters.
Follow up:
Can you solve it in O(N) time and O(1) space?
"""
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def get(S):
s = []
for i in range(len(S)):
if S[i] == "#":
if s:
s.pop()
else:
s.append(S[i])
return s
return get(S) == get(T)
def build():
return "a##c", "#a#c"
return "a#c", "b"
return "ab##", "c#d#"
if __name__ == "__main__":
s = Solution()
print(s.backspaceCompare(*build()))
|
adde802146d98612b2efded9793f157e8093ed51 | DenisPecherin/Lab-2- | /1.py | 1,915 | 3.953125 | 4 | import timeit
# Сравните время вычисления 35-го числа Фибоначчи при помощи формулы Бине,
# итерационной формулы, метода «разделяй и властвуй», метода нисходящего динамического программирования,
# метода восходящего динамического программирования.
# Формула Бине
code_to_test1 = """
from pervoe_zadanie1 import f1
"""
print("Формула Бине")
elapsed_time1 = timeit.timeit(code_to_test1, number=100)/100
print(elapsed_time1)
# Итерационая формула
code_to_test2 = """
n = 35
def f_iteration(n):
a, b = 1, 1
for i in range(3,n+1):
if (i%2 == 0):
a+=b
else:
b+=a
if (a>b):
return a
else:
return b
"""
print("Итерационая формула")
elapsed_time2 = timeit.timeit(code_to_test2, number=100)/100
print(elapsed_time2)
# Разделяй и властвуй
code_to_test3 = """
n = 35
f_rv = lambda n: f_rv(n - 1) + f_rv(n - 2) if n > 2 else 1
"""
print("Разделяй и властвуй")
elapsed_time3 = timeit.timeit(code_to_test3, number=100)/100
print(elapsed_time3)
# Нисходящие ДП
code_to_test4 = """
n = 35
ndp = {0: 0, 1: 1}
def f_ndp(n):
if n in ndp:
return ndp[n]
ndp[n] = f_ndp(n - 1) + f_ndp(n - 2)
return ndp[n]
"""
print("Нисходящие ДП")
elapsed_time4 = timeit.timeit(code_to_test4, number=100)/100
print(elapsed_time4)
# Восходящие ДП
code_to_test5 = """
n = 35
def f_vdp(n):
a = 0
b = 1
for __ in range(n):
a, b = b, a + b
return a
"""
print("Восходящие ДП")
elapsed_time5 = timeit.timeit(code_to_test5, number=100)/100
print(elapsed_time5)
|
a2ce35d9754d48be36973e811b051ea2524178cb | sbezas/AdventOfCode2020 | /Day 02/Day02.py | 1,544 | 3.875 | 4 | from sys import argv
script, input_file = argv
passwordlist = []
validcount = 0
i=0
with open(input_file, "r") as f:
passwordlist = [current_place.rstrip() for current_place in f.readlines()]
for i in passwordlist:
#Locate positions
## Minimum value position
if i[1] == "-":
MinEndPos = 0
MinLength = 1
MinVal = int(i[0])
else:
MinEndPos = 1
MinLength = 2
MinVal = int(i[0:MinEndPos+1])
## Maximum value position
MaxStartPos = MinEndPos + 2
if i[MaxStartPos+1] == " ":
MaxEndPos = MaxStartPos
MaxLength = 1
MaxVal = int(i[MaxStartPos])
else:
MaxEndPos = MaxStartPos + 1
MaxLength = 2
MaxVal = int(i[MaxStartPos:MaxEndPos+1])
# Identify check letter
checkletter = i[MaxEndPos+2]
# Identify password
passwordStartPos = MaxEndPos + 3
password = i[passwordStartPos:]
# Count number of checkletters in password
CheckLetterCount = int(password.count(checkletter))
# Determine if valid
if MinVal <= CheckLetterCount <= MaxVal:
print("Valid Password!")
validcount += 1
else:
print("INVALID PASSWORD!")
#Output
print("Current password: ",i)
print("Length:",len(i))
print("MinEndPos: ",MinEndPos)
print("MinLength: ",MinLength)
print("MaxStartPos: ",MaxStartPos)
print("MaxEndPos: ",MaxEndPos)
print("MaxLength: ",MaxLength)
print("MinVal: ",MinVal)
print("MaxVal: ",MaxVal)
print("Check letter: ", checkletter)
print("Password: ", password)
print("Number of Check letters:" ,CheckLetterCount)
print("Valid passwords: ",validcount)
print("END OF RUN")
print("\n")
|
9a10a6b8a563dc09a41541d54ec5a3a2162516d1 | KULDEEPMALIKM41/Practices | /Python/Single Py Programms/count_substr_diffrent_maner.py | 250 | 3.71875 | 4 | a = 'bcacacacacac'
def count_substring(string,substr):
count1 = 0
for i in range(len(string)-len(substr)+1):
if string[i:i+len(substr)] == substr:
count1+=1
count2 = string.count(substr)
return count1,count2
print(count_substring(a,'aca')) |
bb25603e22ada6aa76a5f9ee979100afdc63671e | Varasekie/Py_homework_proj | /src/learning_1/add_plus.py | 1,994 | 3.796875 | 4 | class Changed(int):
def __add__(self, other):
####继承了int类里面的sub方法,因此不会无限递归
return int.__sub__(self, other)
def __sub__(self, other):
return int.__add__(self, other)
a = Changed(3)
b = Changed(4)
print(a - b)
a = [1, 2, 3, 4]
c = {'key1': 'value1'}
d = 'Varasekie'
b = iter(a)
print(next(b))
print(next(b))
b = iter(c)
print(next(b))
b = iter(d)
print(next(b))
####利用迭代器,打印字符串
while True:
try:
each = next(b)
except StopIteration:
break
print(each)
class Fib():
def __init__(self):
####定义这两个是为了让下面其他的函数也能访问这个值
self.a = 0
self.b = 1
def __iter__(self):
####返回迭代器(自身就是迭代器了
return self
def __next__(self):
####运用加减法
# self.b = self.a + self.b
# self.a = self.b - self.a
####或者利用同时赋值的方法
self.a, self.b = self.b, self.a + self.b
return self.a
fib = Fib()
for num in fib:
if num < 20:
print(num)
else:
print('end')
break
a = 1
b = 2
a, b = b, a + b
print(a)
print(b)
def borner():
print('一个生成器')
####利用yield,在2的地方停止,下一次从4开始,利用next()迭代方法
yield 2
yield 4
####先具象化成某个参数
a = borner()
print(next(a))
print('中间暂停')
print(next(a))
####法二
b = borner()
for i in b:
print(i)
####说明i可以自动检测到是否迭代完成,
def Libs():
a = 0
b = 1
while True:
a, b = b, a + b
yield a
for i in Libs():
if i < 10 :
####使在一行上打印,避免分行打印
print(i, end = ' ')
else:
print('end')
break
a = [i for i in range(10) if not i % 2 == 0]
print(a)
b = { i : i % 2 == 0 for i in range(12) if not (i % 5 == 0) and not i % 3 == 0}
print(b) |
b1d686e61cb21dedd5a2d662809ad98658c89f55 | Emmetttt/euler | /python/30.py | 291 | 3.546875 | 4 | def powers(n):
n = str(n)
i=0
k=0
while i < len(n):
k = k + int(n[i])**5
i+=1
if k == int(n):
return True
else:
return False
i=2
fifth = []
while i < 999999:
if powers(i) == True:
fifth.append(i)
i+=1
print(sum(fifth))
|
10daeee093c90f6dfb797e820bd1227edb5f4816 | MisaelAugusto/computer-science | /programming-laboratory-I/vdwb/bubble.py | 339 | 3.75 | 4 | # coding: utf-8
# Aluno: Misael Augusto
# Matrícula: 117110525
# Problema: Bubblesort
def bubblesort(dados):
update = True
j = 0
while j < len(dados) - 1 and update:
update = False
for i in range(len(dados) - 1):
if dados[i] > dados[i + 1]:
dados[i], dados[i + 1] = dados[i + 1], dados[i]
update = True
j += 1
return dados
|
587ec05bd899fda23b5cd09346a1f754804aaf2b | smilejay/python | /py2013/rename_files.py | 669 | 3.59375 | 4 | # -*- coding: gb2312 -*-
'''
Created on 2013-1-27
@author: Jay Ren
@module: rename_files
@note: rename files in a Windows system.
'''
import os
import re
path = "C:\\Users\\yren9\\Documents\\temp"
def rename_files():
prefix = "\[电影天堂-www\.dygod\.com\]"
for file in os.listdir(path):
if os.path.isfile(os.path.join(path,file))==True:
if re.match("\[电影天堂-www\.dygod\.com\].+", file):
new_name = re.sub(prefix, "", file)
# print(file)
# print(new_name)
os.rename(os.path.join(path,file),os.path.join(path,new_name))
if __name__ == '__main__':
rename_files()
|
dfa746dfd6410142c039d219f5f99def723ddb22 | mipmo/pricecal | /pricecal.py | 3,305 | 4 | 4 | # Import things
import sys
import os
# Begin the KeyboardInterrupt loop
try:
# Introduction
os.system('clear')
print('PRICE CALCULATOR')
print('Enter the prices and weights or amounts of products that need to be compared. Enter as many values as necessary.')
print('If you are done, enter 0 as the weight of the next product.')
print('')
# Set variables
weightTwo = float(-1)
counter = 1
ppuOne = 0
ppuTwo = 0
weightOne = raw_input('Enter the amount or weight of a product: ')
try:
weightOne = float(weightOne)
if weightOne <= 0:
sys.exit('Product 1 apparently does not exist, check values and run program again.')
except ValueError:
sys.exit('Invalid value entered, try again')
priceOne = raw_input('Enter the price of a product: ')
try:
priceOne = float(priceOne)
if priceOne == 0:
sys.exit('Product 1 is free')
if priceOne < 0:
sys.exit('Prices cannot be negative, check values and run program again.')
except ValueError:
sys.exit('Invalid value entered, try again')
while weightTwo != float(0):
weightTwo = raw_input('Enter the amount or weight of another product: ')
try:
weightTwo = float(weightTwo)
if weightTwo == 0:
print('')
if ppuOne == ppuTwo:
print('The Price per unit (PPU) is the same.')
print 'PPU: ', ppuOne
if ppuOne < ppuTwo:
print 'Product', counter,'is the cheapest.'
print('Here is its price per unit compared to the last product entered:')
print 'PPU: ',ppuOne,'VS',ppuTwo
if ppuOne > ppuTwo:
print 'Product', counter,'is the cheapest.'
print('Here is its price per unit compared to the last product entered:')
print 'PPU: ',ppuTwo,'VS',ppuOne
print('')
sys.exit()
if weightTwo <= 0:
sys.exit('The product apparently does not exist, check values and run program again.')
except ValueError:
sys.exit('Invalid value entered, try again')
priceTwo = raw_input('Enter the price of another product: ')
try:
priceTwo = float(priceTwo)
if priceTwo < 0:
sys.exit('Prices cannot be negative, check values and run program again.')
if priceTwo == 0:
sys.exit('The product is is free')
except ValueError:
sys.exit('Invalid value entered, try again')
# Calculations
ppuOne = priceOne / weightOne
ppuTwo = priceTwo / weightTwo
# Evaluations
if (ppuOne) == (ppuTwo):
priceOne = float((priceOne))
weightOne = float((weightOne))
if (ppuOne) < (ppuTwo):
priceOne = float((priceOne))
weightOne = float((weightOne))
if (ppuOne) > (ppuTwo):
priceOne = float((priceTwo))
weightOne = float((weightTwo))
counter = (counter) + 1
print('')
# End the KeyboardInterrupt loop
except KeyboardInterrupt:
print('')
sys.exit() |
644a43bcc71edf13627ec75b8fbd9f0cba530e37 | mishrakeshav/Competitive-Programming | /binarysearch.io/321_level_order_binary_search_tree_to_linked_list.py | 753 | 3.578125 | 4 | # class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
def solve(self, root):
stack = []
stack.append(root)
head = LLNode(-1)
curr = head
while stack:
new = []
for node in stack:
curr.next = LLNode(node.val)
curr = curr.next
if node.left:
new.append(node.left)
if node.right:
new.append(node.right)
stack = new
return head.next
|
32e33b8d3172e126dc808024bbc9bf8c1525bbea | Gitus-Maximus/Skills | /regex/ex13.py | 247 | 4.15625 | 4 | import re
"""
Match any word followed by a comma.
The example below is not the same as re.compile(r"\w+,")
For this will result in [ 'me,' , 'myself,' ]
"""
pattern = re.compile(r"\w+(?=,)")
res = pattern.findall("me, myself, adn I")
print(res) |
afc75b7e6e0087ef9b79f90a629227bb4556c71a | mtfgqd/PythonDemo | /pythonFundation/BasicLearn/DataType.py | 2,480 | 4.21875 | 4 | # 字符串 字符串是以单引号'或双引号"括起来的任意文本
# 如果字符串内部既包含'又包含" 可以用转义字符\来标识
string = 'I\'m \"OK\"!'
print(string)
# 转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\
print('I\'m ok.')
print('I\'m learning\nPython.')
# 如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容
print('''line1
line2
line3''')
# 多行字符串'''...'''还可以在前面加上r使用,\n不会转义成回车换行
print(r'''hello,\n
world''')
# 尔值和布尔代数的表示完全一致,一个布尔值只有True、False两种值,要么是True,要么是False,
# 在Python中,可以直接用True、False表示布尔值(请注意大小写)。布尔值可以用and、or和not运算
print(True)
print(False)
print(True and True)
print(True or False)
print(not False)
# 空值是Python里一个特殊的值,用None表示。None不能理解为0,因为0是有意义的,而None是一个特殊的空值。
# 变量
# 变量在程序中就是用一个变量名表示了,变量名必须是大小写英文、数字和_的组合,且不能用数字开头,
# 等号=是赋值语句,可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量
a = 123 # a是整数
print(a)
a = 'ABC' # a变为字符串
print(a)
# Python变量不需要指定变量类型,变量本身类型不固定的语言称之为动态语言,与之对应的是静态语言。
# 静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。
# 常量
# 所谓常量就是不能变的变量,比如常用的数学常数π就是一个常量。在Python中,通常用全部大写的变量名表示常量
# 但事实上PI仍然是一个变量,Python根本没有任何机制保证PI不会被改变,
# 所以,用全部大写的变量名表示常量只是一个习惯上的用法,如果你一定要改变变量PI的值,也没人能拦住你。
PI = 3.14159265359
# 除法
# /除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数
# 还有一种除法是//,称为地板除,两个整数的除法仍然是整数
print(10 / 3) # 除法 3.33。。
print(10 // 3) # 地板除 3
print(10 % 3) # 取余 1 |
2cb8b272c051b1471063aaa1312f7f45dc5c20b0 | jyosh30/Python | /Python_Day3_Project1.py | 610 | 4.4375 | 4 | # BMI Calculation
Weight = int(input("Enter the weight : ")) # weight in Kgs
Height = int(input("Enter the Height in cms :")) # Height in centimeters
Height = Height / 100 # converting cms into metres
BMI = Weight / (Height * Height)
print(float(BMI))
if BMI < 16.0:
print("Severly Underweight")
elif BMI >= 16.0 and BMI <= 18.5:
print("You are underweight")
elif BMI >= 18.5 and BMI <= 25.0:
print("Your weight is normal")
elif BMI >= 25.0 and BMI <= 30:
print("Overweight")
elif BMI >= 30.0 and BMI <= 40:
print("More Obese")
print("Reduce your food intake")
else:
pass
|
684faec1bfb2df0e9ca13e10574d030e5529327a | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/79_2.py | 1,723 | 3.984375 | 4 | hashlib.sha3_384() in Python
With the help of **hashlib.sha3_384()** method, we can convert the normal
string in byte format is converted to an encrypted form. Passwords and
important files can be converted into hash to protect them with the help of
hashlib.sha3_384() method.
> **Syntax :** hashlib.sha3_384()
>
> **Return :** Return the hash code for the string.
**Example #1 :**
In this example we can see that by using hashlib.sha3_384() method, we are
able to encrypt the byte string or passwords to protect them by using this
method.
__
__
__
__
__
__
__
# import hashlib
import hashlib
# Using hashlib.sha3_384() method
gfg = hashlib.sha3_384()
gfg.update(b'GeeksForGeeks')
print(gfg.digest())
---
__
__
**Output :**
>
> b’\x90\xb3\xee\xa6i\x8e\xc1\xc63\xc6\xe1_#\xbe\xe2F\xb2~\xe2[\xca\xb1I\xc9i\xef\xa5\xb32\xf9\xcc\xd8\x9c\x8c\x89\xd6\xc9\xb1\x9b!\x02\xb4\xaeN\xb9\x90Xo’
**Example #2 :**
__
__
__
__
__
__
__
# import hashlib
import hashlib
# Using hashlib.sha3_384() method
gfg = hashlib.sha3_384()
gfg.update(b'xyz@1234_GFG')
print(gfg.digest())
---
__
__
**Output :**
>
> b’\xfc\xc4/q\xb0x\x0cp\xa7\xfa\xd34\x18{\xaa\xb6\xbb\x08\xb5\xe8\xa9\xc4\xd2\xc6\x9c\xcd-#\xc6\xedt\xbc\t\x0b\x11\xe4\x8bxQAx.C\nv\x1ev’
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
08a75211bce72c9e10800aaf79bdd2e8108de3ee | yurimalheiros/IP-2019-2 | /lista1/marcosvinicius/questao2.py | 175 | 3.75 | 4 | base= float ( input ("digite a largura do retangulo"))
altura = float (input ("digite a altura do retangulo"))
area = base * altura
print (" a area do retangulo e",area)
|
d8f78ad4b3e1500420ef1eef5039f06d972a0af8 | pyplusplusMF/202110_68 | /_68semana06clase19POOEjemplo2.py | 1,944 | 4.09375 | 4 | # Clase del jueves 19 de Junio
# Ejemplo de la clase círculo
# Realizar una clase circulo que tenga como atributos el radio
# los métodos serán el perimetro y el area
import math
class Circulo:
# definir el constructor
def __init__ (self, radio = 1):
self.radio = radio
# Método para obtener el perimetro
def getPerimetro (self):
p = 2 * math.pi * self.radio
return p
# Método para obtener el area
def getArea (self):
a = math.pi * ( self.radio ** 2 )
return a
# Establecer el atributo radio
def setRadio (self, radio):
self.radio = radio
objetoCirculoA = Circulo()
print ('radio = ', objetoCirculoA.radio)
print ('perimetro =', objetoCirculoA.getPerimetro())
print ('area = ', objetoCirculoA.getArea())
objetoCirculoB = Circulo(5)
print ('radio = ', objetoCirculoB.radio)
print ('perimetro =', objetoCirculoB.getPerimetro())
print ('area = ', objetoCirculoB.getArea())
objetoCirculoC = Circulo()
objetoCirculoC.radio = 5
print ('radio = ', objetoCirculoC.radio)
print ('perimetro =', objetoCirculoC.getPerimetro())
print ('area = ', objetoCirculoC.getArea())
# objetoCirculoA = Circulo()
# print ('radio = ', objetoCirculoA.radio)
# print ('perimetro =', objetoCirculoA.getPerimetro())
# print ('area = ', objetoCirculoA.getArea())
# radio = 1
# perimetro = 6.283185307179586
# area = 3.141592653589793
# objetoCirculoB = Circulo(5)
# print ('radio = ', objetoCirculoB.radio)
# print ('perimetro =', objetoCirculoB.getPerimetro())
# print ('area = ', objetoCirculoB.getArea())
# radio = 5
# perimetro = 31.41592653589793
# area = 78.53981633974483
# objetoCirculoC = Circulo()
# objetoCirculoC.radio = 5
# print ('radio = ', objetoCirculoC.radio)
# print ('perimetro =', objetoCirculoC.getPerimetro())
# print ('area = ', objetoCirculoC.getArea())
# radio = 5
# perimetro = 31.41592653589793
# area = 78.53981633974483 |
8d40af814e242f449abd93efe151b3351ecd060f | tt66/LintCode | /K个最近的点-612-2.py | 517 | 3.609375 | 4 | import heapq
'''def s(point,origin):
return ((point[0]-origin[0])**2+(point[1]-point[1])**2,point[0],point[1])'''
'''import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]'''
def ksorted(points,origin,k):
return heapq.nsmallest(k,points,key=lambda point:((point[0]-origin[0])**2+(point[1]-point[1])**2,point[0],point[1]))
points=[(3,4),(4,3),(4,5),(65,0.1)]
print(ksorted(points,(62,3),3))
|
b5570fb148d0631725e3bc2aa35b2375f2198a0d | malaga95/magazyn | /command/commands.py | 4,040 | 3.515625 | 4 | import sys
class Account:
def __init__(self):
self.account = []
# self.add_line()
#def add_line(self):
# value = sys.argv[1]
# comment = sys.argv[2]
# self.account.append(value)
# self.account.append(comment)
def add_to_file(self, value, comment):
with open('konto.txt', 'a') as file:
file.write(str(value) + ',' + str(comment) + '\n')
class Sprzedaz:
def __init__(self):
self.sprzedaz = []
self.add_line()
#id = self.product_id
#price = self.product_price
#count = self.product_count
def add_line(self):
self.id = sys.argv[2]
self.price = sys.argv[3]
self.count = sys.argv[4]
with open (str(sys.argv[1]), 'r') as file:
for line in file.readlines():
print(line)
with open (str(sys.argv[1]), 'a') as file:
file.write(self.id + ',' + self.price + ',' + self.count + '\n')
def check_storage():
pass
def remove_from_storage():
pass
class Zakup:
balance = 0
def __init__(self):
self.id = sys.argv[1]
self.price = sys.argv[3]
self.count = sys.argv[4]
def add_line(self):
if self.id != 'buy_list.txt':
print('Wybrano złą nazwe pliku, aby przeprowadzic zakup uzyj pliku buy_list.txt')
#with open (str(sys.argv[1]), 'r') as file:
# for line in file.readlines()[1:]:
# print(line)
with open (str(sys.argv[1]), 'a') as file:
file.write(self.id + ',' + self.price + ',' + self.count + '\n')
def check_storage():
pass
def check_balance(self):
check = Balance()
total_price = int(self.price) * int(self.count)
if total_price > check.check_balance():
print('nie posiadasz wystarczajaco srodkow na koncie aby dokonac zakupu')
return False
else:
with open ('konto.txt', 'a') as file:
file.write(str((total_price) * -1) + ',' + 'Buy of product' + str(self.id) + '\n')
return True
#def check_balance(self):
# val = int(self.price) * int(self.count)
# with open ('konto.txt', 'r') as file:
# check = Balance()
# check.get_balance(self.balance)
# if val > self.balance:
# print('nie posiadasz wystarczajacych srodkow na zakup produktu')
# else:
# set_amount = self.balance - val
# with open ('konto.txt', 'a') as file:
# file.write({{-val} + ',' + 'Zakup' + {self.id}})
class Storage:
def __init__(self):
with open ('storage.txt', 'r') as file:
for line in file.readlines():
id = line.split(',')[0]
count = line.split(',')[1]
for arg in sys.argv:
if id == arg:
print(count)
class Balance:
balance = 0
def get_balance(self):
with open ('konto.txt', 'r') as file:
for line in file.readlines():
val = line.split(',')[0]
comment = line.split(',')[1]
self.balance += int(val)
def check_balance(self):
self.get_balance()
return self.balance
class Overview:
def __init__(self):
print("Lista zakupów :")
with open ('buy_list.txt', 'r') as file:
for line in file.readlines():
print(line)
print('Lista sprzedazy :')
with open ('sale_list.txt', 'r') as file:
for line in file.readlines():
print(line)
print('Przeglad operacji na koncie :')
with open ('konto.txt', 'r') as file:
for line in file.readlines():
print(line)
print('Stan magazynu :')
with open ('storage.txt', 'r') as file:
for line in file.readlines():
print(line) |
1a39b843dae5da536da1cb6672d36e4788b2a491 | VaskarNath/ml-projects | /Assignment 3/q3_1.py | 9,992 | 3.59375 | 4 | '''
Question 3.1 Skeleton Code
Here you should implement and evaluate the k-NN classifier.
'''
import data
import numpy as np
# Import pyplot - plt.imshow is useful!
import matplotlib.pyplot as plt
from statistics import mode
from sklearn.model_selection import KFold
from scipy import stats as s
from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, mean_squared_error, confusion_matrix, recall_score
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.metrics import plot_confusion_matrix
import pandas as pd
import seaborn as sn
class KNearestNeighbor(object):
'''
K Nearest Neighbor classifier
'''
def __init__(self, train_data, train_labels):
self.train_data = train_data
self.train_norm = (self.train_data**2).sum(axis=1).reshape(-1,1)
self.train_labels = train_labels
def l2_distance(self, test_point):
'''
Compute L2 distance between test point and each training point
Input: test_point is a 1d numpy array
Output: dist is a numpy array containing the distances between the test point and each training point
'''
# Process test point shape
test_point = np.squeeze(test_point)
if test_point.ndim == 1:
test_point = test_point.reshape(1, -1)
assert test_point.shape[1] == self.train_data.shape[1]
# Compute squared distance
test_norm = (test_point**2).sum(axis=1).reshape(1,-1)
dist = self.train_norm + test_norm - 2*self.train_data.dot(test_point.transpose())
return np.squeeze(dist)
def query_knn(self, test_point, k):
'''
Query a single test point using the k-NN algorithm
You should return the digit label provided by the algorithm
'''
distances = self.l2_distance(test_point)
k_nearest_indices = {}
for i in range(len(distances)):
if len(k_nearest_indices) != k:
k_nearest_indices[i] = distances[i]
else:
max_index = max(k_nearest_indices, key=k_nearest_indices.get)
if distances[i] < distances[max_index]:
k_nearest_indices.pop(max_index)
k_nearest_indices[i] = distances[i]
labels = []
for key in k_nearest_indices:
labels.append(self.train_labels[key])
# Seeking for any ties of modal values between two different digit classes
digit = int(s.mode(labels)[0])
max_count = labels.count(digit)
mode_array = []
for i in range(0, 10):
if labels.count(i) == max_count:
mode_array.append(i)
# Handling ties of multiple modal values by picking the nearest digit between the ties
min_distance_in_mode_array = 1000 # assume max distance is less than 1000
if len(mode_array) > 1:
for key in k_nearest_indices:
if self.train_labels[key] in mode_array:
if k_nearest_indices[key] < min_distance_in_mode_array:
min_distance_in_mode_array = k_nearest_indices[key]
digit = self.train_labels[key]
else:
digit = mode_array[0]
return digit
def predict(self, test_data, k):
"""
Predict the labels for entire test_data
"""
result = []
for test_point in test_data:
result.append(self.query_knn(test_point, k))
return result
def predict_proba(self, test_data, k):
"""
Output matrix of probability of being each class for each test_point in test_data
"""
result = []
for test_point in test_data:
# Initializing probability array so that every class has atleast a non-zero probability
prob_array = np.full((10,), 0.01)
# Getting k nearest labels
distances = self.l2_distance(test_point)
k_nearest_indices = {}
for i in range(len(distances)):
if len(k_nearest_indices) != k:
k_nearest_indices[i] = distances[i]
else:
max_index = max(k_nearest_indices, key=k_nearest_indices.get)
if distances[i] < distances[max_index]:
k_nearest_indices.pop(max_index)
k_nearest_indices[i] = distances[i]
labels = []
for key in k_nearest_indices:
labels.append(self.train_labels[key])
# Getting prob_array for the individual test point
for i in range(10):
if labels.count(i) != 0:
prob_array[i] = labels.count(i) / k
result.append(prob_array)
return result
def cross_validation(train_data, train_labels, k_range=np.arange(1, 16)):
'''
Perform 10-fold cross validation to find the best value for k
Note: Previously this function took knn as an argument instead of train_data,train_labels.
The intention was for students to take the training data from the knn object - this should be clearer
from the new function signature.
'''
accuracy_list = []
for k in k_range:
kf = KFold(10, shuffle=True, random_state=89)
accuracy = 0
num = 0
for train_index, test_index in kf.split(range(len(train_data))):
x_train, x_val, y_train, y_val = train_data[train_index], train_data[test_index], \
train_labels[train_index], train_labels[test_index]
knn = KNearestNeighbor(x_train, y_train)
for j in range(len(x_val)):
if knn.query_knn(x_val[j], k) == y_val[j]:
accuracy += 1
num += 1
print(accuracy, " ", num)
accuracy_list.append(accuracy/num)
for l in range(15):
print("The average accuracy across folds for K = ", l + 1, ": ", float("{0:.3f}".format(accuracy_list[l])))
return accuracy_list.index(max(accuracy_list)) + 1
def classification_accuracy(knn, k, eval_data, eval_labels):
'''
Evaluate the classification accuracy of knn on the given 'eval_data'
using the labels
'''
accuracy = 0
num = 0
for j in range(len(eval_data)):
if knn.query_knn(eval_data[j], k) == eval_labels[j]:
accuracy += 1
num += 1
return accuracy/num
def plot_roc_curve(clf, k, test_data, test_labels, type):
y_score = np.array(clf.predict_proba(test_data, k))
y_test = label_binarize(test_labels, classes=range(10))
# Computing ROC curve and ROC area for each class
false_pos_rate = {}
true_pos_rate = {}
roc_auc = {}
# Plotting ROC curve with legend describing the area under curve
for i in range(10):
false_pos_rate[i], true_pos_rate[i], _ = roc_curve(y_test[:, i], y_score[:, i])
roc_auc[i] = auc(false_pos_rate[i], true_pos_rate[i])
for i in range(10):
plt.plot(false_pos_rate[i], true_pos_rate[i], label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.01])
plt.xlabel('Rate of False Positives')
plt.ylabel('Rate of True Positives')
plt.title(
'ROC Curve for each of the 10 Classes of Handwritten Digits')
plt.legend(loc="lower right")
plt.savefig(type + " ROC Curve.pdf")
def make_confusion_matrix(y_pred, y_test, type):
matrix = confusion_matrix(y_test, y_pred)
df_cm = pd.DataFrame(matrix, range(10), range(10))
plt.figure(figsize=(10, 7))
sn.heatmap(df_cm, cmap="coolwarm", annot=True, fmt='.3g')
plt.title("Confusion Matrix")
plt.savefig(type + " Confusion Matrix.pdf")
def get_precision_score(y_pred, y_true):
for digit, score in enumerate(precision_score(y_true, y_pred, average=None)):
print("Precision Score for digit ", digit, ": {0:.3f}".format(score))
def get_error_rate(clf, k, test_data, test_label):
print("Error Rate: ", "{0:.3f}".format(1 - classification_accuracy(clf, k, test_data, test_label)))
def get_recall_score(y_pred, y_true):
for digit, score in enumerate(recall_score(y_true, y_pred, average=None)):
print("Recall Score for digit ", digit, ": {0:.3f}".format(score))
def main():
train_data, train_labels, test_data, test_labels = data.load_all_data('data')
knn = KNearestNeighbor(train_data, train_labels)
k = cross_validation(train_data, train_labels)
print("The value of optimal K: ", k)
# print("Test accuracy: ", float("{0:.3f}".format(classification_accuracy(knn, 1, test_data, test_labels))))
# print("Train accuracy: ", float("{0:.3f}".format(classification_accuracy(knn, 1, train_data, train_labels))))
#
# print("Test accuracy: ", float("{0:.3f}".format(classification_accuracy(knn, 15, test_data, test_labels))))
# print("Train accuracy: ", float("{0:.3f}".format(classification_accuracy(knn, 15, train_data, train_labels))))
print("Test accuracy: ", float("{0:.3f}".format(classification_accuracy(knn, k, test_data, test_labels))))
print("Train accuracy: ", float("{0:.3f}".format(classification_accuracy(knn, k, train_data, train_labels))))
y_pred = knn.predict(test_data, k)
plot_roc_curve(knn, k, test_data, test_labels, "knn")
make_confusion_matrix(y_pred, test_labels, "knn")
get_error_rate(knn, k, test_data, test_labels)
get_precision_score(y_pred, test_labels)
get_recall_score(y_pred, test_labels)
if __name__ == '__main__':
main()
|
ba8d6b83b805237207c631e63e757c029530e506 | Yojanpardo/python | /while_loop.py | 495 | 3.890625 | 4 | # -*- coding: utf-8 -*-
import random
def main():
number_found = False
random_number = random.randint(0,20)
while not number_found:
number_try = int(raw_input('cual crees que es el numero?'))
if number_try==random_number:
print('felicidades, encontró el numero')
number_found=True
elif number_try<random_number:
print('el número que se inventó la máquina es mayor')
else:
print('el número que se inventó la máquina es menor')
if __name__ == '__main__':
main() |
b48d95ae029befef251784fa9c0d660f129dea6a | LounissartHK/pdsnd_github | /bikeshare.py | 9,310 | 4.40625 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs. I want to make it easier for the user to inut his choice byt inputing number instead of full name of the city.
while True:
city_number = input("Tell me which City you would like to explore? For Chicago press 1, for New York City press 2 or Washington press 3?")
if str(city_number) not in ('1', '2', '3'):
print("Your input is incorrect!")
else:
break
if str(city_number) == '1':
city = 'chicago'
elif str(city_number) == '2':
city = 'new york city'
elif str(city_number) == '3':
city = 'washington'
# TO DO: get user input for month (all, january, february, ... , june)
while True:
month_number = input("Enter the number of the month you would like to explore? For Example for February type 2, Data available is only from Janaury to June (1 to 6). For all months just press enter!")
if str(month_number).lower() not in ('1', '2', '3', '4', '5', '6',''):
print("Your input is incorrect!")
else:
break
if str(month_number) == '1':
month = 'january'
elif str(month_number) == '2':
month = 'february'
elif str(month_number) == '3':
month = 'march'
elif str(month_number) == '4':
month = 'april'
elif str(month_number) == '5':
month = 'may'
elif str(month_number) == '6':
month = 'june'
elif str(month_number) == '':
month = 'all'
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day_number = input("Enter the number of the day you would like to explore? For Example for Wednesday type 3. For all days just press enter!")
if str(day_number).lower() not in ('1', '2', '3', '4', '5', '6','7',''):
print("Your input is incorrect!")
else:
break
if str(day_number) == '1':
day = 'monday'
elif str(day_number) == '2':
day = 'tuesday'
elif str(day_number) == '3':
day = 'wednesday'
elif str(day_number) == '4':
day = 'thursday'
elif str(day_number) == '5':
day = 'friday'
elif str(day_number) == '6':
day = 'saturday'
elif str(day_number) == '7':
day = 'sunday'
elif str(day_number) == '':
day = 'all'
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month,day of week and hour from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
df['hour'] = df['Start Time'].dt.hour
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
popular_month = df['month'].mode()[0]
print('Most Popular Month:', popular_month)
# TO DO: display the most common day of week
popular_day = df['day_of_week'].mode()[0]
print('Most Popular Day of the week:', popular_day)
# TO DO: display the most common start hour
popular_hour = df['hour'].mode()[0]
print('Most Popular Start Hour:', popular_hour)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
popular_start_station = df['Start Station'].mode()[0]
print('Most Popular Start Station:', popular_start_station)
# TO DO: display most commonly used end station
popular_end_station = df['End Station'].mode()[0]
print('Most Popular End Station:', popular_end_station)
# TO DO: display most frequent combination of start station and end station trip
df['Start Station & End Station'] = "Start Station: " + df['Start Station'] + " & End Station: " + df['End Station']
popular_combi_station = df['Start Station & End Station'].mode()[0]
print('Most frequent combination of start station and end station trip:', popular_combi_station)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration.
Total Travel Time / Mean Travel Time"""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
total_trip_duration = df['Trip Duration'].sum()
print("The Total Travel Time is roughly %d hours" % round(total_trip_duration/3600,0))
# TO DO: display mean travel time
mean_trip_duration = df['Trip Duration'].mean()
print("The Mean Travel Time is roughly %d minutes" % round(mean_trip_duration/60,0))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def raw_data(df):
"""Offering the user to see the raw data"""
while True:
raw_data = input('\nWould you like to see the raw data? Enter yes or no.\n')
if raw_data not in ('yes', 'no'):
print("Your input is incorrect!")
elif raw_data == "no":
break
elif raw_data == "yes":
i = 0
j = 5
more = "yes"
while more == "yes":
print(df.iloc[i:j])
more = input('\nWould you like to see more data? Enter yes or no.\n')
if more not in ('yes', 'no'):
print("Your input is incorrect!")
elif more == "no": break
elif more == "yes":
i += 5
j += 5
break
def user_stats(df):
"""Displays statistics on bikeshare users.
Count of User Type / Earliest, Most recent and most common year of birth """
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types = df['User Type'].value_counts()
print('This is the count of User Type:', user_types)
# TO DO: Display counts of gender
try:
gender_types = df['Gender'].value_counts()
print('This is the count of the different Gender:', gender_types)
except:
print('Gender is not available in this dataset')
# TO DO: Display earliest, most recent, and most common year of birth
try:
earliest_yob = df['Birth Year'].min()
most_recent_yob = df['Birth Year'].max()
most_common_yob = df['Birth Year'].mode()
print ('The erliest year of birth is {}, the most recent year of birth is {} and the most common year of birth is {}'.format(int(earliest_yob), int(most_recent_yob), int(most_common_yob)))
except:
print('Birth Year is not available in this dataset')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
raw_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
9f3fe0782f0f316b207f36ffcaa0d3bc48fbaf9d | Frann2807/Mi-primer-programa | /adivina_numero/Adivina el numero ganador.py | 167 | 3.875 | 4 | numero_ganador = 35
numero_usuario = int(input("Adivina el numero: "))
if numero_ganador == numero_usuario:
print("Has adivinado")
else:
print("Has perdido") |
449bba69ba31628fd749c3949240293273687bd0 | green-fox-academy/fehersanyi | /python/expressionsandcontrollflow/animal-legs.py | 162 | 3.859375 | 4 | chicken = input('how many chickens live in the farm? ' )
pigs = input('how any pigs live in the farm? ' )
print'there are ', chicken * 2 + pigs * 4, 'legs total'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.