blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
3d7a0e3a35de1daaee1c1d4d57bc6d2b1cfb778a | XavierKoen/cp1404_practicals | /prac_02/files.py | 1,023 | 3.828125 | 4 | """
Do-from-scratch Exercises: Files section
The 4 different tasks are outlined in blocks of code.
"""
# User enters name, which is written into name.txt file.
name = input("Please enter name: ")
out_file_name = open("name.txt", "w")
print(name, file=out_file_name)
out_file_name.close()
# name.txt is opened and read, printing the line with string formatting.
in_file_name = open("name.txt", "r")
print("Your name is {}".format(in_file_name.read()))
in_file_name.close()
# numbers.txt is opened and read, calculating the addition of line 1 and 2 as integers.
# Result is printed.
in_file_numbers = open("numbers.txt", "r")
line1 = int(in_file_numbers.readline())
line2 = int(in_file_numbers.readline())
result = (line1 + line2)
print(result)
in_file_numbers.close()
# numbers.txt is opened and read, while the total for all lines is calculated and printed
# as floating point numbers.
in_file_numbers = open("numbers.txt", "r")
total = 0
i = 0
for line in in_file_numbers:
total = total + float(line)
print(total)
|
15dbca45f3fbb904d3f747d4f165e7dbca46c684 | XavierKoen/cp1404_practicals | /prac_01/loops.py | 924 | 4.5 | 4 | """
Programs to display different kinds of lists (numerical and other).
"""
#Basic list of odd numbers between 1 and 20 (inclusive).
for i in range(1, 21, 2):
print(i, end=' ')
print()
#Section a: List counting in 10s from 0 to 100.
for i in range(0, 101, 10):
print(i, end=' ')
print()
#Section b: List counting down from 20 to 1.
for i in range(1, 21):
j = 21 - i
print(j, end=' ')
print()
#Section c: Print number of stars (*) desired on one line.
number_of_stars = int(input("Number of stars: "))
for i in range(1, number_of_stars + 1):
print("*",end="")
print()
#Section d: Print desired number of lines of stars (*) with increasing number of stars in each line.
# Beginning with one and finishing with desired number.
number_of_stars = int(input("Number of stars: "))
for i in range(1, number_of_stars + 1):
for j in range(1, i + 1):
print("*",end="")
print()
print() |
e1e5bdeab07475e95a766701d6feb6e14fe83494 | XavierKoen/cp1404_practicals | /prac_02/password_checker.py | 2,067 | 4.53125 | 5 | """
CP1404/CP5632 - Practical
Password checker code
"""
MIN_LENGTH = 2
MAX_LENGTH = 6
SPECIAL_CHARS_REQUIRED = False
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get and check a user's password."""
print("Please enter a valid password")
print("Your password must be between {} and {} characters, and contain:".format(MIN_LENGTH, MAX_LENGTH,))
print("\t1 or more uppercase characters")
print("\t1 or more lowercase characters")
print("\t1 or more numbers")
if SPECIAL_CHARS_REQUIRED:
print("\tand 1 or more special characters: {}".format(SPECIAL_CHARACTERS))
password = input("> ")
while not is_valid_password(password):
print("Invalid password!")
password = input("> ")
print("Your {}-character password is valid: {}".format(len(password), password))
def is_valid_password(password):
"""Determine if the provided password is valid."""
# Establish counter variables.
count_lower = 0
count_upper = 0
count_digit = 0
count_special = 0
# If length is wrong, return False.
if MIN_LENGTH <= len(password) <= MAX_LENGTH:
# Count each character using str methods.
for char in password:
count_lower = count_lower + int(char.islower())
count_upper = count_upper + int(char.isupper())
count_digit = count_digit + int(char.isdigit())
# Return False if any are zero.
if count_lower == 0 or count_upper == 0 or count_digit == 0:
return False
else:
# Count special characters from SPECIAL_CHARACTERS string if required.
# Return False if count_special is zero.
if SPECIAL_CHARS_REQUIRED:
for char in password:
count_special = count_special + int(char in SPECIAL_CHARACTERS)
if count_special == 0:
return False
else:
return False
# If we get here (without returning False), then the password must be valid.
return True
main()
|
8b42879e37d01ff9e85cfbb135b8e0b2df6f9882 | XavierKoen/cp1404_practicals | /prac_06/guitars.py | 1,353 | 3.96875 | 4 | """
Program to store information on all of the user's guitars.
"""
from prac_06.guitar import Guitar
def main():
"""
User continually prompted to input guitar make and model name, year of manufacturing, and cost until a blank name is
entered.
Information for each guitar is stored as an instance of the Guitar class.
Each guitar instance is stored as a list of all guitars.
Displays all guitar information nicely formatted, including whether vintage or not (50 years old or more).
Vintage state is determined by Guitar class method .is_vintage.
"""
print("My Guitars!")
my_guitars = []
name = input("Name: ")
while name != '':
year = int(input("Year: "))
cost = float(input("Cost: $"))
new_guitar = Guitar(name, year, cost)
my_guitars.append(new_guitar)
print("{} ({}) : ${} added.".format(name, year, cost))
name = input("Name: ")
print("\n...snip...\n")
print("These are my guitars:")
for i, guitar in enumerate(my_guitars):
if guitar.is_vintage():
vintage_string = " (vintage)"
else:
vintage_string = ""
print("Guitar {}: {:>20} ({}), worth ${:10,.2f}{}".format(i + 1, guitar.name, guitar.year, guitar.cost,
vintage_string))
|
5e687f495c8671d1534c6d74793fee0ad95b66d9 | kaminee1jan/logical-q.py | /count_space_in_string.py | 578 | 3.734375 | 4 | # def check_space(string):
# count = 0
# i=0
# while i<len(string):
# if string[i] == " ":
# count=count+1
# i=i+1
# return count
# string = input("enter the string,,,,,,,,")
# print("number of spaces ",check_space(string))
list1=[10,11,12,13,14,17,18,19]
num=30
i=0
empty=[]
while i<len(list1):
j=i
empty1=[]
while j<len(list1):
if list1[i]+list1[j]==num:
empty1.append (list1[i])
empty1.append(list1[j])
empty.append(empty1)
j=j+1
i=i+1
print(empty)
|
63bb6dd21f15341732cb88f32e75779ea3dfd0c8 | marcinsztajn/BlackJackGame | /black_jack.py | 5,507 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 26 21:13:10 2020
Black jack game in Python
@author: Marcin
"""
import random
suites = ["Clubs","Hearts","Diamonds","Spades"]
ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace']
values = {"Two":2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10,
"Jack":10, "Queen":10, "King":10, "Ace":11}
min_chips = 100
max_chips = 1000
dealers_treshold = 17
# Card class
class Card:
def __init__(self,suite,rank):
self.suite = suite
self.rank = rank
self.value = values[rank]
def __str__(self):
return self.rank + ' of ' + self.suite
class Deck:
def __init__(self):
self.all_cards = []
for suite in suites:
for rank in ranks:
self.all_cards.append(Card(suite,rank))
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
class Player:
def __init__(self, name, bankroll):
self.name = name
self.bankroll = bankroll
def __str__(self):
return self.name + ' has ' + self.bankroll + "$"
def ask_for_bet(max_bet):
bet = 0
while bet == 0:
try:
bet = int(input(f"Provide the bet amount (available: {max_bet}): "))
except:
print("Provide an integer value!")
bet = 0
else:
if bet > max_bet:
print(f"Provided amount is to high. Value need to be less or equal to {max_bet}")
bet = 0
else:
return bet
def hit_or_stand():
decision = ''
while decision == '':
decistion = input("Hit or stay? (H/S): ")
if decistion.lower() in ['h','s']:
return decistion.lower()
else:
decistion = ''
def play_again():
decision = ''
while decision == '':
decistion = input("Do you wan to play again? (y/n): ")
if decistion.lower() in ['y','n']:
return decistion.lower()
else:
decistion = ''
# game logic implementation
username = input("Provide your username: ")
bankroll = 0
while bankroll not in range(min_chips,max_chips+1):
bankroll = int(input(f"Provide the bankroll (not more than {max_chips}$):"))
player = Player(username, bankroll)
deck = Deck()
deck.shuffle()
while True:
# as for bet
round_busted = False
dealer_cards = []
player_cards = []
player_points = 0
dealer_points = 0
in_game = 0
in_game = ask_for_bet(player.bankroll) # runs unitil provided value is correct
player.bankroll = player.bankroll - in_game
in_game = 2*in_game
# give two cards for player and dealer
dealer_cards.append(deck.deal_one())
dealer_cards.append(deck.deal_one())
player_cards.append(deck.deal_one())
player_cards.append(deck.deal_one())
#show player one of the dealers card
#add dealers points
dealer_points += dealer_cards[-1].value
print(f"Dealers first card is: {dealer_cards.pop()} with {dealer_points} points")
#show players cards and add points
for card in player_cards:
player_points += card.value
print(f"Yours cards are: {player_cards.pop()} and {player_cards.pop()} with {player_points} points total")
decision = hit_or_stand()
while decision == 'h':
# get a card from the deck
card = deck.deal_one()
if card.rank == "Ace" and player_points > 10:
player_points += 1
# print(f"You got {card} with 1 point. Your total points: {player_points}")
else:
player_points += card.value
# print(f"You got {card} with {card.value} points. Your total points: {player_points}")
if player_points > 21:
print("You are busted!!!")
round_busted = True
break
print(f"You got {card} and your points are {player_points}")
decision = hit_or_stand()
# computer get card
while dealer_points < dealers_treshold and not round_busted:
card = deck.deal_one()
if card.rank == "Ace" and dealer_points > 10:
dealer_points += 1
print(f"Dealer got {card} with {1} point. Total points {dealer_points}")
else:
dealer_points += card.value
print(f"Dealer got {card} with {card.value} points. Total points {dealer_points}")
if dealer_points > 21:
print("Dealer got busted!!!")
round_busted = True
player.bankroll += in_game
print(f"Congratulations, you won this round and {in_game} points")
print(f"Total {player.bankroll} points")
if not round_busted:
# Compare who has more points
print(f"Your points: {player_points} and Dealer's points {dealer_points}")
if player_points > dealer_points:
print(f"Congratulations, you won this round and {in_game} points")
player.bankroll += in_game
print(f"Total {player.bankroll} points")
elif player_points < dealer_points:
print(f"You lost this round. Your total points: {player.bankroll}")
else:
#tie
print("It was a tie!")
player.bankroll += in_game/2
decision = play_again()
if decision == 'n':
break
|
91b0fa7a85059b9db6200d4a4b75d79dfaa4c3ae | TigranDanielyan/eng-115-2020-Calendar-Suggestion-System-master-version2 | /engs-2020-Calendar-Suggestion-System-master/administrator.py | 428 | 4.03125 | 4 | import HashTable3
def main():
print("you as an administrator body can add and delete students for the start of the cycle of exam day starts")
type = input("if you need to add student from list please enter Add in opposite case please enter Delete")
if type == "Add":
HashTable3.creator()
elif type == "Delete":
HashTable3.deleter()
else:
print("something went wrong proggram ends")
|
3bf05089d63d1e641e6db6a2893e8402ca724d1f | pcrease/song_lyrics_scraper | /scraper.py | 5,107 | 3.59375 | 4 | '''
Created on 05.03.2013
@author: Paul Crease
'''
from bs4 import BeautifulSoup
import re
import psycopg2
import urllib2
def addToDatabase(dataObject):
conn_string = "host='localhost' dbname='postgres' user='postgres' password='platinum'"
# print the connection string we will use to connect
#print "Connecting to database\n ->%s" % (conn_string)
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)
# conn.cursor will return a cursor object, you can use this cursor to perform queries
cursor = conn.cursor()
#print "Connected!\n"
song_link=dataObject[0]
if song_link.__len__()>250:
song_link=song_link[:249]
artist_name=dataObject[1]
if artist_name.__len__()>100:
artist_name=artist_name[:99]
song_title=dataObject[2]
if song_title.__len__()>100:
song_title=song_title[:99]
genre=dataObject[3]
if genre.__len__()>100:
genre=genre[:100]
lyrics=dataObject[4]
#print artist_name+" "+song_title+" "+song_link+" "+genre+" "+lyrics
cursor.execute("INSERT INTO song_lyrics(artist_name ,song_title,song_link,genre,lyrics) VALUES (%s, %s,%s, %s,%s)",(artist_name, song_title,song_link,genre,lyrics))
conn.commit()
# execute our Query
#cursor.execute("SELECT * FROM song_lyrics")
# retrieve the records from the database
#records = cursor.fetchall()
cursor.close()
conn.close()
# print out the records using pretty print
# note that the NAMES of the columns are not shown, instead just indexes.
# for most people this isn't very useful so we'll show you how to return
# columns as a dictionary (hash) in the next example.
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--.*-->', str(element)):
return False
return True
def getArtistSongGenre(pageText, dataObject):
for line in pageText:
if line.find("cf_page_artist")>-1:
#print line+str(line.find("cf_page_artist"))
artist=line[line.find("cf_page_artist")+18:line.find("cf_page_song")-3]
song=line[line.find("cf_page_song")+16:line.find("cf_page_genre")-3]
genre=line[line.find("cf_page_genre")+17:line.find("cf_adunit_id")-3]
dataObject.append(artist)
dataObject.append(song)
dataObject.append(genre)
break
def getLyrics(songString, dataObject):
Lyricurl="http://www.sing365.com/"+songString
try:
LyricPage=urllib2.urlopen(Lyricurl)
except urllib2.HTTPError, err:
if err.code == 404:
print "error 404"
return
else:
print "error other than 404"
return
lyricPageSoup = BeautifulSoup(LyricPage.read())
lyricsDiv=lyricPageSoup.findAll(text=True)
getArtistSongGenre(lyricsDiv, dataObject)
concatText=""
visible_texts = filter(visible, lyricsDiv)
for text in visible_texts:
if text.find("Please")>-1:
dataObject.append(concatText)
#for dObject in dataObject:
#print "33"+dObject
addToDatabase(dataObject)
#print "end of song\n"
break
else:
if text.__len__()>1 and text.find("Lyric")==-1 and text.find("Review")==-1:
concatText=concatText+text.strip('\r\n')
concatText=concatText+", "
#print concatText
continue
#for lyricLine in lyricsDiv:
#print(str(lyricLine))
#matches=re.findall(r'\"(.+?)\"',str(lyricLine))
#if lyricLine.find("page_artist")>0:
#if lyricLine.string!=None:
# print lyricLine
def getSongList(hrefString):
Listurl="http://www.sing365.com/"+hrefString
songListPage=urllib2.urlopen(Listurl)
soupSongListPage = BeautifulSoup(songListPage.read())
songs=soupSongListPage.findAll('a')
for song in songs:
songString= song['href']
if songString.find("lyrics")>0:
dataObject = []
dataObject.append(songString)
#print "song title = "+ songString
getLyrics(songString, dataObject)
#print soup.prettify(None, "minimal")
for i in range(1,12):
if i==1:
url="http://www.sing365.com/artist/m.html"
else:
url="http://www.sing365.com/artist/m"+str(i)+".html"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
artists=soup.findAll('a')
for artist in artists:
hrefString= artist['href']
print hrefString
if hrefString.find("lyrics")>0:
print "artist = "+hrefString
#dataObject.append(hrefString)
getSongList(hrefString)
|
2c07c48685a9095b8297232833e2c7b04a754155 | r25ta/USP_python_2 | /semana4/lista_ordenada.py | 451 | 3.859375 | 4 | def ordenada(lista):
for i in range(len(lista)):
if i == 0:
item = lista[i]
if item <= lista[i]:
item = lista[i]
else:
return False
return True
if __name__ == "__main__":
lista_ordenada=[1,2,2,3,4,5,6,7,8,9]
lista_desordenada = [-1,0,9,2,3,4,6,5,1,8,7]
print(ordenada(lista_ordenada))
print(ordenada(lista_desordenada))
|
8e741eb397889dbbdd86f4a5ecd393af8be1cbaa | r25ta/USP_python_2 | /semana1/matriz_mult.py | 715 | 4 | 4 |
def sao_multiplicaveis(m1,m2):
# RETORNA AS DIMENSÕES DA MATRIZ E TRANSFORMA O RESULTADO EM STRING
d_m1 = str(dimensoes(m1))
d_m2 = str(dimensoes(m2))
# print(d_m1)
# print(d_m2)
# COMPARA QTDE DE COLUNAS DA PRIMEIRA MATRIZ COM A QTDE LINHAS DA SEGUNDA MATRIZ
if(d_m1[-1] == d_m2[0]):
return True
else:
return False
def dimensoes(matriz):
linhas = 0
for l in range(len(matriz)):
colunas = 0
for c in range(len(matriz[l])):
colunas += 1
linhas += 1
return (f"{linhas}X{colunas}")
"""
def main():
m1 = [[1], [2], [3]]
m2 = [[1, 2, 3]]
print(sao_multiplicaveis(m1,m2))
main()
""" |
078ef482518125cdd4b8112c3588673a7c0d8000 | r25ta/USP_python_2 | /semana4/busca_binaria.py | 772 | 3.78125 | 4 | def busca_binaria(lista, elemento):
first = 0
last = len(lista)-1
while first <= last:
midpoint = (first+last)//2
if(elemento == lista[midpoint]):
return midpoint
else:
if(elemento < lista[midpoint]):
last = midpoint - 1
else:
first = midpoint + 1
return None
if __name__=="__main__":
lst_sequencia = [4, 10, 80, 90, 91, 99, 100, 101]
lst_elementos = [80,50]
for elemento in lst_elementos:
indice = busca_binaria(lst_sequencia,elemento)
if indice is None:
print("Não achou elemento ",elemento)
else:
print("O elemento ",elemento, "está no indice", indice)
|
9a40b5f82378e106390ab354e7ab593cf6f6ac97 | r25ta/USP_python_2 | /semana6/elefantes.py | 797 | 3.859375 | 4 | def incomodam(n,item=1, palavra=""):
if(n>=item):
palavra +="incomodam "
return incomodam(n, item+1, palavra)
else:
return palavra
def elefantes(n, item=1, frase=""):
if(n>=item):
if(item==1):
frase= "Um elefante incomoda muita gente\n"
return elefantes(n,item + 1,frase)
else:
frase += str(item) + " elefantes " + incomodam(item) + "muito mais\n"
if(n>item):
frase +=str(item) + " elefantes incomodam muita gente\n"
return elefantes(n,item + 1,frase)
else:
return frase
"""
if __name__=="__main__":
print(elefantes(100))
# print(elefantes(2))
# print(elefantes(1))
# print(elefantes(0))
""" |
2909d4e2b046922afd6f981cdd246e6789edc88a | pizzafreak5/battleship | /battleship_board.py | 1,913 | 3.984375 | 4 |
EMPTY = 'EMPTY'
MISS = 'MISS'
SHIP = 'SHIP'
HIT = 'HIT'
class Board:
def __init__ (self, size = 10):
self.board = []
self.last_change = (EMPTY, 0, 0)
self.size = size
for i in range(size):
elem = []
for i in range(size):
elem.append(EMPTY)
self.board.append(elem)
def get_last_change(self):
return self.last_change
#This function is called to attack a square on the board
#it returns hit or miss, and changes the board
def attack(self, x, y):
if x > self.size or y > self.size: #Check that coord is in bounds
return 'OUT OF BOUNDS'
if self.board[x][y] == SHIP:
self.board[x][y] = HIT
self.last_change = (HIT, x, y)
return HIT
elif self.board[x][y] == EMPTY:
self.board[x][y] = MISS
self.last_change = (MISS, x, y)
return MISS
else:
return 'REPEAT'
#This function checks the square provided.
def check(self, x, y):
if x > self.size or y > self.size: #Check that coord is in bounds
return 'OUT OF BOUNDS'
return self.board[x][y]
def size(self):
return self.size
#Prints the board to console
def print_board(self):
top_string = '' # The topstring will contain the numbers for colums
row_string = ''
format_str = '{:<6}'
top_string += format_str.format('')
for i in range(self.size):
top_string += format_str.format(str(i))
print(top_string)
for i in range(self.size):
row_string += format_str.format(str(i))
for j in range(self.size):
row_string += format_str.format(self.board[i][j])
print(row_string)
row_string = ''
|
3e80845a2e0031bfb21d4585976c1a67c9fdd201 | 2411Shravan/learn-python | /token.py | 243 | 3.828125 | 4 | token=0
name=True
while(name):
token=token+1
print("Token number ",token," please enter the doctor's cabin.")
print("Do you wish to continue ? (0/1)")
n=int(input())
if(n==0):
name=False
else:
continue
|
fec261ea779041d06edb0ef725956afa8f6b2967 | 2411Shravan/learn-python | /binarysearchrecursion.py | 504 | 3.765625 | 4 | def bin_search(l,x,start,end):
if(start==end):
if(l[start]==x):
return start
else:
return -1
else:
mid=int((start+end)/2)
if(l[mid]==x):
return mid
elif(l[mid]>x):
return bin_search(l,x,start,mid-1)
else:
return bin_search(l,x,start+1,end)
r=[2,3,5,55,56,57,58]
index=bin_search(r,2,0,(len(r)-1))
if(index==-1):
print("Not found")
else:
print("Found at position ",index)
|
afc92911c5f9a06b7b98747a91b229e5ec9f8c5c | 2411Shravan/learn-python | /dobblegame.py | 795 | 3.625 | 4 | import string
import random
symbols=[]
symbols=list(string.ascii_letters)
card1=[0]*5
card2=[0]*5
pos1=random.randint(0,4)
pos2=random.randint(0,4)
sames=random.choice(symbols)
symbols.remove(sames)
print(pos1,pos2)
if(pos1==pos2):
card2[pos1]=sames
card1[pos1]=sames
else:
card1[pos1]=sames
card2[pos2]=sames
card1[pos2]=random.choice(symbols)
symbols.remove(card1[pos2])
card2[pos1]=random.choice(symbols)
symbols.remove(card2[pos1])
i=0
while(i<5):
if(i!=pos1 and i!=pos2):
alp=random.choice(symbols)
symbols.remove(alp)
alp1=random.choice(symbols)
symbols.remove(alp1)
card1[i]=alp
card2[i]=alp1
i=i+1
print(card2)
print(card1)
ch=input("Enter the similar character : ")
if(ch==sames):
print("Right")
else:
print("Wrong")
|
00d9d82ee8e5b1da815dd3b91ee642ec416f10c7 | WoohyunSHIN/Python_Libraries | /SqlLite3/02.sqlite-test.py | 1,286 | 3.65625 | 4 | import sqlite3
conn =sqlite3.connect('sqlite3/example.db')
c = conn.cursor()
# Never do this -- insecure!
# target = 'RHAT'
# c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % target)
# 관계형 데이터베이스에서, 1 row == 1 case(data) == 1 record 라고 말한다.
# WHERE 포함 이후의 부분은 조건절이다. 1 record 기준으로 뽑아낸다.
# 데이터를 가져올땐 fecth()를 사용한다 한 행식 접근해서 쓰는 방법을 말한다.
items = c.fetchall()
for item in items:
print(item)
# Do this instead
t = ('RHAT',)
# t1 = (100)
sql='SELECT * FROM stocks WHERE symbol=?'
c.execute(sql,t) #c.execute(sql,(t,t1)) <- 여러개가 한 세트면 () 로 묶어서 넣어줘야한다.
print(c.fetchone())
# Larger example that inserts many records at a time
purchases = [('2006-03-28','BUY','IBM',1000,45.00),
('2006-04-05','BUY','MSFT',1000,72.00),
('2006-04-06','SELL','IBM',500,53.00),]
c.executemany('INSERT INTO stocks VALUES(?,?,?,?,?)', purchases)
conn.commit()
# price 의 오름차순 순서로 데이터 들고오기
c.execute('SELECT * FROM stocks ORDER BY price')
rows = c.fetchall()
for row in rows:
print(row)
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
c.close() |
a416e1b0bba21374835bfb16f79bb92459ad97ab | WoohyunSHIN/Python_Libraries | /DeepLearning/Chapter2/01.perceptron.py | 1,257 | 3.578125 | 4 | # 인간이 인공적으로 정해주는 부분은 w1, w2와 theta 와 같은 임계값을 정의해준다.
import numpy as np
# AND Logic without numpy
def AND(x1,x2):
w1, w2, theta = 0.5, 0.5, 0.7
tmp = x1*w1 + x2*w2
if tmp <= theta:
return 0
elif tmp > theta:
return 1
# AND Logic with numpy
x = np.array([0,1]) # 입력값
w = np.array([0.5, 0.5]) # 임의의 가중치
b = -0.7 # b=bias 편향
print(np.sum(w*x)+b)
def AND_1(x1,x2):
x = np.array([x1,x2])
w = np.array([0.5, 0.5]) #임의의 가중치
b = -0.7
tmp = np.sum(x*w)+b
if tmp <= 0:
return 0
elif tmp > 0:
return 1
# NAND 경우, 가중치와 편향의 부호만 반대이고 나머지는 동일하다.
def NAND(x1,x2):
x = np.array([x1,x2])
w = np.array([-0.5,-0.5])
b = 0.7
tmp = np.sum(x*w)+b
if tmp <= 0:
return 0
elif tmp > 0:
return 1
#
def OR(x1,x2):
x = np.array([x1,x2])
w = np.array([0.5,0.5])
b = -0.2
tmp = np.sum(x*w)+b
if tmp <= 0:
return 0
elif tmp > 0:
return 1
# NAND, OR --> AND 조합으로 만들어지는 XOR 조합
def XOR(x1,x2):
s1 = NAND(x1,x2)
s2 = OR(x1,x2)
y = AND_1(s1,s2)
return y |
fca18d05aa62db66d84ae0b21cb81bd5fcc8f0c5 | WoohyunSHIN/Python_Libraries | /Crawling/09_bs4_bugs.py | 297 | 3.625 | 4 | from bs4 import BeautifulSoup
import urllib.request
url = 'https://music.bugs.co.kr/chart'
response = urllib.request.urlopen(url)
soup = BeautifulSoup(response,'html.parser')
results = soup.select('th>p.title > a')
print(results)
print('______')
for result in results:
print(result.string) |
43fe267d6f460592d7b81c598acf7736df8441a5 | Marcuswkds/ICP1 | /Q1.py | 519 | 4.0625 | 4 | #Question 1
#Differences between Python 2 and Python 3
#1) The print keyword in Python 2 is replaced by the print() function in Python 3
#2) In Python 2 implicit str type is ASCII. But in Python 3 implicit str type is Unicode.
#3) In Python 2, if you write a number without any digits after the decimal point, it rounds your calculation down to the nearest whole number.
# In Python 3, you don't have to worry about the calculation rounding down even if you don't add any digits behind the numbers. ex. 5/2 = 2.5
|
a7a0812e5b5b0d7da40eae8a942bf6460ee964b6 | lucas-m98/cdo_project | /post.py | 1,241 | 3.515625 | 4 |
class RedditPost():
# Initializer for a single reddit post class
def __init__(self, input):
try:
self.title = input["title"]
self.score = input["score"]
self.url = input["permalink"]
# Some posts do not contain thumbnails, so it is necessary to check for them
if "thumbnail" in input.keys():
self.thumbnail = input["thumbnail"]
else:
self.thumbnail = False
if self.thumbnail == "self":
full_text = input['selftext']
if len(full_text) > 100:
full_text = full_text[:100] + "..."
self.text = full_text
else:
self.text = False
if self.thumbnail == "self" or self.thumbnail == "default" or self.thumbnail == "nsfw":
self.thumbnail = False
except Exception as e:
self.title = False
self.text = False
self.thumbnail = False
self.score = False
self.url = False
def __str__(self):
return str({
"title": self.title,
"score": self.score,
"thumbnail": self.thumbnail
})
|
27caf6e1854a5e2795ac48e430b4c1edc60b52e2 | jps27CSE/Data-Structures-and-Algorithms | /Python/Linear Search.py | 435 | 3.953125 | 4 | n=int(input("Enter number of elements:"))
count=0
list=[]
for i in range(0,n):
elements=int(input())
list.append(elements)
search=int(input("Enter the number you want to search:"))
for i in range(0,n):
if list[i]==search:
print("number is present at index:",i+1)
count=count+1
if (count==0):
print("error")
else:
print(f"{search} is present {count} times in the array") |
1051d5d57ba7c8c7cc5d2fd0eac24f15eff265b6 | abhinavk454/Dynamic-Programming-python-code | /01 Knapsack problems/SubsetSumReccursive.py | 279 | 3.609375 | 4 | def subset(arr, k):
if sum(arr) == k:
return True
if not arr:
return False
elif arr[-1] <= k:
return (subset(arr[:-1], k-arr[-1])) or (subset(arr[:-1], k))
elif arr[-1] > k:
return subset(arr[:-1], k)
print(subset([1, 2, 3], 4))
|
b1c33417df30b02f42b8769064907be79d4d1b31 | I-bluebeard-I/Python-Study | /Lesson_1/part01_lesson01_task04.py | 989 | 4.03125 | 4 | """
ЗАДАНИЕ 4
Склонение слова
Реализовать склонение слова «процент» во фразе «N процентов». Вывести эту фразу на экран
отдельной строкой для каждого из чисел в интервале от 1 до 100:
1 процент
2 процента
3 процента
4 процента
5 процентов
6 процентов
...
100 процентов
"""
number = 0
percent = {
'0': 'процентов',
'1': 'процент',
'2': 'процента',
'3': 'процента',
'5': 'процентов',
'4': 'процента',
'6': 'процентов',
'7': 'процентов',
'8': 'процентов',
'9': 'процентов',
}
while number < 100:
number += 1
if 14 >= number >= 10:
print(number, percent['0'])
else:
str_number = str(number)
print(number, percent[str_number[-1]])
|
bdc7cac6740c94c1cea4d3c9c9b9246be176139c | pykili/py-204-hw1-Dyachkova519 | /task_1/solution_1.py | 98 | 3.546875 | 4 | # your code here
a = input()
ma = 0
for i in a:
if int(i) > ma:
ma = int(i)
print(ma)
|
537548a401a27984bfe6c089468fdeb6664b661c | job4Greymore/Python_Structural_Programming | /Topics/Num Rounding.py | 286 | 3.796875 | 4 | #Rounding function a float to an integer.
n = 3.912
p = 2
#Default rounding function without decimal place declaration
# round(n)-rounds to the nearest whole number
r1 = round(n)
print(r1)
#Declaration of decimal place declaration
r2 = round(n, p)
print(r2)
r3 = round(145/2)
print(r3) |
7cf8b93de077f55a20d4df7f4904a6ca29dbfe45 | Pedro312/character | /character.py | 1,151 | 3.65625 | 4 | class Character(object):
def __init__(self, name, hp, damage, attack_speed, armor):
self.name = name
self.damage = damage
self.health = hp
self.attack_speed = attack_speed
self.bag = []
self.armor = armor
def pick_up(self, item):
self.bag.append(item)
print "You put the %s in your bag." % item
def attack(self, target):
target.take_damage(self.damage)
print "You attacked %s for %d damage." % (target.name , self.damage)
def take_damage(self, damage):
if self.armor > 0:
self.armor -= damage
if self.armor <= 0:
if self.health > 0:
self.health -= damage
else:
print "%s is already dead" % self.name
orc1 = Character('The First Orc', 100, 20, 2, 0)
orc2 = Character('The Second Orc', 100, 20, 2, 0)
sam = Character("Sam V", 10, 0.000000000001, 0.0000000001, 50)
ed = Character('Edwin Burgos', 9001, 2, 1, 500)
rob = Character('Roberto Moreno', 80, 100, 2, 200)
bob = Character('Bobby Vixathep', 1, 20, 2, 0)
wiebe = Character('Senor Wiebe', 300, 66, 2, 200) |
ea1dd61656c1c1ab607e1cef9988cf66488e1061 | edmolten/codevita2016 | /c.py | 1,143 | 3.96875 | 4 | #!/usr/bin/env python
# x1 rigth curves
# y1 left curves
# por cada curva derecha x1 gana x2 metros
# por cada curva izquierda y1 gana y2 metros
# la velocidad es S km
# La carrera tiene Z km
# Cada Z1 km ambos conductores paran y tardan x3 e y3 segundos (slo pasa si la distancia faltante es mayor al pit, NO si son iguales).
# s velocidad de cada uno en lnea recta
import math
x1 = int(input())
y1 = int(input())
x2 = int(input()) # meters
y2 = int(input()) # meters
z = int(input()) * 1000 # meters
z1 = int(input()) * 1000 # meters
x3 = int(input()) # sec
y3 = int(input()) # sec
s = int(input()) * 1000 / 3600 # meters / sec
# Metros que gana cada jugador por las curvas
mx = x1 * x2
my = y1 * y2
# Tiempo perdido por pitstops
# Cuantas paradas
pit = z/z1
if (float(pit) == float(z/z1)):
pit -= 1
pit = int(pit)
mx -= pit * x3 * s
my -= pit * y3 * s
if mx > my:
print("Right Hand driver wins race by " + str(math.ceil(abs(mx-my))) + " meters")
elif my > mx:
print("Left Hand driver wins race by " + str(math.ceil(abs(mx-my))) + " meters")
else:
print("Race Drawn") |
b2621c9c0430fd518718226a1aa0684d00e1b2b7 | jeremyyew/tech-prep-jeremy.io | /code/topics/2-lists-dicts-and-strings/E13-roman-to-integer.py | 872 | 3.859375 | 4 | '''
- For each roman numeral, if the current value is less than the next numeral's value, we are at a 'boundary' number e.g. 4, 9, 40, 90, etc.
- If so, then instead of adding the value, we simply subtract that value.
'''
class Solution:
def romanToInt(self, s) -> int:
res = 0
r_to_i = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
for i, n in enumerate(s):
curr_val = r_to_i[n]
if i == len(s) - 1:
res += curr_val
break
next_val = r_to_i[s[i+1]]
if curr_val >= next_val:
res += curr_val
else:
res -= curr_val
return res
# r = Solution().romanToInt('III')
# print(r)
# print(int(set(1)))
|
c68bae850584f142a9aee88eb538dfb8276d4fd6 | jeremyyew/tech-prep-jeremy.io | /code/topics/8-tries/M211-add-and-search-word.py | 1,649 | 3.625 | 4 | '''
If `word[i] == '.'`, then return the result of a search from each existing child, beginning from `word[i+1]`, as if that was the correct child.
'''
class TrieNode:
def __init__(self):
self.children = [None]*26
self.isEnd = False
def contains(self, child):
return self.children[child] is not None
def charToChildKey(self, ch):
return ord(ch)-ord('a')
def getAllChildren(self):
return [child for child in self.children if child]
class WordDictionary:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for c in word:
k = node.charToChildKey(c)
if not node.contains(k):
node.children[k] = self.getNode()
node = node.children[k]
node.isEnd = True
def search(self, word: str) -> bool:
return self.searchRec(word, self.root)
def searchRec(self, word: str, node: TrieNode) -> bool:
for i in range(len(word)):
if word[i] == '.':
for child in node.getAllChildren():
if self.searchRec(word[i+1:], child):
return True
return False
else:
k = node.charToChildKey(word[i])
if not node.contains(k):
return False
node = node.children[k]
return node.isEnd
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
|
d83f455031e2c87eb424d713d71c0b25c0f08119 | jeremyyew/tech-prep-jeremy.io | /code/techniques/7-BFS/H126-word-ladder-ii.py | 2,122 | 3.546875 | 4 | '''
- Store paths instead of path length. It does seem like a lot of space, but even if you use pointers its the same amount of space.
- Once there is a min path, terminate any other path that is the same length.
- Do not use a global visited - we need all paths, including paths that use the same nodes. Instead, check if the next node is in the current path.
- Reduce complexity of checking membership in path, with an additional path_set.
- We must copy path_set for each neighbor, otherwise the path_set gets modified repeatedly.
'''
from typing import List
from collections import deque
class Solution(object):
def findLadders(self, beginWord: str, endWord: str,
wordList: List[str]) -> List[List[str]]:
# preprocess
g = {}
for word in wordList:
for i in range(len(word)):
s = word[:i] + "*" + word[i+1:]
g[s] = g.get(s, []) + [word]
# bfs
q = deque([([beginWord], set([beginWord]))])
paths = []
while q:
# print(q)
# print(paths)
path, path_set = q.popleft()
if paths and len(path) == len(paths[0]):
continue
word = path[-1]
for i in range(len(word)):
s = word[:i] + "*" + word[i+1:]
nbs = g.get(s, [])
for nb in nbs:
if nb == endWord:
paths.append(path + [nb])
elif nb not in path_set:
pcopy = path_set.copy()
pcopy.add(nb)
q.append((path + [nb], pcopy))
return paths
# r = Solution().findLadders("hit", "cog",
# ["hot", "dot", "dog", "lot", "log", "cog"])
# print(r)
# Output:
# [
# ["hit","hot","dot","dog","cog"],
# ["hit","hot","lot","log","cog"]
# ]
r = Solution().findLadders("red", "tax",
["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"])
print(r)
# [["red","ted","tad","tax"],["red","ted","tex","tax"],["red","rex","tex","tax"]]
|
5a8c2f4cb9c5932b9c5c231070546011e0f8b4bf | jeremyyew/tech-prep-jeremy.io | /code/techniques/14-dynamic-programming/M516-longest-palindromic-subsequence.py | 2,285 | 3.546875 | 4 | '''
For each new element, traverse the string backwards looking for elements to form new symmetries with, deriving the new length from the length of inner palindromes. Start from `0`, and every time you shift `i` to the right, shift `j` backwards from `i-1` to `0`.
1. Let `dp(j, i)` be the length of the longest palindromic subsequence (LPS) from `j` to `i` inclusive. Then, for `s[j:i+1]`, if `s[j] == s[i]`, we have the chance to make a new LPS, so we may add two elements (`i` and `j`) to the LPS length from `j+1` to `i-1`, i.e. `dp(j+1, i-1)`.
2. Else, `dp(j,i)` is either the length of some previous LPS `dp(j, i-1)` (which may be either the length of some previous LPS that included `s[j]`, or some LPS between `j+1` to `i-1`), or some new inner LPS between `j+1` and `i`, that includes `s[i]`. Thus `dp(j, i)` is the max of the previous value `dp(j, i-1)` and new value `dp(j+1, i)`.
Formally,
```
if s[j] == s[i]:
dp(j, i) = 2 + dp(j+1, i-1)
else:
dp(j, i) = max(dp(j, i-1), dp(j+1, i))
```
Time complexity is O(N^2).
The implementation here uses O(N) space instead of O(N^2), so the recurrence relation is not clearly reflected in the indexing in the code; we save the previous row of values `dp(j, i-1)` as `prev`.
Adapted from https://leetcode.com/problems/longest-palindromic-subsequence/discuss/99117/Python-standard-DP-beats-100-(with-%22pre-processing%22).
Other notes:
[3] If it is already a palindrome, return whole string. (For beating TLE on Leetcode.)
[4] Base case j=i=0: the max length of any palindromic substring from j to i is 1, as dp[0] itself forms a 1-length palindromic substring.
[5] Copy previous row, for reference.
[6] Base case j=i>0: Same as j=i=0, dp[j] itself forms a 1-length palindromic substring.
'''
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
if s == s[::-1]: # [3]
return len(s)
S = len(s)
dp = [0] * S
dp[0] = 1 # [4]
for i in range(1, S):
prev = dp[:] # [5]
dp[i] = 1 # [6]
for j in range(i-1, -1, -1):
if s[i] == s[j]: # [1]
dp[j] = 2 + prev[j+1]
else: # [2]
dp[j] = max(prev[j], dp[j+1])
return dp[0]
|
dc804c10e9cff208ff56ae4380c3112a014a4496 | jeremyyew/tech-prep-jeremy.io | /code/topics/2-lists-dicts-and-strings/E283-move-zeroes.py | 763 | 3.953125 | 4 | '''
- If zero, add to zeros, which is the number of consecutive zeroes directly before index i.
- If non-zero and we have no consecutive zeros: pass.
- If non-zero and we have at least one zero before i:
- swap the first zero(at index i - zeros) with the current value.
- note that the number of consecutive zeroes before i remains the same.
'''
class Solution(object):
def moveZeroes(self, nums):
i = 0
zeros = 0
for i in range(len(nums)):
if nums[i] == 0:
zeros += 1
elif zeros > 0:
nums[i - zeros] = nums[i]
nums[i] = 0
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
|
13966d924e45e21f69b44bf5059ce6c21837300e | jeremyyew/tech-prep-jeremy.io | /code/techniques/2-two-pointers/M15-three-sum.py | 5,336 | 3.609375 | 4 | import itertools
from typing import List
# My version of someone else's solution below. For modularity, I abstract the two-sum scan, and pass it an array slice instead of indices.
# We simply require the twoSum to return the values that add up to the target (instead of indices), with no duplicates, and it cannot assume sorted values in general. Keep in mind we must also give it the complement of the target, not the target itself, since we are aiming for zero-sum.
class Solution(object):
# Scans sorted array nums from left and right to find two numbers that sum to the the target, i.e. so that we have a zero sum. We know it is better to sort once in threeSum, so we don't re-sort here - this is an optimization which doesn't break modularity, since we don't necessarily assume sorted for other twoSums.
# Also skips repeated numbers, so we won't have duplicates.
def twoSum(self, target, nums):
# nums.sort()
res = []
l = 0
r = len(nums) - 1
while l < r:
diff = nums[l] + nums[r] - target
if diff < 0: # [3]
l += 1
elif diff > 0: # [4]
r -= 1
else: # [5]
res.append([nums[l], nums[r]])
while l < r and nums[l] == nums[l+1]: # [6]
l += 1
while l < r and nums[r] == nums[r-1]: # [6]
r -= 1
l += 1
r -= 1
return res
def threeSum(self, nums):
res = []
nums.sort()
length = len(nums)
for i in range(length-2): # [8]
if nums[i] > 0:
break # [7]
if i > 0 and nums[i] == nums[i-1]:
continue # [1]
# We need to make target negative since we are trying to find the twoSum of its complement, so that target + x + y = 0.
target = nums[i]
# Set the appropriate l index. r-index will always be the same. # [2]
res_i = self.twoSum(-target, nums[i+1:])
# To demonstrate modularity:
# res_i = twoSumWithDict(-target, nums[i+1:])
# Include the target.
res += [(target, x, y) for x, y in res_i]
return res
def twoSumWithDict(target, nums):
# One pass with hash. Includes duplicate pairs but not equivalent combinations.
comps = {}
res = set()
# print(target, nums)
for i in range(len(nums)):
x = nums[i]
if x in comps:
res.add((comps[x], x))
else:
comps[target - x] = x
return [list(twoSum) for twoSum in res]
# https://leetcode.com/problems/3sum/discuss/232712/Best-Python-Solution-(Explained)
'''
We select a target, and find two other numbers which make total zero.
For those two other numbers, we move pointers, l and r, to try them.
First, we sort the array, so we can easily move i around and know how to adjust l and r.
If the number is the same as the number before, we have used it as target already, continue. [1]
We always start the left pointer from i+1 because the combination of 0~i has already been tried. [2]
Now we calculate the total:
If the total is less than zero, we need it to be larger, so we move the left pointer. [3]
If the total is greater than zero, we need it to be smaller, so we move the right pointer. [4]
If the total is zero, bingo! [5]
We need to move the left and right pointers to the next different numbers, so we do not get repeating result. [6]
We do not need to consider i after nums[i]>0, since sum of 3 positive will be always greater than zero. [7]
We do not need to try the last two, since there are no rooms for l and r pointers.
You can think of it as The last two have been tried by all others. [8]
'''
class SolutionExample(object):
def threeSum(self, nums):
res = []
nums.sort()
length = len(nums)
for i in range(length-2):
if nums[i] > 0:
break # [7]
if i > 0 and nums[i] == nums[i-1]:
continue # [1]
l, r = i+1, length-1 # [2]
while l < r:
total = nums[i]+nums[l]+nums[r]
if total < 0: # [3]
l += 1
elif total > 0: # [4]
r -= 1
else: # [5]
res.append([nums[i], nums[l], nums[r]])
while l < r and nums[l] == nums[l+1]: # [6]
l += 1
while l < r and nums[r] == nums[r-1]: # [6]
r -= 1
l += 1
r -= 1
return res
# This is brute force, takes O(nC3). Too slow on large inputs.
# class Solution:
# def threeSum(self, nums: List[int]) -> List[List[int]]:
# threeSums = set()
# threeCombs = itertools.combinations(nums, 3)
# for threeTuple in threeCombs:
# if sum(threeTuple) == 0:
# # We convert to list to sort it, so different combinations are equivalent. We then convert back to tuple since we need it to be hashable to be addable to the set.
# threeSums.add(tuple(sorted(list(threeTuple))))
# return list(threeSums)
# res = Solution().threeSum([-1, 0, 1, 2, -1, -4])
# print(res)
|
04825716476c0340ee05c32b6d373a32a365f312 | jeremyyew/tech-prep-jeremy.io | /code/fb-prep/M287-find-duplicate-number.py | 1,095 | 3.6875 | 4 | class Solution:
def findDuplicate(self, nums):
i = 0
while i != nums[i]:
print(i)
k = nums[i]
nums[i] = i
i = k
# [1]: nums[i], i = i, nums[i]
print(nums)
return i
r = Solution().findDuplicate([1, 1, 2, 3, 4])
print(r)
r = Solution().findDuplicate([1, 3, 4, 2, 2])
print(r)
class SolutionDetectCycle:
def findDuplicate(self, nums):
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
p1, p2 = nums[0], slow
while p1 != p2:
p1 = nums[p1]
p2 = nums[p2]
return p1
class SolutionDetectCycleAlt:
def findDuplicate(self, nums):
slow = fast = 0
while not (nums[slow] == nums[fast] and slow != fast):
print(slow, fast)
slow = nums[slow]
fast = nums[fast]
if nums[slow] == nums[fast]:
break
fast = nums[fast]
return nums[slow]
|
ac0145ec2c124e57de681fddb861c116a0a3ec9d | jeremyyew/tech-prep-jeremy.io | /code/topics/4-trees-and-graphs/E104-maximum-depth-of-binary-tree.py | 1,021 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class SolutionRec:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
else:
return max(self.maxDepth(root.right), self.maxDepth(root.left)) + 1
# Here we use shared memory to achieve tail recursion. We could also do iterative to have no recursion. Note python's stdlib max is O(n).
class Solution:
def writeMaxDepth(self, node: TreeNode, depth):
if node is not None:
self.writeMaxDepth(node.left, depth + 1)
self.writeMaxDepth(node.right, depth + 1)
else:
self.max_depth = max(self.max_depth, depth)
def maxDepth(self, root: TreeNode) -> 'int':
if root is None:
return 0
self.max_depth = 0
self.writeMaxDepth(root.left, 1)
self.writeMaxDepth(root.right, 1)
return self.max_depth
|
d6ddba1536a4377251089a3df2ad91fb87b987b8 | jeremyyew/tech-prep-jeremy.io | /code/techniques/8-DFS/M341-flatten-nested-list-iterator.py | 606 | 4 | 4 | '''
- Only pop and unpack what is necessary.
- Pop and unpack when `hasNext` is called - it ensures there is a next available for `next`, if there really is a next.
- At the end only need to check if stack is nonempty - stack nonempty and last element not integer is not possible.
'''
class NestedIterator(object):
def __init__(self, nestedList):
self.stack = nestedList[::-1]
def next(self):
return self.stack.pop().getInteger()
def hasNext(self):
while self.stack and not self.stack[-1].isInteger():
nl = self.stack.pop()
self.stack.extend(nl.getList()[::-1])
return self.stack |
ef7e005111123d2a239cbfd8a1e9f0e75fd435f4 | jeremyyew/tech-prep-jeremy.io | /code/techniques/4-merge-intervals/M57-insert-interval.py | 3,586 | 3.859375 | 4 | '''
- We present a simple linear solution.
- It is possible to do binary search, but deceivingly tricky to decide what to return or the indexes to insert at.
- An attempt is done below.
'''
from typing import List
class SolutionLinear:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
def overlap(a, b) -> bool:
return not (before(a, b) or after(a, b))
def before(a, b) -> bool:
return a[1] < b[0]
def after(a, b) -> bool:
return a[0] > b[1]
def merge(a, b) -> List[int]:
return([min(a[0], b[0]), max(a[1], b[1])])
# [1] Base case []: immediately return `newInterval`.
if not intervals:
return [newInterval]
merged = []
i = 0
while i < len(intervals):
if before(newInterval, intervals[i]):
break
if overlap(newInterval, intervals[i]):
newInterval = merge(newInterval, intervals[i])
else:
merged.append(intervals[i])
i += 1
merged += [newInterval] + intervals[i:]
return merged
# class Solution:
# def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
# def overlap(a, b) -> bool:
# return not (before(a, b) or after(a, b))
# def before(a, b) -> bool:
# return a[1] < b[0]
# def after(a, b) -> bool:
# return a[0] > b[1]
# def merge(a, b) -> List[int]:
# return([min(a[0], b[0]), max(a[1], b[1])])
# # [1] Base case []: immediately return `newInterval`.
# if not intervals:
# return [newInterval]
# # [2] Get rid of edge cases where `newInterval` is before the first or after the last interval, so later we may consider less.
# if before(newInterval, intervals[0]):
# return [newInterval] + intervals
# if after(newInterval, intervals[-1]):
# return intervals + [newInterval]
# l, r = 0, len(intervals) - 1
# # [2] Binary search to find the first possible insertion start point.
# while l <= r:
# if l == r:
# if before(newInterval, intervals[l]):
# l = r = l - 1
# break
# elif after(newInterval, intervals[l]):
# l = r = l + 1
# break
# m = (l + r) // 2
# if before(newInterval, intervals[m]):
# r = m
# elif after(newInterval, intervals[m]):
# l = m+1
# else:
# if newInterval[1] <= intervals[m][1]:
# r = m
# if newInterval[0] >= intervals[m][0]:
# l = m
# while r < len(intervals):
# if overlap(intervals[r], newInterval):
# newInterval = merge(intervals[r], newInterval)
# break
# r += 1
# print(l, r)
# return (intervals[:l+1]) + [newInterval] + intervals[r:]
# r = Solution().insert([[2, 6], [7, 9]], [15, 18])
# print(r)
|
72a5f79be816896fcdfbab8dd0a54f1588d25551 | jeremyyew/tech-prep-jeremy.io | /code/topics/1-searching-and-sorting/M148-sorted-list.py | 1,589 | 4.125 | 4 | Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
pass
# Iterative mergesort function to
# sort arr[0...n-1]
def mergeSort(self, head):
current_size = 1
left = head
while left:
left = head
while left:
mid = left + current_size - 1
right = len(a) - 1 if 2 * current_size + left - 1 > len(a)-1 else 2 * current_size + left - 1
mergeTwoLists(a, left, mid, right)
left = left.next
current_size = 2 * current_size
# Merge Function
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
node = ListNode(None)
head = node
while True: # better than a termination condition, because its tricky to refactor the code to pop the list for the next iteration to check, when you can't keep a reference to which list you want to pop at the end.
print(node.val)
if l1 is None and l2 is None:
return
# there is at least one non-None
if l1 is None or l2 is None:
if l1 is None:
some = l2
else:
some = l1
node.next = some
return head.next
# both are non-None
if l1.val < l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
return head.next |
0cc2d611995b7dea4b0a25b0c712472a59b0f2b5 | ravitejaseelam/Shell | /JsonActions.py | 5,187 | 3.5 | 4 | import json
import sys
import os
import os.path
def ask_which_to_keep(each1, each2, dic):
print("\nSame priority is encountered Plz handle by giving which one to keep\n")
print(json.dumps(each1, indent=4))
print(json.dumps(each2, indent=4))
name = input("Enter name to be inserted")
if each1["name"] == name:
dic[each1['Id']] = each1
elif each2["name"] == name:
dic[each2['Id']] = each2
else:
print("Name not found plz enter the correct name ")
return dic
def check(each, dic):
if each['priority'] < dic[each['Id']]['priority']:
dic[each['Id']] = each
elif each['priority'] == dic[each['Id']]['priority']:
dic = ask_which_to_keep(each, dic[each['Id']], dic)
return dic
def is_file_exist_check(filename):
if not os.path.isfile(filename):
print(filename + ' File dosent exist')
sys.exit(0)
def is_file_empty_check(filename):
if os.path.getsize(filename) == 0:
print('File is empty')
sys.exit(1)
def load_json_data_from_file(filename):
with open(filename, 'r') as f:
return [json.loads(line) for line in f]
def get_duplicates(x):
x = [i for i in x if i['healthchk_enabled'] == True]
t = [each['Id'] for each in x]
duplicates = [item for item in t if t.count(item) > 1]
t = [each for each in x if each['Id'] in duplicates]
return t
def print_if_duplicates(t):
if len(t) != 0:
sorted_data = sort_when_healthchk_enbled(t)
print("These are the Duplicate Data in provided file" + filename)
print(json.dumps(sorted_data, indent=4))
return True
return False
def remove_duplicates(x):
dic = {}
for each in x:
if each['Id'] not in dic:
dic[each['Id']] = each
else:
dic = check(each, dic)
return dic.values()
def sort_when_healthchk_enbled(x):
x = [i for i in x if i['healthchk_enabled'] == True]
return sorted(x, key=lambda k: (k['priority'], int(k["Id"]), k["name"]))
def load_json_data_into_file(outputfilename, lines):
json_object = json.dumps(lines, indent=4)
with open(outputfilename, "w") as outfile:
outfile.write(json_object)
def verify_arguments():
if len(sys.argv) < 3:
print(
"Plz provide requires arguments in command line example(python " + sys.argv[0] + " source.json output.json")
exit(3)
elif len(sys.argv) > 3:
print("Extra arguments found in command line Plz look into an example(python " + sys.argv[
0] + " source.json output.json")
exit(3)
def delete_object_from_conflicts(t, name, id):
for i in t:
if i["name"] == name and i["Id"] == id:
t.remove(i)
return t
return t
def delete_object_from_original(x, name, id):
for i in x:
if i["name"] == name and i["Id"] == id:
x.remove(i)
return x
def get_id_conflicts(conflict):
Ids = []
for i in conflict:
Ids.append(i["Id"])
return Ids
verify_arguments()
filename = sys.argv[1]
outputfilename = sys.argv[2]
is_file_exist_check(filename)
is_file_empty_check(filename)
original = load_json_data_from_file(filename)
conflict = get_duplicates(original)
i = print_if_duplicates(conflict)
if i:
resp = input("Do you want to the duplicates to be deleted? (y/n)")
if resp == 'y':
resp2 = input("By default the priority with high number is deleted to you want to proceed? (y/n)")
if resp2 == 'y':
original = remove_duplicates(original)
elif resp2 == 'n':
while len(conflict) != 0:
print_if_duplicates(conflict)
print("\nPLZ RESOLVE CONFLICTS ONE BY ONE BY GIVING NAME AND ID FROM ABOVE OBJECTS\n")
Ids = get_id_conflicts(conflict)
Ids=set(Ids)
if (len(Ids) > 1):
Id = input("Enter id to be handled:")
else:
Id = Ids.pop()
print(Id+" is selected to be handled")
Names = input("Enter names to be deleted:").split(",")
for Name in Names:
conflict_dup = conflict.copy()
conflict = delete_object_from_conflicts(conflict, Name, Id)
if conflict == conflict_dup:
print("\nIncorrect name and id \nPlz try id and name only from above printed objects\n")
else:
original = delete_object_from_original(original, Name, Id)
conflict = get_duplicates(conflict)
print("\nSuccessfully deleted " + Name + " from conflict created by id:" + Id + "\n")
else:
print("Wrong Input it should be either y or n be carefull with case")
sys.exit(0)
elif resp == 'n':
pass
else:
print("Wrong Input it should be either y or n be carefull with case")
sys.exit(0)
lines = sort_when_healthchk_enbled(original)
load_json_data_into_file(outputfilename, lines)
print("Process Done Plz find the output in file " + outputfilename)
|
065004e81dc28ae4d4a6acee52d3808bb8498841 | vgattani-ds/programming_websites | /hackerrank/10_days_of_Statistics/day_7_spearmans_rank_correlation_coefficient.py | 803 | 3.6875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
def get_rank(X):
indices = list(range(len(X)))
indices.sort(key=lambda x: X[x])
rank = [0] * len(indices)
for i, x in enumerate(indices):
rank[x] = i
return rank
def correlation(*args):
X = args[0]
Y = args[1]
n_obs = args[2]
r_X = get_rank(X)
r_Y = get_rank(Y)
nr = 0
for x, y in zip(r_X, r_Y):
nr += (x-y)**2
dr = n_obs*(n_obs**2 - 1)
result = 1 - (6*nr)/dr
return result
if __name__ == "__main__":
lines = iter(sys.stdin)
total_obs = int(next(lines))
X = list(map(float, next(lines).split()))
Y = list(map(float, next(lines).split()))
result = correlation(X, Y, total_obs)
print(round(result, 3)) |
4536c7d2256fa95c62720c0f12eb5e9a2b952937 | vgattani-ds/programming_websites | /leetcode/1081_smallestSubsequence.py | 665 | 3.640625 | 4 | class Solution:
def smallestSubsequence(self, s: str) -> str:
last_index = {}
for index, char in enumerate(s):
last_index[char] = index
result = []
for index, char in enumerate(s):
if char not in result:
while result and char < result[-1] and index < last_index[result[-1]]:
result.pop()
result.append(char)
return "".join(result)
if __name__ == "__main__":
s = "bcabc"
print(Solution().smallestSubsequence(s))
print(f"Correct Answer is: abc") |
416883b316d6201e6d052e74dad1f21876179d52 | vgattani-ds/programming_websites | /leetcode/0229_majorityElement.py | 1,123 | 3.875 | 4 | from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
if n <= 1:
return nums
cand1=None
cand2=None
count1=0
count2=0
for num in nums:
if num == cand1:
count1 += 1
elif num == cand2:
count2 += 1
elif count1==0:
cand1 = num
count1 += 1
elif count2==0:
cand2 = num
count2+=1
else:
count1-=1
count2-=1
count1=0
count2=0
for num in nums:
count1 += num==cand1
count2 += num==cand2
result=[]
if count1>n/3: result.append(cand1)
if count2>n/3:
result.append(cand2)
return result
if __name__ == "__main__":
nums=[1,1,1,3,3,2,2,2]
print(Solution().majorityElement(nums))
print("Correct Answer is: [1,2]") |
2cf57cec07d96fb6187b12d51bdb0d54d9b69d7d | vgattani-ds/programming_websites | /hackerrank/python_practice/second_lowest_grade.py | 814 | 3.75 | 4 | if __name__ == '__main__':
nested_list = []
for _ in range(int(input())):
name = input()
score = float(input())
nested_list.append([name,-score])
max_v = float("-inf")
runner_v = float("-inf")
runner_stu = []
max_stu = []
for name, score in nested_list:
if score > runner_v:
if score > max_v:
max_v, runner_v = score, max_v
runner_stu = max_stu[:]
max_stu = [name]
elif score < max_v:
runner_v = score
runner_stu = [name]
else:
max_stu.append(name)
elif score == runner_v:
runner_stu.append(name)
for name in sorted(runner_stu):
print(name, end="\n") |
9ecf0251760eb7dea1897f5c73ca64715de98785 | vgattani-ds/programming_websites | /leetcode/0414_thirdMax.py | 917 | 3.9375 | 4 | from typing import List
class Solution:
def thirdMax(self, nums: List[int]) -> int:
max_num = set()
for num in nums:
max_num.add(num)
if len(max_num) > 3:
max_num.remove(min(max_num))
if len(max_num) < 3:
return max(max_num)
else:
return min(max_num)
#copied O1Soln
def thirdMax1(self, nums: List[int]) -> int:
one = -float('inf')
two = -float('inf')
three = -float('inf')
for num in nums:
if num > one:
one, two, three = num, one, two
elif two < num < one:
two, three = num, two
elif three < num < two:
three = num
if three == -float('inf'):
return one
else:
return three |
cf2076024b465c84689f6ba78cdd675c7b3f518c | vgattani-ds/programming_websites | /leetcode/0905_sortArrayByParity.py | 784 | 3.546875 | 4 | from typing import List
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
odd = []
insert_index = 0
for i in A:
if i%2 == 0:
A[insert_index] = i
insert_index += 1
else:
odd.append(i)
for i in range(insert_index, len(A)):
A[i] = odd[i - insert_index]
return A
def sortArrayByParity_O1(self, A: List[int]) -> List[int]:
#two pass: first add all the even nos and then add all the odd nos.O(n) and O(n)
i = 0
for j in range(len(A)):
if A[j]%2 == 0:
A[i], A[j] = A[j], A[i]
i+=1
return A
|
849cc598ac09b5f899b312e95245d93d88ac4d79 | vgattani-ds/programming_websites | /hackerrank/10_days_of_Statistics/day_6_clt_3.py | 520 | 3.765625 | 4 |
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
import math
lines = iter(sys.stdin)
n = int(next(lines))
mean = float(next(lines))
std = float(next(lines))
p = float(next(lines))
z = float(next(lines))
mean_clt = mean
std_clt = std/math.sqrt(n)
a = mean_clt + 1.96*std_clt
b = mean_clt - 1.96*std_clt
print(round(b,2))
print(round(a,2)) |
e6947f9fb72f38a30cd59a50d38d6112b978a625 | vgattani-ds/programming_websites | /leetcode/1352_ProductOfNumbers.py | 1,595 | 3.5 | 4 | from functools import reduce
from math import prod
class ProductOfNumbers:
def __init__(self):
self.nums=list()
def add(self, num: int) -> None:
self.nums.append(num)
return
if not self.nums:
self.nums.append(num)
return
last_number = self.nums[-1]*num
self.nums.append(last_number)
def getProduct(self, k: int) -> int:
last_k_nums = self.nums[-1*k:]
return prod(last_k_nums)
#return reduce((lambda x, y: x* y), last_k_nums)
#return self.nums[k`]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)
'''
class ProductOfNumbers:
def __init__(self):
self.i = 0
self.products = [1]
self.last_seen_zero = 0
def add(self, num: int) -> None:
self.i += 1
if num == 0:
self.products.append(1)
self.last_seen_zero = self.i
else:
self.products.append(self.products[-1] * num)
def getProduct(self, k: int) -> int:
N = len(self.products)
if self.last_seen_zero >= N - k:
return 0
return int(self.products[-1] / self.products[-k-1])
'''
if __name__ == "__main__":
input1 = ["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
input2 = [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
answer = [null,null,null,null,null,null,20,40,0,null,32] |
081c39e989688e3bce6a6eee4fc2df42e3fe756d | zhichaoZhang/hotfix_patch | /zzc-python3-webapp/www/db/Connect2MysqlTest.py | 800 | 3.734375 | 4 | # coding=utf-8
# 导出MySql驱动
import mysql.connector # 设置用户名、密码、数据库名
conn = mysql.connector.connect(user='root',
password='admin_zzc',
host='127.0.0.1',
database='test')
cursor = conn.cursor()
# 创建user表
cursor.execute('create table user2 (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意mysql的占位符是%s
cursor.execute('insert into user2 (id, name) value (%s, %s)', ['1', 'Michael'])
cursor.rowcount
# 提交事务
conn.commit()
cursor.close()
# 运行查询
cursor = conn.cursor()
cursor.execute('select * from user2 where id = %s', ('1',))
values = cursor.fetchall()
print(values)
cursor.close()
# 关闭连接
conn.close()
|
02303308d186f5f0b89eba92cf9728f06835b859 | eluke66/checkers | /python/python/src/Move.py | 3,044 | 3.546875 | 4 | '''
Created on Apr 9, 2017
@author: luke
'''
from Coordinate import Coordinate
from KingPiece import KingPiece
class Move(object):
def __init__(self, piece, board, moveFrom, moveTo):
self.piece = piece
self.board = board
self.moveFrom = moveFrom
self.moveTo = moveTo
def __repr__(self):
return "{} moving from {} to {}".format(self.piece, self.moveFrom, self.moveTo)
@staticmethod
def simpleMove(board, piece, startCoord, endCoord):
return SimpleMove(piece, board, startCoord, endCoord)
@staticmethod
def jumpMove(board, piece, startCoord, endCoord):
return JumpMove(piece, board, startCoord, endCoord, Coordinate.extending(startCoord, endCoord))
@staticmethod
def multiJumpMove(board, piece, startCoord, endCoord, move):
return MultiJumpMove(piece, board, startCoord, endCoord, Coordinate.extending(startCoord, endCoord), move)
def moveAndKingPiece(self, piece):
self.board.placePieceAt(piece, self.moveTo)
if self.board.isFinalRowForPiece(piece, self.moveTo) and piece.canBeKinged:
self.board.placePieceAt(KingPiece(piece.color), self.moveTo)
class SimpleMove(Move):
def __init__(self, piece, board, moveFrom, moveTo):
super().__init__(piece, board, moveFrom, moveTo)
def execute(self):
del self.board[self.moveFrom]
self.moveAndKingPiece(self.piece)
def unExecute(self):
del self.board[self.moveTo]
self.board[self.moveFrom] = self.piece
class JumpMove(Move):
def __init__(self, piece, board, moveFrom, existingPieceLocation, moveTo):
super().__init__(piece, board, moveFrom, moveTo)
self.removedPiece = None
self.existingPieceLocation = existingPieceLocation
def execute(self):
if self.removedPiece is None:
self.removedPiece = self.board[self.existingPieceLocation]
del self.board[self.moveFrom]
self.moveAndKingPiece(self.piece)
del self.board[self.existingPieceLocation]
else:
raise RuntimeError("Trying to re-execute jump move " + str(self))
def unExecute(self):
if self.removedPiece is not None:
del self.board[self.moveTo]
self.board[self.moveFrom] = self.piece
self.board[self.existingPieceLocation] = self.removedPiece
self.removedPiece = None
else:
raise RuntimeError("Trying to unexecute jump move that has not been executed" + str(self))
class MultiJumpMove(JumpMove):
def __init__(self, piece, board, moveFrom, existingPieceLocation, moveTo, previousMove):
super().__init__(piece, board, moveFrom, existingPieceLocation, moveTo)
self.previousMove = previousMove
def execute(self):
self.previousMove.execute()
JumpMove.execute(self)
def unExecute(self):
JumpMove.unExecute(self)
self.previousMove.unExecute()
|
9a6002e2d82d75a10a1df8a68fad30ed8fa6325f | PrathushaKoouri/Competitive-Coding-6 | /80_LoggerRateLimiter(359).py | 1,776 | 3.890625 | 4 | # To implement double linked list we need a Node, created Node.
class Node:
def __init__(self, timestamp, message):
self.timestamp = timestamp
self.message = message
self.prev = None
self.next = None
class Logger:
# Here, initialized all the pointers in double linked list and also map and size are initialized.
def __init__(self):
self.head = Node(0, "")
self.tail = Node(0, "")
self.head.next = self.tail
self.tail.prev = self.head
self.head.prev = None
self.tail.next = None
self.max_time = 10
self.map = {}
def shouldPrintMessage(self, timestamp, message) -> int:
if message in self.map:
node = self.map[message]
if timestamp-node.timestamp < self.max_time:
return False
self.moveToHead(node,timestamp)
else:
if len(map) >= self.max_time:
self.removeTail()
self.addToHead(timestamp,message)
def addToHead(self, timestamp, message):
newnode = Node(timestamp,message)
newnode.next = self.head.next
self.head.next = newnode
newnode.prev = self.head
newnode.next.prev = newnode
self.map[message] = newnode
def removeTail(self):
self.tail.prev.next = self.tail.next
self.tail.next.prev = self.tail.prev
self.map.pop(self.tail.message, None)
def moveToHead(self, node, timestamp):
node.timestamp = timestamp
node.prev.next = node.next
node.next.prev = node.prev
node.next = self.head.next
node.prev = self.head
self.head.next = node
node.next.prev = node
|
30c3168bef3c13592401b05f3e140cb35a239484 | yanviegas/small_codes | /teste_1_quadrado.py | 160 | 3.796875 | 4 | side = float(input("Digite o valor correspondente ao lado de um quadrado: "))
peri = 4*side
area = side**2
print("perímetro:", peri, "- área:", area)
|
6b2ca73b9e5ccf01fa7ab8a4c1c54cc793b4feba | yanviegas/small_codes | /teste_1_fatorial.py | 160 | 3.984375 | 4 | num = int(input("Digite o valor de n: "))
if num != 0:
fat = num
else:
fat = 1
while num > 1:
num = num - 1
fat = fat * num
print(fat)
|
fe99c8ccc57283cfb6daf8f39f4c507e8730957c | yanviegas/small_codes | /exer_2_inverte_seq.py | 253 | 3.875 | 4 | def main():
x = int(input("Digite um número: "))
lista = []
while x != 0:
lista.append(x)
x = int(input("Digite um número: "))
for y in range(len(lista) - 1, -1, -1):
print(lista[y])
main()
|
0de0d10a0c66f4248d12cbe59f506f49e08d796c | pallavineelamraju/MyEffort | /PythonPrograms/hackerrankprograms/countsubstr.py | 345 | 3.984375 | 4 | def count_substring(string,sub_string):
l=len(sub_string)
count=0
for i in range(0,len(string)):
if(string[i:i+len(sub_string)] == sub_string ):
count+=1
return count
str=input()
if(1<=len(str)<=200):
substr=input()
print(count_substring(str,substr))
else:
print("string length is out of range")
|
ed24a3bdc6d9260988b8e5bc8a247b1c7ab9dc7b | sachin1005singh/complete-python | /python_program/all program/15list_use.py | 249 | 4 | 4 | i = 0
numbers = []
while i<6:
print("At the top i is %d" %i)
numbers.append(i)
i += 1
print("Numbers now:", numbers)
print("At bottom i is %d" %i)
print("The number :")
for num in numbers:
print(num)
|
e01ebd5c8a72ea703ef839b4260d792a819d9089 | sachin1005singh/complete-python | /python_program/all program/8reading_file.py | 873 | 3.90625 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print("Here's your file %s" %filename)
print(txt.read())
print("Type filname again :")
file_again = input("$")
txt_again = open(file_again)
print(txt_again.read())
# use of file read and write
print("We're going to erase %r" %filename)
print("If you don't want that , hit CTRL +c")
print("If you want that, hit Enter")
input("?")
print("open the file....")
target = open(filename,'w')
print("Turncating the file. goodbyyy!")
target.truncate()
print("Now i'm gonig to ask you for three line. ")
line1 = input("$ line1 :")
line2 = input("$ line2 :")
line3 = input("$ line3 :")
print("Now I'm gonig to write these to the file.")
target.write(line1 )
target.write(line2 + "\n")
target.write(line3 + "\n")
print("task complete . we close it.")
target.close() |
902738dec190609def2231db3b3b2a42506b7ff9 | sachin1005singh/complete-python | /python_program/fabonic series.py | 166 | 3.5 | 4 | # use of fabonic series
def fab(n):
res = []
a, b = 0,1
while a<n:
res.append(a)
a,b = b, a+b
return res
fa = fab(100)
|
73bac6a349743b14c5a7e78f1aacbe2b460e3fb8 | sachin1005singh/complete-python | /python_program/function use.py | 173 | 3.921875 | 4 | #use of function
def greet(name,msg):
""" this function is for basic use of
function."""
print("hello", name + ',', msg)
greet("sachin","good morning!")
|
5ccb88df6a21f7a105c7c08d2551412c4cc307bb | sachin1005singh/complete-python | /python_program/findvowel.py | 218 | 4.28125 | 4 | #vowels program use of for loop
vowel = "aeiouAEIOU"
while True:
v = input("enter a vowel :")
if v in vowel:
break
print("this in not a vowel ! try again !!")
print("thank you")
|
5a5b44d7f3f64701e827a9e1c2bc072ceeebff79 | Meormy/PIAIC_Assignments_1 | /InterestCalculator.py | 436 | 3.875 | 4 | # A = Total Accrued Amount (principal + interest)
# P = Principal Amount
# I = Interest Amount
# r = Rate of Interest per year in decimal; r = R/100
# R = Rate of Interest per year as a percent; R = r * 100
# t = Time Period involved in months or years
# Equation:
# A = P(1 + rt)
P = int(input("Enter Amount : "))
R = int(input("Enter Rate : "))
r = float(R / 100)
t = int(input("Enter Time Period : "))
A = P * (1 + (r*t))
print (A)
|
81fa7d68ab70c6319c299caadb885b5f34e162b0 | zhou-jia-ming/Learn-AI | /ch1/prog1.py | 1,640 | 3.59375 | 4 | # -*- encoding: utf-8 -*-
# @FileName: prog1.py
# @Author: Zhou Jiaming
# @Time: 8/25/21 10:36 PM
"""
三个门后边有两个门空的,一个有奖
要求: 选择一个门,争取获得奖品
你选中一个门,还没有打开门。
然后主持人打开另一个空的门。
此时你换一个门会得到更大的概率吗?
"""
import random
def DoorAndPrizeSim(switch, loopNum):
"""
模拟各种情况下的中奖概率
:param switch:
:param loopNum:
:return:
"""
win = 0
total = 0
for loop in range(loopNum):
# 初始化奖品和选择的门
prize = random.randint(0, 2)
initialChoose = random.randint(0, 2)
doors = [0,1,2]
doors.remove(prize) # 移除有奖门
if initialChoose in doors:
doors.remove(initialChoose) # 移除选中门
# 随机打开一个门,改门不是选中门并且是没有奖品的。
n = len(doors)
r = random.randint(0, n-1)
openDoor = doors[r]
# 计算判断后的门
if(switch):
secondChoice = 3 - openDoor - initialChoose
else:
secondChoice = initialChoose
total += 1
if (secondChoice == prize):
win +=1
return win/total
if __name__ == "__main__":
print("when switching, the winning rate is ",
DoorAndPrizeSim(True, 1000000))
print("when not switching, the winning rate is ",
DoorAndPrizeSim(False, 1000000))
# 一个可能的输出如下:
# when switching, the winning rate is 0.666942
# when not switching, the winning rate is 0.333271
|
23196f4de3a93497995f5f55cd58455bd024c7d5 | w4995-dl-colorization/Colorization-with-Attention | /ops.py | 4,475 | 3.625 | 4 | import tensorflow as tf
def _variable(name, shape, initializer):
"""Helper to create a Variable stored on CPU memory.
Args:
name: name of the Variable
shape: list of ints
initializer: initializer of Variable
Returns:
Variable Tensor
"""
var = tf.get_variable(name, shape, initializer=initializer, dtype=tf.float32)
return var
def _variable_with_weight_decay(name, shape, stddev, wd=0.001):
"""Helper to create an initialized Variable with weight decay.
Note that the Variable is initialized with truncated normal distribution
A weight decay is added only if one is specified.
Args:
name: name of the variable
shape: list of ints
stddev: standard devision of a truncated Gaussian
wd: add L2Loss weight decay multiplied by this float. If None, weight
decay is not added for this Variable.
Returns:
Variable Tensor
"""
var = _variable(name, shape, tf.truncated_normal_initializer(stddev=stddev, dtype=tf.float32))
if wd is not None:
weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var
def conv2d(scope, input, kernel_size, stride=1, dilation=1, relu=True, wd=0.001):
"""convolutional layer
Args:
scope: string, variable_scope name
input: 4-D tensor [batch_size, height, width, depth]
kernel_size: 4-D tensor [k_height, k_width, in_channel, out_channel]
stride: int32, the stride of the convolution
dilation: int32, if >1, dilation will be used
relu: boolean, if relu is applied to the output of the current layer
wd: float32, weight decay/regularization coefficient
Return:
output: 4-D tensor [batch_size, height * stride, width * stride, out_channel]
"""
with tf.variable_scope(scope) as scope:
kernel = _variable_with_weight_decay('weights',
shape=kernel_size,
stddev=5e-2,
wd=wd)
if dilation == 1:
conv = tf.nn.conv2d(input, kernel, [1, stride, stride, 1], padding='SAME')
else:
conv = tf.nn.atrous_conv2d(input, kernel, dilation, padding='SAME')
biases = _variable('biases', kernel_size[3:], tf.constant_initializer(0.0))
bias = tf.nn.bias_add(conv, biases)
if relu:
conv1 = tf.nn.relu(bias)
else:
conv1 = bias
return conv1
def deconv2d(scope, input, kernel_size, stride=1, wd=0.001):
"""deconvolutional layer for upsampling
Args:
scope: string, variable_scope name
input: 4-D tensor [batch_size, height, width, depth]
kernel_size: 4-D tensor [k_height, k_width, in_channel, out_channel]
stride: int32, the stride of the convolution
wd: float32, weight decay/regularization coefficient
Return:
output: 4-D tensor [batch_size, height * stride, width * stride, out_channel]
"""
batch_size, height, width, in_channel = [int(i) for i in input.get_shape()]
out_channel = kernel_size[3]
kernel_size = [kernel_size[0], kernel_size[1], kernel_size[3], kernel_size[2]]
output_shape = [batch_size, height * stride, width * stride, out_channel]
with tf.variable_scope(scope) as scope:
kernel = _variable_with_weight_decay('weights',
shape=kernel_size,
stddev=5e-2,
wd=wd)
deconv = tf.nn.conv2d_transpose(input, kernel, output_shape, [1, stride, stride, 1], padding='SAME')
biases = _variable('biases', (out_channel), tf.constant_initializer(0.0))
bias = tf.nn.bias_add(deconv, biases)
deconv1 = tf.nn.relu(bias)
return deconv1
def batch_norm(scope, input, train=True, reuse=False):
"""Batch Normalization Layer
Args:
scope: string, variable_scope name
input: 4-D tensor [batch_size, height, width, depth]
train: boolean, if it is training
reuse: boolean, if it is reused
Return:
output: 4-D tensor [batch_size, height * stride, width * stride, out_channel]
"""
return tf.contrib.layers.batch_norm(input, center=True, scale=True, updates_collections=None,
is_training=train, trainable=True, scope=scope)
|
b7767437a8b10ab79584dee7c62d6dcc312a0df3 | vvarga007/linux_tools | /python/examples/Math.py | 1,313 | 3.515625 | 4 | from unittest import TestCase
"""
Example code to demonstrate Sphinx capabilities.
Sphinx uses reStructuredText as its markup language,
and many of its strengths come from the power and straightforwardness of
reStructuredText and its parsing and translating suite, the Docutils.
"""
class Math:
""" Methods for arithmetic operations """
@staticmethod
def multiply(*args: int):
"""
Multiply input parameters
:type args: :class:`list` of :class:`int`
:param args: List of integers
"""
result = 1
for x in args:
result *= x
return result
@staticmethod
def sum(*args: int):
"""
Addition of input parameters
:type args: :class:`list` of :class:`int`
:param args: List of integers
"""
result = 0
for x in args:
result += x
return result
class Test(TestCase):
""" Methods for unittesting """
def test_multiply(self):
""" Unittest for Math.multiply """
result = Math().multiply(4, 5, 6)
self.assertEqual(result, 120, 'Multiplication error!')
def main():
math = Math()
print(math.sum(4, 5, 6))
print(math.multiply(4, 5, 6))
Test().test_multiply()
if __name__ == '__main__':
main()
|
be933bc97528fe0e1dac8c5e4adff84032070dac | ssd338/Python-leaning | /function/function3.py | 188 | 3.625 | 4 | def p_plus(a, b):
print(a + b)
def r_plus(a, b):
return a + b
p_result = p_plus(2, 3)
r_result = r_plus(2, 3)
print(p_result, r_result) #return 값이 없으므로 p_result는 none |
ddef902f4d6dbab328949b2fe67854e3afd2c01a | kartsridhar/Problem-Solving | /HackerRank/10-Days-of-Statistics/Day0/weightedMean.py | 246 | 3.84375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
x = list(map(float, input().split()))
w = list(map(float, input().split()))
weighted = sum(i*j for i, j in zip(x, w))
avg = weighted/sum(w)
print('%.1f' % avg) |
74a079f8a0c40df56f5412dd4723cb2368b3759a | kartsridhar/Problem-Solving | /halindrome.py | 1,382 | 4.25 | 4 | """
Given a string S. divide S into 2 equal parts S1 and S2. S is a halindrome if
AT LEAST one of the following conditions satisfy:
1. S is a palindrome and of length S >= 2
2. S1 is a halindrome
3. S2 is a halindrome
In case of an odd length string, S1 = [0, m-1] and S2 = [m+1, len(s)-1]
Example 1:
input: harshk
output: False
Explanation 1:
S does not form a palindrome
S1 = har which is not a halindrome
S2 = shk which is also not a halindrome.
None are true, so False.
Example 2:
input: hahshs
output: True
Explanation 2:
S is not a palindrome
S1 = hah which is a palindrome
S2 = shs which is also a palindrome
Example 3:
input: rsrabdatekoi
output: True
Explanation 3:
rsrabd, atekoi
Neither are palindromic so you take each word and split again
Break down rsrabd coz it's not palindromic,
rsr, abd.
rsr length is >=2 and is a palindrome hence it's true
"""
def splitString(s):
return [s[0:len(s)//2], s[len(s)//2:]] if len(s) >= 2 else []
def checkPalindrome(s):
return s == s[::-1] if len(s) >= 2 else False
def checkHalindrome(s):
print(s)
if checkPalindrome(s):
return True
else:
splits = splitString(s)
if len(splits) == 0:
return False
else:
for i in splits:
return checkHalindrome(i)
return False
inputs = 'rsrabdatekoi'
print(checkHalindrome(inputs)) |
408d751896467c077d7dbc1ac9ffe6239fed474d | kartsridhar/Problem-Solving | /HackerRank/Problem-Solving/Basic-Certification/unexpectedDemand.py | 1,630 | 4.40625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'filledOrders' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY order
# 2. INTEGER k
#
"""
A widget manufacturer is facing unexpectedly high demand for its new product,. They would like to satisfy as many customers as possible. Given a number of widgets available and a list of customer orders, what is the maximum number of orders the manufacturer can fulfill in full?
Function Description
Complete the function filledOrders in the editor below. The function must return a single integer denoting the maximum possible number of fulfilled orders.
filledOrders has the following parameter(s):
order : an array of integers listing the orders
k : an integer denoting widgets available for shipment
Constraints
1 ≤ n ≤ 2 x 105
1 ≤ order[i] ≤ 109
1 ≤ k ≤ 109
Sample Input For Custom Testing
2
10
30
40
Sample Output
2
"""
def filledOrders(order, k):
# Write your code here
total = 0
for i, v in enumerate(sorted(order)):
if total + v <= k:
total += v
else:
return i
else:
return len(order)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
order_count = int(input().strip())
order = []
for _ in range(order_count):
order_item = int(input().strip())
order.append(order_item)
k = int(input().strip())
result = filledOrders(order, k)
fptr.write(str(result) + '\n')
fptr.close()
|
dfc62ddbade85590df3743bc838e458f120f0259 | kartsridhar/Problem-Solving | /Ocado/necklaceProblem.py | 883 | 4.0625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
# You have a list where each number points to another.Find the length of the longest necklace
# A[0] = 5
# A[1] = 4
# A[2] = 3
# A[3] = 0
# A[4] = 1
# A[5] = 2
def solution(A):
# write your code in Python 3.6
if len(A) == 0:
return 0
else:
longest = 0 # to keep track of the longest chain
for i in range(len(A)):
length = 1 # shortest length of a chain will have 1 bead
start = A[i] # starting with the current index
while A[start] != A[i]:
length += 1 # incrementing the length until the start and end beads match
start = A[start]
if length > longest: # if length longer than the longest, update
longest = length
return longest |
4d6c6e1aae0f3a6163b541ebd08e1353c22cf496 | kartsridhar/Problem-Solving | /HackerRank/Problem-Solving/Strings/strongPassword.py | 1,257 | 3.734375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumNumber function below.
def minimumNumber(n, password):
# Return the minimum number of characters to make the password strong
count = 0
numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "!@#$%^&*()-+"
criteria = [False] * 4 # num = 0, lower = 1, upper = 2, special = 3
for i in range(n):
if password[i] in numbers:
criteria[0] = True
elif password[i] in lower_case:
criteria[1] = True
elif password[i] in upper_case:
criteria[2] = True
elif password[i] in special_characters:
criteria[3] = True
if not all(criteria):
count = criteria.count(False)
if len(password) + count < 6:
count += 6 - (len(password) + count)
else:
if len(password) < 6:
count = 6 - len(password)
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
password = input()
answer = minimumNumber(n, password)
fptr.write(str(answer) + '\n')
fptr.close()
|
0bb4a60d97bd89abc8f458373ae62035e6d35ff7 | kartsridhar/Problem-Solving | /findLargestNumber.py | 471 | 3.890625 | 4 | def isSorted(num):
digits = list(str(num))
unique = list(set(digits))
if digits != unique:
return False
else:
return digits == list(sorted(digits))
def findLargestNumber(num):
if num < 10:
return num
while num > 9:
if not isSorted(num):
num -= 1
else:
return num
return 0
if __name__ == "__main__":
num = int(input())
result = findLargestNumber(num)
print(result)
|
23e05ad2a184f9427b0750391ae2c8626a904c11 | kartsridhar/Problem-Solving | /angryIntegers.py | 743 | 3.640625 | 4 | # count the number of angry numbers less than the current number
# angry number = an integer of the form a^x + b^y
# upper bound = 100000
def computeAxBy(a, b):
upperBound = 9223372036854775806
result = []
x = 1
y = 1
while x <= upperBound:
while y <= upperBound:
if x + y <= upperBound:
result.append(x + y)
y *= b
x *= a
y = 1
return result
def countAngry(n, a, b, x):
integers = computeAxBy(a, b)
for i in range(n):
print(sum(1 for j in integers if j < x[i]))
if __name__ == '__main__':
n = int(input())
a = int(input())
b = int(input())
x = list(map(int, input().split()))
countAngry(n, a, b, x) |
0974094bbfa2495cf4b67090c11c708eaa303443 | kartsridhar/Problem-Solving | /2sigma/substrings.py | 935 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'findSubstrings' function below.
#
# The function accepts STRING s as parameter.
#
def findSubstrings(s):
# Write your code here
# start iterating from the 0th index of the string. if it is a vowel, start a new loop from i+1 and check if that character is a consonant.
# If it is a consonant, append it to the results
# sort the results in the end and the return [0] and [-1] elements of the result list.
s.lower()
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
result = []
for i in range(len(s)):
if s[i] in list(vowels):
for j in range(i+1, len(s)):
if s[j] in list(consonants):
result.append(s[i:j+1])
result.sort()
print(result[0])
print(result[-1])
if __name__ == '__main__':
s = input()
findSubstrings(s)
|
ae2873c9c7a2ed57885f647fcba53c80f1fc4ba5 | kartsridhar/Problem-Solving | /HackerRank/Problem-Solving/Dynamic-Programming/fibonacciModifiedMem.py | 746 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the fibonacciModified function below.
def fib(t1, t2, n, dp):
if dp[n] != None:
return dp[n]
result = 0
if n == 1:
result = t1
elif n == 2:
result = t2
else:
result = fib(t1,t2,n-2,dp) + (fib(t1,t2,n-1,dp) ** 2)
dp[n] = result
return result
def fibonacciModified(t1, t2, n):
dp = [None] * (n+1)
return fib(t1,t2,n,dp)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t1T2n = input().split()
t1 = int(t1T2n[0])
t2 = int(t1T2n[1])
n = int(t1T2n[2])
result = fibonacciModified(t1, t2, n)
fptr.write(str(result) + '\n')
fptr.close()
|
870e96663b255d9dde315db16b386a95e2370ba3 | kartsridhar/Problem-Solving | /HackerRank/10-Days-of-Statistics/Day6/centralLimitTh1.py | 313 | 3.5625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
maxWt = float(input())
n = float(input())
mean = float(input())
std = float(input())
mean *= n
std = std * math.sqrt(n)
phi = lambda m, v, val : 0.5 * (1+math.erf((val-m)/(v*math.sqrt(2))))
print(round(phi(mean, std, maxWt), 4)) |
60be71eb81f110604599a4feec973cbd1042dbe6 | jin-sj/git_ci_test | /koreantools/utils/audio_utils.py | 1,827 | 3.640625 | 4 | """ Utily functions to process audio files """
import os
import sys
import wave
def pcm_to_wave(pcm_file_path, num_channels=1, num_bytes=2, frame_rate=16000,
nframes=0, comp_type="NONE", comp_name="NONE"):
""" Converts a raw .pcm file to .wav file
Args:
pcm_file_path (str): Full path to pcm file
num_channels (int): 1 for Mono, 2 for stereo
num_bytes (int): Number of bytes per sample width
frame_rate (int): Frame rate
nframes (int): n frames
comp_type (str): Compression type
comp_name (str): Compression description
"""
with open(pcm_file_path, 'rb') as pcmfile:
pcmdata = pcmfile.read()
wav_name = pcm_file_path.split('.')[0] + '.wav'
wavfile = wave.open(wav_name, 'wb')
wavfile.setparams((num_channels, num_bytes, frame_rate, nframes, comp_type, comp_name))
wavfile.writeframes(pcmdata)
wavfile.close()
def main():
""" Main entry """
if len(sys.argv) < 2:
print("Please provide root dir for the pcm files")
sys.exit(1)
num_channels = 1
num_bytes = 2
frame_rate = 16000
nframes = 0
comp_type = 'NONE'
comp_name = 'NONE'
i = 0
filename = ''
for root, _, files in os.walk(sys.argv[1]):
for name in files:
if ".pcm" in name:
filename = os.path.join(root, name)
pcm_to_wave(filename, num_channels=num_channels, num_bytes=num_bytes,
frame_rate=frame_rate, nframes=nframes, comp_type=comp_type,
comp_name=comp_name)
i += 1
if i % 200 == 0:
print("Completed converting: %d files, current file: %s" % (i, filename))
if __name__ == "__main__":
main()
|
fd3d933e3a214e1378851cd253bea6850d41f9b0 | jingd16/python-challenge | /PyPoll/main.py | 3,693 | 3.890625 | 4 | import os
import csv
#Set path to read and write CSV file
csvpath = os.path.join("Resources", "election_data.csv")
output_file = os.path.join("analysis", "PyPoll.txt")
Total_vote = 0
Newlist =[]
Newlist2=[]
voterID_List = []
Location_List = []
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
#Skip the header
csv_header = next(csvreader)
#Loop through the CSV file to:
# 1. Count how many rows/vote in total
# 2. Create a list for each column in CSV file, and add the list while looping through all the rows
for row in csvreader:
#Count total Votes from total line of rows
Total_vote = Total_vote + 1
#add each value into a list
candidate_name = str(row[2])
voterID = str(row[0])
location = str(row[1])
Newlist.append(candidate_name)
voterID_List.append(voterID)
Location_List.append(location)
#Print Headline of the summary
print("Election Results")
print("---------------------")
#Print total vote
print("Total Votes: " + str(Total_vote))
print("---------------------")
#Create a new Candidate list, but delete all repeatitive values/names
Newlist2=list(set(Newlist))
#Count the new candidiate list, and find out how many candidates are there, so we can setup how many times we need to loop through the dataset
count_Loop = len(Newlist2)
name_of_Candidate = ""
Candidiate_Vote_Count = 0
winner = ""
winner_count = 0
#Create a list of results, so we can write the information into a CSV file later.
Results_List=[]
#Now we know how many candidates in total, setup a loop to go through the dataset x amount of times, to add up votes for that candidate
for x in range(0, count_Loop):
#Create a turple by zipping all the collumns/lists
#---Check with TA/Manager---
# How to ask the pointer to go to the top of the turple when completing multiple loop. Tried to define the pollData(Turple) outside the loop, so it's more efficient, but it will only provide information for first candidiates.
pollData = zip(voterID_List, Location_List, Newlist)
name_of_Candidate = Newlist2[x]
#Reset vote count for each candidate
Candidiate_Vote_Count = 0
#looping through the turple according to the candidate name, and add up votes for Each candidates.
for y in pollData:
if y[2] == name_of_Candidate:
Candidiate_Vote_Count = Candidiate_Vote_Count + 1
per_vote = round((Candidiate_Vote_Count / Total_vote) * 100, 0)
#Print results + Save the result to a list to write a text file later
print(name_of_Candidate + ": " + str(per_vote) +"% (" + str(Candidiate_Vote_Count) + ") ")
Results_List.append(name_of_Candidate + ": " + str(per_vote) +"% (" + str(Candidiate_Vote_Count) + ") ")
#Compare the vote result and find the person with highest count, then print the winner name
if per_vote > winner_count:
winner_count = per_vote
winner = name_of_Candidate
print("---------------------")
print ("Winner: " + winner)
print("---------------------")
#write the summary information to a text file
with open(output_file, "w") as outputFile:
csvwriter = csv.writer(outputFile)
csvwriter.writerow(["Election Results"])
csvwriter.writerow(["------------------------------"])
csvwriter.writerow(["Total Votes: " + str(Total_vote)])
csvwriter.writerow(["------------------------------"])
for row in Results_List:
csvwriter.writerow([row])
csvwriter.writerow(["------------------------------"])
csvwriter.writerow(["Winner: " + winner])
csvwriter.writerow(["------------------------------"]) |
2852f25cf0c6b440307fc5af947f2bbcbe83496a | akshaykhadka/My-Projects | /_1_Cricket_Game.py | 5,610 | 4.03125 | 4 | import random
def toss_coin():
coin = input("Choose 'E' for Even and 'O' for odd -> ")
print(" ")
your_num = int(input("Now select a number between 0-5: "))
random_num = random.randint(0, 5)
print(" ")
print("your number {} and computer's number {}".format(your_num, random_num))
random_sum = your_num + random_num
if coin.lower() == 'e':
if random_sum % 2 == 0:
return True
else:
return False
elif coin.lower() == 'o':
if random_sum % 2 == 0:
return False
else:
return True
else:
if random_sum % 2 == 0:
return False
else:
return True
def zero_adjuster(x, y):
if x == 0:
return y
else:
return x
def game_replay():
replay = input("Do you want another game? Enter y/n: ")
if replay.lower() == 'y':
return True
else:
return False
def win_check(player_score, computer_score):
if player_score > computer_score:
print("You Won !!!")
elif computer_score > player_score:
print("You Lost :( ")
else:
print("The Game is drawn.")
def check_if_won(x, y):
pass
# Now starts the game compilation...
#####################################
while True:
# Printing the Welcome Note
print("Welcome to the Game of Cricket !")
print(" ")
# Starting the game
game_on = False
play = input("Are you ready to play? Enter y/n: ")
if play == 'y':
game_on = True
else:
game_on = False
break
# Tossing the coin
player_chance = False
computer_chance = False
if toss_coin():
player_chance = True
print(" ")
print("You Won the toss, your batting first...")
else:
computer_chance = True
print(" ")
print("You Lost the toss, you'll bowl first...")
player_score = 0
computer_score = 0
while game_on:
# Setting OUT = False first
out = False
# Initiating player's turn...
while not out and player_chance:
# Asking for the user input and generating computer's number
user_input = -1
while not (user_input >= 0 and user_input < 6):
user_input = int(input("Enter a number between 0-5: "))
computer_number = random.randint(0, 5)
# Checking wether OUT or NOT OUT
if user_input == computer_number:
out = True
print("Computer's number: {}".format(computer_number))
print("\n")
print("OUT !!!")
print("\n")
print("Your total score {}".format(player_score))
print("\n")
if computer_chance:
game_on = False
computer_chance = False
break
computer_chance = True
break
else:
# Adjusting for the zero
user_input = zero_adjuster(user_input, computer_number)
player_score += user_input
print("Computer's number: {}".format(computer_number))
print("Your score -> {}".format(player_score))
print(" ")
# Check whether the player has already won
if computer_chance:
if player_score > computer_score:
game_on = False
computer_chance = False
break
# Keep asking for the player input until the player is OUT
# Again setting OUT = False for the computer
out = False
# Initiating computer's turn...
while not out and computer_chance:
# Again asking for the user input and generating computer's number
user_input = -1
while not (user_input >= 0 and user_input < 6):
user_input = int(input("Enter a number between 0-5: "))
computer_number = random.randint(0, 5)
# Checking whether the computer is OUT or NOT
if user_input == computer_number:
out = True
print("Computer's number: {}".format(computer_number))
print("\n")
print("Computer is OUT !!!")
print("\n")
print("computer's total score {}".format(computer_score))
print("\n")
if player_chance:
game_on = False
break
player_chance = True
break
else:
computer_number = zero_adjuster(computer_number, user_input)
computer_score += computer_number
print("Computer's number: {}".format(computer_number))
print("computer's score -> {}".format(computer_score))
print(" ")
# Check wether the computer has already won
if player_chance:
if computer_score > player_score:
game_on = False
break
# Keep asking for the player's input until the computer is OUT
# Deciding who won the game
print("Your total score {}".format(player_score))
print("computer's total score {}".format(computer_score))
print(" ")
win_check(player_score, computer_score)
print("\n")
# Asking user for the replay
if game_replay():
game_on = True
else:
print("\n")
print("Thank You for playing !!")
break
|
914c7c8db0d3d316d22d899ba6756368ae4eb392 | pythonmite/Daily-Coding-Problem | /problem_6_medium.py | 514 | 4.1875 | 4 | """
Company Name : DropBox
Problem Statement : Find the second largest element in the list. For example: list :[2,3,5,6,6]
secondlargestelement >>> [5]
"""
def findSecondLargestNum(arr:list):
max = arr[0]
for num in arr:
if num > max:
max = num
secondlargest = 0
for num in arr:
if num > secondlargest and num < max:
secondlargest = num
return secondlargest
arr = [2,3,5,6,6]
answer = findSecondLargestNum(arr)
print(answer)
# >>> 5
|
c08a00b4024394ba9514e576d8382edb74ae62a5 | anonomity/PolynomialPopulation | /src/population.py | 3,112 | 3.515625 | 4 | from src.DNA import DNA
from matplotlib import pyplot as plt
import random
class population:
def __init__(self, d, amount, cluster1, cluster2,mutation):
self.d = d
self.amount = amount
self.cluster1 = cluster1
self.cluster2 = cluster2
self.generations = 0
self.mutation = mutation
numofClus = len(cluster1)
def create_population(self,d,amount,cluster1,cluster2):
self.cluster1 = cluster1
self.cluster2 = cluster2
self.d = d
self.amount = amount
matingpool = []
popu = []
self.popu = popu
for i in range(amount):
popu.insert(i,DNA(d,cluster1,cluster2))
self.calc_fitness(amount,cluster1,cluster2)
plt.show()
# for y in range(amount):
# print(popu[y].score)
self.matingpool = matingpool
#calculate fitness
finished = 0
perfect_score = 10
return popu
def calc_fitness(self,amount,cluster1,cluster2):
popu =self.popu
for w in range(amount):
popu[w].fitness(cluster1, cluster2)
#print(popu[w].fitness(cluster1, cluster2))
popu[w].plotDNA(cluster1, cluster2)
return popu
def natural_selection(self,pop,amount,cluster1,cluster2):
self.pop = pop
maxfitness = 0
for i in range(amount):
if (pop[i].fitness(cluster1,cluster2)) > maxfitness:
#print(pop[i].fitness(cluster1, cluster2))
maxfitness = pop[i].fitness(cluster1,cluster2)
for w in range(amount):
fit = pop[w].fitness(cluster1,cluster2)
for i in range(fit):
self.matingpool.insert(i,pop[w])
return self.matingpool
def newPop(self,pop,mp,mutation):
self.mp = mp
self.pop = pop
length = len(pop)
leng = len(mp)
random.shuffle(mp)
if leng > 0:
for i in range(length):
m = random.randint(0,leng-1)
f = random.randint(0,leng-1)
#random mother
M = mp[m]
#random father
F = mp[f]
child = M.crossover(F)
child.mutate(mutation)
self.pop[i] = child
self.generations = self.generations + 1
return self.pop
def getBest(self):
record = 0.0
index = 0
for i in range(len(self.pop)):
if self.pop[i].fitness(self.cluster1,self.cluster2) > record:
index = i
record = self.pop[i].fitness(self.cluster1,self.cluster2)
return record
def getAverageFitness(self,pop,cluster1,cluster2):
self.cluster1 = cluster1
self.cluster2 = cluster2
self.pop = pop
popAvg = 0
for i in range(len(pop)):
popAvg = popAvg + pop[i].fitness(cluster1,cluster2)
popPer = popAvg / (len(pop) * 10)
return popPer*100 |
a8878ae25f45e5513652a7db6145af19c2055d3c | okayell/Scikit-learn_practice | /LinearRegression_1.py | 1,663 | 3.78125 | 4 | import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
# ------簡單線性迴歸模型 y = a + bX(只有一個解釋變數)------ #
# 建立 氣溫 與 營業額 陣列資料
temperatures = np.array([29,28,34,31,
25,29,32,31,
24,33,25,31,
26,30])
drink_sales = np.array([7.7,6.2,9.3,8.4,
5.9,6.4,8.0,7.5,
5.8,9.1,5.1,7.3,
6.5,8.4])
# 建立 X 解釋變數的DataFrame物件
X = pd.DataFrame(temperatures, columns=['Temperature'])
# 建立 target 反應變數(y)的DataFrame物件
target = pd.DataFrame(drink_sales,columns=["Drink_Sales"])
y = target["Drink_Sales"]
# 建立 lm 線性迴歸物件
lm = LinearRegression()
# 呼叫 fit() 函數來訓練模型
lm.fit(X,y) #第一個參數: 解釋變數, 第二個參數: 反應變數
print("迴歸係數:", lm.coef_) # 顯示 迴歸係數(b)
print("截距:", lm.intercept_) # 顯示 截距(a)
# ------------------模型建立完成------------------------ #
# ------------------使用模型預測------------------------ #
new_temperatures = pd.DataFrame(np.array([26,30])) # 新溫度的DataFrame物件
predicted_sales = lm.predict(new_temperatures) # 利用 predict() 預測營業額
print(predicted_sales)
# ------------------繪製迴歸縣------------------------ #
import matplotlib.pyplot as plt
plt.scatter(temperatures, drink_sales)
regression_sales = lm.predict(X)
plt.plot(temperatures,regression_sales,"b")
plt.plot(new_temperatures,predicted_sales,"ro",markersize=10)
plt.show()
|
6de65ef6542225345787c1472099ac24fe4f2192 | sf19pb1-hardeep-leyl/homework | /name_game.py | 404 | 3.53125 | 4 | """
name_game.py
Translate the input name to the Name song
"""
import sys
while True:
try:
name = input("Please type a name: ")
except EOFError:
sys.exit(0)
rest = name[1:]
nameGame = name + "," + name + ",bo-b" + rest + "\n"
nameGame += "Banana-fana fo-f" + rest + "\n"
nameGame += "Fee-fi-mo-m" + rest + "\n"
nameGame += name + "!!"
print(nameGame)
|
df7bcf4e2fef6069d52de88a7b9e456851bf9bd7 | patelkajal18/textAdventure | /islandandme.py | 3,002 | 4.25 | 4 | #Start
print("You were having a great summer by yourself alone in the middle of the ocean on a boat. You take a little nap to take a break from your self pity session. When you wake up, you find yourself on an island and your boat is broken. You are really hungry but you also need shelter. Will you find food or shelter?")
#If incorrect answer is typed
def elsecase():
print("That's not an option silly!")
print("Start over by choosing food or shelter!")
game()
#Game
def game():
task1 = input()
if task1 == "food":
print("You decide to find some food. Type 'hunt' to look for animals or type 'fruit' to gather fruits")
task2 = input()
if task2 == "hunt":
print("You run into a jaguar!!! Type 'run' to run away or type 'fight' to try scaring the jaguar")
task3 = input()
if task3 == "run":
print("The jaguar is faster than you silly! You DIE!!")
elif task3 == "fight":
print("You can't fight a jaguar alone silly! You DIE!!")
else:
elsecase()
elif task2 == "fruit":
print("You can only find some red berries. Type 'eat' to eat them or type 'not' to not risk it")
task3 = input()
if task3 == "eat":
print("Everyone knows not to eat red suspicious berries! You are POISONED and DIE!!")
elif task3 == "not":
print("Girl why you starving yourself? You STARVE and DIE!!")
else:
elsecase()
else:
elsecase()
elif task1 == "shelter":
print("You choose to build shelter. Type 'mountain' to climb the mountain or type 'beach' look around the beach?")
task2 = input()
if task2 == "mountain":
print("While climbing up the mountain you run into a tiger! Type 'run' or 'hide' to try escaping the tiger")
task3 = input()
if task3 == "run":
print("You can't out run a tiger silly! You DIE!!")
elif task3 == "hide":
print("You hide in a cave but you get caught because of a dead end. You DIE!!")
else:
elsecase()
elif task2 == "beach":
print("You find scraps of your broken boat. Type 'rebuild' to try rebuilding it or type 'house' to build a house out of the scraps")
task3 = input()
if task3 == "rebuild":
print("YAY! You rebuild the boat and set off to go back home. Bon Voyage!")
elif task3 == "house":
print("You take too long to build the house and before you can finish, the cold night freezes you to DEATH!!")
else:
elsecase()
else:
elsecase()
else:
elsecase()
#Start/Restart game
print("start")
print("Type 'food' to find food or 'shelter' to go find shelter.")
game()
|
87439d1bf08409b01de0bff41cd6e4789ea36ef9 | rsarwas/aoc | /2019-19/answers.py | 3,312 | 3.78125 | 4 | import sys
from computer import Computer
def solve(intcode):
# Simple brute force solution
# we could print the 10 by 10 results to see if there is a cone pattern
# and limit the edges of the cone, but this is just too easy.
# While not stated clearly in the instructions, the program halts after
# creating the output. It cannot be resumed. It can also not be restarted
# I need to "reload" the int code for each run.
total = 0
results = []
for y in range(50):
row = []
results.append(row)
for x in range(50):
computer = Computer(intcode)
computer.push_input(y)
computer.push_input(x)
computer.start()
output = computer.pop_output()
row.append(output)
if output == 1:
total += 1
# print(x, y, output, total)
# print(''.join(['.' if i == 0 else '#' for i in row]))
return total
def run(intcode, x, y):
computer = Computer(intcode)
computer.push_input(y)
computer.push_input(x)
computer.start()
return computer.pop_output()
def solve2(intcode, x_avg, y_avg):
"""
Scan the full width and height of the beam (+/- width) @ (x_avg,y_avg)
"""
width = 120
last_val = 0
x_min, x_max, y_min, y_max = 0, 0, 0, 0
for x in range(x_avg - width, x_avg + width):
beam = run(intcode, x, y_avg)
if beam != last_val:
if beam == 1:
x_min = x
else:
x_max = x-1
#print("Y:", y_avg, "X:", x-1, last_val, x, beam)
last_val = beam
last_val = 0
for y in range(y_avg - width, y_avg + width):
beam = run(intcode, x_avg, y)
if beam != last_val:
if beam == 1:
y_min = y
else:
y_max = y-1
#print("X:", x_avg, "Y:", y-1, last_val, y, beam)
last_val = beam
print("@ ({0},{1}) X:{2}-{3} Y:{4}-{5}".format(x_avg, y_avg,
x_avg-x_min, x_max-x_avg+1, y_avg-y_min, y_max-y_avg+1))
def solve3(intcode, x_avg, y_avg):
"""
Scan for the maximum edge of the beam @ (x_avg,y_avg)
Assuming it is close to 100
"""
size = 100
for width in range(size - 5, size + 5):
beam = run(intcode, x_avg + width, y_avg)
if beam == 0:
break
for height in range(size - 5, size + 5):
beam = run(intcode, x_avg, y_avg + height)
if beam == 0:
break
print("@ ({0},{1}) W:{2} H:{3}".format(x_avg, y_avg, width, height))
def main():
program = [int(x) for x in sys.stdin.read().split(',')]
answer = solve(program)
print("Part 1: {0}".format(answer))
#solve2(program, 1630, 1400)
#solve2(program, 1640, 1400)
#solve2(program, 1650, 1400)
#solve2(program, 1822, 1556)
#solve2(program, 1821, 1556)
#solve2(program, 1822, 1557)
#solve3(program, 1822, 1556)
#solve3(program, 1821, 1556)
#solve3(program, 1822, 1557)
#solve3(program, 1868, 1596)
#for x in range(1863, 1870):
# for y in range(1590, 1598):
# solve3(program, x, y)
solve3(program, 1865, 1593)
answer = 1865 * 10000 + 1593
print("Part 2: {0}".format(answer))
if __name__ == '__main__':
main()
|
ae3cf1c9686d5ab5d23aa88f657305857ff21015 | rsarwas/aoc | /2022-08/answers.py | 3,640 | 3.8125 | 4 | # Data Model:
# ===========
# lines is a list of "\n" terminated strings from the input file
def part1(lines):
map = parse(lines)
trees = visible(map)
# display(trees,len(map))
return len(trees)
def part2(lines):
data = parse(lines)
# print(scenic_score(1,2,data))
# print(scenic_score(3,2,data))
best = 0
for r in range(len(data)):
for c in range(len(data[r])):
score = scenic_score(r, c, data)
if score > best:
best = score
return best
def parse(lines):
map = []
for line in lines:
line = line.strip()
row = [int(char) for char in line]
map.append(row)
return map
def visible(data):
result = set() # unique (r,c) tuples
# check rows
for r in range(len(data)):
# looking left to right
tallest = -1
for c in range(len(data[r])):
height = data[r][c]
if height > tallest:
result.add((r, c))
tallest = height
if height == 9:
break
# looking right to left
tallest = -1
for c in range(len(data[r]) - 1, -1, -1):
height = data[r][c]
if height > tallest:
result.add((r, c))
tallest = height
if height == 9:
break
# check columns
# looking top to bottom
tallest = [-1] * len(data[0])
for r in range(len(data)):
for c in range(len(data[r])):
height = data[r][c]
if height > tallest[c]:
result.add((r, c))
tallest[c] = height
# looking bottom to top
tallest = [-1] * len(data[0])
for r in range(len(data) - 1, -1, -1):
for c in range(len(data[r])):
height = data[r][c]
if height > tallest[c]:
result.add((r, c))
tallest[c] = height
return result
def scenic_score(r, c, data):
r_count = len(data)
c_count = len(data[0])
if r == 0 or c == 0 or c == c_count - 1 or r == r_count - 1:
# on an edge so one of the distance will be zero, so score is zero
return 0
height = data[r][c]
# look down; increase r to edge or tree of equal or greater height
down = 0
ri = r + 1
while ri < r_count:
down += 1
if data[ri][c] >= height:
break
ri += 1
if down == 0:
return 0
# look down; decrease r to edge or tree of equal or greater height
up = 0
ri = r - 1
while ri >= 0:
up += 1
if data[ri][c] >= height:
break
ri -= 1
if up == 0:
return 0
# look right; increase c to edge or tree of equal or greater height
right = 0
ci = c + 1
while ci < c_count:
right += 1
if data[r][ci] >= height:
break
ci += 1
if right == 0:
return 0
# look left; decrease c to edge or tree of equal or greater height
left = 0
ci = c - 1
while ci >= 0:
left += 1
if data[r][ci] >= height:
break
ci -= 1
if left == 0:
return 0
# print(r, c, up, left, right, down)
return up * down * left * right
def display(trees, size):
grid = []
for i in range(size):
row = ["."] * size
grid.append(row)
for r, c in trees:
grid[r][c] = "#"
for row in grid:
print("".join(row))
if __name__ == "__main__":
lines = open("input.txt").readlines()
print(f"Part 1: {part1(lines)}")
print(f"Part 2: {part2(lines)}")
|
61f9cb0446e9aabc4181fe436e2768d854c1e7ad | rsarwas/aoc | /2018-15/answers.py | 7,841 | 3.828125 | 4 | # Data Model:
# ===========
# lines is a list of "\n" terminated strings from the input file
# map is a dictionary keyed with a (row,col) tuple, containing values
# indicating the contents of the location '.' open floor, ('G',hp) or ('E',hp)
POWER = 3
HP = 200
WALL = "#"
OPEN = "."
GOBLIN = "G"
ELF = "E"
def part1(lines):
map = parse(lines)
# display(32, map)
round = do_battle(map)
return score(round, map)
def do_battle(map, elf_power=POWER, goblin_power=POWER):
round = 0
while True:
for unit in ordered_units(map):
# Safety valve during testing
if round > 100:
display(7, map)
print(round, map)
return -1
if not unit in map or map[unit] == OPEN:
# unit was killed before it's turn began, skip it
continue
targets = get_targets(map, unit)
if not targets:
# If there are no targets for this unit, we are done!
# print(round)
# display(32, map)
return round
target = first_attackable_target(unit, targets, map)
if target:
if map[target][0] == ELF:
power = goblin_power
else:
power = elf_power
attack(map, target, power)
else:
best_move = find_best_move(map, unit, targets)
if best_move:
unit = move(map, unit, best_move)
target = first_attackable_target(unit, targets, map)
if target:
if map[target][0] == ELF:
power = goblin_power
else:
power = elf_power
attack(map, target, power)
round += 1
# print(round)
# display(7,map)
def part2(lines):
map = parse(lines)
# display(32, map)
initial_elf_count = count_elves(map)
elf_power = POWER
while True:
# safety valve
if elf_power > 100:
print("aborting")
return -1
map = parse(lines)
round = do_battle(map, elf_power)
lost_elves = initial_elf_count - count_elves(map)
if lost_elves == 0:
print("Elf Power Required", elf_power)
return score(round, map)
# print(elf_power, lost_elves, round)
elf_power += 1
def count_elves(map):
elves = 0
for unit in map:
unit_type = map[unit][0]
if unit_type == ELF:
elves += 1
return elves
def parse(lines):
map = {}
for r,line in enumerate(lines):
for c,char in enumerate(line):
if char == OPEN:
map[(r,c)] = char
if char == GOBLIN or char == ELF:
map[(r,c)] = (char, 200)
return map
def display(size, map):
output = []
for row in range(size):
line = [WALL]*size
output.append(line)
for key in map:
(r,c) = key
value = map[key]
line = output[r]
line[c] = value[0]
for line in output:
print("".join(line))
for key in map:
if map[key][0] != OPEN:
print(f"{map[key][0]}{key} = {map[key][1]}")
def ordered_units(map):
units = []
for location in map:
unit = map[location]
if (unit[0] == GOBLIN or unit[0] == ELF) and unit[1] > 0:
units.append(location)
units.sort()
return units
def get_targets(map, unit):
unit_type = map[unit][0]
if unit_type == GOBLIN:
search_type = ELF
else:
search_type = GOBLIN
targets = []
for location in map:
unit = map[location]
if unit[0] == search_type:
targets.append(location)
return set(targets)
def first_attackable_target(unit, targets, map):
# To attack, the unit first determines all of the targets that
# are in range of it by being immediately adjacent to it.
# If there are no such targets, the unit ends its turn.
# Otherwise, the adjacent target with the fewest hit points is selected;
# in a tie, the adjacent target with the fewest hit points which is
# first in reading order is selected.
r,c = unit
target = None
min_hp = 201
# search in reading order
for dr, dc in [(-1,0), (0,-1), (0,1), (1,0)]: # reading order
loc = (r+dr, c+dc)
if loc in targets:
loc_hp = map[loc][1]
if loc_hp < min_hp:
target = loc
min_hp = loc_hp
return target
def attack(map, target_location, force):
unit = map[target_location]
unit = (unit[0], unit[1] - force)
if unit[1] <= 0:
map[target_location] = OPEN
else:
map[target_location] = unit
def find_first_move(map, unit, targets):
# JUST FOR TESTING
# find first open space in reading order and move to it
r,c = unit
if (r-1,c) in map and map[(r-1,c)] == OPEN:
return (r-1,c)
if (r,c-1) in map and map[(r,c-1)] == OPEN:
return (r,c-1)
if (r,c+1) in map and map[(r,c+1)] == OPEN:
return (r,c+1)
if (r+1,c) in map and map[(r+1,c)] == OPEN:
return (r+1,c)
return None
def find_best_move(map, unit_loc, targets):
# prune to reachable targets
# identify all attack points of reachable targets
# find closest attack point (ties resolved in reading order)
# find shortest path to closest attack point (ties resolved in reading order of first move)
# return first move in shortest path
# alternatively look at the 4 adjacent location in reading order and
# calculate the path length to the closest reachable target, return the shortest
# alternatively, lock at the 4 adjacent in reading order, if we find a target, return
# otherwise, similarly check each of the adjacent that is open, ad infinitum until we find a target
# or there is nothing left to check
loc = unit_loc
new_set = {loc}
total_set = set()
path = {loc:[]}
while True:
if not new_set: #empty, i.e nothing was found in last iteration
break
total_set = total_set | new_set
search_list = list(new_set)
search_list.sort() # put in reading order
new_set = set()
for loc in search_list:
for r,c in [(-1,0), (0,-1), (0,1), (1,0)]: # reading order
new_loc = (loc[0]+r, loc[1]+c)
if new_loc in targets:
# print(targets)
# print(new_loc)
# print(total_set)
# print(path)
return path[loc][0]
if new_loc in total_set or new_loc in new_set:
continue
if new_loc in map and map[new_loc] == OPEN:
new_set.add(new_loc)
path[new_loc] = path[loc] + [new_loc]
return None
def move(map, unit, best_move):
map[best_move] = map[unit]
map[unit] = OPEN
return best_move
def score(round, map):
total_g = 0
total_e = 0
for location in map:
unit = map[location]
if unit[0] == GOBLIN:
total_g += unit[1]
if unit[0] == ELF:
total_e += unit[1]
if total_e == 0:
return round * total_g
if total_g == 0:
return round * total_e
# oops, we called for the score before all battles are done
return -1
if __name__ == '__main__':
# data = open("input.txt").read() # as one big string
# lines = open("test6.txt").readlines() # as a list of line strings
lines = open("input.txt").readlines() # as a list of line strings
print(f"Part 1: {part1(lines)}")
print(f"Part 2: {part2(lines)}")
|
2bede8133579085185e2fe8b9794e2fe4562878a | rsarwas/aoc | /2022-18/answers.py | 5,217 | 3.515625 | 4 | # Data Model:
# ===========
# lines is a list of "\n" terminated strings from the input file
def part1(lines):
data = parse(lines)
# data = [(1,1,1), (2,1,1)] # testg data; result should be 10
result = solve(data)
return result
def part2(lines):
data = parse(lines)
result = solve2(data)
return result
def parse(lines):
data = []
for line in lines:
line = line.strip()
items = line.split(",")
x, y, z = int(items[0]), int(items[1]), int(items[2])
data.append((x, y, z))
return data
def solve(data):
result = 0
for drop in data:
result += exposed(drop, data)
return result
def solve2(drops):
"""find all the exterior cells in the bounding box, and count the sides that
contact with the drops"""
drop_set = set(drops)
ext_faces = 0 # total of exterior edges that I found
x_min, y_min, z_min, x_max, y_max, z_max = extents(drops)
x_min -= 1
y_min -= 1
z_min -= 1
x_max += 1
y_max += 1
z_max += 1
start = (x_min, y_min, z_min)
deltas = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)]
ext = set() # set external cells that have been processed
process = {start} # set of external cells to process
# process is to:
# 1) find connected external cells, that are not:
# a) ensure inside bounding box
# b) ensure not all ready processed or in processing queue
# b) ensure not part of drops
# 2) Count the sides that the external cells touch the drops
# The strategy of searching just the bnounding box has two problems
# 1) it misses faces on the bounding box, and
# 2) will miss any exterior cells that are isoilated from the main exterior volume,
# this will happen if a ring of drops exist along one of the bounding faces.
# it appears this may be happening in the puzzle problem.
while process:
cell = process.pop()
# print("process",cell)
x, y, z = cell
ext.add(cell)
for (dx, dy, dz) in deltas:
neighbor = x + dx, y + dy, z + dz
if neighbor in ext or neighbor in process:
continue
(nx, ny, nz) = neighbor
if (
nx < x_min
or nx > x_max
or ny < y_min
or ny > y_max
or nz < z_min
or nz > z_max
):
# not in bounding box; ignore
continue
if neighbor in drop_set:
ext_faces += 1
continue
# print("add", neighbor)
process.add(neighbor)
return ext_faces
def exposed(drop, drops):
x, y, z = drop
exposed = 6
for other in drops:
x1, y1, z1 = other
if y1 == y and z1 == z and (x1 == x + 1 or x1 == x - 1):
exposed -= 1
elif x1 == x and z1 == z and (y1 == y + 1 or y1 == y - 1):
exposed -= 1
elif x1 == x and y1 == y and (z1 == z + 1 or z1 == z - 1):
exposed -= 1
return exposed
def find_holes(drops):
x_min, y_min, z_min, x_max, y_max, z_max = extents(drops)
drop_set = set(drops)
voids = []
for x in range(x_min + 1, x_max):
for y in range(y_min + 1, y_max):
for z in range(z_min + 1, z_max):
if (x, y, z) in drop_set:
continue
if neighbors((x, y, z), drops) == 6:
voids.append((x, y, z))
return voids
def extents(drops):
x_max, y_max, z_max = (-1e6, -1e6, -1e6)
x_min, y_min, z_min = (1e6, 1e6, 1e6)
for drop in drops:
x, y, z = drop
if x < x_min:
x_min = x
if x > x_max:
x_max = x
if y < y_min:
y_min = y
if y > y_max:
y_max = y
if z < z_min:
z_min = z
if z > z_max:
z_max = z
return x_min, y_min, z_min, x_max, y_max, z_max
def neighbors(void, drops):
x, y, z = void
neighbors = 0
for drop in drops:
x1, y1, z1 = drop
if y1 == y and z1 == z and (x1 == x + 1 or x1 == x - 1):
neighbors += 1
elif x1 == x and z1 == z and (y1 == y + 1 or y1 == y - 1):
neighbors += 1
elif x1 == x and y1 == y and (z1 == z + 1 or z1 == z - 1):
neighbors += 1
return neighbors
def display(drops):
x_min, y_min, z_min, x_max, y_max, z_max = extents(drops)
print(x_min, y_min, z_min, x_max, y_max, z_max)
cube = []
for z in range(z_max - z_min + 1):
level = []
for y in range(y_max - y_min + 1):
row = ["."] * (x_max - x_min + 1)
level.append(row)
cube.append(level)
for drop in drops:
x, y, z = drop
cube[z - z_min][y - y_min][x - x_min] = "#"
level_n = z_min
for level in cube:
print("z = ", level_n)
for i, row in enumerate(level):
print((i + y_min) % 10, "".join(row))
level_n += 1
if __name__ == "__main__":
lines = open("input.txt").readlines()
print(f"Part 1: {part1(lines)}")
print(f"Part 2: {part2(lines)}")
|
fe56b2aba085594a6530eeb7b432d1c3ae812ca1 | rsarwas/aoc | /2015-03/answers.py | 2,242 | 3.578125 | 4 | # Data Model:
# ===========
# input is a single line of 4 characters {<,>,^,v}
# visits is a dictionary with an (x,y) tuple for the key
# and value is the number of times visited
def part1(line):
visits = {}
(x,y) = (0,0)
visits[(x,y)] = 1
for move in line:
if move == 'v':
y -= 1
elif move == '^':
y += 1
elif move == '<':
x -= 1
elif move == '>':
x += 1
else:
print(f'unexpected input: {move}; Skipping.')
continue
if (x,y) in visits:
visits[(x,y)] += 1
else:
visits[(x,y)] = 1
return len(visits)
def part2(line):
visits = {}
(x,y) = (0,0)
(rx,ry) = (0,0)
visits[(x,y)] = 2
real_santa = True
for move in line:
if real_santa:
if move == 'v':
y -= 1
elif move == '^':
y += 1
elif move == '<':
x -= 1
elif move == '>':
x += 1
else:
print(f'unexpected input: {move}; Skipping.')
continue
if (x,y) in visits:
visits[(x,y)] += 1
else:
visits[(x,y)] = 1
else:
if move == 'v':
ry -= 1
elif move == '^':
ry += 1
elif move == '<':
rx -= 1
elif move == '>':
rx += 1
else:
print(f'unexpected input: {move}; Skipping.')
continue
if (rx,ry) in visits:
visits[(rx,ry)] += 1
else:
visits[(rx,ry)] = 1
real_santa = not real_santa
return len(visits)
if __name__ == '__main__':
# print(f"test 1a {part1('>')} == 2")
# print(f"test 2a {part1('^>v<')} == 4")
# print(f"test 3a {part1('^v^v^v^v^v')} == 2")
# print(f"test 1b {part2('^v')} == 3")
# print(f"test 2b {part2('^>v<')} == 3")
# print(f"test 3b {part2('^v^v^v^v^v')} == 11")
lines = open("input.txt").readlines() # as a list of line strings
print(f"Part 1: {part1(lines[0])}")
print(f"Part 2: {part2(lines[0])}")
|
fbb5b5aaca9032c33b9030eed7bf35e7faed16c0 | rsarwas/aoc | /2022-01/answers.py | 1,932 | 4.03125 | 4 | """A solution to an Advent of Code puzzle."""
# Data Model:
# ===========
# _lines_ is a list of "\n" terminated strings from the input file.
# Each line is an integer or empty (just a newline).
# There is no empty line at the end
# _totals_ is list of integers. Each one is the sum of a group of
# integers in the input. Groups are separated by an empty line.
import os.path # to get the directory name of the script (current puzzle year-day)
INPUT = "input.txt"
def part1(lines):
"""Solve part 1 of the problem."""
totals = totalize_calories(lines)
return max(totals)
def part2(lines):
"""Solve part 2 of the problem."""
totals = totalize_calories(lines)
totals.sort()
top_three = totals[-3:]
return sum(top_three)
def totalize_calories(lines):
"""Read the calories in each line and provide a total for each group.
The calories for each group are sequential and separated by a blank line.
The calories for the (n+1)th group are after the nth blank line.
Return a list of totals for each group."""
totals = []
group_total = 0
for line in lines:
line = line.strip()
if line:
# Add this amount to the current group's total.
group_total += int(line)
else:
# We are done with totalizing a group. Save it and start a new group
totals.append(group_total)
group_total = 0
# Add any remaining group total to the list.
if group_total > 0:
totals.append(group_total)
return totals
def main(filename):
"""Solve both parts of the puzzle."""
_, puzzle = os.path.split(os.path.dirname(__file__))
with open(filename, encoding="utf8") as data:
lines = data.readlines()
print(f"Solving Advent of Code {puzzle} with {filename}")
print(f"Part 1: {part1(lines)}")
print(f"Part 2: {part2(lines)}")
if __name__ == "__main__":
main(INPUT)
|
e79922fcc84dd252f76cd4e5a8e9de9486187f77 | rsarwas/aoc | /2022-25/answers.py | 1,103 | 3.9375 | 4 | """A solution to an Advent of Code puzzle."""
def part1(lines):
"""Solve part 1 of the problem."""
total = 0
for line in lines:
total += to_decimal(line.strip())
return to_snafu(total)
SNAFU = {"2": 2, "1": 1, "0": 0, "-": -1, "=": -2}
DECIMAL = {2: "2", 1: "1", 0: "0", -1: "-", -2: "="}
def to_decimal(snafu):
"""Convert a snafu string to a decimal integer."""
result = 0
factor = 5 ** (len(snafu) - 1)
for char in snafu:
result += factor * SNAFU[char]
factor //= 5
return result
def to_snafu(decimal):
"""Convert a decimal integer to a snafu string."""
quot = decimal // 5
rem = decimal % 5
digits = []
while quot > 0 or rem > 2:
if rem > 2:
rem -= 5
quot += 1
digits.append(DECIMAL[rem])
rem = quot % 5
quot //= 5
digits.append(DECIMAL[rem])
digits.reverse()
return "".join(digits)
if __name__ == "__main__":
with open("input.txt", encoding="utf8") as data_file:
data = data_file.readlines()
print(f"Part 1: {part1(data)}")
|
523d5b0a7100e8efc1b6432b8955ddb19b6d9722 | Imperiopolis/ccmakers-python | /Day 1/03 formatStrings.py | 395 | 3.96875 | 4 | print "There are %d types of people." % 10
print "Those who know %s and those who %s." % ('binary', "don't")
print "Isn't that joke so funny?! %r" % False
print "This is the left side of..." + "a string with a right side."
print "This is the left side of...", "a string with a right side."
# what happens if you use %r instead of %s?
# what's the different between separating with a , and a + |
9df42cc268791c01464b91358474059c4b9a27d5 | Kranek/BlockBuster | /blocks.py | 3,596 | 3.671875 | 4 | """
This file contains block variants used in the BlockBuster
"""
from pygame.sprite import Sprite
from gamedata import Assets
class Block(Sprite):
"""
Basic block type
"""
WIDTH = 30
HEIGHT = 15
def __init__(self, x, y, color):
"""
Initialize with coordinates and block "color" for regular blocks
:param x: x coordinate of the play-field
:param y: y coordinate of the play-field
:param color: block color number (0-5)
:return:
"""
Sprite.__init__(self)
self.type = color
self.image = Assets.blocks[color] # pygame.image.load("gfx/brick05.png")
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.dead = False
def on_collide(self):
"""
Default action when the ball collides with block
:return:
"""
return self.kill()
def kill(self):
"""
Default action when the block dies (set dead true and return points)
:return: Amount of points the block is worth
"""
self.dead = True
return 100 + 10 * self.type
def draw(self, screen, offset=(0, 0)):
"""
Method called each frame to (re)draw the object
:param screen: PyGame surface to draw the object on
:param offset: Needed if you want to draw at different position than default (0, 0)
:return:
"""
screen.blit(self.image, (self.rect.x + offset[0], self.rect.y + offset[1]))
class BlockExplosive(Block):
"""
Explosive Block, kills its neighbours on hit
"""
def __init__(self, x, y):
"""
Init only with position, does not take the color argument
:param x: x coordinate of the play-field
:param y: y coordinate of the play-field
:return:
"""
Block.__init__(self, x, y, 0)
self.image = Assets.blockE
def kill(self):
"""
Kill action of the Explosive Block (does not return points)
:return:
"""
self.dead = True
return False
class BlockIndestructible(Block):
"""
Indestructible Block
"""
def __init__(self, x, y):
"""
Init only with position, does not take the color argument
:param x: x coordinate of the play-field
:param y: y coordinate of the play-field
:return:
"""
Block.__init__(self, x, y, 0)
self.image = Assets.blockI
def kill(self):
"""
Don't you die on me!
:return:
"""
return False
class BlockMultiHit(Block):
"""
MultiHit Block
"""
def __init__(self, x, y):
"""
Init only with position, does not take the color argument
:param x: x coordinate of the play-field
:param y: y coordinate of the play-field
:return:
"""
Block.__init__(self, x, y, 2)
self.image = Assets.blocksM[2]
def on_collide(self):
"""
Hitting the block decreases its integrity
:return:
"""
if self.type <= 0: # FIXME: Change variable not to use type as integrity counter
return self.kill()
else:
self.type -= 1
self.image = Assets.blocksM[self.type]
return False
def kill(self):
"""
Kill action of the MultiHit block (kill and return 400 points)
:return: Amount of points the four blocks would be worth (since it requires 4 hits)
"""
self.dead = True
return 400
|
cfa1d639c413d97d0cedfb6fe6881ba9c7d52dae | Kranek/BlockBuster | /blockbuster.py | 1,614 | 3.515625 | 4 | """
The main file of the BlockBuster. Run it to play and have fun!
"""
from gamedata import Assets
from gameclock import GameClock
from pygame import init
from pygame.display import set_caption, set_icon, set_mode, get_surface, flip
from pygame.event import get
from constants import LEVEL_WIDTH, LEVEL_HEIGHT
from GameStateMenu import GameStateMenu
import Tkinter as Tk
if __name__ == '__main__':
ROOT = Tk.Tk()
ROOT.withdraw()
init()
Assets.load_images()
GAME_ICON = Assets.gameIcon
set_caption('BlockBuster')
set_icon(GAME_ICON)
# WINDOW = set_mode((LEVEL_WIDTH, LEVEL_HEIGHT))
set_mode((LEVEL_WIDTH, LEVEL_HEIGHT))
SCREEN = get_surface()
flip()
CONTEXT = dict()
GAMESTATE = GameStateMenu(CONTEXT, SCREEN)
CONTEXT["gamestate"] = GAMESTATE
# noinspection PyUnusedLocal
def _update(_):
"""
Pump events to the current GameState and tell its objects to update
:param _: unused dt provided by GameClock
:return:
"""
events = get()
CONTEXT["gamestate"].handle_input(events)
CONTEXT["gamestate"].update()
# gamestate.handle_input(events)
# gamestate.update()
# noinspection PyUnusedLocal
def _draw(_):
"""
Ask the current GameState to redraw itself
:param _: unused interp provided by GameClock
:return:
"""
# gamestate.draw()
CONTEXT["gamestate"].draw()
flip()
CLOCK = GameClock(max_ups=60, max_fps=60, update_callback=_update, frame_callback=_draw)
while True:
CLOCK.tick()
|
dfda4d8dd6f8e90f15c6247636eaf7a83358d61b | ALXlixiong/Python | /2019.8.7/test.py | 115 | 3.90625 | 4 | #coding:UTF-8
num =10
if num == 8:
print("8")
elif num == 6:
print("6")
else:
print("10")
print("end")
|
cf5b7929308ea1f2343e9f0a905eee8599a5209c | osakhsa/FirstAPI | /v3/create_tables.py | 511 | 3.671875 | 4 | import sqlite3
con = sqlite3.connect('data.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY ASC, name TEXT UNIQUE, price REAL)')
cur.execute('INSERT INTO items VALUES (null, "chair", 1500)')
cur.execute('INSERT INTO items VALUES (null, "cupboard", 3000)')
cur.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY ASC, username TEXT UNIQUE, password TEXT)')
cur.execute('INSERT INTO users VALUES (null, "Stepan", "123456")')
con.commit()
con.close()
|
6699cc593e0ff334ac5fe9e1ed574bc51f5528a9 | Ph0en1xGSeek/ACM | /LeetCode/56.py | 775 | 3.71875 | 4 | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) == 0:
return []
intervals.sort(key=lambda item: item.start)
ret = []
l = intervals[0].start
r = intervals[0].end
for i in range(1, len(intervals)):
if intervals[i].start <= r:
r = max(r, intervals[i].end)
else:
ret.append([l, r])
l = intervals[i].start
r = intervals[i].end
ret.append([l, r])
return ret
|
d352eb5219c39d38076d2d46690e9853bf1ea574 | Ph0en1xGSeek/ACM | /LeetCode/21.py | 848 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
i = l1
prei = i
j = l2
prej = j
head = tmp = ListNode(0)
while i != None and j != None:
tmp.next = ListNode(0)
tmp = tmp.next
if i.val < j.val:
tmp.val = i.val
prei = i
i = i.next
else:
tmp.val = j.val
prej = j
j = j.next
if i != None:
tmp.next = i
if j != None:
tmp.next = j
return head.next |
a6e9d4dd78bb918d56b6c77333cc96dab3070081 | Ph0en1xGSeek/ACM | /LeetCode/189.py | 562 | 3.5625 | 4 | class Solution(object):
def reverse(self, nums, l, r):
while(l < r):
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) == 0 or k == 0:
return
if k > len(nums):
k %= len(nums)
nums.reverse()
self.reverse(nums, 0, k-1)
self.reverse(nums, k, len(nums)-1) |
85a564273e14acc4a430aa1d0bcabf09105e5f5b | Ph0en1xGSeek/ACM | /LeetCode/20.py | 802 | 3.75 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
arr = []
for i in s:
if i == '(' or i == '[' or i == '{':
arr.append(i)
elif i == ')':
if len(arr) > 0 and arr[-1] == '(':
arr.pop()
else:
return False
elif i == ']':
if len(arr) > 0 and arr[-1] == '[':
arr.pop()
else:
return False
elif i == '}':
if len(arr) > 0 and arr[-1] == '{':
arr.pop()
else:
return False
if len(arr) > 0:
return False
return True |
51a700adff1571f3b83ce7ef30cc83772ae8f354 | Ph0en1xGSeek/ACM | /LeetCode/108.py | 1,420 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if len(nums) == 0:
return []
root = self.make(nums, 0, len(nums)-1)
return root
def make(self, nums, l, r):
root = TreeNode(0)
if l > r:
return None
if l == r:
root.val = nums[l]
return root
mid = (l+r)>>1
root.val = nums[mid]
root.left = self.make(nums, l, mid-1)
root.right = self.make(nums, mid+1, r)
return root
class Solution {
public:
TreeNode* construct(vector<int> &num, int left, int right) {
if(left > right) {
return nullptr;
}else if(left == right) {
return new TreeNode(num[left]);
}
int mid = left + ((right - left) >> 1);
TreeNode *node = new TreeNode(num[mid]);
node->left = construct(num, left, mid-1);
node->right = construct(num, mid+1, right);
return node;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
int sz = num.size();
TreeNode *head = nullptr;
if(sz == 0) {
return head;
}
head = construct(num, 0, sz-1);
return head;
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.