blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
845afa79098673df25b04509c3d4f6d5fa5ece88 | cmulliss/gui_python | /revision/fns2.py | 258 | 3.90625 | 4 | def add(x, y):
result = x + y
print(result)
add(5, 3)
# positional arguments
def say_hello(name, surname):
print(f"Hello, {name} {surname}")
name = input("enter your name: ")
surname = input("enter your surname: ")
say_hello(name, surname)
|
530395a78cb52fe90e3e14aa9826fe2296e91ec7 | rakesh-29/data-structures | /data structures/searching/binary search/interview problems on binary search/find index of last occurance of an element in an array.py | 650 | 3.6875 | 4 | def last_ocuurance(list,searchnumber):
left_index=0
right_index=len(list)-1
count=0
while left_index<=right_index:
mid_index = (left_index + right_index) // 2
mid_number = list[mid_index]
if mid_number==searchnumber:
count=mid_index
left_index=mid_index+1
elif mid_number<searchnumber:
left_index=mid_index+1
else:
right_index=mid_index-1
if count==0:
print("search number not found in the list")
return -1
return count
list=[1,2,2,2,2,2,3,4,5,6,7,8,9,10]
print(last_ocuurance(list,2)) |
cb846597571710f580b0b9b5c883f284004d5fa6 | Dolj0/Data-Analysis-with-Python-2021 | /part01-e11_interleave/src/interleave.py | 389 | 4.21875 | 4 | #!/usr/bin/env python3
def interleave(*lists):
listForZip=[]
returnList=[]
for x in lists:
listForZip.append(x)
zipped = list(zip(*listForZip))
for x in zipped:
for i in x:
returnList.append(i)
return returnList
def main():
print(interleave([1, 2, 3], [20, 30, 40], ['a', 'b', 'c']))
if __name__ == "__main__":
main()
|
8733471d811c3d78abc78b6a48110351b12c3e72 | evil1086/Part-2---Regression | /multipleLinearRegression.py | 1,321 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 08:34:32 2019
@author: user
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#IMPORT DATASETS
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# tranform categorical data
from sklearn.preprocessing import LabelEncoder , OneHotEncoder
labelencoder_X = LabelEncoder()#LabelEncoder can be used to normalize labels.
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features=[3])
X = onehotencoder.fit_transform(X).toarray()
#avoiding dummy variable
X = X[:, 1:]
#spliting the dataset
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
#feature scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""
#linear regression
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#prediction
y_pred = regressor.predict(X_test)
#visualizing the result
plt.scatter(X_train, y_train, color='red')
plt.plot(X_train, regressor.predict(y_train))
plt.show() |
ac93cc8a77a26fbf7205c3060eb217770ef5fb2f | huanglun1994/learn | /python编程从入门到实践/第八章/8-8.py | 779 | 4 | 4 | # -*- coding: utf-8 -*-
__authour__ = 'Huang Lun'
#定义一个函数,接受三个参数表示歌手名和专辑名和歌曲数,歌曲数为可选形参,返回字典
def make_album(singer, album, quantity=''):
music_album = {'Singer': singer.title(), 'Album': album.title()}
if quantity:
music_album['Quantity'] = quantity
return music_album
#利用循环提示用户输入信息,并提示退出条件
while True:
print('\nPlease tell me your favorite singer and album:')
print("(enter 'q' at any time to quit)")
singer = input('Singer: ')
if singer == 'q':
break
album = input('Album: ')
if album == 'q':
break
#调用函数并打印返回的字典
album_dict = make_album(singer, album)
print(album_dict)
|
742349631149c8f17ef4c0a30793a20f937b81d4 | Fengyongming0311/TANUKI | /小程序/001.ReverseString/把GBK字节转换为utf-8字节.py | 516 | 3.71875 | 4 |
#encode 是编码
#decode 是解码
"""s = "周杰伦"
bs1 = s.encode("GBK")
bs2 = s.encode("utf-8")
print (bs1)
print (bs2)
"""
#把一个GBK字节转化成utf-8的字节
gbk = b'\xd6\xdc\xbd\xdc\xc2\xd7'
s = gbk.decode("gbk") #解码 因为原编码就是GBK所以用GBK方式解码
print (s)
utf8 = s.encode("utf-8") #用utf-8编码
print (utf8)
don = utf8.decode("utf-8")
print ("###################")
print (don)
"""
1. str.encode("编码") 进行编码
2. bytes.decode("编码") 进行解码
""" |
48ed34932b355c2afef1caaabe7e499e885ee279 | NiltonGMJunior/hackerrank-problem-solving | /algorithms/warmup/plus_minus.py | 481 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def plusMinus(arr):
positive_ratio = sum([elem > 0 for elem in arr]) / n
negative_ratio = sum([elem < 0 for elem in arr]) / n
zero_ratio = sum([elem == 0 for elem in arr]) / n
print("{:.6f}\n{:.6f}\n{:.6f}".format(
positive_ratio, negative_ratio, zero_ratio))
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
|
d50e7a7f736db28ecd3776c1bdcf283c7910fe90 | italormb/Exercicio_python_basico | /Curso_de_Python_3_Basico/Fase_10/desafio29.py | 247 | 3.90625 | 4 | #desafio 29
velocidade=float(input('Escreva a velocidade do seu carro em km/h:'))
if velocidade>80:
multa=(velocidade-80)*7
print('A multa vai custar {}' .format(multa))
else:
print('Respeitou a leis de transito, Parabéns!!!')
print('DETRAN') |
0abb270ac131411e6f5ab261ea5053c6fa984f49 | hightechfarmer/ControlPyWeb | /build/lib.linux-x86_64-2.7/controlpyweb/abstract_reader_writer.py | 719 | 3.859375 | 4 | from abc import ABC, abstractmethod
class AbstractReaderWriter(ABC):
@abstractmethod
def read(self, addr: str) -> object:
"""This method provides a response to a read request, based on last load"""
pass
@abstractmethod
def read_immediate(self, addr: str) -> object:
"""This method must provide an immediate response to a read request"""
pass
@abstractmethod
def write(self, addr: str, value: object):
"""This method captures the need to write a value, but isn't necessarily immediate"""
pass
@abstractmethod
def write_immediate(self, addr: str, value: object):
"""This method should force an immediate write"""
pass
|
6f63b41f54e15eeb762ded0454162a430eb57779 | zhuxingyue/pythonDemo | /python基础/day08/hm_05_函数demo3.py | 295 | 3.953125 | 4 | def printLine(char, times):
print(char * times)
def printLines(char, times):
"""打印多行分割线
:param char: 分割线样式字符
:param times: 分割线个数
"""
row = 0
while row < 5:
printLine(char, times)
row += 1
printLines("_", 20)
|
4d728a78c6b284d56b4a501c0c60203839ebbde6 | codafett/python | /uncategorised/combine_words.py | 486 | 3.5625 | 4 | def combine_words(word, **kwargs):
if "prefix" in kwargs:
return "{0}{1}".format(kwargs["prefix"], word)
if "suffix" in kwargs:
return "{0}{1}".format(word, kwargs["suffix"])
return word
print(combine_words("child")) # 'child'
print(combine_words("child", prefix="man")) # 'manchild'
print(combine_words("child", suffix="ish")) # 'childish'
print(combine_words("work", suffix="er")) # 'worker'
print(combine_words("work", prefix="home")) # 'homework'
|
d0c20901a2ea5c875f268a206cd074eafb306f2e | KillianWalshe/PE | /5.py | 639 | 3.6875 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
match=0
while match==0:
for num in range(1,1000000000):
count=0
for i in range (1,21):
if(num%i==0):
#print(count)
count+=1
if(count==20):
print(num)
match=1
break
else:
break
print("out of range")
break
|
eb86a94f7bd3cf72a74275dcd08023e987d3177e | shahuji/hello-world | /part-2/s1.py | 2,203 | 3.734375 | 4 | #
# import operator
# print('practical 1')
#
# print("Hello World")
#
# dict = {3: 40, 1: 20, 4: 50, 2: 30, 0: 10}
# print("before editing dict => ", dict)
# dict1 = sorted(dict.items(), key=operator.itemgetter(1), reverse=False)
# print('after editing in ascending order dict => ', dict1)
# dict2 = sorted(dict.items(), key=operator.itemgetter(1), reverse=True)
# print('after editing dictionary in descending order => ', dict2)
# print('practical 2')
# d1 = {0: 1, 1: 2}
# d2 = {2: 3, 3: 4}
# d3 = {4: 5, 5: 6}
# d4 = {}
# for i in (d1, d2, d3): d4.update(i)
#
# print('=> d1: ', d1, '\j=> d2: ', d2, '\j=> d3: ', d3, '\j=> d4: ', d4)
# import math
# from builtins import range
#
# print('practical 3')
# j = int(input("Enter the no.(1 to 9) :"))
# d5 = dict()
# for i in range(j + 1):
# d5[i] = int(math.pow(float(i), 2))
#
# print(d5)
# print("Practical 4")
# keys = ['red', 'green', 'blue']
# values = ['#FF0000', '#008000', '#0000FF']
# d6 = dict(zip(keys, values))
# print(d6, "\nNow in sorted form")
# for i in sorted(d6):
# print('%s: %s' % (i, d6[i]))
# from collections import Counter
#
# item_list = [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item3', 'amount': 750}]
# d7 = Counter()
# for d in item_list:
# d7[d['item']] += d['amount']
#
# print("Dictionary from list => ", d7)
# Merging to dictionary using ** notation for **kwargs
# p1 = {"X": 100, "Y": 200, "Z": 300}
# p2 = {"A": 10, "B": 20, "C": 30}
# p3 = {**p1, **p2}
#
# print(p3)
# Array start
# import array as arr
#
# a = arr.array('i', [1, 2, 3])
# for i in range(0, 3):
# print(a[i], end=" ")
#
# print('\nend')
#
# a.insert(1, 4)
# for i in range(0, 3):
# print(a[i], end=" ")
#
# a.insert(1, 2)
# a.insert(2, 3)
# print("")
#
# for i in range(0, 3):
# print(a[i], end=" ")
#
# a.append(5)
# for i in range(0, 3):
# print(a[i], end=" ")
# print()
# try catch handle
# while True:
# try:
# a1 = int(input("Input a number: "))
# break
# except ValueError:
# print("\nThis is not a number. Try again...", ValueError)
# print()
|
7bb5f16f017c36e032eb95cbe1d47f26a50c490a | jakobtsmith/team-14 | /PythonScripts/TicTacToe/Board.py | 9,640 | 3.625 | 4 | import random as rand
from os import system
from collections import defaultdict
class BoardEnvironment:
def __init__(self):
"init board"
def set_players(self, AI):
self.AI = AI
self.reset()
def reset(self):
self.turn = 'X'
self.board = list('---------')
if(rand.random() < 0.5):
self.current_player = True
else:
self.current_player = False
return self.current_player
def print_board(self, board_string = None):
if not board_string:
B = self.board
else:
B = board_string
check_for = ['X', 'O']
print(B[0] if B[0] in check_for else 1,'|', B[1] if B[1] in check_for else 2,'|', B[2] if B[2] in check_for else 3, sep='')
print('-----')
print(B[3] if B[3] in check_for else 4,'|', B[4] if B[4] in check_for else 5,'|', B[5] if B[5] in check_for else 6, sep='')
print('-----')
print(B[6] if B[6] in check_for else 7,'|', B[7] if B[7] in check_for else 8,'|', B[8] if B[8] in check_for else 9, sep='')
def get_state(self):
return "".join(self.board)
def other_player(self):
return not self.current_player
def available_actions(self, first):
return [ind for ind, val in enumerate(self.board) if val == '-']
def play_game(self):
self.reset()
while( not self.is_full() ):
system('clear')
if( not self.current_player ):
choice = self.AI.select_action(None)
else:
self.print_board()
choices = self.available_actions(None)
print("Select your space to play. Your pieces are", self.turn + '.', "Current choices are")
print(list(x+1 for x in choices))
choice = 10
while(choice not in choices):
choice = input()
choice = int(choice) - 1
if(choice not in choices):
print("Spot not available. Current choices are")
print(list(x+1 for x in choices))
self.board[choice] = self.turn
if self.winner(self.turn):
system('clear')
if(self.current_player):
print("You won!")
else:
print("You lost!")
self.print_board()
return self.current_player
self.turn = 'X' if self.turn == 'O' else 'O'
self.current_player = not self.current_player
system('clear')
self.print_board()
print("Tie!")
return None
def winner(self, check_for = ['X', 'O']):
straight_lines = ((0,1,2),(3,4,5),(6,7,8),(0,3,6),
(1,4,7),(2,5,8),(0,4,8),(2,4,6))
for turn in check_for:
for line in straight_lines:
if all(x == turn for x in (self.board[i] for i in line)):
return turn
return ''
def is_full(self):
return('-' not in self.board)
class Agent:
def __init__(self, environment, difficulty, policy = 'max'):
self.environment = environment
self.policy = policy
self.Q = ''
if policy == 'max':
with open(difficulty, 'r') as f:
for i in f.readlines():
self.Q = i
self.Q = eval(self.Q)
self.Q = defaultdict(lambda: 0.0, self.Q)
self.reset_past()
def reset_past(self):
self.past_action = None
self.past_state = None
def select_action(self, first):
available_actions = self.environment.available_actions(first)
if(self.policy == 'random'):
choice = rand.choice(available_actions)
else:
Q_vals = [self.Q[(self.environment.get_state(), x)] for x in available_actions]
max_val = max(Q_vals)
max_pos = [i for i, j in enumerate(Q_vals) if j == max_val]
max_indices = [available_actions[x] for x in max_pos]
choice = rand.choice(max_indices)
self.past_state = self.environment.get_state()
self.past_action = choice
return choice
class LeagueEnvironment:
def __init__(self, board_environment):
self.board = board_environment
def set_players(self, player_names, league_agents, board_agents):
self.player_names = player_names
self.league_agents = league_agents
self.board_agents = board_agents
assert(len(player_names) == len(league_agents) == len(board_agents) )
self.num_players = len(player_names)
def reset_pair(self):
# randomly select 2 players
player_indices = list(range(self.num_players))
self.Ai = rand.choice(player_indices)
self.board.set_players(self.board_agents[self.Ai])
self.first = self.board.reset()
self.league_agents[self.Ai].reset_past()
self.A_wins = 0;
self.A_chips=100;
self.Player_wins = 0;
self.Player_chips=100;
self.ties = 0;
self.state_perspective = 'A' # the state in wins/ties/losses for which player
self.chip_mul=1
self.min_bid=5
self.game_counter=1
def get_state(self): ### how to tell who is calling get_state?
return (self.A_chips,self.A_wins,self.ties,self.Player_chips,self.Player_wins,self.player_names[self.Ai],'learning strategy and tactics')
def pair_games_played(self):
return self.A_wins + self.ties + self.B_wins
def available_actions(self, first):
if first:
return ['quit','single bet','double bet','triple bet']
else:
return ['quit','call']
def play_pair(self):
system('clear')
self.reset_pair()
player_choice = ''
while(True):
if self.first:
player_choice = self.league_choice(True)
AI_choice = self.league_agents[self.Ai].select_action(False)
print("Opponent chose", AI_choice)
else:
AI_choice = self.league_agents[self.Ai].select_action(True)
player_choice = self.league_choice(False, AI_choice)
if AI_choice == 'quit' or player_choice == 'quit':
break
elif AI_choice == 'single bet' or player_choice == 'single bet':
self.chip_mul=1
elif AI_choice == 'double bet' or player_choice == 'double bet':
self.chip_mul=2
elif AI_choice == 'triple bet' or player_choice == 'triple bet':
self.chip_mul=3
winner = self.board.play_game()
self.first = not self.first
if winner == True:
print("Player wins!")
self.Player_wins += 1
self.Player_chips += self.min_bid*self.chip_mul
self.A_chips -= self.min_bid*self.chip_mul
elif winner == False:
print("Ai wins!")
self.A_wins += 1
self.A_chips += self.min_bid*self.chip_mul
self.Player_chips -= self.min_bid*self.chip_mul
else:
self.ties += 1
if self.A_chips <= 0 or self.Player_chips <= 0:
break
if player_choice == 'quit' or self.Player_chips <= 0:
print("Player is no longer playing")
else:
print("Play again? 1 for yes, 0 for no")
again = -1
while again < 0 or again > 1:
again = int(input())
if again == 1:
self.play_pair()
return
def league_choice(self, first, AI_choice = ''):
choice_list = self.available_actions(first)
i = 0
p_input = -1
print("You currently have", self.Player_chips, "chips and", self.Player_wins, "wins.")
if AI_choice:
print("Opponent chose", AI_choice)
print('Select a choice from the list:')
for choice in choice_list:
print(i, choice)
i += 1
while p_input < 0 or p_input > len(choice_list):
p_input = int(input())
return choice_list[p_input]
def select_difficulty(select = False):
x = 0
diffdict = {1 : r'easy.txt',
2 : r'medium.txt',
3 : r'hard.txt'}
if select:
while(x > 3 or x < 1):
print("Select a difficulty:")
print("1: Easy")
print("2: Medium")
print("3: Hard")
x = int(input())
else:
x = rand.randint(1, 3)
return diffdict[x]
#system('clear')
board = BoardEnvironment()
league = LeagueEnvironment(board)
player_names = []
board_agents = []
league_agents = []
player_names.append('learning strategy and tactics')
board_agents.append(Agent(board, select_difficulty(), 'max'))
league_agents.append(Agent(league, 'league.txt', 'max'))
player_names.append('learning tactics only')
board_agents.append(Agent(board, select_difficulty(), 'max'))
league_agents.append(Agent(league, 'league.txt', 'random'))
player_names.append('learning strategy only')
board_agents.append(Agent(board, select_difficulty(), 'random'))
league_agents.append(Agent(league, 'league.txt', 'max'))
player_names.append('no learning')
board_agents.append(Agent(board, select_difficulty(), 'random'))
league_agents.append(Agent(league, 'league.txt', 'random'))
league.set_players(player_names, league_agents, board_agents)
league.play_pair()
#board.set_players(AI)
#board.play_game()
|
7dc8aa7ef76707d4b9dbb97af7cad34923ec4506 | buribae/aoc-2020 | /01.py | 2,700 | 4.0625 | 4 | from common.util import *
# --- Day 1: Report Repair ---
# After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island.
# Surely, Christmas will go on without you.
# The tropical island has its own currency and is entirely cash-only.
# The gold coins used there have a little picture of a starfish; the locals just call them stars.
# None of the currency exchanges seem to have heard of them, but somehow,
# you'll need to find fifty of these coins by the time you arrive so you can pay the deposit on your room.
# To save your vacation, you need to get all fifty stars by December 25th.
# Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar;
# the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
# Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input);
# apparently, something isn't quite adding up.
# Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together.
#
# For example, suppose your expense report contained the following:
# 1721
# 979
# 366
# 299
# 675
# 1456
#
# In this list, the two entries that sum to 2020 are 1721 and 299.
# Multiplying them together produces 1721 * 299 = 514579, so the correct answer is 514579.
#
# Of course, your expense report is much larger.
# Find the two entries that sum to 2020; what do you get if you multiply them together?
def part1(data):
nums = [int(i) for i in data]
for n in nums:
if 2020 - n in nums:
return n * (2020 - n)
print(solution("day01", part1, split_parser))
# ----------- TEST
test1 = """
1721
979
366
299
675
1456
"""
def test_answer():
assert part1(test1.split()) == 514579
# --- Part Two ---
# The Elves in accounting are thankful for your help;
# one of them even offers you a starfish coin they had left over from a past vacation.
# They offer you a second one if you can find three numbers in your expense report that meet the same criteria.
#
# Using the above example again, the three entries that sum to 2020 are 979, 366, and 675.
# Multiplying them together produces the answer, 241861950.
#
# In your expense report, what is the product of the three entries that sum to 2020?
def part2(data):
expenses = [int(n) for n in data]
for idx, expense in enumerate(expenses):
others = expenses[:idx] + expenses[idx + 1 :]
target = 2020 - expense
for o in others:
if target - o in others:
return expense * o * (target - o)
print(solution("day01", part2, split_parser))
|
3aa0ab289bfe53bcbc2e72f84a2de0a4d665f3b7 | dubesar/WebScraping | /code/commands.py | 1,285 | 3.8125 | 4 | soup.title
(gives the title tag of the page)
soup.title.string
(gives the string in the title tag)
soup.a
(gives the output - <a id="top"></a>)
So to get all the links on the page we have:
soup.find_all("a")
(This gives all the links on the page)
soup.find_all('table')
(This gives all the tables on the page)
Inorder to find the table you want we can use:
soup.find_all('table',class_='wikitable sortable plainrowheaders') - This is for example we have to type the class of table we want
#Generate lists
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
for row in right_table.findAll("tr"):
cells = row.findAll('td')
states=row.findAll('th') #To store second column data
if len(cells)==6: #Only extract table body not heading
A.append(cells[0].find(text=True))
B.append(states[0].find(text=True))
C.append(cells[1].find(text=True))
D.append(cells[2].find(text=True))
E.append(cells[3].find(text=True))
F.append(cells[4].find(text=True))
G.append(cells[5].find(text=True))
#import pandas to convert list to data frame
import pandas as pd
df=pd.DataFrame(A,columns=['Number'])
df['State/UT']=B
df['Admin_Capital']=C
df['Legislative_Capital']=D
df['Judiciary_Capital']=E
df['Year_Capital']=F
df['Former_Capital']=G
df
|
f8d13f48a1dc6474cf4a88d1bba6dec34b59f045 | kewaltakhe/csa1 | /base_conversion_related/setclear.py | 1,550 | 3.75 | 4 | from binary import dtb,btd
def mask_generator(n):
return 1<<n
def main():
num=int(input("Enter a number in decimal <= 65535 :"))
if num>65535:
print("ERROR! Decimal number should be <= 65535.\n\n")
return 0
print("The number in 16 bit binary form is:{0}\n".format(dtb(num)))
print("\t\t\t===SET and CLEAR===\nSelect a bit for set&clear operation. Numbering is done from 0-15 from right to left---")
n_bit=int(input())
if n_bit>15:
print("ERROR! position of bit should be <= 15.\n\n")
return 0
#generate the musk register with the given bit:
mask=mask_generator(n_bit)
print("\n-->enter 1 for set. \n-->enter 2 for clear.\n-->enter 3 for Exit.")
op=int(input())
if op==1:
operation="set"
result=num|mask
print("\nAfter {0}, the binary form is:{1}\n".format(operation,dtb(result)))
return 1 #returning 1 as success
elif op==2:
operation="clear"
result=num&(~mask)
print("\nAfter {0}, the binary form is:{1}\n".format(operation,dtb(result)))
return 1 #returning 1 as success
elif op==3:
return 3 #returning 3 to exit the loop
else:
print("\nInvalid operation!")
return 0 #returning 0 for fail and continue the loop
print("\nAfter {0}, the binary form is:{1}".format(operation,dtb(result)))
if __name__=="__main__":
while True:
status=main()
if status==3:
break
elif status==0:
continue
|
60aee1f64b4f376e30f153d3e16da773aa8b0e1e | eqtstv/Advent-of-Code-2020 | /day_02/day2_1/day2_1.py | 418 | 3.53125 | 4 | def get_data(filename):
with open(filename, "r") as f:
data = [line.strip() for line in f]
return data
data = get_data("input.txt")
parsed_data = [
[line.split()[0].split("-"), line.split()[1][0], line.split()[2]] for line in data
]
valid = 0
for i in parsed_data:
letter = i[1]
count = i[2].count(letter)
if int(i[0][0]) <= count <= int(i[0][1]):
valid += 1
print(valid) |
6c310fa4948a9ce49ea7d0236b33ed6e0abc91c8 | zabsec/Python101-for-Hackers | /comprehensions_demo.py | 1,605 | 4.65625 | 5 | list1 = ['a', 'b', 'c'] # This is a normal list. From this we can create a list comprehension.
print(list1)
list2 = [x for x in list1] # It iterates over each element in list1 and adds it into list 2. This is called a
# comprehension.
print(list2)
list3 = [x for x in list1 if x == 'a'] # We can add conditionals in list comprehensions
print(list3)
list4 = [x for x in range(5)] # This takes the range from 0-4 then iterates it on this list.
print(list4)
list5 = [hex(x) for x in range(5)] # This turns each element in the range(5) to hex when it iterates it into list5
print(list5)
list6 = [hex(x) if x > 0 else "X" for x in range(5)] # Another way to give complicated conditionals in comprehensions.
print(list6)
list7 = [x * x for x in range(5)] # For each element in each range(5), we can perform arithmetic operations before
# they are iterated into our list
print(list7)
list8 = [x for x in range(5) if x == 0 or x == 1] # We can use booleans in list comprehensions
print(list8)
list9 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # This is a nested list
list10 = [y for x in list9 for y in x] # This is saying "take the lists of elements y from the nested list x and
# create a new list of each y that are in x"
print(list10)
set1 = {x + x for x in range(5)} # This is a set comprehension
print(set1)
list11 = [c for c in "string"] # We can make list comprehensions from strings
print(list11)
print("".join(list11)) # This turns the list back into one string since there are no spaces in there.
print("-".join(list11)) # This turns into a string with a hyphen between each letter.
|
0df6a597f689b5bfa7d544a3af9853a3bdbef420 | Lorranysousc/ExerciciosDeRepeticao | /ex14.py | 492 | 4 | 4 | '''Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares e a quantidade de números impares.'''
num_par = num_impar = 0 #Ambas variáveis iniciam o programa valendo 0.
for cont in range (1, 11):
num = int(input(f'Digite o {cont}º número: '))
if num % 2 == 0:
num_par += 1 #Abreviação de "num_par = num_par + 1"
else:
num_impar += 1
print(f'Você digitou {num_par} números pares e {num_impar} números ímpares.') |
c5e15c515e4ab2dbbf20f91e38b1546c5c3bcef5 | Lixinran1213/python | /Chapter 7/7.3.1.py | 599 | 3.5 | 4 | unconfirmed_user= ['alice','briand','canndace']
confirmed_user = ['yemao','dali']
#
while unconfirmed_user:
#pop()以每次一个的方式从列表unconfirmed_user的末尾删除用户
#将被删除的用户存在user里
user = unconfirmed_user.pop()
print("verifying user: "+user.title())
#将被删除的用户加到列表confirmed_user里
confirmed_user.append(user)
#循环到unconfirmed_user里没有元素,程序自动停止
#显示所有已验证的用户:
print("\nThe following users have benn confirmed:")
for confirmed_users in confirmed_user:
print(confirmed_users.title())
|
da56cfc6f82b42c9b16ac712aaf93e97a08d19d0 | vyasvalluri/Python_Practice | /DiceSimulator.py | 1,063 | 3.6875 | 4 | import random
from os import system
ans = "y"
while ans == 'y':
x = random.randint(1,6)
system("clear")
if(x == 1):
print("---------")
print("| |")
print("| O |")
print("| |")
print("---------")
if(x == 2):
print("---------")
print("| |")
print("|O O|")
print("| |")
print("---------")
if(x == 3):
print("---------")
print("| O |")
print("| O |")
print("| O |")
print("---------")
if(x == 4):
print("---------")
print("|O O|")
print("| |")
print("|O O|")
print("---------")
if(x == 5):
print("---------")
print("|O O|")
print("| 0 |")
print("|O O|")
print("---------")
if(x == 6):
print("---------")
print("|O O|")
print("|O O|")
print("|O O|")
print("---------")
ans = input("Dice again : y ? ")
|
20163ed56874b72221e274827ea240c3334c4cf7 | amelialin/tuple-mudder | /Problems/palindrome_in_string.py | 1,590 | 4.25 | 4 | # Write a function to find the longest palindrome in a string.
from palindrome import palindrome
def palindrome_in_string(string):
""" Trying out using doctest.
>>> palindrome_in_string("aba")
'aba'
"""
for i in range(len(string)):
for j in range(i + 1):
substring = string[j:len(string) - (i - j)]
if palindrome(substring) == True:
return substring
if __name__ == '__main__':
from sys import argv
script, string = argv
print palindrome_in_string(string)
# ==PSEUDOCODE==
# set counter = 0
# start with full string, evaluate if palindrome if not, check the 2 substrings that are length-1 long, then 3 substrings that are length-2 long, etc. example:
# for i = 0, check string from string[0] to string[length]
# for i = 1
# check string from string[0] to string[length - 1]
# check string from string[1] to string[length]
# for i = 2
# check string from string[0] to string[length-2]
# check string from string[1] to string[length-1]
# check string from string[2] to string[length]
# if yes at any point, then store that in a variable and return it
# if always no, spit out the last 1-character letter in the string
# def palindrome_in_string(string):
# length_of_string = len(string)
# print "length of string:", length_of_string
# for i in range(0, length_of_string):
# print "i", i
# for j in range(0, i + 1): # CHECK LATER
# print "j", j
# substring = string[j:length_of_string - (i - j)]
# print "Currently checking:", substring
# if palindrome(substring) == True:
# print "Palindrome!", substring
# return substring
|
169aacc77484e1c7baa9c81190a0f7081ee87c0c | chammansahu/100days-of-python | /day 1 fundamentals/2variables.py | 350 | 3.75 | 4 | # variable are declared directly without any keyword
#global variable scope
name="chamamn"
age=29
def printAges():
#local scope
#using global keyword
localName="chamamn"
LocalAge=29
#casting of variable
x=str("some value")
y=int(100)
#get the type
print(type(x))
print(type(y))
printAges()
|
7979918df76db87aad086767513ceeb6f291d552 | AreebHamad/a-level_compsci | /LinkedList_OOP_01.py | 562 | 3.84375 | 4 | class Node():
def __init__(self, data, pointer):
self.data = data
self.pointer = pointer
lengthOfList = int(input("Length of list: "))
linkedList = [Node("", i+1) for i in range(0, lengthOfList)]
freePointer = 0
linkedList[lengthOfList].pointer = None
def addLinkedList(linkedList, freePointer):
if freePointer == None:
print("List is empty")
else:
linkedList[freePointer].data = input("Input data into linked list: ")
freePointer = linkedList[freePointer].pointer
return linkedList, freePointer
|
b329740a001807d25868e71032c07fca5fb7345b | hackfengJam/EffectivePython | /di2zhang/test22.py | 526 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__Author__ = "HackFun"
__Date__ = '2017/9/28 11:54'
# # 方法一
# NAME, AGE, SEX, EMAIL = xrange(4)
#
#
# student = ('hackfun', 16, 'male', '1@1.com')
#
# print student[NAME]
# # 方法二
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'sex', 'email']) # 类的工厂
s = Student('hackfun', 16, 'male', '1@1.com')
print s.name
s = Student(name='hackfun1', age=17, sex='female', email='2@2.com')
print s.name |
cfb644388d2e13ef5a5014c8ee44bfb560e034d3 | Kiran-RD/leetcode_solutions | /538_Convert_BST_to_Greater_Tree.py | 1,804 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Using reverse inorder traversal
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
self.curr_sum = 0
def dfs(node):
if not node:
return
dfs(node.right)
self.curr_sum += node.val
node.val = self.curr_sum
dfs(node.left)
return node
return dfs(root)
#----------------------------------------------------------------------------------------
# kind of Brute Force
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
elements = self.dfs(root)
self.elements_sorted = sorted(elements)
return self.replace(root)
def dfs(self, node):
if not node:
return []
lst = []
lst += self.dfs(node.left)
lst.append(node.val)
lst += self.dfs(node.right)
return lst
def replace(self, node):
if not node:
return
self.replace(node.left)
node.val = self.get_sum(node.val)
self.replace(node.right)
return node
def get_sum(self, val):
n = r = len(self.elements_sorted) - 1
l = 0
i = 0
while l <= r:
mid = (l + r) // 2
if self.elements_sorted[mid] == val:
while mid > 0 and self.elements_sorted[mid - 1] == val:
mid -= 1
i = mid
break
elif val > self.elements_sorted[mid]:
l = mid + 1
else:
r = mid - 1
return sum(self.elements_sorted[i:]) |
d2a8f4e4e1cd8afcc0353abfc6fe6aff9bb4160e | esharma3/Python-Challenge | /PyBank/main-PyBank.py | 1,915 | 3.53125 | 4 |
import os
import csv
revenue, change_in_revenue, date = [], [], []
total_revenue = 0
count = 0
in_filepath = os.path.join('Input & Output', 'budget_data.csv')
out_filepath = os.path.join('Input & Output', 'budget_data_analysis.csv')
with open(in_filepath, newline = '') as in_file:
reader = csv.reader(in_file, delimiter=',')
header = next(reader)
# Calculating total number of months by counting the number of rows in the csv file
# Adding Profit/Loss to revenue list & dates to date list
for row in reader:
count += 1
revenue.append(row[1])
date.append(row[0])
# Calculating the total amount of Profit/Losses
for i in range(0, count):
total_revenue += int(revenue[i])
# Calculating increase/decrease in revenue and adding it to change_in_revenue list # Calculating the average of changes
for i in range(0, count-1):
change_in_revenue.append(int(revenue[i+1]) - int(revenue[i]))
avg_of_changes = round(sum(change_in_revenue)/(count - 1), 2)
# Calculating the greatest increase and greatest decrease (min_increase) in profilt/loss changes
max_increase = change_in_revenue[0]
min_increase = change_in_revenue[0]
for j in range(1, count-1):
if max_increase < int(change_in_revenue[j]):
max_increase = int(change_in_revenue[j])
related_date1 = date[j+1]
if min_increase > int(change_in_revenue[j]):
min_increase = int(change_in_revenue[j])
related_date2 = date[j+1]
summary = (
"Financial Analysis\n"
"---------------------\n"
f"Total Months: {count}\n"
f"Total: ${total_revenue}\n"
f"Average Change: ${avg_of_changes}\n"
f"Greatest Increase in Profits: {related_date1} (${max_increase})\n"
f"Greatest Decrease in Profits: {related_date2} (${min_increase})"
)
# Printing output to the terminal
print(summary)
# Writing output to the file
with open(out_filepath, 'w+', newline = '') as out_text:
out_text.write(summary)
|
a93a63a0610b3be5d371a6dca3913196c26e8d31 | lucaspessoafranca/python-exer | /Mundo_1/31_aumentos_Multiplos.py | 523 | 3.875 | 4 | # Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.
salario = float(input('Digite o seu salário:'))
if salario > 1250:
aumento = salario + (salario*0.10)
print(f'Seu novo salário com aumento de 10% SERÁ R${aumento}')
elif salario <= 1250:
aumento = salario + (salario*0.15)
print(f'Seu novo salário com aumento de 15% SERÁ R${aumento}')
|
debe63d349344cf54cc6af5c8172072d16b5e653 | jappanrana/practice | /python/BrainF*ck/using1memory.py | 760 | 4.15625 | 4 | # ord(value) is inbuilt function for getting ASCII value of char
x = input("Enter your string to be printed:")
x = list(x)
currentvalue = 0
# empty list for storing ascii value
asciilst = []
# getting ascii value of every char
for item in x:
asciilst.append(ord(item))
# declaring empty list for storing BF code chars
final = ""
# code to get BF code that changes 1 memory location value to required value and prints it
for item in asciilst:
while currentvalue != item:
if currentvalue > item:
final += "-"
currentvalue -= 1
else:
final += "+"
currentvalue += 1
final += "."
# write final string on file to copy
f_obj = open("answer.txt","w")
f_obj.write(final)
f_obj.close()
# print str
print(final)
input("bye!") |
5658c65b585356e5eade12097d9df667d54ea0c0 | proTao/leetcode | /1. backtracking/046.py | 616 | 3.671875 | 4 | class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums) == 0:
return []
visited = {i:False for i in nums}
def deeper(path):
if len(path) == len(nums):
res.append(path)
for i in nums:
if not visited[i]:
visited[i] = True
deeper(path + [i])
visited[i] = False
deeper([])
return res
s = Solution()
print(s.permute([1,2])) |
d582dca5551134f9fad17d83c350e95e272b3a88 | trgomes/estrutura-de-dados | /aula7/merge_sort.py | 1,777 | 3.59375 | 4 | import unittest
def _merge(seq_esquerda, seq_direita):
n_esquerda = len(seq_esquerda)
n_direita = len(seq_direita)
lista_mesclada = [0] * (n_direita + n_esquerda)
i_esquerda = i_direita = 0
while i_direita + i_esquerda < len(lista_mesclada):
if i_esquerda < n_esquerda and (i_direita == n_direita or seq_esquerda[i_esquerda] < seq_direita[i_direita]):
lista_mesclada[i_esquerda + i_direita] = seq_esquerda[i_esquerda]
i_esquerda += 1
else:
lista_mesclada[i_esquerda + i_direita] = seq_direita[i_direita]
i_direita += 1
return lista_mesclada
def merge_sort(seq):
n = len(seq)
if n <= 1:
return seq
metade = n // 2
esquerda = merge_sort(seq[:metade])
direita = merge_sort(seq[metade:])
return _merge(esquerda, direita)
class MergeTestes(unittest.TestCase):
def test_listas_vazias(self):
self.assertListEqual([], _merge([], []))
def test_lista_uma_lista_unitaria(self):
self.assertListEqual([1], _merge([1], []))
def test_listas_unitarias(self):
self.assertListEqual([1, 2], _merge([1], [2]))
def test_listas_intercaladas(self):
self.assertListEqual([1, 2, 3, 4, 5, 6], _merge([1, 3, 5], [2, 4, 6]))
class OrdenacaoTestes(unittest.TestCase):
def teste_lista_vazia(self):
self.assertListEqual([], merge_sort([]))
def teste_lista_unitaria(self):
self.assertListEqual([1], merge_sort([1]))
def teste_lista_binaria(self):
self.assertListEqual([1, 2], merge_sort([2, 1]))
def teste_lista_desordenada(self):
self.assertListEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], merge_sort([9, 7, 1, 8, 5, 3, 6, 4, 2, 0]))
if __name__ == '__main__':
unittest.main()
|
8a7e4ab827e50758e0a4129c2d5c69f55cba4714 | Michelmat359/hackathon_python | /kata2/if2.py | 625 | 3.921875 | 4 | '''
Escribir un programa para una empresa que tiene salas de juegos para todas las
edades y quieren calcular de forma automatica el precio que debe cobrar a sus clientes
por entrar. El programa debe preguntar al usuario la edad del cliente y mostrar el precio de la entrada.´
Si el cliente es menor de 4 años puede entrar gratis, si tiene entre 4 y 18 años debe pagar 5€ y si
es mayor de 18 años, 10€
'''
edad = input("Introduce tu edad: ")
edad = int(edad)
if edad <4:
print("El precio de la entrada es 0.")
elif edad >= 4 and edad <= 18:
print("El precio es 5€")
else:
print("El precio es 10€")
|
7908e615a7cb72ec98c3163aa81d64a21a7c9862 | mic0ud/Leetcode-py3 | /src/841.keys-and-rooms.py | 1,907 | 3.640625 | 4 | #
# @lc app=leetcode id=841 lang=python3
#
# [841] Keys and Rooms
#
# https://leetcode.com/problems/keys-and-rooms/description/
#
# algorithms
# Medium (61.81%)
# Likes: 677
# Dislikes: 61
# Total Accepted: 56.4K
# Total Submissions: 90.1K
# Testcase Example: '[[1],[2],[3],[]]'
#
# There are N rooms and you start in room 0. Each room has a distinct number
# in 0, 1, 2, ..., N-1, and each room may have some keys to access the next
# room.
#
# Formally, each room i has a list of keys rooms[i], and each key rooms[i][j]
# is an integer in [0, 1, ..., N-1] where N = rooms.length. A key rooms[i][j]
# = v opens the room with number v.
#
# Initially, all the rooms start locked (except for room 0).
#
# You can walk back and forth between rooms freely.
#
# Return true if and only if you can enter every room.
# Example 1:
#
#
# Input: [[1],[2],[3],[]]
# Output: true
# Explanation:
# We start in room 0, and pick up key 1.
# We then go to room 1, and pick up key 2.
# We then go to room 2, and pick up key 3.
# We then go to room 3. Since we were able to go to every room, we return
# true.
#
#
# Example 2:
#
#
# Input: [[1,3],[3,0,1],[2],[0]]
# Output: false
# Explanation: We can't enter the room with number 2.
#
#
# Note:
#
#
# 1 <= rooms.length <= 1000
# 0 <= rooms[i].length <= 1000
# The number of keys in all rooms combined is at most 3000.
# @lc code=start
class Solution:
def canVisitAllRooms(self, rooms: [[int]]) -> bool:
m = len(rooms)
entered = [False for _ in range(m)]
def dfs(i):
entered[i] = True
for k in rooms[i]:
if not entered[k]:
dfs(k)
dfs(0)
for e in entered:
if not e:
return False
return True
# @lc code=end
if __name__ == '__main__':
s = Solution()
s.canVisitAllRooms([[1],[2],[3],[]])
|
6cb4ecf952e7f331c1de84db64ada117e9a4e213 | zuzanadostalova/Python-for-biologists | /06_Conditional_tests.py | 2,601 | 3.59375 | 4 | # Conditional tests
# print(df["Drosophila melanogaster"][4]) Drosoph. ananassae
# print(df["Drosophila melanogaster"][4][1]) second letter "r" in Drosoph. ananassae
data = open("data.csv")
for line in data:
column = line.rstrip("\n").split(",")
species = column[0]
sequence = column[1]
gene = column[2]
expression = column[3]
# print(species)
# I. Several species
if species == "Drosophila melanogaster" or species == "Drosophila simulans":
print(gene)
# Drosophila melanogaster
# kdy647
# Drosophila melanogaster
# jdg766
# Drosophila simulans
# kdy533
# Drosophila yakuba
# Drosophila ananassae
# Drosophila ananassae
# II. length range
# Sol.I:
length = len(sequence)
if length in range(91,109):
print(gene)
# kdy647 - disappears when 109
# kdy533 - has 90 b - it is better to set the range from 91 to 110
# teg436 -
# Sol.II:
if len(sequence) > 90 and len(sequence) < 110:
print(gene)
# kdy647 - disappears when 109
# teg436
# III. AT content
a_count = sequence.count("a")
t_count = sequence.count("t")
at_count = (a_count+t_count)/length
print(at_count)
# 0.7247706422018348
# 0.5641025641025641
# 0.5333333333333333
# 0.2857142857142857
# 0.5299145299145299
# 0.45918367346938777
if ((a_count+t_count)/length) < 0.5 and int(expression) > 200:
print(gene)
# teg436
# IV. high low medium
if at_count > 0.65:
print(gene + " has high AT content")
if at_count > 0.45 and at_count < 0.65:
print(gene + " has medium AT content")
if at_count < 0.45:
print(gene + " has low AT content")
# V. complex condition
first_letter = gene[0]
print(first_letter)
# k
# j
# k
# h
# h
# t
# Sol.I:
# Wrong:
if first_letter == "k" or "h":
print(gene)
# prints everything
# kdy647
# jdg766
# kdy533
# hdt739
# hdu045
# teg436
if first_letter == "k" or first_letter == "h":
print(gene)
# kdy647
# kdy533
# hdt739
# hdu045
# works well but if "AND" condition with melanogaster would be added to the end
# it would not be applied
# Sol.II:
if first_letter == "k":
print(gene)
# kdy647
# kdy533
# Except from Drosoph. melanogaster:
if first_letter == "k" and species != "Drosophila melanogaster":
print(gene)
# kdy533
if first_letter == "h":
print(gene)
# hdt739
# hdu045 - do not use "OR", "OR" is True if at least one is True
|
3f4d212cb84b70adde0275725133b4106cddcdc9 | hanv698/PythonDjangoLuminar | /designs/sample.py | 115 | 3.625 | 4 | def sub(num1,num2):
#if num1<num2:
#(num1,num2)=(num2,num1)
return abs(num1-num2)
print(sub(10,20)) |
7dc058ecdafb6638b319d64cec6f98906cac81c9 | annekadeleon/Codeacademy-Learn-Python-2 | /A_Day_at_the_Supermarket.py | 708 | 3.9375 | 4 | #list called shopping_list
shopping_list = ["banana", "orange", "apple"]
#dictionary called stock
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
#dictionary called prices
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
#function called compute_bill takes one argument, a list called food
def compute_bill(food):
#initialise variable total to zero
total = 0
#for every item in food
for item in food:
#if item is available in stock list
if stock[item] > 0:
#add priceo of item from prices list to total
total += prices[item]
#remove one from item's stock number
stock[item] -= 1
#returns total
return total
#returns 5.5
print compute_bill(shopping_list)
|
84400b981fded289d90bc98cd2bc360c38638286 | adharris/euler | /problems/problems_000_099/problems_030_039/problem_037.py | 1,513 | 3.703125 | 4 |
import click
from tools.primes import unbounded_sieve_of_eratosthenes
from tools.numbers import digit_count
@click.command('37')
@click.option('--verbose', '-v', count=True)
def problem_037(verbose):
"""Truncatable primes.
The number 3797 has an interesting property. Being prime itself, it is
possible to continuously remove digits from left to right, and remain
prime at each stage: 3797, 797, 97, and 7. Similarly we can work from
right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left
to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
"""
found_primes = set()
truncatable_primes = set()
def is_truncatable(prime):
if prime < 10:
return False
for truncaction in truncactions(prime):
if truncaction not in found_primes:
return False
return True
for prime in unbounded_sieve_of_eratosthenes(100000):
found_primes.add(prime)
if is_truncatable(prime):
truncatable_primes.add(prime)
if len(truncatable_primes) >= 11:
break
click.echo(",".join(str(p) for p in sorted(truncatable_primes)))
click.echo(sum(truncatable_primes))
def truncactions(number):
digits = digit_count(number)
for i in range(digits - 1):
yield number % (10 ** (digits - i - 1))
yield number // 10 ** (i + 1) |
6d5382d36d2e8184524f2c3eb771df29e8ebced5 | joshloh/WikiScrape | /src/get_links3.py | 5,593 | 3.546875 | 4 | # Code written by:
# Joshua Loh, Denton Phosavanh
# 2016
# Webcraping
import urllib.request, urllib.error, urllib.parse # Load web page
from bs4 import BeautifulSoup # Easier scraping
from bs4 import SoupStrainer # More efficient loading
# Other
import argparse
import textwrap
import sys
from unidecode import unidecode # Strip diactritics from characters
from queue import *
# Takes in a set, and returns a sorted list
def streamline(a):
a = list(a)
a.sort()
return a
# Link should not start with any of these
def is_actually_a_wiki_link(link):
bad_starts = ["Wikipedia:", "Help:", "File:", "Special:"]
# Links to another Wikipedia page
if link is not None and link.startswith("/wiki/"):
content = link[6:]
for item in bad_starts:
if content.startswith(item):
return False
return True
return False
# From a string in the form of "Wikipedia_Article_Name",
# create the BeautifulSoup object of it, and return
# a list of all the links that it contains
def get_links(s):
# Set up the scraper
wiki = "https://en.wikipedia.org/wiki/" + s
try:
page = urllib.request.urlopen(wiki)
except urllib.error.HTTPError:
print("An error occurred in opening this page")
print("This is most likely due to either of two reasons:")
print("a) Your internet connection isn't internetting")
print("b) The Wikipedia page %s does not exist" % wiki)
exit(3)
except Exception:
import traceback
exit(4)
else:
# only load the parts of the page contained in a <p>
soup = BeautifulSoup(page, "html.parser", parse_only=SoupStrainer("p"))
# Stores the name of all the outgoing Wiki pages
link_array = set() # Use a set to avoid duplicate entries
# Extract every <a> that is in a <p>, store them in link_array
para_links = soup.find_all("a")
for para_link in para_links:
link = para_link.get("href")
# Only pull (relevant parts of) relevant pages
if is_actually_a_wiki_link(link):
# Strip everything after the last `#` symbol
# in the link (Wikipedia fragment identifier)
last_octothorpe = link.rfind('#')
if last_octothorpe == -1: # No octothorpe
link_array.add(link[6:])
else:
link_array.add(link[6:last_octothorpe])
# Return the result.
# Call this if you want it sorted,
# otherwise just return link_array
return streamline(link_array)
# Recursive depth-first search
def dfs(site, depth, DEPTH_LIMIT, target, verbosity):
# Base cases, have reached depth limit, or found target
if depth >= DEPTH_LIMIT:
return
elif site == target:
print("Got to " + site + " at depth " + str(depth))
exit(12)
global visited_links
visited_links.add(site)
indent = "\t"*depth
print(indent + "Visiting: " + site)
# Output all the links that can be seen from this page
indent += "\t"
link_array = get_links(site)
for l in link_array:
print(indent + l)
# recursion (Another sneaky base case)
for l in link_array:
if not l in visited_links:
dfs(l, depth+1, DEPTH_LIMIT, target, verbosity)
# Iterative breadth-first search
def bfs(site, target, verbosity):
global visited_links
fringe = Queue()
fringe.put(site)
print(site)
# Keep searching until have run out of potential expansions
while (not fringe.empty()):
current_link = fringe.get()
# print(current_link)
link_array = get_links(current_link)
for l in link_array:
print("Child: " + l)
# Check for exit state
if l == "Aboriginal_peoples_in_Canada" or l == target:
print("Found")
exit(13)
# If a node has not already been visited, queue for expansion
if not l in visited_links:
fringe.put(l)
visited_links.add(l)
def argparse_setup():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
# Describe the program and arguments briefly
description=textwrap.dedent("""\
Finds a path between pages [start] and [target] on Wikipedia
Set options on how the program will run
Default values:
---------------
a : bfs
d : 2
s : Sun_Dance
t : Adolf_Hitler
v : 1
---------------
"""),
# Gloss over exit details
epilog=textwrap.dedent("""\
Exit status:
------------
0 : Everything worked as planned
2 : Error parsing arguments
3 : urllib.error.HTTPError
4 : General exception from urllib.request
""")
)
# Which search to use
parser.add_argument(
"-a", "--algorithm",
default = "bfs",
choices = ["dfs", "bfs"],
help = "which search to use"
)
# dfs depth
parser.add_argument(
"-d", "--depth",
default = 2,
type = int,
help = "maximum search depth of dfs. use in conjunction with dfs)"
)
# Starting page
parser.add_argument(
"-s", "--start",
default = "Sun_Dance",
help = "which page to start the search from (formatted to Wikipedia standards)"
)
# Target page
parser.add_argument(
"-t", "--target",
default = "Adolf_Hitler",
help = "the page for which to search"
)
# Level of output
parser.add_argument(
"-v", "--verbosity",
default = 1,
type = int,
help = "the level of output to use (higher => more output)"
)
return parser
#+-------------------------------
#| main
#+-------------------------------
# Parse the program's arguments
parser = argparse_setup()
args = parser.parse_args()
if args.verbosity >= 1:
print(args)
args.start = unidecode(args.start)
# Keep track of which links have been visited
visited_links = set()
visited_links.add(args.start)
# Run either dfs or bfs, depending on arguments
if args.algorithm == "dfs":
dfs(args.start, 0, args.depth, args.target, args.verbosity)
else:
bfs(args.start, args.target, args.verbosity) |
1c50a574d0b057c5e6692afa6f23c72ad9a53ba8 | Maze-Solving-AI-Team/DevelopmentFiles | /intersection.py | 29,542 | 4.34375 | 4 | '''
=INTERSECTIONS=
intersections solves a maze by marking intersections and paths traveled
blue=intersection
red=path the AI came into the intersection from
green=path the AI has used already(hit dead end and came back to intersection)
- \/ this is repeated until the end \/ -
AI moves until it finds an intersection
places blue on intersection and red on path traveled
moves into white tile
if intersection is blue(traveled), then AI checks for white
if no white is present(all paths traveled), then AI travels back down red path until it hits previous intersection
- \/ special cases \/ -
+if there are consecutive intersections(no space in between)
-AI cannot put red down(or it overwrites the blue of the other intersection)
-if all paths are traveled and no red is present, AI checks for blue(instead of red)
+(IN PROGRESS)if there is 1 space between intersections and they connect to each other on another path(loop)
-when AI goes around loop and goes onto first intersection,
-it sees that there are 2 red blocks(1 correct from entering, 1 wrong from 2nd intersection)
-then uses a log of coordinates of red to find oldest red around it and travel down the path
'''
# Import modules
import sys, pygame, time, math
from time import sleep
from pygame.locals import *
from PIL import Image
import timing
from main import sleep
from main import maze
maze=('maze10.png')
# Initialize
img = Image.open(maze)
change = 3
width = img.width * change
height = img.height * change
screen = pygame.display.set_mode((width,height))
background = pygame.image.load(maze).convert()
newscreen = pygame.transform.scale(background, (width, height))
sleepTime = sleep
#number of turns
upCount = 0
leftCount = 0
rightCount = 0
#Colors
color = (0, 188, 0)
white = (255, 255, 255)
black = (0, 0, 0, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
green = (0, 188, 0)
# Recognizing black/white
#-print(width, height)
size = [img.size]
#-print(size[0])
colors = img.getcolors()
#-print(colors)
pix = img.load()
list = []
# Locate the starting coordinate
for x in range(0,180):
if pix[x,179] == (255, 255, 255, 255):
list.append(x)
xvalueOfStart = list[0] * change
#-print(xvalueOfStart)
blockSize = len(list) * change
yvalueOfStart = height - blockSize
list = []
# Locate the ending coordinate
for x in range(0,180):
if pix[x,0] == (255, 255, 255, 255):
list.append(x)
xvalueOfEnd = list[0] * change
#-print(xvalueOfEnd)
pygame.draw.rect(newscreen, color, pygame.Rect(xvalueOfStart, yvalueOfStart, blockSize, blockSize))
screen.blit(newscreen, (0,0))
pygame.display.update()
time.sleep(sleepTime)
# Function to move forward
def moveUp(x, y, blocksize, newcolor):
pygame.draw.rect(newscreen, newcolor, pygame.Rect(x, y, blockSize, blockSize))
pygame.draw.rect(newscreen, color, pygame.Rect(x+1, y - blocksize+1, blockSize-2, blockSize-2))
screen.blit(newscreen, (0,0))
pygame.display.update()
global currentY
global currentX
currentY = y - blocksize
currentX = x
# Function to move down
def moveDown(x, y, blocksize, newcolor):
pygame.draw.rect(newscreen, newcolor, pygame.Rect(x, y, blockSize, blockSize))
pygame.draw.rect(newscreen, color, pygame.Rect(x+1, y + blocksize+1, blockSize-2, blockSize-2))
screen.blit(newscreen, (0,0))
pygame.display.update()
global currentY
global currentX
currentY = y + blocksize
currentX = x
# Function to move left
def moveLeft(x, y, blocksize, newcolor):
pygame.draw.rect(newscreen, newcolor, pygame.Rect(x, y, blockSize, blockSize))
pygame.draw.rect(newscreen, color, pygame.Rect(x - blocksize+1, y+1, blockSize-2, blockSize-2))
screen.blit(newscreen, (0,0))
pygame.display.update()
global currentX
global currentY
currentX = x - blocksize
currentY = y
# Function to move right
def moveRight(x, y, blocksize, newcolor):
pygame.draw.rect(newscreen, newcolor, pygame.Rect(x, y, blockSize, blockSize))
pygame.draw.rect(newscreen, color, pygame.Rect(x + blocksize+1, y+1, blockSize-2, blockSize-2))
screen.blit(newscreen, (0,0))
pygame.display.update()
global currentX
global currentY
currentX = x + blocksize
currentY = y
#Initialization of currentX and currentY
def varsInit(x, y):
global currentX
global currentY
global direction
currentX = x
currentY = y
direction = 1
#Algorithm to determine direction to move if facing up
def up(replace):
global direction
if newscreen.get_at((currentX, currentY - blockSize)) == white:#up
moveUp(currentX, currentY, blockSize, replace)
#-print("up-Move up called")
time.sleep(sleepTime)
direction = 1
elif newscreen.get_at((currentX + blockSize, currentY)) == white:#right
moveRight(currentX, currentY, blockSize, replace)
#-print("up-Move right called")
time.sleep(sleepTime)
direction = 2
elif newscreen.get_at((currentX - blockSize, currentY)) == white:#left
moveLeft(currentX, currentY, blockSize, replace)
#-print("up-Move left called")
time.sleep(sleepTime)
direction = 3
#check for blue paths
elif newscreen.get_at((currentX,currentY-blockSize))==blue:
moveUp(currentX, currentY, blockSize, replace)
#-print("up-Move up blue called")
time.sleep(sleepTime)
direction = 1
elif newscreen.get_at((currentX+blockSize,currentY))==blue:
#-print("up-Move right blue called")
time.sleep(sleepTime)
direction = 2
elif newscreen.get_at((currentX-blockSize,currentY))==blue:
moveLeft(currentX, currentY, blockSize, replace)
#-print("up-Move left blue called")
time.sleep(sleepTime)
direction = 3
#check rear
elif newscreen.get_at((currentX, currentY + blockSize)) == white or newscreen.get_at((currentX, currentY + blockSize)) == blue:#down
moveDown(currentX, currentY, blockSize, replace)
#-print("up-Move down called")
time.sleep(sleepTime)
direction = 4
#-print("direction-up", direction)
#Algorithm to determine direction to move if facing right
def right(replace):
global direction
if newscreen.get_at((currentX + blockSize, currentY)) == white:#right
moveRight(currentX, currentY, blockSize, replace)
#-print("right-Move right called")
time.sleep(sleepTime)
direction = 2
elif newscreen.get_at((currentX, currentY + blockSize)) == white:#down
moveDown(currentX, currentY, blockSize, replace)
#-print("right-Move down called")
time.sleep(sleepTime)
direction = 4
elif newscreen.get_at((currentX, currentY - blockSize)) == white:#up
moveUp(currentX, currentY, blockSize, replace)
#-print("right-Move up called")
time.sleep(sleepTime)
direction = 1
#check blue
elif newscreen.get_at((currentX + blockSize, currentY)) == blue:#right
moveRight(currentX, currentY, blockSize, replace)
#-print("right-Move right blue called")
time.sleep(sleepTime)
direction = 2
elif newscreen.get_at((currentX, currentY + blockSize)) == blue:#down
moveDown(currentX, currentY, blockSize, replace)
#-print("right-Move down called")
time.sleep(sleepTime)
direction = 4
elif newscreen.get_at((currentX, currentY - blockSize)) == blue:#up
moveUp(currentX, currentY, blockSize, replace)
#-print("right-Move up blue called")
time.sleep(sleepTime)
direction = 1
#check rear
elif newscreen.get_at((currentX - blockSize, currentY)) == white or newscreen.get_at((currentX - blockSize, currentY)) == blue:#left
moveLeft(currentX, currentY, blockSize, replace)
#-print("right-Move left called")
time.sleep(sleepTime)
direction = 3
#-print("direction-right", direction)
#Algorithm to determine direction to move if facing left
def left(replace):
global direction
if newscreen.get_at((currentX - blockSize, currentY)) == white:#left
moveLeft(currentX, currentY, blockSize, replace)
#-print("left-Move left called")
time.sleep(sleepTime)
direction = 3
elif newscreen.get_at((currentX, currentY - blockSize)) == white:#up
moveUp(currentX, currentY, blockSize, replace)
#-print("left-Move up called")
time.sleep(sleepTime)
direction = 1
elif newscreen.get_at((currentX, currentY + blockSize)) == white:#down
moveDown(currentX, currentY, blockSize, replace)
#-print("left-Move down called")
time.sleep(sleepTime)
direction = 4
#check blue
elif newscreen.get_at((currentX - blockSize, currentY)) == blue:#left
moveLeft(currentX, currentY, blockSize, replace)
#-print("left-Move left blue called")
time.sleep(sleepTime)
direction = 3
elif newscreen.get_at((currentX, currentY - blockSize)) == blue:#up
moveUp(currentX, currentY, blockSize, replace)
#-print("left-Move up blue called")
time.sleep(sleepTime)
direction = 1
elif newscreen.get_at((currentX, currentY + blockSize)) == blue:#down
moveDown(currentX, currentY, blockSize, replace)
#-print("left-Move down blue called")
time.sleep(sleepTime)
direction = 4
#check rear
elif newscreen.get_at((currentX + blockSize, currentY)) == white or newscreen.get_at((currentX + blockSize, currentY)) == blue:#right
moveRight(currentX, currentY, blockSize, replace)
#-print("left-Move right called")
time.sleep(sleepTime)
direction = 2
#-print("direction-left", direction)
#Algorithm to determine direction to move if facing down
def down(replace):
global direction
if newscreen.get_at((currentX, currentY + blockSize)) == white:#down
moveDown(currentX, currentY, blockSize, replace)
#-print("down-Move down called")
time.sleep(sleepTime)
direction = 4
elif newscreen.get_at((currentX - blockSize, currentY)) == white:#left
moveLeft(currentX, currentY, blockSize, replace)
#-print("down-Move left called")
time.sleep(sleepTime)
direction = 3
elif newscreen.get_at((currentX + blockSize, currentY)) == white:#right
moveRight(currentX, currentY, blockSize, replace)
#-print("down-Move right called")
time.sleep(sleepTime)
direction = 2
#check blue
elif newscreen.get_at((currentX, currentY + blockSize)) == blue:#down
moveDown(currentX, currentY, blockSize, replace)
#-print("down-Move down blue called")
time.sleep(sleepTime)
direction = 4
elif newscreen.get_at((currentX - blockSize, currentY)) == blue:#left
moveLeft(currentX, currentY, blockSize, replace)
#-print("down-Move left blue called")
time.sleep(sleepTime)
direction = 3
elif newscreen.get_at((currentX + blockSize, currentY)) == blue:#right
moveRight(currentX, currentY, blockSize, replace)
#-print("down-Move right blue called")
time.sleep(sleepTime)
direction = 2
#check rear
elif newscreen.get_at((currentX, currentY - blockSize)) == white or newscreen.get_at((currentX, currentY - blockSize)) == blue:#up
moveUp(currentX, currentY, blockSize, replace)
#-print("down-Move up called")
time.sleep(sleepTime)
direction = 1
#-print("direction-down", direction)
#returns boolean if current tile is intersection
def isIntersection():
global direction
paths = 0
#-print("isIntersection")
if newscreen.get_at((currentX, currentY - blockSize)) == white or newscreen.get_at((currentX, currentY - blockSize)) == red or newscreen.get_at((currentX, currentY - blockSize)) == green or newscreen.get_at((currentX, currentY - blockSize)) == blue:
paths = paths + 1
#-print("returnUp")
if newscreen.get_at((currentX - blockSize, currentY)) == white or newscreen.get_at((currentX - blockSize, currentY)) == red or newscreen.get_at((currentX - blockSize, currentY)) == green or newscreen.get_at((currentX - blockSize, currentY)) == blue:
paths = paths + 1
#-print("returnLeft")
if newscreen.get_at((currentX + blockSize, currentY)) == white or newscreen.get_at((currentX + blockSize, currentY)) == red or newscreen.get_at((currentX + blockSize, currentY)) == green or newscreen.get_at((currentX + blockSize, currentY)) == blue:
paths = paths + 1
#-print("returnRight")
if newscreen.get_at((currentX, currentY + blockSize)) == white or newscreen.get_at((currentX, currentY + blockSize)) == red or newscreen.get_at((currentX, currentY + blockSize)) == green or newscreen.get_at((currentX, currentY + blockSize)) == blue:
paths = paths + 1
#-print("returnDown")
#-print("direction-isIntersection", direction)
if paths > 2:
#-print(paths)
#-print("isIntersection-TRUE")
return True
else:
#-print(paths)
#-print("isIntersection-FALSE")
return False
varsInit(xvalueOfStart, yvalueOfStart)
moveUp(currentX, currentY, blockSize, white)
direction = 1
def checkSurround(color):#returns direction or 0 if no color present on intersection paths
global direction
paths=0
x=0
if newscreen.get_at((currentX, currentY - blockSize)) == color:#up
#direction = 4
#-print("checkRed-red up-AI faces down")#debug
paths+=1
x=1
if newscreen.get_at((currentX + blockSize, currentY)) == color:#right
#direction = 3
#-print("checkRed-red right-AI faces left")#debug
paths+=1
x=2
if newscreen.get_at((currentX - blockSize, currentY)) == color:#left
#direction = 2
#-print("checkRed-red left-AI faces right")#debug
paths+=1
x=3
if newscreen.get_at((currentX,currentY+blockSize))==color:#down
#direction = 1
#-print("checkRed-red down-AI faces up")#debug
paths+=1
x=4
if paths>1:
x=5
#-print("checkRed-no red present")#debug
return x
#-print("direction-checkRed", direction)
def addCount(isInt,directionMove,firstTime):
global direction,rightCount,upCount,leftCount
#direction=direction coming into intersection
#directionMove=direction leaving intersection
if isInt:
#-print("addCount-isIntersection-TRUE")#debug
#-print("addCount-checkRed output",checkSurround(red))
if checkSurround(red)==4:#AI faces up
#-print("addCount-AI up")#debug
if directionMove==1:#up
upCount+=1
if directionMove==3:#left
leftCount+=1
if directionMove==2:#right
rightCount+=1
if direction==4:#AI comes from top
upCount-=1
if direction==3:#AI comes from right
rightCount-=1
if direction==2:#AI comes from left
leftCount-=1
if checkSurround(red)==3:#AI faces right
#-print("addCount-AI right")#debug
if directionMove==2:#right
upCount+=1
if directionMove==1:#up
leftCount+=1
if directionMove==4:#down
rightCount+=1
if direction==3:#AI comes from right
upCount-=1
if direction==1:#AI comes from bottom
rightCount-=1
if direction==4:#AI comes from top
leftCount-=1
if checkSurround(red)==2:#AI faces left
#-print("addCount-AI left")#debug
if directionMove==3:#left
upCount+=1
if directionMove==4:#down
leftCount+=1
if directionMove==1:#up
rightCount+=1
if direction==2:#AI comes from left
upCount-=1
if direction==4:#AI comes from top
rightCount-=1
if direction==1:#AI comes from bottom
leftCount-=1
if checkSurround(red)==1:#AI faces down
#-print("addCount-AI down")#debug
if directionMove==4:#down
upCount+=1
if directionMove==2:#right
leftCount+=1
if directionMove==3:#left
rightCount+=1
if direction==1:#AI comes from bottom
upCount-=1
if direction==2:#AI comes from left
rightCount-=1
if direction==3:#AI comes from right
leftCount-=1
#check blue
if checkSurround(red)==0:
if checkSurround(blue)==4:#AI faces up
#-print("addCount-AI up")#debug
if directionMove==1:#up
upCount+=1
if directionMove==3:#left
leftCount+=1
if directionMove==2:#right
rightCount+=1
if direction==4:#AI comes from top
upCount-=1
if direction==3:#AI comes from right
rightCount-=1
if direction==2:#AI comes from left
leftCount-=1
if checkSurround(red)==3:#AI faces right
#-print("addCount-AI right")#debug
if directionMove==2:#right
upCount+=1
if directionMove==1:#up
leftCount+=1
if directionMove==4:#down
rightCount+=1
if direction==3:#AI comes from right
upCount-=1
if direction==1:#AI comes from bottom
rightCount-=1
if direction==4:#AI comes from top
leftCount-=1
if checkSurround(red)==2:#AI faces left
#-print("addCount-AI left")#debug
if directionMove==3:#left
upCount+=1
if directionMove==4:#down
leftCount+=1
if directionMove==1:#up
rightCount+=1
if direction==2:#AI comes from left
upCount-=1
if direction==4:#AI comes from top
rightCount-=1
if direction==1:#AI comes from bottom
leftCount-=1
if checkSurround(red)==1:#AI faces down
#-print("addCount-AI down")#debug
if directionMove==4:#down
upCount+=1
if directionMove==2:#right
leftCount+=1
if directionMove==3:#left
rightCount+=1
if direction==1:#AI comes from bottom
upCount-=1
if direction==2:#AI comes from left
rightCount-=1
if direction==3:#AI comes from right
leftCount-=1
intersectionX=[]
intersectionY=[]
intersectionNum=0
# Check if all paths of an intersection have been travelled. If so, go back on red
def intersection(isInt,firstTime):
global direction, upCount, rightCount, leftCount, intersectionX,intersectionY
if firstTime:#if first time at intersection, then add x/y cordinates of red
if direction==1:#facing up
intersectionX.append(currentX)
intersectionY.append(currentY+blockSize)
elif direction==2:#facing right
intersectionX.append(currentX-blockSize)
intersectionY.append(currentY)
elif direction==3:#facing left
intersectionX.append(currentX+blockSize)
intersectionY.append(currentY)
elif direction==4:#facing down
intersectionX.append(currentX)
intersectionY.append(currentY-blockSize)
print("X-",intersectionX)
print(" y-",intersectionY)
#pygame.draw.rect(newscreen, (100,100,100), pygame.Rect(currentX-blockSize, currentY-blockSize, blockSize, blockSize))
print("intersectionNum",intersectionNum)
time.sleep(2)
if newscreen.get_at((currentX, currentY - blockSize)) == white:#up
addCount(isInt,1,firstTime)
direction = 1
moveUp(currentX, currentY, blockSize, blue)
print("int-move-up")
elif newscreen.get_at((currentX + blockSize, currentY)) == white:#right
addCount(isInt,2,firstTime)
direction = 2
moveRight(currentX, currentY, blockSize, blue)
print("int-move-right")
elif newscreen.get_at((currentX - blockSize, currentY)) == white:#left
addCount(isInt,3,firstTime)
direction = 3
moveLeft(currentX, currentY, blockSize, blue)
print("int-move-left")
elif newscreen.get_at((currentX, currentY + blockSize)) == white:#down
addCount(isInt,4,firstTime)
direction = 4
moveDown(currentX, currentY, blockSize, blue)
print("int-move-down")
else:
if checkSurround(red)==5:#more than 1 red path
print("more than 1 red path")
for z in range(0,len(intersectionX)):
if intersectionX[z]==currentX-blockSize:#left
if intersectionY[z]==currentY:
addCount(isInt,3,firstTime)
direction=3
moveLeft(currentX,currentY,blockSize,blue)
print("int-to red-left")
break
elif intersectionX[z]==currentX+blockSize:#right
if intersectionY[z]==currentY:
addCount(isInt,2,firstTime)
direction=2
moveRight(currentX,currentY,blockSize,blue)
print("int-to red-right")
break
elif intersectionY[z]==currentY-blockSize:#up
if intersectionX[z]==currentX:
addCount(isInt,1,firstTime)
direction=1
moveUp(currentX,currentY,blockSize,blue)
print("int-to red-up")
break
elif intersectionY[z]==currentY+blockSize:#down
if intersectionX[z]==currentX:
addCount(isInt,4,firstTime)
direction=4
moveDown(currentX,currentY,blockSize,blue)
print("int-to red-down")
break
print("z-",z)
else:#1 red path
print("only 1 red path")
'''
print("intersection-length",len(intersectionX))
print("intersectionX",intersectionX[intersectionNum-1])
print("currentX",currentX)
if intersectionX[intersectionNum-1]>currentX:#left
addCount(isInt,3,firstTime)
direction=3
moveLeft(currentX,currentY,blockSize,blue)
print("GHASJFHFJWHAUJSHFWAHSDJNWAJSKFJWHANMSDKWASIJD")
'''
'''
if checkSurround(red) == 0:#no red
if newscreen.get_at((currentX, currentY - blockSize)) == blue:#up
addCount(isInt,1,firstTime)
direction = 1
moveUp(currentX, currentY, blockSize, blue)
elif newscreen.get_at((currentX + blockSize, currentY)) == blue:#right
addCount(isInt,2,firstTime)
direction=2
moveRight(currentX, currentY, blockSize, blue)
elif newscreen.get_at((currentX - blockSize, currentY)) == blue:#left
addCount(isInt,3,firstTime)
direction=3
moveLeft(currentX, currentY, blockSize, blue)
elif newscreen.get_at((currentX, currentY + blockSize)) == blue:#down
addCount(isInt,4,firstTime)
direction = 4
moveDown(currentX, currentY, blockSize, blue)
elif checkSurround(red)==1:
addCount(isInt,1,firstTime)
direction = 1
moveUp(currentX, currentY, blockSize, blue)
elif checkSurround(red)==2:
addCount(isInt,2,firstTime)
direction = 2
moveRight(currentX, currentY, blockSize, blue)
elif checkSurround(red)==3:
addCount(isInt,3,firstTime)
direction = 3
moveLeft(currentX, currentY, blockSize, blue)
elif checkSurround(red)==4:
addCount(isInt,4,firstTime)
direction = 4
moveDown(currentX, currentY, blockSize, blue)
'''
time.sleep(5)
# ------------- OUR ALGORITHM -------------
while 0 != currentY:
pygame.event.get()
#for x in range(0,10):
getCur = newscreen.get_at((currentX, currentY))
isInt=isIntersection()
if direction == 1:#up
if isInt:
if getCur == blue:#blue=intersection tile
moveDown(currentX, currentY, blockSize, blue)
moveUp(currentX, currentY, blockSize, green)#green=used path
intersection(isInt,False)
else:
if newscreen.get_at((currentX, currentY + blockSize)) != blue:#down
pygame.draw.rect(newscreen, red, pygame.Rect(currentX, currentY+blockSize, blockSize, blockSize))#set red path into intersection
pygame.draw.rect(newscreen, blue, pygame.Rect(currentX, currentY, blockSize, blockSize))#set current space to blue
intersectionNum+=1
intersection(isInt,True)
else:
if newscreen.get_at((currentX, currentY - blockSize)) == blue:
moveUp(currentX, currentY, blockSize, white)
else:
up(white)
elif direction == 2:#right
if isInt:
if getCur == blue:#blue=intersection tile
moveLeft(currentX, currentY, blockSize, blue)
moveRight(currentX, currentY, blockSize, green)#green=used path
intersection(isInt,False)
else:
if newscreen.get_at((currentX-blockSize, currentY)) != blue:#left
pygame.draw.rect(newscreen, red, pygame.Rect(currentX-blockSize, currentY, blockSize, blockSize))#set red path into intersection
pygame.draw.rect(newscreen, blue, pygame.Rect(currentX, currentY, blockSize, blockSize))#set current space to blue
intersectionNum+=1
intersection(isInt,True)
else:
if newscreen.get_at((currentX + blockSize, currentY)) == blue:
moveRight(currentX, currentY, blockSize, white)
else:
right(white)
elif direction == 3:#left
if isInt:
if getCur == blue:#blue=intersection tile
moveRight(currentX, currentY, blockSize, blue)
moveLeft(currentX, currentY, blockSize, green)#green=used path
intersection(isInt,False)
else:
if newscreen.get_at((currentX+blockSize, currentY)) != blue:#right
pygame.draw.rect(newscreen, red, pygame.Rect(currentX+blockSize, currentY, blockSize, blockSize))#set red path into intersection
pygame.draw.rect(newscreen, blue, pygame.Rect(currentX, currentY, blockSize, blockSize))#set current space to blue
intersectionNum+=1
intersection(isInt,True)
else:
if newscreen.get_at((currentX - blockSize, currentY)) == blue:
moveLeft(currentX, currentY, blockSize, white)
else:
left(white)
elif direction == 4:#down
if isInt:
if getCur == blue:#blue=intersection tile
moveUp(currentX, currentY, blockSize, blue)
moveDown(currentX, currentY, blockSize, green)#green=used path
intersection(isInt,False)
else:
if newscreen.get_at((currentX, currentY - blockSize)) != blue:#up
pygame.draw.rect(newscreen, red, pygame.Rect(currentX, currentY-blockSize, blockSize, blockSize))#set red path into intersection
pygame.draw.rect(newscreen, blue, pygame.Rect(currentX, currentY, blockSize, blockSize))#set current space to blue
intersectionNum+=1
intersection(isInt,True)
else:
if newscreen.get_at((currentX, currentY + blockSize)) == blue:
moveDown(currentX, currentY, blockSize, white)
else:
down(white)
#-print("direction-main", direction)
|
ec5c1f67132ee49f005cbcd923334e483c984434 | moorea8239/cti110 | /M5HW1_Moore.py | 608 | 4.34375 | 4 | #CTI 110
#M5HW1 - Distance Traveled
#10/29
#moorea
#Write a program that displays the distance traveled after the user inputs
#speed and number of hours.
def main():
#have the user input speed of vehicle in mph
milesPerHour = int(input("What is the speed of the vehicle in MPH?: "))
#have the user input time traveled in hours
hoursTraveled = int(input("How many hours has it traveled?: ")) + 1
distanceTraveled = milesPerHour * hoursTraveled
for x in range(1, hoursTraveled):
print(x * milesPerHour)
main()
|
4e61fa92218f561ac7180e945b06a87a0272ec88 | gorahohlov/Python_course | /Python1_lss1/P1_lss1_tsk3.py | 140 | 3.8125 | 4 | # -------------
b = int(input('Введите целое число от 1 до 9: '))
print(b * 3 + b * 2 * 10 + b * 100)
# -------------
|
9cc1ec31e16dc8ffc259d2cc788888d9dda9d248 | LucaOnline/theanine-synthetase | /parse_fasta.py | 998 | 3.875 | 4 | """The `parse_fasta` module exposes functions for reading FASTA files."""
from typing import Iterator, Tuple
def parse_fasta(filename: str) -> Iterator[Tuple[str, str]]:
"""
Parses the FASTA file with the provided filename. Returns
an iterator of tuples, structured with the sequence name
in the first element and the sequence itself in the second.
"""
with open(filename, "r") as f:
data = f.read()
if data[0] != ">":
raise ValueError("input file is not a FASTA file")
currentSeq = []
currentKey = ""
for line in data.splitlines():
if line.startswith(">"):
if currentKey != "":
yield currentKey, "".join(currentSeq)
currentSeq = []
currentKey = line[1:].split()[0] # Only key on the protein name
else:
currentSeq.append(line.strip().upper())
# Return last pair, if it exists
if currentKey != "":
yield currentKey, "".join(currentSeq)
|
85038eafdfd46210409de3a7ded0cd1f247da93e | AndresFernandoGarcia/Practicals | /Practical 2/Prac2_exceptionsdemo.py | 1,156 | 4.375 | 4 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
This error will occur when the input is the right type but an inappropriate value therefore the error appears.
If the input was dog, the int() function tries to convert the string to a number but it can't since the letters
cannot be changed into a number
2. When will a ZeroDivisionError occur?
This will occur when a number is divided by 0, since that is an undefined number it cannot be displayed.
3. Could you change the code to avoid the possibility of a ZeroDivisionError?
using a while loop to keep asking for a denominator that isn't 0
denominator = int(input("Enter the denominator: "))
while(denominator == 0)
print("Error denominator cannot be 0")
denominator = int(input("Enter the denominator: "))
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.") |
e9abb38eed2b2beba42ff069d457afa1ac2a3fa9 | Jfeng3/careercup | /Others/insert_in_ordered_circular_linkedlist.py | 2,341 | 4.03125 | 4 | '''
link: http://www.careercup.com/question?id=13273690
user: jfeng
company: Walmart
type: Linkedlist
desc: Insert an element in a ordered (ascending) circular linked list. After inserting return the node with the smallest element.
'''
class ListNode:
def __init__(self,val):
self.val = val
self.next = None
def insert(head,val):
if head is None:
dummy = ListNode(val)
dummy.next = dummy
return dummy
current = head
small = None
insert = False
start = True
elem = ListNode(val)
while current!=head or start:
start = False
if not insert and current.val<=elem.val and current.next.val >=elem.val:
current.next,elem.next = elem,current.next
insert = True
current = current.next.next
continue
if current.val>current.next.val:
small = current.next
if not insert and elem.val<=current.next.val:
current.next,elem.next = elem, current.next
small = elem
return small
if not insert and elem.val>=current.val:
current.next,elem.next = elem, current.next
return elem.next
current = current.next
if insert and small is not None:
return small
elif not insert:
head.next,elem.next = elem,head.next
return head if head.val<=elem.val else elem
def create_circle_linkedlist(num):
if len(num) ==0 :
return None
dummy = ListNode(0)
current = dummy
for item in num:
node = ListNode(item)
current.next = node
current = current.next
current.next = dummy.next
return dummy.next
def printList(node):
current = node
start = False
rslt = ""
while current is not node or start is False:
start = True
rslt +=str(current.val)+'-'
current = current.next
print rslt
x = create_circle_linkedlist([3,5,6,7,2,3])
printList(x)
small = insert(x,6)
printList(small)
x = create_circle_linkedlist([3,3,3,3,3,3])
printList(x)
small = insert(x,6)
printList(small)
x = create_circle_linkedlist([3])
printList(x)
small = insert(x,6)
printList(small)
x = create_circle_linkedlist([])
small = insert(x,6)
printList(small)
|
a59f9281c5e32aaf1affc706fa3aa2d58135ccd9 | ultimatumvizz/python50 | /py31.py | 519 | 3.734375 | 4 | # ramanujam numbers-------------these are numbers of kind in which a number can be represented as the pair of sum of 2 cubic numbers
from itertools import permutations
liz=[i for i in permutations(range(1,200),2)]
sumCubes=dict()
raman=dict()
for i in range(0,len(liz)):
a=liz[i][0]**3
b=liz[i][1]**3
if a+b not in sumCubes.keys():
sumCubes[a+b]=liz[i]
if a+b in sumCubes.keys():
if sumCubes[a+b][0] not in liz[i]:
x=[]
x=sumCubes[a+b]
raman[a+b]=(liz[i],x)
print sorted(raman.keys())
|
de33940247b998407b926b39b02da0c8609d9e08 | Lingrui/Leetcode | /Algorithms/Easy/Judge_route_circle.py | 331 | 3.828125 | 4 | #!/usr/bin/python
class Solution:
def judgeCircle(self,moves):
'''
:type moves: str
:rtype: bool
'''
return len(moves)%2 == 0 and moves.count('U')==moves.count('D') and moves.count('L')==moves.count('R')
if __name__ == '__main__':
x = str(input("input moves:"))
print("Is it a circle? :",Solution().judgeCircle(x))
|
7da15d1eba348deafe0ffd6a618d3ffeadb9263a | Srikesh89/PythonBootcamp | /Python Scripts/skyline.py | 451 | 3.859375 | 4 | #Skyline Exercise
def myfunc(string):
skyline_string = ''
string_length = len(string)
current_index = 0
while(current_index < string_length):
if(current_index%2==1):
#do odd letter
skyline_string += string[current_index].lower()
else:
#do even
skyline_string += string[current_index].upper()
current_index += 1
return skyline_string
print(myfunc('abcdefgh')) |
585b244c094c2ada3452650ea213e9a40b2befdb | stdlibz/PythonTraining | /Devisors | 218 | 3.921875 | 4 | #!/usr/bin/python
def Devisors ( num ):
i = 1
list = []
while ( i <= num ):
if ( num % i == 0 ):
list.append(i)
i+=1
list.append(num)
return list
print Devisors(int(raw_input("Please enter a number: ")))
|
107916219a279eaca959b402a1fee20c69a179df | newkeros/Projet_2 | /parserbook.py | 2,413 | 3.53125 | 4 | """Parse all data needed and put it in a dictionary"""
from request import request
def get_title(article):
"""Return the title of a book"""
title = article.find("div", class_="col-sm-6 product_main").h1.text
return title
def get_product_upc(article):
"""Return the product UPC from a book"""
tableau = article.select("tr")
return tableau[0].td.text
def get_product_description(article):
"""Return the product description of a book"""
product_description_text = article.select("p")
return product_description_text[3].text
def get_price_including_tax(article):
"""Return the price of a book including tax"""
price_with_tax = article.select("tr")
return price_with_tax[3].td.text
def get_price_excluding_tax(article):
"""Return the price of a book excluding tax"""
price_without_tax = article.select("tr")
return price_without_tax[2].td.text
def get_number_available(article):
"""Return the number of books available"""
number_available = article.select("p")
return number_available[1].text.strip().strip(" Instock)available(")
def get_category(soup):
"""Return the name of the category"""
category = soup.ul.find_all("a")[-1].text
return category
def get_review_rating(article):
"""Return the book review rating"""
review_rating = article.find_all("p")[2]
return review_rating.get("class")[-1]
def get_image_url(article):
"""Return the image url"""
get_image = article.find_all("img")[0]
return get_image.get("src").replace("../../", "http://books.toscrape.com/")
def get_all_product_infos(url):
"""Return a dictionnary will all book informations"""
product_infos = dict()
soup = request(url)
article = soup.find("article")
product_infos["product_page_url"] = url
product_infos["product_upc"] = get_product_upc(article)
product_infos["title"] = get_title(article)
product_infos["price_including_tax"] = get_price_including_tax(article)
product_infos["price_excluding_tax"] = get_price_excluding_tax(article)
product_infos["number_available"] = get_number_available(article)
product_infos["product_description"] = get_product_description(article)
product_infos["category"] = get_category(soup)
product_infos["review_rating"] = get_review_rating(article)
product_infos["image_url"] = get_image_url(article)
return product_infos
|
e9c47823e93bb34ac4ff04d266b3c11cb23c2407 | acemodou/Working-Copy | /DataStructures/v1/code/leet/Heaps/sort_k_sorted.py | 2,299 | 3.53125 | 4 | def sortKSortedArray(array, k):
minHeapWithKElements = MinHeap(array[: min(k+1, len(array))])
sortedIdx = 0
for idx in range(k+1, len(array)):
array[sortedIdx] = minHeapWithKElements.remove()
sortedIdx +=1
minHeapWithKElements.insert(array[idx])
while not minHeapWithKElements.isEmpty():
array[sortedIdx] = minHeapWithKElements.remove()
sortedIdx +=1
return array
class MinHeap:
def __init__(self, array):
self.heap = self.buildHeap(array)
self.length = len(array)
def buildHeap(self, array):
for pos in range(1, len(array)):
self.siftUp(array, pos )
return array
def PARENT(self, idx):
return (idx -1) >> 1
def CHILD(self, idx):
return (idx << 1) + 1
def siftUp(self, array, pos):
# Hold the value at pos and keep going up until there is nothing smaller than it
temp = array[pos]
while pos > 0 and temp < array[self.PARENT(pos)]:
array[pos] = array[self.PARENT(pos)]
pos = self.PARENT(pos)
array[pos] = temp
def siftDown(self, pos):
child = self.CHILD(pos)
while child <= len(self.heap)-1:
if len(self.heap)-1 > child and self.heap[child+1] < self.heap[child]:
child = child+1
if self.heap[pos] > self.heap[child]:
self.swap(pos, child, self.heap)
pos = child
child = self.CHILD(pos)
else:
break
def isEmpty(self):
return len(self.heap) == 0
def insert(self, value):
self.heap.append(value)
self.length +=1
self.siftUp(self.heap, len(self.heap)-1)
def peek(self):
return self.heap[0]
def swap(self, x, y, heap):
if x != y:
heap[x], heap[y] = heap[y], heap[x]
def remove(self):
x = self.peek()
self.swap(0, len(self.heap)-1, self.heap)
deleted_ele = self.heap.pop()
assert f'{x} == {deleted_ele}, {x}!{deleted_ele}'
self.length -=1
self.siftDown(0)
return deleted_ele
|
9285b96e7a8ce6217001078068f5f73beb8c41be | daniel-reich/turbo-robot | /FqFGnnffKRo8LKQKP_5.py | 651 | 3.96875 | 4 | """
**Mubashir** needs your help to filter out **Simple Numbers** from a given
list.
### Simple Numbers
89 = 8^1 + 9^2
135 = 1^1 + 3^2 + 5^3
Create a function to collect these numbers from a given range between `a` and
`b` (both numbers are inclusive).
### Examples
simple_numbers(1, 10) ➞ [1, 2, 3, 4, 5, 6, 7, 8, 9]
simple_numbers(1, 100) ➞ [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
simple_numbers(90, 100) ➞ []
### Notes
N/A
"""
def simple_numbers(a, b):
result = []
for i in range(a, b + 1):
if sum(int(n) ** x for x, n in enumerate(str(i), start = 1)) == i:
result.append(i)
return result
|
7c2c89201ae56cc533e38875660eac92d1306d8a | silazor/IS211_Assignment1 | /Assignment1_part1.py | 654 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class ListDivideException(Exception):
"""An error occurred"""
def listDivide(numbers, divide = 2):
cnt = 0
for num in numbers:
if num % divide == 0:
cnt += 1
return(cnt)
def testlistDivide():
try:
print(listDivide([1, 2, 3, 4, 5]))
print(listDivide([2, 4, 6, 8, 10]))
print(listDivide([30, 54, 63, 98, 100], divide=10))
print(listDivide([]))
print(listDivide([2, 4, 6, 8, 10], 1))
except ListDivideException:
print("InvalidInputError:")
testlistDivide()
|
3eab2b3db912a7efa5c6914e9479eb5227401a32 | danielsunzhongyuan/my_leetcode_in_python | /sqrtx_69.py | 532 | 3.53125 | 4 | class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if 1 <= x <= 3:
return 1
if x in (4, 5):
return 2
start, end = 1, x
while (start + 1 < end):
mid = (start + end) / 2
if mid * mid == x:
return mid
elif mid * mid < x:
start = mid
else:
end = mid
if end * end <= x:
return end
return start
|
19fc2e99243b186c116bc839e0db8442c25279a4 | law-lee/runestone | /gates.py | 5,434 | 3.796875 | 4 | class LogicGate:
'''A logic gate should contain name and output'''
def __init__(self,n):
self.name = n
self.output = None
def getName(self):
return self.name
def getOutput(self):
self.output = self.performGateLogic()
return self.output
class BianryGate(LogicGate):
'''A binary gate contains two pins'''
def __init__(self,n):
LogicGate.__init__(self,n)
self.pinA = None
self.pinB = None
def setPinA(self,p):
if self.pinA == None:
self.pinA = p
def setPinB(self,p):
if self.pinB == None:
self.pinB=p
def getPinA(self):
if self.pinA == None:
return int(input("Enter Pin A input for gate "+self.getName()+"-->"))
elif isinstance(self.pinA, Connector):
return self.pinA.getFromGate().getOutput()
else:
return self.pinA
def getPinB(self):
if self.pinB == None:
return int(input("Enter Pin B input for gate "+self.getName()+"-->"))
elif isinstance(self.pinB, Connector):
return self.pinB.getFromGate().getOutput()
else:
return self.pinB
def setConnectPin(self,source):
if self.pinA == None:
self.pinA = source
elif self.pinB == None:
self.pinB = source
else:
print("No empty Pin !")
class UnaryGate(LogicGate):
'''A unary gate contains one pin'''
def __init__(self,n):
LogicGate.__init__(self,n)
self.pinO = None
def setpinO(self,p):
if self.pinO == None:
self.pinO = p
def getpinO(self):
if self.pinO == None:
return int(input("Enter Pin input for gate "+self.getName()+"-->"))
elif isinstance(self.pinO, Connector):
return self.pinO.getFromGate().getOutput()
else:
return self.pinO
def setConnectPin(self,source):
if self.pinO == None:
self.pinO = source
else:
print("No empty Pin !")
class AndGate(BianryGate):
'''And gate perform and logic algorithm'''
def __init__(self,n):
BianryGate.__init__(self,n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if a == 1 and b == 1:
return 1
else:
return 0
class OrGate(BianryGate):
'''Or gate perform or logic algorithm'''
def __init__(self,n):
BianryGate.__init__(self,n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if a == 0 and b == 0:
return 0
else:
return 1
class NotGate(UnaryGate):
'''Not gate perform not logic algorithm'''
def __init__(self,n):
UnaryGate.__init__(self,n)
def performGateLogic(self):
a = self.getpinO()
if a == 0:
return 1
else:
return 0
class Connector:
'''A connector connect a logic gate's output and a logic gate's input'''
def __init__(self,fgate,tgate):
self.fromgate = fgate
self.togate = tgate
tgate.setConnectPin(self)
def getFromGate(self):
return self.fromgate
def getToGate(self):
return self.togate
class ExorGate(BianryGate):
'''EXOR gate different inputs OUTPUT 1 '''
def __init__(self,n):
BianryGate.__init__(self,n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if (a==0 and b==1) or (a==1 and b==0):
return 1
else:
return 0
class HalfAdder:
'''A half adder needs two input ,two output'''
def __init__(self,a=None,b=None):
self.inA = a
self.inB = b
self.xorg = ExorGate("XorG")
self.andg = AndGate("AndG")
self.xorg.setPinA(self.inA)
self.andg.setPinA(self.inA)
self.xorg.setPinB(self.inB)
self.andg.setPinB(self.inB)
self.sum = self.xorg.getOutput()
self.carry = self.andg.getOutput()
def getresult(self):
return str(self.carry)+str(self.sum)
class FullAdder:
'''A full adder has three inputs a,b,Cin , two outputs Sum,Cout'''
def __init__(self,a=None,b=None,Cin=None):
self.inA = a
self.inB = b
self.Cin = Cin
self.xorg1 = ExorGate("XorG1")
self.xorg2 = ExorGate("XorG2")
self.andg1 = AndGate("AndG1")
self.andg2 = AndGate("AndG2")
self.org1 = OrGate("OrG1")
self.xorg1.setPinA(self.inA)
self.xorg1.setPinB(self.inB)
self.andg1.setPinA(self.inA)
self.andg1.setPinB(self.inB)
self.xorg2.setPinB(self.Cin)
self.andg2.setPinB(self.Cin)
Connector(self.xorg1,self.xorg2)
Connector(self.xorg1,self.andg2)
Connector(self.andg2,self.org1)
Connector(self.andg1,self.org1)
self.sum = self.xorg2.getOutput()
self.carry = self.org1.getOutput()
def getCin(self):
return self.Cin
def getSum(self):
return self.sum
def getresult(self):
return str(self.carry) + str(self.sum)
def main():
while True:
a = int(input("Input adder A: "))
b = int(input("Input adder B: "))
cin = int(input("Input Cin: "))
ha = FullAdder(a,b,cin)
print(ha.getresult())
if __name__ == '__main__':
main() |
7f87ec226c74829e0639256310d321de0cd42e2b | YajithVishwa/Python-Lab | /poly area.py | 739 | 3.796875 | 4 | class triangle():
def area(self):
a=10
b=20
c=(a*b)/2
print("Area of triangle is",c)
def perimeter(self):
a=10
b=20
c=30
d=a+b+c
print("Perimeter of triangle",d)
class frustum():
def area(self):
import math
pi=math.pi
r=10
R=20
l=10
c=pi*l*(R+r)
print("Curved surface area of frustum",c)
def perimeter(self):
print("Volume of frustum")
import math
pi=math.pi
r=10
R=20
l=30
h=30
c=1/3*pi*h*(r*r+R*R+r*R)
print("Volume of frustum",c)
tr=triangle()
fr=frustum()
for c in (tr,fr):
c.area()
c.perimeter()
|
121c33ff9a1cefb2d44eb7005e2accaf19d4645d | saikrishna6415/python-problem-solving | /starnumpyramid.py | 303 | 3.984375 | 4 | n = int(input("enter number : "))
for i in range(1,n+1):
print((n-i)*" ",end=" ")
for j in range(1,i+1):
if i %2==0:
print(str(j)+" ",end="")
else:
print("* ",end="")
print()
# enter number : 5
# *
# 1 2
# * * *
# 1 2 3 4
# * * * * * |
3490e91a6f2cf3cf3af3f835be6b75a90af7644e | Utpal18/LabWork | /LAB WORK 2/positive neg.py | 177 | 4.03125 | 4 | num=int(input('enter num'))
positive=False
if num>0:
positive=True
print(positive)
elif num<0:
positive=False
print(positive)
else:
print('number is zero')
|
c772393eea5a4197c983120eaaecebaf981917ee | jphouminh71/csci1200_ArtOfComputationalThinking | /Labs/Lab 10/Lab10.zip/player.py | 1,197 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 17 00:30:06 2017
@author: ioanafleming
"""
class Player():
def __init__(self, is_human, is_next, total_score, hold_value): #constructor
self.is_human = is_human # a boolean value
self.is_next = is_next # a boolean value
self.total_score = total_score # an integer representing the total number of points (after each turn)
self.hold_value = hold_value # an integer representing the value the player holds at (meaning, the value at which it automatically chooses to pass rather than roll).
def get_is_human(self):
return self.is_human
def set_is_human(self, is_human):
self.is_human = is_human
def get_is_next(self):
return self.is_next
def set_is_next(self, is_next):
self.is_next = is_next
def get_total_score(self):
return self.total_score
def set_total_score(self, total_score):
self.total_score = total_score
def get_hold_value(self):
return self.hold_value
def set_hold_value(self, hold_value):
self.hold_value = hold_value |
2607028b8a400adbfcbb7ed4505b204bc814d1a9 | lattrellsapon/chatbots | /Old/smartbot/src/webscrape/webscrape.py | 933 | 3.515625 | 4 |
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.aut.ac.nz/study/study-options/engineering-computer-and-mathematical-sciences/courses/bachelor-of-computer-and-information-sciences/software-development-major'
# Opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
# HTML Parsing
page_soup = soup(page_html, "html.parser")
# Grabs all papers
papers = page_soup.findAll("a", {"class": "paperbox"})
filename = "softwaredevpapers.csv"
f = open(filename, "w")
headers = "PaperCode, PaperName\n"
f.write(headers)
# Loop through each papers
for paper in papers:
# Paper Code
paper_code = paper["id"]
# Paper Name
paper_name = paper.text
print("Paper Code: " + paper_code)
print("Paper Name: " + paper_name)
f.write(paper_code + "," + paper_name.replace(",", "|") + "\n")
f.close()
|
aaa4e1b9ded1849555f7d4a912f8a17a7efdceb1 | forever0136789/python-100 | /python-57.py | 393 | 3.6875 | 4 | from tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
#实际上画的是线段,这里19条连成了一个更长的线段
canvas.create_line(x0,y0,x1,y1, width=1, fill='red')
x0 = x0 - 5
y0 = y0 - 5
x1 = x1 + 5
y1 = y1 + 5
mainloop()
|
9e515f231d03ebdd252ef8057dfe3198c6a7217d | m-wrzr/code30 | /solutions/13/solution.py | 2,459 | 3.609375 | 4 | # solution is not really efficient, workaround with deadline for execution if a partial solution is not promising
# maybe revisit and fix, but the problem is not that interesting imo
from math import sqrt
from itertools import count, islice
import signal
# returns the value of a jamcoin in base x - output as base 10
def getvalueforbase(coin, base, n):
res = 0
for i, c in enumerate(coin):
res += c * (base ** (n - 1 - i))
return res
class TimedOutExc(Exception):
pass
def deadline(timeout, *args):
def decorate(f):
def handler(signum, frame):
raise TimedOutExc()
def new_f(*args):
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
return f(*args)
signa.alarm(0)
new_f.__name__ = f.__name__
return new_f
return decorate
# check if a number is prime
# efficient solution from
# http://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python
@deadline(5)
def isprime(n):
try:
if n < 2:
return 1
for number in islice(count(2), int(sqrt(n) - 1)):
if not n % number:
return number
return -1
except TimedOutExc as e:
return -1
# super weird coin increment - this code is stupid
def updatejamcoin(coin, n):
return '1' + '{0:b}'.format(int("".join([str(e) for e in coin[1:(n - 1)]]), 2) + 1).zfill(n - 2) + '1'
inputSize = "large"
output = "Case #1:\n"
fileInput = "C-" + inputSize + "-practice.in"
fileOutput = "C-" + inputSize + "-output.txt"
file = open(fileInput, "r")
nCase = int(file.readline())
# n is length of jamcoin, j is amount distinct
n, j = [int(s) for s in file.readline().split(" ")]
# init jamcoin
jamcoin = [0] * n
jamcoin[0] = 1
jamcoin[n - 1] = 1
while j > 0:
print(jamcoin)
allbase = []
# get according decimal values
for i in range(2, 11):
allbase.append(getvalueforbase(jamcoin, i, n))
primes = [isprime(i) for i in allbase]
if -1 not in primes:
j -= 1
output += "".join(str(s) for s in jamcoin)
for res in primes:
output += " " + str(res)
output += "\n"
print("found solution {} to go".format(j))
# update jamcoin
jamcoin = [int(e) for e in list(updatejamcoin(jamcoin, n))]
print(output)
# write to txt
with open(fileOutput, "w") as text_file:
text_file.write(output)
|
a15c7b9f125b2a9fc451a29deecadead648bae6a | Rushi4001/python-practice-programming | /decorator.py | 325 | 3.921875 | 4 |
def subtraction(a,b):
return a-b
def ourdecorator(fun_game):
return fun_game(1,5) #but we dont want given value not in negative format then we another function in next code
def main():
ret=ourdecorator(subtraction)
print("subtraction is ",ret)
if __name__=="__main__":
main() |
62c946d80e36d2a66d3e9fb37e37b0cc8081813e | JaredJWoods/CIS106-Jared-Woods | /ses8/PS8p3 [JW].py | 576 | 4 | 4 | def examAverage(exam1, exam2):
average = (exam1+exam2)/2
return average
print("Would you like to check your exam average?")
choice = input("Type 'yes' or 'no': ")
print()
while choice == str("yes"):
exam1 = float(input("Enter your score for the 1st exam: "))
exam2 = float(input("Enter your score for the 2nd exam: "))
average = examAverage(exam1, exam2)
print("Your average score is: ",average, "%")
print()
print("Would you like to check another average?")
choice = input("Type 'yes' or 'no': ")
print()
print()
print()
print("Goodbye.") |
eddab909503972bc2ad68924b397033619437227 | LijaAlex12/Python3 | /tuples.py | 270 | 3.59375 | 4 | # tuples
# immutable but member objects may be mutable
x=()
x=(1,2,3)
# parenthesis optional
x=1,2,3
# single item tuple
x=2,
list1=[]
x=tuple(list1)
# del(x[1]) error
# x[1]=8 error
# 2 item tuple:list and int member objects mutable
x=([1,2],3)
del(x[0][1])
print(x) |
878a3fff897acdcec74837286c54734f4a15e92c | johanqr/python_basico_2_2019 | /Semana1/Practica03.py | 402 | 3.609375 | 4 | #Para revisar los tipos de datos
#numero entero
#definir un numero entero
mi_variable = 123456
#ver contenido de variable
print(mi_variable)
#Caso 1
print('El valor de la variable llamada mi_variable es', mi_variable)
#Caso 2
print('El valor de la variable llamada "mi_variable" es', mi_variable)
#Caso 3
print("El valor de la variable llamada \"mi_variable es\"", mi_variable) |
7c9502ffa7067462bb259e360e5ebeb7ffae7ac7 | JorgeOrobio/COMPUTACION_GRAFICA_2019_2 | /Clases/Clase9/rosa_polar_giro.py | 1,032 | 3.53125 | 4 | import pygame
from libreria import*
#colores
if __name__ == '__main__':
pygame.init()
pantalla = pygame.display.set_mode((ancho,alto))
Puntos = Puntos_A_Pantalla(Rosa_polar(6,200))
pygame.draw.polygon(pantalla, color_aleatorio(), Puntos,3)
pygame.display.flip()
fin = False
while not fin:
for event in pygame.event.get():
if event.type == pygame.QUIT:
fin = True
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 4:
Puntos_A_Cartesiano(Puntos)
Rotar_Puntos_Horario(Puntos,-3)
Puntos_A_Pantalla(Puntos)
if event.button == 5:
Puntos_A_Cartesiano(Puntos)
Rotar_Puntos_Horario(Puntos,3)
Puntos_A_Pantalla(Puntos)
pantalla.fill(negro)
Plano_Cartesiano(pantalla)
pygame.draw.polygon(pantalla, color_aleatorio(), Puntos, 1)
pygame.display.flip()
|
e7f056fd19368a5b0fb2e125f3278aa9cb907450 | deepak8910/python_practise | /tree.py | 748 | 3.671875 | 4 | class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
node0 = TreeNode(3)
node1 = TreeNode(4)
node2 = TreeNode(5)
node0.left = node1
node0.right = node2
print(node0.right.key)
tree_tuple = ((1,3,None), 2, ((None, 3, 4), 5, (6, 7, 8)))
print(tree_tuple)
def parse_tuple(data):
# print(data)
if isinstance(data, tuple) and len(data) == 3:
node = TreeNode(data[1])
node.left = parse_tuple(data[0])
node.right = parse_tuple(data[2])
elif data is None:
node = None
else:
node = TreeNode(data)
return node
tree2 = parse_tuple(((1,3,None), 2, ((None, 3, 4), 5, (6, 7, 8))))
print(tree2.left.left.key)
parse_tuple(tree_tuple) |
9227303f43bf0f124d5419357a01f2c3d8f33c52 | dbswl4951/programmers | /programmers_level4/도둑질.py | 772 | 3.546875 | 4 | '''
[ POINT ]
1) 첫번째 집을 턴 경우 => 마지막 집 못 털음
2) 첫번째 집을 털지 않은 경우 => 마지막 집 털 수 있음
두 개의 경우로 나눠서 생각해야 함
'''
def solution(money):
# 첫번째 집 턴 경우
dp=[0]*len(money)
dp[0],dp[1]=money[0],money[0]
# 범위에서 마지막 집 제외
for i in range(2,len(money)-1):
dp[i]=max(dp[i-2]+money[i],dp[i-1])
result=max(dp)
# 첫번째 집 털지 않은 경우
dp = [0] * len(money)
dp[1]=money[1]
# 마지막 집 털 수 있음 (범위에 포함)
for i in range(2,len(money)):
dp[i]=max(dp[i-2]+money[i],dp[i-1])
result=max(result,max(dp))
return result
#print(solution([1,2,3,1]))
#print(solution([7,1,1,6,3])) |
90d02e1ee6cc96f1093cd290d2397cbedba18b0a | JohnnyFang/datacamp | /foundations-of-probability-in-python/03-important-probability-distributions/07-smartphone-battery-example.py | 1,054 | 4.5 | 4 | """
Smartphone battery example
One of the most important things to consider when buying a smartphone is how long the battery will last.
Suppose the period of time between charges can be modeled with a normal distribution with a mean of 5 hours and a standard deviation of 1.5 hours.
A friend wants to buy a smartphone and is asking you the following questions.
Instructions 1/3
1. What is the probability that the battery will last less than 3 hours?
"""
# Probability that battery will last less than 3 hours
less_than_3h = norm.cdf(3, loc=5, scale=1.5)
print(less_than_3h)
"""What is the probability that the battery will last more than 3 hours?"""
# Probability that battery will last more than 3 hours
more_than_3h = norm.sf(3, loc=5, scale=1.5)
print(more_than_3h)
"""What is the probability that the battery will last between 5 and 7 hours?"""
# Probability that battery will last between 5 and 7 hours
P_less_than_7h = norm.cdf(7, loc=5, scale=1.5)
P_less_than_5h = norm.cdf(5, loc=5, scale=1.5)
print(P_less_than_7h - P_less_than_5h)
|
b929110288a0919bd57de700743345139eae5e7b | AnmolKhawas/PythonAssignment | /Assignment2/Q6.py | 179 | 4.4375 | 4 | num=int(input("Enter a number:"))
if(num%5==0 and num%3==0):
print('The given number is divisible by 3 and 5')
else:
print('The given number is not divisible by 3 and 5')
|
55ecef47e8d569f7ceb5a10847a6ccbe30bd8dbc | pyCERN/algorithm | /UVa/10000-/11000-11099/11060.py | 1,317 | 3.640625 | 4 | # Topological Sort
from collections import deque
def topsort(queue, in_edge, out_edge):
for key in in_edge.keys():
if in_edge[key] == []:
queue.append(key)
while queue:
queue = sorted(queue, key=lambda x: bev_order[x], reverse=True)
bev = queue.pop()
print(' ' + bev, end='')
bev_tmp_list = out_edge[bev].copy()
for next_bev in bev_tmp_list:
out_edge[bev].remove(next_bev)
in_edge[next_bev].remove(bev)
if in_edge[next_bev] == []:
queue.append(next_bev)
print('.')
TC = 1
while True:
try:
if TC != 1:
print()
N = input()
except EOFError:
break
N = int(N)
in_edge = {}
out_edge = {}
bev_order = {}
queue = deque() # set of nodes with no in-edge
for i in range(N):
bev = input()
in_edge[bev] = []
out_edge[bev] = []
bev_order[bev] = i
M = int(input())
for _ in range(M):
bev1, bev2 = input().split(' ')
if bev1 == bev2: continue
in_edge[bev2].append(bev1)
out_edge[bev1].append(bev2)
input()
print('Case #{}: Dilbert should drink beverages in this order:'.format(TC), end='')
topsort(queue, in_edge, out_edge)
TC += 1 |
7f81fe997557159ebcc69bc983c2822bf03f7893 | windanger/Exercise-on-internet | /25.py | 263 | 3.859375 | 4 | #题目:求1+2!+3!+...+20!的和。
#程序分析:此程序只是把累加变成了累乘。
def resut(i) :
total = 1
while i :
total = total * i
i -=1
return total
adds = 0
for i in range(1,21) :
adds += resut(i)
print(adds) |
49b12030a56d3acf17cc8b07a2e71816b8d50946 | aboubakrs/365DaysofCode | /Day13/Day 13 - Exo4.py | 499 | 4.125 | 4 | #Les Fonctions avec Paramètres !
print("Exercice : C'est ma Premiere Fonction avec Parametre")
#Définition Fonction
def tableMultiplication(inVariant):
print("La table de Multiplication par ", inVariant)
n = 1
while(n <11):
print(inVariant, "*", n, "=", inVariant*n)
n = n + 1
#Utilisation d'une variable saisie par le User
a = int(input("Veuillez saisir un nom pour lequel vous souhaitez la Table de Multiplication : "))
#Appel de la fonction
tableMultiplication(a) |
0a0ca9327a6eb0e1da13c5e6164900e12277c493 | RochesterinNYC/Project-Euler | /euler_5.py | 624 | 3.5 | 4 | import euler_ops
import sys
import math
number_max = 20
increment = euler_ops.mult_primes(number_max)
count = increment
min_divisor = math.floor(number_max / 2)
divisor = 0
is_evenly_divisible = False
current_divisible = True
while is_evenly_divisible is False:
current_divisible = True
divisor = min_divisor
while current_divisible is True and divisor <= number_max:
if count % divisor is not 0:
current_divisible = False
divisor += 1
if current_divisible is True:
is_evenly_divisible = True
else:
count += increment
euler_ops.print_answer(count, sys.argv)
|
e7471a9cfaae9a394955bd8c829068c02ba02167 | HLAvieira/Curso-em-Video-Python3 | /Pacote-download/aulas_python_cev/ex_29_multa_km.py | 207 | 3.765625 | 4 | velocidade = float(input('Digite a velocidade do carro em Km/h ::::: '))
if velocidade > 80.0:
print('você foi multado em R${:.2f} '. format((velocidade-80.0)*7))
else:
print('Velocidade permitida') |
c30732766a93210946afd895b1a4c982de45b489 | rjcmarkelz/QB3_Python_Course | /ex3.2.1.py | 4,174 | 4.03125 | 4 | delimiter = ","
string_to_split = "I am a well-written sentence, and so I \
dependably have punctuation. "
list_from_string = string_to_split.split(delimiter)
print "clause one %s" % list_from_string[0]
print "clause two %s" % list_from_string[1]
###
list_from_string = string_to_split.split(' ')
for word in list_from_string:
print word
list_from_string = string_to_split.split('a')
for vowel_handicapped_lump in list_from_string:
print vowel_handicapped_lump
list_from_string = list(string_to_split)
for letter in list_from_string:
print letter
#define how many string splits to do in a row
string_to_split = "I am a well-written sentence, and so I \
dependably have punctuation. "
list_from_string = string_to_split.split(' ', 3)
for item in list_from_string:
print item
#two delimitors next to one another
list_from_string = string_to_split.split('t')
for consonant_crippled_lump in list_from_string:
print consonant_crippled_lump
print "-"*10
#using defaults this should look the same as the splitting by spaces
list_from_string = string_to_split.split()
for item in list_from_string:
print item
print "-"*10
#this is not the same as splitting by spaces---no empty items
string_to_split = " this is a different string"
list_from_string = string_to_split.split()
for item in list_from_string:
print item
print "-"*10
string_to_split = ''' complete
\t\t whitespace chaos
!!!!!!!!!!!!!!!!! '''
list_from_string = string_to_split.split()
for item in list_from_string:
print item
#default split() removes all whitespace at the begining and of the string
#condense all adjacent whitespace to single space characters
#split on those spaces
#however....there are a few hangups using split()
print "-"*10
print "-"*10
print "-"*10
print "stringsplit() hangups:"
toes = '''went to the market
stayed home
had roast beef
had none
cried wee wee wee all the way home'''
#splitlines splits all the linebreaks
list_from_string = toes.splitlines()
for toe in list_from_string:
print "this little piggy %s" % toe
print "-"*10
#from the end of the string
last_toe = "and_this_little piggy went wee wee wee all the way home"
#when given a second argument, reverse split counts!!!
list_from_string = last_toe.rsplit(' ', 7)
for item in list_from_string:
print item
print "-"*10
#partition vs. split, similar but different
rhyme = '''There was a crooked man
Who walked a crooked mile.
He found a crooked sixpence
Against a crooked stile.
He bought a crooked cat
Which caught a crooked mouse,
And they all lived together
In a crooked little house.'''
#you can split on words as well as single letters and symbols
split_list = rhyme.split('crooked', 1)
print "List output:"
for item in split_list:
print item
print "-"*10
partition_list = rhyme.partition('crooked')
print "Partition output:"
for item in partition_list:
print item
print "-"*10
print "-"*10
#what if the delimiter doesn't occur within the string?
split_list = rhyme.split('happiness', 1)
print "List output:"
for item in split_list:
print item
partition_list = rhyme.partition('happiness')
print "Partition output:"
for item in partition_list:
print item
print "-"*10
print "-"*10
#split() handles this in a non elegant way
#partition does a better job
# if rhyme.split('happiness')[1]:
# else:
# if rhyme.partition('happiness')[2]:
# else:
#######
#join()
#######
broken = ['hu', 'm', 'pty', ' du', 'mpty']
all_the_kings_horses = 'n~n*^'
all_the_kings_men = '>+O'
first_try = all_the_kings_horses.join(broken)
second_try = all_the_kings_men.join(broken)
if (first_try == 'humpty dumpty') or (second_try == 'humpty dumpty'):
print "hooray!"
else:
print '''All the king's horses and all the king's men couldn't put
Humpty together again'''
print "-"*10
print "-"*10
third_try = ''.join(broken)
print third_try
#when using join you do not need to declare the seperate variables to
# act as glue
fairy_tail_characters = ['witch', 'rapunzel', 'prince']
plot = 'hair'.join(fairy_tail_characters)
print plot
#testing startswith(), endswith(), and find()
|
01789d46c1ad86d62f861f304161d73c6a85c8e8 | Chethanr2/pro1 | /Excerise/argv.py | 332 | 3.546875 | 4 | n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
count = 0; sum = 0
avg = student_marks[query_name]
for i in avg:
count = count + 1
sum = sum + i
val = sum / count
print("{:.2f}".format(val)) |
32ace55d77aa28e2744c4785053be6d6874e833d | abobakrh/Problem-Solving | /odd_even_linklist.py | 746 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
is_odd = True
odd_list = ListNode(0)
odd_head = odd_list
even_list = ListNode(0)
even_head = even_list
while head:
if is_odd:
odd_list.next = head
odd_list = odd_list.next
else:
even_list.next = head
even_list = even_list.next
is_odd = not is_odd
head = head.next
even_list.next = None
odd_list.next = even_head.next
return odd_head.next
|
3a75c782311cca7c22ea8fd36e2824a567c199a7 | ltrujello/Rational_Series | /rational_interpolating_functions.py | 2,448 | 3.609375 | 4 | import math
from loewner_matrix import rational_interpolate
from polynomials_and_series import p_over_q_vals, series
from decimal import *
def rational_interpolate_function_vals(x_data, p, q, return_approximation = False):
'''
Let x_data = [x_1, x_2, ... , x_n]. Let p, q be some functions.
This function analyzes a sequence of values
___ ___
| p(x_0) p(x_1) p(x_n) |
| ------ ------ ------ |
| q(x_0) , q(x_1) , ... , q(x_n) |
___ ___
and finds a rational function
p'(x)
f(x) = ----------
q'(x)
which interpolates the values at the points x_0, x_1, .... , x_n.
Since this is motivated with the goal of interpolating values
so that we can build a rational series, we also compute the infinite sum
\infty
----,
\ p'(k)
/ (1/10)^k ------
----` q'(k)
k = 0
Our goal is to find p', q' so that the above sum equals pi.
___________parameters___________
x_data : (list of floats) x-coordinates for values of interest
numer : (string) numerator of function values we wish to interpolate
denom : (string) denominator of function values we wish to interpolate
Note that numer and denom need to be math functions that Python can understand. For example,
if a factorial appears in the expression, one must write "math.factorial(x)" instead of "x!".
'''
# Evaluate function at points, collect them, call it y_data
y_data = p_over_q_vals(p, q, x_data)
# Interpolate the (x,y) data
inter_p, inter_q, inter_p_exp, inter_q_exp = rational_interpolate(x_data, y_data)
# Inform the reader of the polynomials obtained by interpolation (To do: make it more readable)
# print("NUMERATOR \n", inter_p_exp, "\n")
# print("DENOMINATOR \n", inter_q_exp, "\n")
# Compute and display the infinite sum
summands_for_series = p_over_q_vals(inter_p, inter_q, list(range(0, 100)), coeff = 1/16)
print("SUM: ", Decimal(series(summands_for_series)))
print("ERROR: ", Decimal(math.pi) - Decimal(series(summands_for_series)))
if return_approximation:
return inter_p_exp, inter_q_exp
p = "(16^x)"
q = "(4*x + 1)*(4*x + 3)" |
3739d789f66541308c07ac8c4a2ccfdcfba110a3 | ShuweiLeung/Accurate-Positioning | /Positioning.py | 1,246 | 3.578125 | 4 | #Premise: suppose data is stored in JSON file.
import json
import geoip2.database
class Geo:
def obtainGeo(self, path):
"""
:param path the file path of your JSON file
:return:
"""
input = open(path, "r")
for line in input:
obj = json.loads(line)
ip = obj["ip"]
#load external database to obtain geographical info
#This creates a Reader object. You should use the same object across multiple requests as creation of it is expensive.
reader = geoip2.database.Reader('your path to GeoLite2-City.mmdb')
#Replace "city" with the method corresponding to the database that you are using, e.g., "country".
geo = reader.city(ip)
country_iso_code = geo.country.iso_code #'US'
country = geo.country.name #United States
country_Chinese = geo.country.names['zh-CN'] #u'美国'
state = geo.subdivisions.most_specific.name #'Minnesota'
state_iso_code = geo.subdivisions.most_specific.iso_code #'MN'
city = geo.city.name #'Minneapolis'
postcode = geo.postal.code #'55455'
latitude = geo.location.latitude #'44.9733'
longitude = geo.location.longitude #'-93.2323'
reader.close()
input.close()
|
a417b8085ba4b75ce5421b90016231ba75a53733 | ironboxer/leetcode | /python/1109.py | 1,951 | 3.625 | 4 | """
https://leetcode.com/problems/corporate-flight-bookings/
1109. Corporate Flight Bookings
Medium
555
105
Add to List
Share
There are n flights, and they are labeled from 1 to n.
We have a list of flight bookings. The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to j inclusive.
Return an array answer of length n, representing the number of seats booked on each flight in order of their label.
Example 1:
Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]
Constraints:
1 <= bookings.length <= 20000
1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000
1 <= bookings[i][2] <= 10000
"""
from typing import List
class Solution:
"""
TLE
"""
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * n
for i, j, v in bookings:
# NOTE: slow
for k in range(i-1, j):
res[k] += v
return res
class Difference:
def __init__(self, nums):
assert nums
self.diff = [0] * len(nums)
self.diff[0] = nums[0]
for i in range(1, len(nums)):
self.diff[i] = nums[i] - nums[i-1]
def increment(self, i, j, val):
self.diff[i] += val
if j + 1 < len(self.diff):
self.diff[j + 1] -= val
def result(self):
res = [0] * len(self.diff)
res[0] = self.diff[0]
for i in range(1, len(self.diff)):
res[i] = res[i-1] + self.diff[i]
return res
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
diff = Difference([0] * n)
for i, j, v in bookings:
diff.increment(i-1, j-1, v)
return diff.result()
if __name__ == '__main__':
bookings = [
[1,2,10],
[2,3,20],
[2,5,25]
]
n = 5
print(Solution().corpFlightBookings(bookings, n))
|
d8ce865ec0ffd3f50f33679d5e2c27f0d0749607 | akotwicka/Learning_Python_Udemy | /dziedziczenie.py | 1,825 | 3.6875 | 4 | class Cake:
bakery_offer = []
def __init__(self, name, kind, taste, additives, filling):
self.name = name
self.kind = kind
self.taste = taste
self.additives = additives.copy()
self.filling = filling
self.bakery_offer.append(self)
def show_info(self):
print("{}".format(self.name.upper()))
print("Kind: {}".format(self.kind))
print("Taste: {}".format(self.taste))
if len(self.additives) > 0:
print("Additives:")
for a in self.additives:
print("\t\t{}".format(a))
if len(self.filling) > 0:
print("Filling: {}".format(self.filling))
print('-' * 20)
@property
def full_name(self):
return "--== {} - {} ==--".format(self.name.upper(), self.kind)
class SpecialCake(Cake):
def __init__(self, name, kind, taste, additives, filling, occasion, shape, ornaments, text):
super().__init__(name, kind, taste, additives, filling)
self.occasion = occasion
self.shape = shape
self.ornaments = ornaments
self.text = text
def show_info(self):
super().show_info()
print("Occasion: {}".format(self.occasion))
print("Shape: {}".format(self.shape))
print("Ornaments: {}".format(self.ornaments))
print("Text: {}".format(self.text))
birthday = SpecialCake('birthday cake', 'cake', 'chocolate', ['chocolate', 'coconut','cherries'], 'chocolate cream', 'birthday', 'round', 'flores', 'Happy Birthday')
wedding = SpecialCake('wedding cake', 'cake', 'vanilla', ['raspberries', 'strawberries'], 'vanilla cream', 'wedding', 'round', '-', 'Mrs & Mr')
birthday.show_info()
wedding.show_info()
for i in SpecialCake.bakery_offer:
print(i.full_name)
i.show_info() |
6f6a6dde82e4c5507fb1b2691a62ff1645dd5849 | Vk-Demon/vk-code | /ckcompany16.py | 376 | 3.546875 | 4 | nnum=int(input()) # Given a number N and array of N integers, print the difference between the indices of smallest and largest number(if there are multiple occurances, consider the first occurance).
lt=[int(i) for i in input().split()]
for i in range(0,nnum):
if(lt[i]==max(lt)):
x=i
break
for i in range(0,nnum):
if(lt[i]==min(lt)):
y=i
break
print(x-y)
|
88f1829d01b84a9e2f26ccbc72a08abdd5e5c706 | asefrind/madlib-shapedraw | /ShapeDraw.py | 968 | 4.1875 | 4 | # Shape Drawing
def TriangleDraw():
print(" /|")
print(" / |")
print(" / |")
print(" /___|")
def SquareDraw():
print("----------------")
print("| |")
print("| |")
print("| |")
print("| |")
print("----------------")
def RandomDraw():
print("| - - - - - - | | | |")
print(" | - - - - - | |")
print(" | - - - - | | |")
print(" | - | - - | |")
print(" || | - - |")
print(" |___________________|")
# Let user choose which shape to draw
i = 1
while i < 4:
selector = input("Choose between: Square/Triangle/Random: ")
if selector == "Square":
print(SquareDraw())
elif selector == "Triangle":
print(TriangleDraw())
elif selector == "Random":
print(RandomDraw())
i = i + 1 |
0e7f5c15b99aa1fb921652ac76e83d216db9f506 | WinrichSy/Codewars_Solutions | /Python/6kyu/TotalPrimes.py | 1,339 | 3.984375 | 4 | #Total Primes
#https://www.codewars.com/kata/5a516c2efd56cbd7a8000058
import math
import itertools
#Used for caching values
primed = {}
def is_prime(num):
maximum = math.ceil(math.sqrt(num))
if num%maximum == 0:
return False
for i in range(3, maximum, 2):
if num%i == 0:
return False
return True
def get_total_primes(a, b):
#Gets a list of possible combinations of viable answers
a_len = len(str(a))
b_len = len(str(b))
prime_nums = ['2','3','5','7']
list_of_nums = []
for i in range(a_len, b_len+1):
list_of_nums += itertools.product(prime_nums, repeat=i)
list_of_nums = [int(''.join(i)) for i in list_of_nums]
ans = []
i = 0
while(list_of_nums[i]<a):
i+=1
while(a<=list_of_nums[i] and list_of_nums[i]<b and i<len(list_of_nums)-1):
#If answer is cached, just append it
if list_of_nums[i] in primed or list_of_nums[i]==2:
ans.append(list_of_nums[i])
i+=1
continue
#Skips even numbers
if list_of_nums[i]%2==0:
i+=1
continue
#Will check if value is prime or not
if is_prime(list_of_nums[i]):
ans.append(list_of_nums[i])
primed[list_of_nums[i]] = list_of_nums[i]
i+=1
return(len(ans))
|
c2502c543ef130a14513bc9f8134d7f4c4358718 | Olga404/Node | /main.py | 7,643 | 4.0625 | 4 | class Node():
def __init__(self,value, next_node=None):
self.value = value
self.next_node = next_node
#print(self.value)
def print_list(lst):
tmp=lst
while tmp.next_node!=None:
print (tmp.value,end='->')
tmp=tmp.next_node
print (tmp.value)
def print_rec(lst):#рекурсивно обращается к последующему элементу
print (lst.value,end='')
if lst.next_node!=None:
print ('->',end='')
print_rec(lst.next_node)
import confignode
def copylist(lst): #создает копию листа. создаем узел - в него данные, и т.д
tmp=lst
head=tmp.value #голова,которая пришла
copy=Node(head)
while tmp.next_node!=None: #если не указывает на конец
tmp=tmp.next_node
copy=Node(tmp.value,copy)
if confignode.flag==True:
return reverse(copy)
else: return copy
def reverse(lst):
confignode.flag=False
#print_list(copylist(lst))
return copylist(lst)
#start,middle,end
def add_list(lst,value,location): #lst -наш список,value -что вставить,location - куда вставить
if location=='start':
return Node(value,lst)
else:
if location=='end':
result=Node(value,copylist(lst))
return reverse(result)
else:
if location=='middle':
count=1
lst_copy=lst
lst_copy2=lst
while lst_copy.next_node!=None:
count+=1
lst_copy=lst_copy.next_node
print('длина списка = ',count)
print_list(lst)
pos=int(count/2)+1 #вычисляем середину,куда вставлять число,ну и округляем
print('вставить число на позицию',pos)
res=None
count=1
while lst.next_node!=None:
if pos==count:
res=Node(value,res)#вставка нужного числа
res=Node(lst.value,res)
lst=lst.next_node
count+=1
res=Node(lst.value,res)
if pos==2:
res=Node(lst_copy2.value)
res=Node(value,res)
res=Node(lst.value,res)
return reverse(res)
def del_list(lst,location):
tmp=lst
if location=='start':
return reverse(copylist(lst.next_node))
else:
if location=='end':
return copylist(reverse(tmp).next_node)
else:
if location=='middle':
count=1
lst_copy=lst
lst_copy2=lst
while lst_copy.next_node!=None:
count+=1
lst_copy=lst_copy.next_node
print('длина списка = ',count)
print_list(lst)
pos=int(count/2)+1 #вычисляем середину,откуда удалять число,ну и округляем
print('удалить число с позиции',pos)
res=None
count=1
while lst.next_node!=None:
if pos!=count:
res=Node(lst.value,res)
lst=lst.next_node
count+=1
res=Node(lst.value,res)
return reverse(res)
#конкатенация
def plus(lst,other):
print_list(lst)
print('+')
print_list(other)
print('=')
res=reverse(lst)
while other.next_node!=None:
res=Node(other.value,res)
other=other.next_node
res=Node(other.value,res)
return reverse(res)
#пересечение
def intersection(lst,other):
res = None
while lst!=None:
tmp = other
while tmp!=None:
#print('Сравниваем ',lst.value,'и',tmp.value)
if lst.value == tmp.value:
#print('!')
if res!=None: #если новый список уже не пустой
res = Node(lst.value, res)
else: #если первый эл-т кладем в новый список
res = Node(lst.value)
tmp = tmp.next_node
lst = lst.next_node
return reverse(res)
'''
def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
def bubble_sort(lst):
res=None
tmp=lst
cnt=0
while tmp!=None:
cnt+=1
tmp=tmp.next_node
print(cnt)
j=0
while j!=cnt-1:
res=lst
i=0
while i!=cnt-1:
lst2=lst.next_node
if lst.value>lst2.value:
print(lst.value,'и',lst2.value)
lst.value,lst2.value=lst2.value,lst.value
res=Node(lst.value,res)
lst=lst.next_node
i+=1
j+=1
return res
'''
def bubbleSort(lst,n):
tmp=lst
#длину списка определим
cnt=0
while tmp!=None:
cnt+=1
tmp=tmp.next_node
#print(cnt)
tmp=lst
for passnum in range(cnt-1,0,-1):
lst=tmp
for i in range(passnum):
lst2=lst.next_node
if lst.value>lst2.value:
#print(lst.value,'и',lst2.value)
lst.value,lst2.value=lst2.value,lst.value
lst=lst.next_node
if n=='ascending':
return tmp
else:
if n=='descending':
return reverse(tmp)
#Срезка по последовательности seq (start:finish:step)
def seq(lst,start,finish,step):
print_list(lst)
tmp=lst
res=None
#длину списка определим
cnt=0
while tmp!=None:
cnt+=1
tmp=tmp.next_node
for i in range(cnt):
if i%step==0 and i<=finish and i>=start:
res=Node(lst.value,res)
lst=lst.next_node
return reverse(res)
#temp=tmp.next_node #указатель на следующий
#print_list(temp.value)
node5= Node(2)
node4 = Node(7,node5)
node3 = Node(0, node4)
node2 = Node(4,node3)
node1 = Node(3,node2)
#copylist(node1)
print('Исходный список:')
print_list(node1)
print('Его копия:')
print_rec(copylist(node1))
print('\nОбращение порядка списка на противоположный:')
print_rec(reverse(node1))
#_____________________________________________________
add=0
print('\n\nВставка - в начало cписка числа ',add,':')
print_list(add_list(node1,add,'start'))
print('\nВставка - в конец cписка числа ',add,':')
print_list(add_list(node1,add,'end'))
print('\nВставка - в середину cписка числа ',add,':')
print_list(add_list(node1,add,'middle'))
#_____________________________________________________
print('\n\nУдаление числа из начала cписка')
print_list(del_list(node1,'start'))
print('\nУдаление числа из конца cписка')
print_list(del_list(node1,'end'))
print('\nУдаление числа из середины cписка')
print_list(del_list(node1,'middle'))
#_____________________________________________________
print('\n\nКонкатенация')
print_list(plus(node1,node3))
#_____________________________________________________
print('\n\nПересечение')
print_list(intersection(node1,node3))
#_____________________________________________________
'''
print('\n\nСортировка пузырьком')
#ascending descending по возрастанию,по убыванию
print('\nпо возрастанию')
print_list(bubbleSort(node1,'ascending'))
print('\nпо убыванию')
print_list(bubbleSort(node1,'descending'))
'''
#_____________________________________________________
start=3
finish=4
step=1
print('\n\nСрезка с позиции',start,'по позицию',finish,'с шагом=',step)
print_list(seq(node1,start,finish,step))
|
15b7d4632ed2c70f90d48d42f3223414e0ad0373 | PC-coding/Exercises | /data_structures/linked_lists/2_search_item/solution/solution.py | 455 | 3.96875 | 4 | # Write your solution here
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class linkedList:
def __init__(self, head=None):
self.head = head
def search(self, x):
current_node = self.head
while not current_node is None:
if current_node.data == x:
return True
else:
current_node = current_node.next
return False |
b10f23f87c3eee2b27adefca83d7d6886ad4b88c | BlackBloodLT/URI_Answers | /Python3/1_INICIANTE/uri1002.py | 880 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Área do Círculo
A fórmula para calcular a área de uma circunferência é: area = π . raio2.
Considerando para este problema que π = 3.14159:
- Efetue o cálculo da área, elevando o valor de raio ao quadrado e
multiplicando por π.
Entrada
A entrada contém um valor de ponto flutuante (dupla precisão), no caso, a
variável raio.
Saída
Apresentar a mensagem "A=" seguido pelo valor da variável area, conforme
exemplo abaixo, com 4 casas após o ponto decimal. Utilize variáveis de dupla
precisão (double). Como todos os problemas, não esqueça de imprimir o fim de
linha após o resultado, caso contrário, você receberá "Presentation Error".
"""
"""
Created on Thu May 6 21:49:16 2021
@author: lamarkscavalcanti
"""
raio = float(input())
areaCirculo = pow(raio,2)*3.14159
print("A=%0.4f" %areaCirculo) |
e0d4bcf086f5186be4855598622a6936796c9360 | jnoriega3/final-project | /new.py | 1,619 | 4.21875 | 4 | import random
from random import shuffle
words=("github", "shell", "bacon", "variables", "boolean values", "operators", "functions", "lists", "the none value", "global scope", "for and while loops", "in and not operators")
#Codinng Joke (meant for word scramble ...My code is not working, I have no idea why---My code works, I have know idea why!
print()
print('.............Welcome to Words with Coders..........')
print()
print('.....Brought to you by the 2016 Valencia Automaters......')
print()
play=input(" ..Do you want to play? (yes, no, or enter to quit)")
while play=="yes":
word=random.choice(words)
correct=word
scramble=""
while word:
position = random.randrange(len(word))
scramble += word[position]
word = word[:position] + word[(position + 1):]
print()
print("Your scramble is:", scramble)
points=100
guess=input("\nYour Guess:")
while guess != correct and guess !="":
print()
print()
print("Guess again!")
print()
print("Really? You can't figure it out?")
guess = input("Your guess:")
if guess == correct:
print("Exactly right!!\n")
print("And your final score is..."+str(points))
print()
play=input(" ..Do you want to play? (yes, no, or enter to quit)")
print()
print("thanks for hanging Python Master!")
input("]\n\nI hope you enjoyed the praced on the word with Python. Presss the enter key to exit. Come back soon!")
|
73e03491435f4f8de13335c2bde385df516d90b0 | iulian39/UBB | /1st year/First Semester/Fundamentals of programming - python/Lab5-7/BookClass.py | 8,870 | 3.71875 | 4 | import copy
class Book:
def __init__(self, repo):
self.__repo = []
self.__availableBooks = []
self.__repo = copy.deepcopy(repo)
self.__availableBooks = copy.deepcopy(repo.getAll())
def AddNewBooks(self, ID, title, description, author):
'''
Adds a new book to the list
'''
if len(title) == 0 or len(author) == 0:
return False
while True:
try:
ID = int(ID)
if self.__repo.CheckId(ID):
break
else:
return False
except ValueError:
return False
self.__repo.add(ID, title, description, author)
self.__availableBooks.append(self.__repo.lastItem())
return True
def VerifyID(self, id):
'''
Verifies if there exists the given id into the list.
'''
return self.__repo.CheckId(id)
def List(self):
'''
Prints the list of books
'''
for i in self.__repo.getAll():
print(i)
def RemoveBooks(self, ID, Rentals):
'''
Removes a book from the list
'''
while True:
if len(self.__repo.getAll()) == 0:
return False
try:
ID = int(ID)
if not self.__repo.CheckId(ID):
break
else:
return False
except ValueError:
return False
self.__repo.remove(ID)
for i in Rentals.getAllRentals():
if i.bookID == ID:
i.removeBookId(ID)
break
self.removeAvailbaleBook(ID)
return True
def ModifyTitle(self, idOfBook, newTitle):
'''
Modifies the title of a book
'''
while True:
try:
idOfBook = int(idOfBook)
if not self.__repo.CheckId(idOfBook):
break
else:
return False
except ValueError:
return False
if len(newTitle) > 0:
self.__repo.updateTitle(idOfBook, newTitle)
for i in self.__availableBooks:
if i.id == idOfBook:
i.title = newTitle
return True
else:
return False
def ModifyDescription(self, idOfBook, newDescription):
'''
Modifies the description of a book
'''
while True:
try:
idOfBook = int(idOfBook)
if not self.__repo.CheckId(idOfBook):
break
else:
return False
except ValueError:
return False
self.__repo.updateDescription(idOfBook, newDescription)
for i in self.__availableBooks:
if i.id == idOfBook:
i.description = newDescription
return True
def ModifyAuthor(self, idOfBook, newAuthor):
'''
Modifies the author of a book
'''
while True:
try:
idOfBook = int(idOfBook)
if not self.__repo.CheckId(idOfBook):
break
else:
return False
except ValueError:
return False
if len(newAuthor) == 0:
return False
self.__repo.updateAuthor(idOfBook, newAuthor)
for i in self.__availableBooks:
if i.id == idOfBook:
i.author = newAuthor
return True
def ModifyID(self, oldID, newId):
'''
Modifies the id of a book
'''
while True:
try:
oldID = int(oldID)
if not self.__repo.CheckId(oldID):
break
else:
return False
except:
return False
while True:
try:
newId = int(newId)
if self.__repo.CheckId(newId):
break
else:
return False
except ValueError:
return False
self.__repo.updateID(oldID, newId)
for i in self.__availableBooks:
if i.id == oldID:
i.id = newId
return True
def setRepo(self, newRepo):
self.__repo.ItemsInRepo(newRepo)
def getAllBooks(self):
"""
Return all repository data
Returns the live list of the repository
"""
return self.__repo
def getAllBook(self):
"""
Return all repository data
Returns the live list of the repository
"""
return self.__repo.getAll()
def getAllAvailbleBooks(self):
"""
Return all repository data
Returns the live list of the repository
"""
return self.__availableBooks
def removeAvailbaleBook(self, ID):
'''
Removes a book from the availableBooks list only, the book list is not affected
'''
for i in range(len(self.__availableBooks) - 1, -1, -1):
if self.__availableBooks[i].id == ID:
del self.__availableBooks[i]
return True
return False
def addNewAvailableBook(self, bookID):
'''
Adds back a book from the list into the available books
'''
for i in self.__repo.getAll():
if i.id == bookID:
self.__availableBooks.append(i)
return True
return False
def UpdateStatistics(self, bookID):
'''
Updates the statistics of a book
'''
ok = False
for i in self.__repo.getAll():
if i.id == bookID:
i.IncrementRentals()
ok = True
if ok == True:
return True
else:
return False
def PrintMostRentedBooks(self):
'''
Prints the list descending by the most rented books
'''
# for i in self.__repo.sortByRentals():
# print(str(i) + " RENTED : " + str(i.getRentals()) + " TIME(S)")
return self.__repo.sortByRentals()
def saveTEXT(self, fileName):
'''
Calls the function from the repository that saves the file
'''
return self.__repo.writeBooksText(fileName)
def saveDB(self, c, conn):
return self.__repo.writeBooksDatabase(c, conn)
def savePICKLE(self, fileName):
'''
Calls the function from the repository that saves the file
'''
return self.__repo.writeBooksPickle(fileName)
def PrintMostRentedAuthor(self):
'''
Prints the list descending by the most rented author
'''
newList = []
for i in self.__repo.getAll():
ok = False
if i.getRentals() > 0:
for j in newList:
if j[0] == i.author:
j[1] += i.rentals
ok = True
if ok == False:
s = [i.author, i.rentals]
newList.append(s)
if len(newList) == 0:
return
newList.sort(key=lambda newList: newList[0])
newList.sort(key=lambda newList: newList[1], reverse=True)
return newList
# for i in newList:
# ok = False
# printed = False
# for j in self.__repo.getAll():
# if i[0] == j.author:
# if printed == False:
# print("Author : " + j.author)
# printed = True
# print(j)
# ok = True
# if ok == True:
# print("Number of rentals : " + str(i[1]))
# @staticmethod
# def printList(list):
# '''
# Prints the books having the same author
# '''
# sum = 0
# for i in sorted(list, key=lambda x: x.rentals, reverse=True):
# print(i)
# sum += i.getRentals()
# print("Total: ", sum)
def SearchBooks(self, Title):
'''
Searches for books having a certain title/part of title
'''
list = []
if len(Title) > 0:
Title = Title.lower()
ok = False
for i in self.__repo.getAll():
if i.title.lower().find(Title) != -1:
list.append(i)
ok = True
if ok == True:
return list
else:
return False
else:
return False
def getLen(self):
'''
Returns the lenght of the book list
'''
return len(self.__repo.getAll())
|
b62b47d5fce39cc1310af6f1d3be347ca2e15baa | ArpanMajumdar/tech-knowledge-base | /languages/python/python-examples/src/formatting_and_linting_demo.py | 240 | 3.609375 | 4 | # Type hints
def print_hello(name: str) -> str:
"""
Returns a greeting message
:param name: Name of person
:return: Hello message
"""
msg = "Hello " + name + " !"
print(msg)
return msg
print_hello("Arpan")
|
3f8a0444948177807771a6134dfdf5a026f91c0d | DJSiddharthVader/PycharmProjects | /PythonPractice/2. Even or Odd.py | 935 | 4.3125 | 4 | '''Ask the user for a number. Depending on whether the number is even or odd, print out
an appropriate message to the user. Hint: how does an even / odd number react differently
when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two numbers: one number to check (call it num) and one number
to divide by (check). If check divides evenly into num, tell that to the user.
If not, print a different appropriate message.'''
def oddoreven(x,y)
x = int(input("Enter a number: "))
y = int(input("Enter a second number: "))
if y != 0:
if x%y == 0:
print("does divide evenly")
else:
print("doesn't divide evenly")
else:
if x%2 == 0:
if x%4 == 0:
print("divisible by 4")
else:
print("Even")
else:
print("Odd")
|
b84b69e4445cac8c2923c8f474ba1ba48120c3a6 | schwerdt/Yahoo_and_API | /exercise1.py | 3,568 | 3.9375 | 4 | import urllib
import sys
import csv
import datetime
#The base url for yahoo finance to get stock prices is stored as a global
#Update it here if it ever changes
yahoo_url ="http://real-chart.finance.yahoo.com/table.csv?s="
def compute_stock_data():
#Ask the user for a ticker symbol, starting and ending dates
ticker_symbol = input('Input your ticker symbol as a string: ')
print "We also need the date range for stock data you want to look at."
begin_date = input("Beginning date (YYYY-MM-DD): ")
end_date = input("Ending date (YYYY-MM-DD): ")
#Check date range (make sure end date is after begin date)
if not check_date_range(begin_date,end_date):
print "Your ending date was before your beginning date."
sys.exit()
#Try to download the file for this ticker symbol
data_file = retrieve_stock_data_file(ticker_symbol,begin_date,end_date)
print("We retrieved the stock data")
#Read the file into a list of dictionaries
with open(data_file) as f:
data_table = [val for val in csv.DictReader(f,delimiter=',')]
print " Week Ave Volume"
for row in data_table:
print row['Date'], row['Volume']
#Build the url needed to get the csv file. This requires converting parameters
#from the date range and from the ticker symbol into the url string.
def retrieve_stock_data_file(ticker_symbol,begin_date,end_date):
#Get the day,month, year for the begin and end date
begin_date = begin_date.split('-')
end_date = end_date.split('-')
#Determine the numerical parameters for the begin and end date
begin_year = begin_date[0]
begin_month = int(begin_date[1]) - 1
begin_day = begin_date[2]
end_year = end_date[0]
end_month = int(end_date[1]) - 1
end_day = end_date[2]
#The month should be in the form 01 for Feb, 11 for Dec
if begin_month < 10:
begin_month = '0' + str(begin_month)
else:
begin_month = str(begin_month)
if end_month < 10:
end_month = '0' + str(end_month)
else:
end_month = str(end_month)
stock_url = yahoo_url + ticker_symbol
#Add begin date
stock_url = stock_url + '&a=' + begin_month + '&b=' + begin_day + '&c=' + begin_year
stock_url = stock_url + '&d=' + end_month + '&e=' + end_day + '&f=' + end_year
#Averaged weekly (g = w)
stock_url = stock_url + '&g=w'
#Get the .csv file
stock_url = stock_url + '&ignore=.csv'
stock_filename = ticker_symbol + '.csv'
print stock_url
#Try to download it (*try* because we don't know if the user gave us a valid ticker symbol.)
urllib.urlretrieve(stock_url,stock_filename)
#We don't know if the user gave us a valid ticker symbol, so we need to
#make sure the file is not a 'Not Found' page
with open(stock_filename) as f:
filedata = f.readlines()
searchfile = [val.find('Not Found') for val in filedata if val.find('Not Found') != -1]
if len(searchfile) != 0:
print "The page was not found. Your ticker symbol or your date range may not"
print "be valid."
sys.exit()
else:
return stock_filename
def check_date_range(begin_date,end_date):
begin_date = begin_date.split('-')
end_date = end_date.split('-')
begin_date = datetime.date(int(begin_date[0]),int(begin_date[1]),int(begin_date[2]))
end_date = datetime.date(int(end_date[0]),int(end_date[1]),int(end_date[2]))
#Returns true if the beginning date is earlier than the ending date
return begin_date < end_date
|
47a2d5d72dd29ea7c960619de24a87a5b4e4a2c2 | nightjuggler/puzzles | /honeycomb.py | 3,045 | 3.96875 | 4 | #!/usr/bin/python
#
# This is a constant time solution to the honeycomb cell distance puzzle at https://affirm.com/jobs
# by Pius Fischer -- March 1, 2013
#
import math
import sys
def get_xy_for_cell(cell):
assert isinstance(cell, int) and cell > 0
# Determine which ring the cell is located in.
# Ring 0 consists only of cell 1.
# Ring 1 consists of the 6 cells 2 through 7.
# Each subsequent ring contains 6 more cells than the previous ring.
# So the n'th ring (for n > 0) has 6*n cells and the first n rings have a total
# of 1 + 6 + 12 + ... + 6 * n cells.
# This is equivalent to 1 + 6 * (1 + 2 + ... + n) = 1 + 6 * n * (n + 1) / 2
# which is 1 + 3 * n * (n + 1).
# So to find the ring a given cell is located in, we want to solve the following:
# cell = 3 * ring * (ring + 1) + 1
# Let's say c = (cell - 1) / 3
# Then we have c = ring^2 + ring
# Using the quadratic formula, we get ring = (-1 + sqrt(1 + 4 * c)) / 2
ring = int(math.ceil((math.sqrt(4 * (cell - 1.0) / 3 + 1) - 1) / 2))
# Determine the position (counterclockwise from 0 to 6*ring-1) within the ring.
position = 3 * ring * (ring + 1) + 1 - cell
# Now determine x and y.
# x
# -5 -4 -3 -2 -1 0 1 2 3 4
# -3 48 28 29 30 31 54
# -2 47 27 13 14 15 32 55
# -1 46 26 12 4 5 16 33 56
# y 0 45 25 11 3 1 6 17 34 57
# 1 70 44 24 10 2 7 18 35 58
# 2 69 43 23 9 8 19 36 59
# 3 68 42 22 21 20 37 60
# 4 67 41 40 39 38 61
# Start with position 0: x = 0, y = ring
# For each position between 1 and ring: x += 1, y -= 1
# For each position between ring+1 and 2*ring: y -= 1
# For each position between 2*ring+1 and 3*ring: x -= 1
# For each position between 3*ring+1 and 4*ring: x -= 1, y += 1
# For each position between 4*ring+1 and 5*ring: y += 1
# For each position between 5*ring+1 and 6*ring-1: x += 1
x_mult = (1, 0, -1, -1, 0, 1)
y_mult = (-1, -1, 0, 1, 1, 0)
i = 0
x = 0
y = ring
while i < 6:
delta = position - i * ring
if delta <= ring:
x += delta * x_mult[i]
y += delta * y_mult[i]
break
x += ring * x_mult[i]
y += ring * y_mult[i]
i += 1
assert i < 6
return x, y
def get_distance(x1, y1, x2, y2):
assert isinstance(x1, int)
assert isinstance(y1, int)
assert isinstance(x2, int)
assert isinstance(y2, int)
delta_x = x1 - x2
delta_y = y1 - y2
abs_delta_x = delta_x if delta_x >= 0 else -delta_x
abs_delta_y = delta_y if delta_y >= 0 else -delta_y
if (delta_x < 0 and delta_y > 0) or (delta_x > 0 and delta_y < 0):
return abs_delta_y if abs_delta_x < abs_delta_y else abs_delta_x
return abs_delta_x + abs_delta_y
if __name__ == '__main__':
cell1 = int(sys.argv[1])
cell2 = int(sys.argv[2])
x1, y1 = get_xy_for_cell(cell1)
x2, y2 = get_xy_for_cell(cell2)
distance = get_distance(x1, y1, x2, y2)
print "The distance between cells %u (%d, %d) and %u (%d, %d) is %u." % (
cell1, x1, y1, cell2, x2, y2, distance)
|
00d4f0bc4f4deb099352d73d9084f2bdafe0c94b | kathuman/Python3_Essential_Training | /04 Syntax/syntax-objects.py | 701 | 4 | 4 | #!/usr/bin/python3
# syntax.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Egg: #class is like a blue print, which defines how the object is created.
def __init__(self, kind = 'fried'): # this is a constructor
self.kind = kind
def whatKind(self):
return self.kind
def main():
fried = Egg() #creat an object called 'fried', based on the class called "Egg".
# The object encapsulate all the data and functions defined in the class.
scrambled = Egg('scrambled')
print(fried.whatKind())
print(scrambled.whatKind())
if __name__ == "__main__": main()
|
9b82bb8c64299540e0bb9659d1944cac8c0370dc | Graziellah/BootCampPython | /d01/ex00/book.py | 1,303 | 3.671875 | 4 | from recipe import Recipe
import datetime
import time
class Book:
def __init__(self):
self.name = ""
self.last_update = ""
self.creation_date = datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
self.recipes_list = {
"starter": {},
"lunch": {},
"dessert": {}
}
def get_recipe_by_name(self, name):
for elem in self.recipes_list.keys():
if self.recipes_list[elem].get(name):
display = str(self.recipes_list[elem][name])
print(display)
def get_recipes_by_types(self, recipe_type):
if recipe_type in self.recipes_list:
for elem in self.recipes_list[recipe_type].keys():
print("- ", elem)
def add_recipe(self, recipe):
if isinstance(recipe, Recipe):
if "cookies" in self.recipes_list[recipe.recipe_type].keys():
error = recipe.name + " already exist in books for "
error += recipe.recipe_type + " meal"
print(error)
self.recipes_list[recipe.recipe_type][recipe.name] = recipe
self.last_update = datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
else:
raise ValueError("Argument is not a Recipe instance")
|
8c7032d85476c0f3d4d4d80c3d58e953e16d30f9 | volkir31/university | /lab1/31_task.py | 264 | 3.90625 | 4 | max_digit = 0
index_of_digit = -1
max_digit_index = -1
while True:
digit = int(input())
index_of_digit += 1
if digit > max_digit:
max_digit = digit
max_digit_index = index_of_digit
if digit == 0:
break
print(max_digit_index) |
453dd5c39ad68db8772b6c6b42c72055d6324a1f | UmangAgrawal1998/cancer | /SpeechAVA.py | 482 | 3.859375 | 4 | #Importing the Pyttsx3 module for text to speech conversion
import pyttsx3
#Function to convert text to speech passed as value
def speech(text):
engine=pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
rate = engine.getProperty('rate')
engine.setProperty('rate', rate-20)
engine.say(text)
engine.runAndWait()
'''text='enter'
while text!='exit':
speech(text)
text = str(input('Enter the text: '))'''
|
77db21342482e78e1960c72c312b72e7be1abb56 | irakliintskirveli/python-challenge | /ananlyzePyPoll/main.py | 487 | 3.640625 | 4 | import os
import csv
# Files to load (Remember to change these)
file_to_load = "election_data_2.csv"
#open the csv file
with open(file_to_load) as election:
reader=csv.reader(election)
#skipp headers, 1st row
#Set empty list variable
next(reader)
totalvotes = [ ]
#loop through the row to count vote ID
for row in reader:
totalvotes.append(row[0])
print("Election Results")
print("-----------------------------------")
print("Total Votes:", len(totalvotes))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.