blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cb42198d430f4b66a4644422e6598d9414c79a5e | chauncyfxm/niPython | /python_03/continue.py | 92 | 3.578125 | 4 | i = 0
while i < 20:
if i == 6:
i += 2
continue
i += 1
print (i)
print ('ijjiij')
|
46c10809f08c9e8354fef2523dd7e284a2e2ad79 | zhangqinlove/- | /ex-5.4.py | 174 | 3.546875 | 4 | def multi(*a):
if len(a)==0:
return 0
t=1
for i in a:
t=t*i
return t
print(multi(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20))
|
7f8cd9222f9b6f8e6c9aecb004cee30a3019e67b | M0673N/Programming-Fundamentals-with-Python | /01_basic_syntax_conditional_statements_and_loops/exercise/10_christmas_spirit.py | 744 | 3.984375 | 4 | quantity = int(input())
days_left = int(input())
ornament_set = 2
tree_skirt = 5
tree_garlands = 3
tree_lights = 15
spirit = 0
price = 0
if days_left % 10 == 0:
spirit -= 30
for day in range(1, days_left + 1):
if day % 11 == 0:
quantity += 2
if day % 2 == 0:
price += quantity * ornament_set
spirit += 5
if day % 3 == 0:
price += quantity * tree_skirt + quantity * tree_garlands
spirit += 13
if day % 5 == 0:
price += tree_lights * quantity
spirit += 17
if day % 3 == 0:
spirit += 30
if day % 10 == 0:
spirit -= 20
price += tree_skirt + tree_lights + tree_garlands
print(f"Total cost: {price}")
print(f"Total spirit: {spirit}")
|
83b42e1c81cffdb1c9cfdd9a68c8b4e58a585804 | SadSack963/blackjack | /main.py | 4,521 | 3.96875 | 4 | import random
from art import logo
# Initialize variables
deck = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
play = True
cards = {}
game = False
# Initialize the hands
def init_hands():
global cards
cards = {
"Player": {"hand": [], "score": 0},
"Dealer": {"hand": [], "score": 0},
}
# Deal the initial cards
def init_deal():
# Deal initial cards (dealt cards are not removed from the deck)
for i in range(0, 2):
card = random.choice(deck)
cards["Player"]["hand"].append(card)
cards["Player"]["score"] += card
card = random.choice(deck)
cards["Dealer"]["hand"].append(card)
cards["Dealer"]["score"] += card
# Display initial hands to the player
print(f'Your hand: {cards["Player"]["hand"]}, score: {cards["Player"]["score"]}')
print(f'Dealer hand: [{cards["Dealer"]["hand"][0]}, _ ]')
# Does Player want a new card?
def new_card_player():
new_card = input("Do you want another card? Y/(N) ").lower()
if new_card == "y":
card = random.choice(deck)
cards["Player"]["hand"].append(card)
cards["Player"]["score"] += card
print(f'Your hand: {cards["Player"]["hand"]}, score: {cards["Player"]["score"]}')
# Check Player score.
# If > 21 then check for Ace and make value = 1
if cards["Player"]["score"] > 21:
bust = True
i = 0
while bust and i < len(cards["Player"]["hand"]):
for _ in cards["Player"]["hand"]:
if cards["Player"]["hand"][i] == 11:
cards["Player"]["hand"][i] = 1
cards["Player"]["score"] -= 10
bust = False
new_card_player()
i += 1
if bust:
print(f'You Lose! You bust with a score of {cards["Player"]["score"]}')
global game
game = False
else:
new_card_player()
else:
new_card_player()
# Check for Blackjack
def check_blackjack():
if cards["Player"]["score"] == 21:
if cards["Dealer"]["score"] == 21:
print("Draw. Dealer also has Blackjack.")
else:
print("You win! You have Blackjack.")
print(f'Your hand: {cards["Player"]["hand"]}, score: {cards["Player"]["score"]}')
print(f'Dealer hand: {cards["Dealer"]["hand"]}, score: {cards["Dealer"]["score"]}')
global game
game = False
# New Dealer cards
def new_card_dealer():
while cards["Dealer"]["score"] < 17:
card = random.choice(deck)
cards["Dealer"]["hand"].append(card)
cards["Dealer"]["score"] += card
print(f'Dealer\'s hand: {cards["Dealer"]["hand"]}, score: {cards["Dealer"]["score"]}')
# Check Dealer score.
# If > 21 then check for Ace and make value = 1
if cards["Dealer"]["score"] > 21:
bust = True
i = 0
while bust and i < len(cards["Dealer"]["hand"]):
for _ in cards["Dealer"]["hand"]:
if cards["Dealer"]["hand"][i] == 11:
cards["Dealer"]["hand"][i] = 1
cards["Dealer"]["score"] -= 10
bust = False
new_card_dealer()
i += 1
if bust:
print(f'You Win! Dealer bust with a score of {cards["Dealer"]["score"]}')
global game
game = False
# Compare scores to decide winner
def decide_winner():
if cards["Dealer"]["score"] > cards["Player"]["score"]:
print("You Lose!")
if cards["Dealer"]["score"] == cards["Player"]["score"]:
print("Draw")
if cards["Dealer"]["score"] < cards["Player"]["score"]:
print("You Win!")
print(f'Your hand: {cards["Player"]["hand"]}, score: {cards["Player"]["score"]}')
print(f'Dealer hand: {cards["Dealer"]["hand"]}, score: {cards["Dealer"]["score"]}')
global game
game = False
# ---------------------------------------------
# Start Game
while play:
if input("Do you want to play a game of Blackjack? (Y)/N ").lower() == "n":
play = False
continue
else:
game = True
# Print logo
print(logo)
init_hands()
init_deal()
check_blackjack()
if game:
new_card_player()
if game:
new_card_dealer()
if game:
decide_winner()
|
923ae07135dc96a9849f7b526bb89bbf192e4566 | dmcglinchey2779/Quantopian-Python-Scripts | /Quant_Tutor_L5.py | 2,397 | 4 | 4 | """ Lesson 5 - The Data Object
data object - look up current or historical pricing and volume data for
any security. data is available in handle_data() and before_trading_start()
as well as any scheduled functions.
data.current() - return most recent value of given field(s) for a given asset(s)
Requires two arguements: the asset or list of assets and the field or list of
fields being queried. Possible fields include 'price', 'open', 'high', 'low',
'close', and 'volume'.
"""
data.current(sid(24), 'price') #get most recent price
data.current([sid(24), sid(8554)], 'price') # return panda series indexed by asset
"""get last known low and high prices returns pandas DataFrame(indexed by assets
fields as columns)"""
data.current([sid(24), sid(8554)], ['low', 'high'])
data.can_trade(sid(24))
""" Lesson 6 - The histoy Function
data object has a function history() which gets trailing windows of historical
pricing or volume data. data.history() Requires 4 arguments:
an asset or list of assets, a field or list of fields, an integer lookback window
and a lookback frequency"""
#example: returns a pandas series containing price history of AAPL over last 10 days
hist = data.history(sid(24), 'price', 10, '1d')
#mean price over the last 10 days
mean_price = hist.mean()
#'1d' frequency the most recent value in data.history() will be current
#date which could be partial day
#10 complete days
data.history(sid(8554), 'volume', 11, '1d')[:1].mean()
#return type of data.history() depends on input types - eg returns pandas DF
#get last 5 minutes of volume data for each security in our list
hist = data.history([side(24), sid(8554), sid(5061)], 'volume', 5, '1m')
#calculate the mean volume for each security in our DataFrame
mean_volumes = hist.mean(axis = 0)
#if we pass list of fields, return pandas Panel indexed by field, having date
#as major axis and assets as minor axis
#low and high minut bar histor for each security
hist = data.history([sid(24), sid(8554), sid(5061)], 'low', 'high', 5, '1m')
#calculate the mean low and high over the last 5 minutes
means = hist.mean()
mean_lows = means.['low']
mean_highs = means['high']
def initialize(context):
#AAPL, MSFT, SPY
context.security_list = [sid(24), sid(8554), sid(5061)]
def handle_data(context, data):
hist = data.history(context.security_list, 'volume', 10, '1m').mean()
print hist.mean()
|
db347195199dc2b1f1fd6daa85207f7e7ecea339 | naye0ng/Algorithm | /Programmers/해시/전화번호목록.py | 370 | 3.59375 | 4 | """
전화번호목록
"""
def solution(phone_book):
phone_book = sorted(phone_book)
front = 0
while front < len(phone_book) :
for target in phone_book[front+1:]:
if phone_book[front].startswith(target) :
return False
front += 1
return True
print(solution(["117","976742","449", "97674223", "5521144921"])) |
fa70cff2a89d673477cd4141b5ed6ac8d99c939a | vinayjawadwar/Learnpython | /OperatorOverloading.py | 861 | 3.75 | 4 | a =5
b=6
print(a+b)
print(int.__add__(a,b)) #behind the seen __add __ used
class Student:
def __init__(self,m1,m2):
self.m1 = m1
self.m2 = m2
def __add__(self, other):
m1 = self.m1 + other.m1
m2 = self.m2 + other.m2
s3 = Student(m1,m2)
return s3
def __gt__(self, other):
r1 = self.m1 + self.m2
r2 = other.m1 + other.m2
if r1>r2:
return True
else:
return False
def __str__(self):
return "{} {}".format(self.m1,self.m2)
s1 = Student(57,77)
s2 = Student(68,75)
s3 = s1+ s2
print(s3.m1)
print(s3.m2)
if s1 > s2:
print("s1 wins")
else:
print("s2 wins")
a = 10 # it print value but
print(a.__str__())
print(s1) # it printing only address without __str__() fun
print(s2) |
f07b63b0c9c48272ea9f192a39a7156009827a3b | itsEmShoji/TCScurriculum | /2_dungeon_crawl/hard/SmartDeque.py | 557 | 3.546875 | 4 | from collections import deque
class SmartDeque:
def __init__(self, mode_in):
# TODO: initialize our instance variables
def push(self, elt):
# TODO:check if our mode is a stack ('s')
# TODO: add elt to the left of our data
# TODO: if our mode is not 's', append elt normally
def pop(self):
# TODO: call popleft() and return the item we popped
def empty(self):
# TODO: return whether the SmartDeque is empty
def front(self):
# TODO Return the first item in the SmartDequeu
|
da94f8c14bac692267dfec2063b1bcd699eaa827 | Jesta398/project | /datastruvctures/polymorphism/quest2.py | 276 | 3.859375 | 4 |
class Parent1:
def m1(self):
print("inside parent1")
class Parent2:
def m1(self):
print("inside parent2")
class child(Parent1,Parent2):#chils is inheriting parent1 and parent2
def m3(self):
print("inside child")
c=child()
c.m3()
c.m1() |
0942a221f908f3f7edde81247db6a0ffa8be7fb0 | mrc-a2p/python-project | /turtle_funciones.py | 1,002 | 3.953125 | 4 | import turtle
def main():
window = turtle.Screen()
window.setup(350, 350, 0, 0) #TAMAÑO VENTANA
window.title("Ejemplo de ventana")
#window.screensize(300, 300)
# turtle.dot(10, 0, 0, 0)
dave = turtle.Turtle()
#dave = turtle.hideturtle()
#turtle.goto(50, 30)
turtle.pencolor("red")
make_square(dave)
#Mantiene la ventana abierta
turtle.mainloop()
def make_square(dave):
#Poner en la consola los grados que necesites
lenght = int(input('Tamaño de cuadrado: '))
for i in range(4):
make_line_and_turn(dave, lenght)
def make_line_and_turn(dave, lenght):
dave.forward(lenght)
dave.left(90)
dave.pencolor("blue")
#dave.goto(50, 10)
# def camino_tortuga(dave):
# dave.penup()
# dave.goto(100, 50)
# dave.dot(10, 255, 0, 0)
# turtle.goto(100, 50)
# turtle.dot(10, 255, 0, 0)
if __name__== '__main__':
import sys
sys.exit(int(main() or 0))
#main()
|
2e0e4700abca6329602b242243b82c5692ea93e0 | cenk-celik/rosalind_solutions | /python_script/open_reading_frames.py | 2,774 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Open Reading Frames
# ## Problem
#
# Either strand of a DNA double helix can serve as the coding strand for RNA transcription. Hence, a given DNA string implies six total reading frames, or ways in which the same region of DNA can be translated into amino acids: three reading frames result from reading the string itself, whereas three more result from reading its reverse complement.
#
# An open reading frame (ORF) is one which starts from the start codon and ends by stop codon, without any other stop codons in between. Thus, a candidate protein string is derived by translating an open reading frame into amino acids until a stop codon is reached.
#
# > **Given:** A DNA string **s** of length at most 1 kbp in FASTA format.
#
# > **Return:** Every distinct candidate protein string that can be translated from ORFs of **s.** Strings can be returned in any order.
# In[ ]:
dna_codon_table = {
"TTT":"F", "CTT":"L", "ATT":"I", "GTT":"V",
"TTC":"F", "CTC":"L", "ATC":"I", "GTC":"V",
"TTA":"L", "CTA":"L", "ATA":"I", "GTA":"V",
"TTG":"L", "CTG":"L", "ATG":"M", "GTG":"V",
"TCT":"S", "CCT":"P", "ACT":"T", "GCT":"A",
"TCC":"S", "CCC":"P", "ACC":"T", "GCC":"A",
"TCA":"S", "CCA":"P", "ACA":"T", "GCA":"A",
"TCG":"S", "CCG":"P", "ACG":"T", "GCG":"A",
"TAT":"Y", "CAT":"H", "AAT":"N", "GAT":"D",
"TAC":"Y", "CAC":"H", "AAC":"N", "GAC":"D",
"TAA":"STOP", "CAA":"Q", "AAA":"K", "GAA":"E",
"TAG":"STOP", "CAG":"Q", "AAG":"K", "GAG":"E",
"TGT":"C", "CGT":"R", "AGT":"S", "GGT":"G",
"TGC":"C", "CGC":"R", "AGC":"S", "GGC":"G",
"TGA":"STOP", "CGA":"R", "AGA":"R", "GGA":"G",
"TGG":"W", "CGG":"R", "AGG":"R", "GGG":"G"
}
# In[ ]:
def complementary_dna(dna_string):
replace_bases = {"A":"T","T":"A","G":"C","C":"G"}
return ''.join([replace_bases[base] for base in reversed(dna_string)])
# In[ ]:
def translate(fragment):
peptide = []
methionine = fragment.find("ATG")
codons = [fragment[methionine:methionine+3] for methionine in range(methionine, len(fragment), 3)]
for codon in codons:
peptide += dna_codon_table.get(codon)
return ''.join(map(str, peptide))
# In[ ]:
with open("rosalind_orf.txt") as file:
for line in file:
if line.startswith(">"):
nextline = str()
else:
nextline += (line.strip("\n"))
dna_string = nextline
# In[ ]:
import re
pattern = re.compile(r'(?=(ATG(?:...)*?)(?=TAA|TAG|TGA))')
fragments = []
for string in re.findall(pattern, dna_string):
fragments.append(string)
for string in re.findall(pattern, complementary_dna(dna_string)):
fragments.append(string)
# In[ ]:
for string in set(fragments):
print(translate(string))
|
681e8beaad24ff4e59fe482fd8bddd79df80fab1 | sachinjose/Coding-Prep | /CTCI/Stack & Queue/q3.4.py | 809 | 3.953125 | 4 | class Stack:
def __init__(self):
self.s = []
def push(self,e):
self.s.append(e)
def pop(self):
if len(self.s) == 0:
return False
else:
return self.s.pop()
def top(self):
if len(self.s) == 0:
return False
else :
return self.s[-1]
def is_empty(self):
return len(self.s) == 0
def length(self):
return len(self.s)
class Queue:
def __init__(self):
self.a = Stack()
self.b = Stack()
def enqueue(self,item):
self.a.push(item)
def dequeue(self):
while(self.a.is_empty()!=True):
temp = self.a.pop()
self.b.push(temp)
tmp = self.b.pop()
while(self.b.is_empty() != True):
temp = self.b.pop()
self.a.push(temp)
return tmp
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
|
bfad97f35cee5bbd84fb0133555872db1695a97c | anitrajpurohit28/PythonPractice | /python_practice/List_programs/1_interchange_first_last_elements.py | 2,372 | 4.46875 | 4 | # 1 Python program to interchange first and last elements in a list
print("-----1------")
def swap_list_using_temp1(input_list):
temp = input_list[0]
input_list[0] = input_list[-1]
input_list[-1] = temp
my_list = [1, 2, 3, 4, 5, 6, 7]
swap_list_using_temp1(my_list)
print(my_list)
print("-----2------")
def swap_list_using_temp_len(input_list):
length_of_list = len(input_list)
temp = input_list[0]
input_list[0] = input_list[length_of_list - 1]
input_list[length_of_list - 1] = temp
my_list = [1, 2, 3, 4, 5, 6, 7]
swap_list_using_temp_len(my_list)
print(my_list)
print("-----3------")
def swap_list_using_tuple_variable(input_list):
# Storing the first and last element
# as a pair in a tuple variable get
get = input_list[0], input_list[-1]
# unpacking tuple elements
input_list[-1], input_list[0] = get
my_list = [1, 2, 3, 4, 5, 6, 7]
swap_list_using_tuple_variable(my_list)
print(my_list)
print("-----4------")
def swap_list_using_push_pop(input_list):
curr_element = input_list.pop()
input_list.insert(0, curr_element)
my_list = [1, 2, 3, 4, 5, 6, 7]
swap_list_using_push_pop(my_list)
print(my_list)
print("-----5------")
def swap_list_using_star_oper_tuple(input_list):
# In this function, input arg is modified but not reflected
# into calling function hence we are returning the value
# to calling function
start, *mid, last = input_list
# print(start, mid, last) # 1 [2, 3, 4, 5, 6] 7
# By copying the variable directly into variable input_list,
# input_list will turn into tuple
# Now, input_list is a tuple; its not a list anymore
input_list = last, *mid, start
# print(input_list)
# calling function will get the right value only if
# this function returns and calling function will receive it
return input_list
# list property will be lost by this method
my_list = [1, 2, 3, 4, 5, 6, 7]
swap_list_using_star_oper_tuple(my_list)
print(my_list)
my_list = swap_list_using_star_oper_tuple(my_list)
print(my_list)
print("-----6------")
def swap_list_using_star_oper_list(input_list):
start, *middle, end = input_list
input_list = [end, *middle, start]
return input_list
my_list = [1, 2, 3, 4, 5, 6, 7]
swap_list_using_star_oper_list(my_list)
print(my_list)
my_list = swap_list_using_star_oper_list(my_list)
print(my_list) |
b7f7becea5df583f824a681213140a3c8111db6d | KlaudiaGolebiowska/aplikacja_bankowa | /test/test_cash_machine.py | 2,631 | 3.640625 | 4 | """
Bankomat:
Czy można wypłacić pieniądze.
Czy łączy się z kontem.
Czy brak pieniędzy w bankomacie jest obsługiwany
Czy brak pieniędzy na koncie jest obsługiwany.
"""
import unittest
from parameterized import parameterized
from app.account import Account
from app.card import Card
from app.cash_machine import CashMachine
class TestCashMachine(unittest.TestCase):
def test_whenCashMachineIsCreated_itWorks(self):
# Given
cash_machine = CashMachine()
# When
status_of_cash_machine = cash_machine.is_working()
# Then
self.assertTrue(status_of_cash_machine)
def test_whenCardIsInserted_thenCashMachineIsAbleToReceiveIt(self):
# Given
account = Account(amount=1, owner="Owner of Card")
card = Card(account=account, pin=1234)
cash_machine = CashMachine()
# When
cash_machine.insert_card(card)
inserted_card = cash_machine.card_inside()
# Then
self.assertEqual(card, inserted_card)
def test_whenLevelOfCashIsChecked_thenItIsReturned(self):
# Given
level_of_cash = 10000
cash_machine = CashMachine(start_cash=level_of_cash)
# When
found_level_of_cash = cash_machine.check_level_of_cash()
# Then
self.assertEqual(level_of_cash, found_level_of_cash)
def test_whenLevelIsLow_thenThereIsPossibilityToAddCash(self):
# Given
start_cash = 100
inserted_cash = 9900
cash_machine = CashMachine(start_cash=start_cash)
# When
cash_machine.fill_cash(inserted_cash)
found_level_of_cash = cash_machine.check_level_of_cash()
# Then
self.assertEqual(start_cash + inserted_cash, found_level_of_cash)
def test_whenStartCashIsNotInt_thenRaiseValueError(self):
with self.assertRaisesRegex(ValueError, "should be integer"):
start_cash = "10000"
cash_machine = CashMachine(start_cash=start_cash)
@parameterized.expand([
["1_zloty", 1, 100],
["10_zloty", 10, 100],
["100_zloty", 100, 1000],
["1000_zloty", 1000, 10000],
["10000_zloty", 10000, 10000]
])
def test_whenWantToWithdrawCash_thenCashIsReturned(self, name, wanted_cash, start_cash):
# Given
cash_machine = CashMachine(start_cash=start_cash)
# When
withdrawn_cash = cash_machine.withdraw(wanted_cash)
cash_level = cash_machine.check_level_of_cash()
# Then
self.assertEqual(wanted_cash, withdrawn_cash)
self.assertEqual(start_cash - wanted_cash, cash_level) |
23805f105c09f2c9a560563ed2ff2d5b02fdf126 | quocthang0507/PythonExercises | /Chapter 1/Ex53.py | 322 | 3.59375 | 4 | # 53. Hãy đếm số lượng chữ số lớn nhất của số nguyên dương n.
from Ex51 import MaxDigit
if __name__ == "__main__":
while True:
n = int(input('n = '))
if n > 0:
break
count = str(n).count(MaxDigit(n))
print('There are {} max digits in {}'.format(count, n))
|
aed08fe1902657d51c9907c0553790d402ba4c51 | oew1v07/Medial | /medial.py | 1,994 | 3.78125 | 4 | """Set of functions to calculate the medial axis transform
Steps involved:
1. Thresholding an image to create a binary image
2. Find all boundary pixels in the image.
3. For each non-boundary pixel find the distance to the
nearest boundary pixel, using Euclidean distance
4. Calculate Laplacian of the distance image.
5. Items with large values in the Laplacian image are
considered to be part of the medial axis"""
import numpy as np
import matplotlib as plt
from scipy.misc import imsave
from scipy.ndimage.filters import laplace
from scipy.ndimage.morphology import distance_transform_edt
from skimage.data import coins
from thresholds import thresholds
def medial(image):
"""Creates a medial axis transform image
Args
----
image: ndarray
The image of which the medial axis is to be calculated.
This should be a binary image.
visualise: bool
Option to visualise the medial axis transform.
Returns
-------
out: ndarray
A boolean image with the medial axis pixels
"""
# Remove noise and make sure it's thresholded
im = thresholds(image)
# Calculate distance to all border pixels for each non-border pixel
dist = distance_transform_edt(im)
# Calculate laplacian
lap = laplace(dist, mode="constant")
# Select items that are maximums and therefore less than 0
out = lap < 0
# Mask all items that are outside the boundaries
# using the original image
resultImage = np.logical_and(np.logical_not(out), im )
return dist, lap, resultImage
def coins_image():
im = coins()
thresh_im = thresholds(im)
return thresh_im
def run_rect():
rect = np.ones((256, 256))
rect[20:50, 20:70] = 1
dist, lap, out = medial(rect)
return out
def run_coins():
thresh_im = coins_image()
imsave("coins.png", thresh_im)
dist, lap, out = medial(thresh_im)
return out
medial_coins = run_coins()
imsave("output.png", medial_coins)
|
fa3ef45b0a879b392e6b39ccd2c4a919960a645b | physmath17/learning_python | /think_python/chap5/triangle.py | 965 | 4.46875 | 4 | def is_triangle(a, b, c) :
""" takes a, b, c as the inputs and converts them to integers, these are the side lengths of the triangle """
if int(a) + int(b) > int(c) and int(c) + int(b) > int(a) and int(c) + int(a) > int(b) :
print("Yes, the given side lengths form a triangle.")
elif int(a) + int(b) == int(c) and int(b) + int(c) >= int(a) and int(c) + int(a) >= int(b) :
print("We have a degenerate triangle.")
elif int(b) + int(c) == int(a) and int(c) + int(a) >= int(b) and int(a) + int(b) >= int(c) :
print("We have a degenerate triangle.")
elif int(c) + int(a) == int(b) and int(a) + int(b) >= int(c) and int(b) + int(c) >= int(a) :
print("We have a degenerate triangle.")
else :
print("No, the given side lengths do not forma triangle.")
x = float(input('enter the first side : '))
y = float(input('enter the second side : '))
z = float(input('enter the third side : '))
is_triangle(x, y, z)
|
1cf0674a5cec62512c35341a550bef69f77967da | hrushibhosale92/numerical_computing | /newton_raphson.py | 668 | 3.875 | 4 | def func( x ):
f = (x+5)**2
return f
def derivFunc( x ):
df = 2*(x+5)
return df
# Function to find the root
def newtonRaphson( x ):
h = func(x) / derivFunc(x)
i = 0
x_old = x
while True:
h = func(x_old)/derivFunc(x_old)
# x(i+1) = x(i) - f(x) / f'(x)
x_new = x_old - h
i = i + 1
print(i , x_new, h)
if abs(x_new-x_old) < 0.0001:
break
x_old = x_new
print("The value of the root is : ",
"%.4f"% x_new)
x0 = -20 # Initial values assumed
newtonRaphson(x0) |
3d36a5dfa87f05f370e23d9942fd2026a62f6be5 | dhumindesai/Problem-Solving | /ik/graph/is_graph_tree.py | 2,667 | 3.78125 | 4 | # from collections import deque
#
#
# def is_it_a_tree(node_count, edge_start, edge_end):
# if node_count < 1:
# return False
#
# # bfs
# def isCycleBfs(root):
# q = deque()
# q.append(root)
# visited[root] = 1
#
# while q:
# node = q.popleft()
# for neighbor in adjList[node]:
# if visited[neighbor] == -1:
# visited[neighbor] = 1
# q.append(neighbor)
# parent[neighbor] = node
# else:
# # check if neighbor is not parent (cross edge detection)
# if parent[node] != neighbor:
# return True
# return False
#
# # build graph
# adjList = [[] for _ in range(node_count)]
# visited = [-1 for _ in range(node_count)]
# parent = [-1 for _ in range(node_count)]
#
# for i in range(len(edge_start)):
# adjList[edge_start[i]].append(edge_end[i])
# adjList[edge_end[i]].append(edge_start[i])
#
# # outer loop
# component = 0
# for i in range(node_count):
# if component > 1:
# return False
# if visited[i] == -1:
# component += 1
# if isCycleBfs(i):
# return False
#
# return True
# Complete the function below
# The function accepts an INTEGER node_count, two INTEGER_ARRAYs edge_start and edge_end as parameters and
# is expected to return a BOOLEAN
def is_it_a_tree(n, edge_start, edge_end):
# 2. dfs
def is_cycle_in_dfs(root):
visited[root] = True
for neighbor in adjList[root]:
if not visited[neighbor]:
# tree edge
visited[neighbor] = True
parent[neighbor] = root
if is_cycle_in_dfs(neighbor):
return True
else:
# check for the backedge
if neighbor is not parent[root]:
return True
return False
# 1. create a graph
adjList = [[] for _ in range(n)]
visited = [False for _ in range(n)]
parent = [-1 for _ in range(n)]
components = 0
for i in range(len(edge_start)):
adjList[edge_start[i]].append(edge_end[i]) # i = 1 => edgList[0].append(2)
adjList[edge_end[i]].append(edge_start[i])
# 3. outer loop
for vertex in range(n):
if not visited[vertex]:
components += 1
if components > 1:
return False
if is_cycle_in_dfs(vertex):
return False
return True
print(is_it_a_tree(4, [0,0], [1,2])) |
72657c084eb68561cfda42a8c1920ddb0e04801c | jgam/hackerrank | /sorting/bubblesort.py | 611 | 3.546875 | 4 | def countSwaps(a):
num_swap = 0
if a == sorted(a):
print('Array is sorted in', num_swap, 'swaps.')
print('First Element:', a[0])
print('Last Element:', a[-1])
return 0
else:
for i in range(1,len(a)):
for j in range(len(a)-i):
if a[j] > a[j+1]:
first_num, second_num = a[j+1], a[j]
a[j+1] = second_num
a[j] = first_num
num_swap += 1
print('Array is sorted in', num_swap, 'swaps.')
print('First Element:', a[0])
print('Last Element:', a[-1]) |
8e5f3e81bb4094d7063543e05e5840469ef57061 | Han1s/flask-official-tutorial | /flaskr/db.py | 3,036 | 3.796875 | 4 | import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db():
"""
g is a special object that is unique for each request.
It is used to store data that might be accessed by multiple functions during the request.
The connection is stored and reused instead of creating a new connection
if get_db is called a second time in the same request.
"""
"""
current_app is another special object that points to the Flask application
handling the request.
Since you used an application factory,
there is no application object when writing the rest of your code.
get_db will be called when the application has been created and is handling a request,
so current_app can be used.
"""
"""
sqlite3.Row tells the connection to return rows that behave like dicts.
This allows accessing the columns by name.
"""
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
"""
close_db checks if a connection was created by checking if g.db was set.
If the connection exists, it is closed.
Further down you will tell your application about the close_db function
in the application factory so that it is called after each request.
"""
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
"""
open_resource() opens a file relative to the flaskr package,
which is useful since you won’t necessarily know where that location is
when deploying the application later.
get_db returns a database connection,
which is used to execute the commands read from the file.
"""
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
"""
click.command() defines a command line command called init-db
that calls the init_db function and shows a success message to the user.
You can read Command Line Interface to learn more about writing commands.
"""
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
"""
The close_db and init_db_command functions need to be registered with the application instance;
otherwise, they won’t be used by the application.
However, since you’re using a factory function,
that instance isn’t available when writing the functions.
Instead, write a function that takes an application and does the registration.
"""
"""
app.teardown_appcontext() tells Flask to call that function
when cleaning up after returning the response.
"""
# app.cli.add_command() adds a new command that can be called with the flask command.
"""
Import and call this function from the factory.
Place the new code at the end of the factory function before returning the app.
"""
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
|
b6e1c06e7b76d5150954d939b1461c792296c9bf | JasmineBharadiya/pythonBasics | /task_9_pattern.py | 195 | 4.0625 | 4 | #max of 3
def max(x,y,z):
if x>y and x>z:
print "x is max"
elif y>z and y>x:
print "y is max"
else:
print "z is max"
|
52fb542600445cfa6758f93d4307913c71012af6 | nigelbrennan/Anxiety-App | /programming_2_ca117-master/programming_2_ca117-master/Lab 11.1/file_111.py | 3,638 | 3.828125 | 4 | class File(object):
FILE_PERMISSIONS = 'rwx'
def __init__(self, fille, name, size=0, per=None):
self.file = fille
self.name = name
self.size = size
if per == None:
self.per = 'null'
else:
self.per = per
def __str__(self):
return 'File: {}\nOwner: {}\nPermissions: {}\nSize: {} bytes'.format(self.file, self.name, self.per, self.size)
def has_access(self, name, per):
if name == self.name:
return 'Access granted'
else:
if per in self.per:
return 'Access granted'
else:
return 'Access denied'
def enable_permission(self, name, per):
if name == self.name:
if self.per == 'null':
if per == 'w' or per == 'r' or per == 'x':
self.per = per
else:
if not per in self.per:
if per == 'w' or per == 'r' or per == 'x':
self.per += per
else:
print('Access denied')
def get_permissions(self):
return ''.join(sorted(self.per))
def disable_permission(self, name, per):
if name == self.name:
k = self.per
self.per = k.replace(per, '')
else:
print('Access denied')
def main():
# Display available permissions
print('File permissions: {}'.format(File.FILE_PERMISSIONS))
# Create some files
f1 = File('poem.txt', 'joe')
f2 = File('readme.txt', 'max', 1000, 'r')
f3 = File('secret.txt', 'fred', 100)
# Display file details
print('File details...')
print(f1)
print(f2)
print(f3)
# Check access rights
print('Access rights...')
print(f3.has_access('fred', 'r'))
print(f3.has_access('fred', 'w'))
print(f3.has_access('fred', 'x'))
print(f3.has_access('mary', 'r'))
print(f3.has_access('mary', 'w'))
print(f3.has_access('mary', 'x'))
# Fred enables read permission
print('Fred enables read permission...')
f3.enable_permission('fred', 'r')
# Mary enables write permission
print('Mary enables write permission...')
f3.enable_permission('mary', 'w')
# Check access rights
print('Access rights...')
print(f3.has_access('mary', 'r'))
print(f3.has_access('mary', 'w'))
print(f3.has_access('mary', 'x'))
# Fred enables write and execute permissions
print('Fred enables write permission...')
f3.enable_permission('fred', 'w')
print('Fred enables execute permission...')
f3.enable_permission('fred', 'x')
# Check access rights
print('Access rights...')
print(f3.has_access('mary', 'r'))
print(f3.has_access('mary', 'w'))
print(f3.has_access('mary', 'x'))
print(f3.has_access('lily', 'r'))
print(f3.has_access('vera', 'w'))
print(f3.has_access('bran', 'x'))
# Display permissions
print('Permissions: {}'.format(f3.get_permissions()))
# Fred disables write permission
print('Fred disables write permission...')
f3.disable_permission('fred', 'w')
# Vera disables execute permission
print('Vera disables execute permission...')
f3.disable_permission('vera', 'x')
# Check access rights
print('Access rights...')
print(f3.has_access('mary', 'r'))
print(f3.has_access('mary', 'w'))
print(f3.has_access('mary', 'x'))
# Display permissions
print('Permissions: {}'.format(f3.get_permissions()))
# Play with permissions
print('Fred disables write permission...')
f3.disable_permission('fred', 'w')
print('Permissions: {}'.format(f3.get_permissions()))
print('Fred enables write permission...')
f3.enable_permission('fred', 'w')
print('Fred enables write permission...')
f3.enable_permission('fred', 'w')
print('Permissions: {}'.format(f3.get_permissions()))
f3.enable_permission('fred', 'w')
print('Fred enables invalid permission...')
f3.enable_permission('fred', 'z')
print('Permissions: {}'.format(f3.get_permissions()))
if __name__ == '__main__':
main()
|
cb816f84ef457424ab0e22e5080b7b7bc54513e9 | roeiherz/CodingInterviews | /RecursionsDP/PaintFill.py | 366 | 3.609375 | 4 | __author__ = 'roeiherz'
"""
Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen
(represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until
the color changes from the original color.
"""
if __name__ == '__main__':
screen = np.zeros((10, 10, 3))
|
00db574758fc16263d193147cf51f329a654a2db | Striz-lab/infa_2019_strizhak | /lab4/03(edited).py | 5,373 | 3.5625 | 4 | from graph import*
windowSize(720, 500)
canvasSize(2000, 2000)
brushColor(100, 200, 200)
rectangle(0, 0, 720, 500)
brushColor(20, 200, 0)
penColor(20, 200, 0)
rectangle(0, 300, 720, 720)
penColor(0, 0, 0)
def ellipsee(x, y, a, b, fi):
penColor('orange')
c=math.cos(fi)
d=math.sin(fi)
penSize(2)
for i in range (-a,a):
v = (b**2-(i*b/a)**2)**0.5
for j in range (-b,b):
if abs(j) <= v:
x1 = i*c+j*d
y1 = j*c-i*d
x2 = x1+x
y2 = y1+y
point (x2, y2, -1)
def ellipseee(x, y, a, b, fi):
penColor('black')
c=math.cos(fi)
d=math.sin(fi)
penSize(2)
for i in range (-a,a):
v = (b**2-(i*b/a)**2)**0.5
for j in range (-b,b):
if abs(j) <= v:
x1 = i*c+j*d
y1 = j*c-i*d
x2 = x1+x
y2 = y1+y
point (x2, y2, -1)
def ellipse(x0, y0, a, b):
x=x0-b
y=y0
N=100
dx=2*b/N
penSize(0)
brushColor(130, 130, 130)
while (x<x0+b) :
rectangle(x, y, x+dx, 2*y0-y)
x=x+dx
y=y0+a*(1-(x-x0)**2/b**2)**0.5
brushColor(180,180,180)
circle(x0, y0-(a+10), 20)
penSize(2)
line(x0-15, y0-35, x0-50, y0+20)
line(x0+15, y0-35, x0+50, y0+20)
polyline([(x0-10, y0+45), (x0-20, y0+80), (x0-30, y0+80)])
polyline([(x0+10, y0+45), (x0+20, y0+80), (x0+30, y0+80)])
penSize(1)
#byket(x0-100, y0+10)
def woman(x0, y0):
brushColor(150, 10, 100)
penColor(150, 10, 100)
polygon([(x0, y0), (x0+25, y0+100), (x0-25, y0+100)])
penSize(0)
brushColor(180,180,180)
penColor(180,180,180)
penColor(0,0,0)
circle(x0, y0, 15)
penSize(1)
polyline([(x0-10, y0+100), (x0-10, y0+130), (x0-20, y0+130)])
polyline([(x0+10, y0+100), (x0+10, y0+130), (x0+20, y0+130)])
def love(x0, y0):
line(x0, y0, x0-2, y0-30)
x0-=2;y0-=30
brushColor(250, 0, 0)
penColor(250,0,0)
penSize(0)
polygon([(x0, y0), (x0, y0-80), (x0-30, y0-70)])
circle(x0-23, y0-70,10)
circle(x0-8, y0-75,10)
penColor(0,0,0)
def byket1(x0, y0):
brushColor('yellow')
penColor('yellow')
polygon([(x0, y0), (x0+30, y0-10), (x0+10, y0-30)])
brushColor(150, 10, 10)
penColor(150, 10, 10)
circle(x0+25, y0-15, 7.5)
brushColor(250, 0, 0)
penColor(250,0,0)
circle(x0+15, y0-25, 7.5)
brushColor(250, 250, 250)
penColor(250,250,250)
circle(x0+25, y0-25, 7.5)
penColor(0,0,0)
def byket2(x0, y0):
brushColor('yellow')
penColor('yellow')
polygon([(x0, y0), (x0+20, y0-30), (x0-20, y0-30)])
brushColor(150, 10, 10)
penColor(150,10,10)
circle(x0-10, y0-35, 12)
brushColor(250, 0, 0)
penColor(250, 0, 0)
circle(x0+10, y0-35, 12)
brushColor(250, 250, 250)
penColor(250, 250, 250)
circle(x0, y0-45, 12)
penColor(0,0,0)
def family(x,y,h):
ellipse (100, 1.635*x, 2*h, h)
love(50,320)
woman(190, 250)
line(x, y, 150, 320)
woman(300, 250)
ellipse(390, 1.635*x, 2*h, h)
line(305, 270, 340, 320)
byket1(440, 320)
def kit(x,y,h):
penColor('orange')
brushColor('orange')
polygon([(x-1.5*h,y),(x-1.3*h,y+1.5*h),(x-1.7*h,y+2*h),(x-2.5*h,y+1.7*h),(x-2.25*h,y+0.3*h)])
ellipsee(x-(2.25*h+2.5*h)/2, y+h, int(h/5), int(5*h/6), -19*3.14/180)
ellipsee(x-(1.7*h+2.5*h)/2, y+(1.7*h+2*h)/2, int(2*h/3), int(h/5), (-20)*3.14/180)
brushColor(20, 200, 0)
penColor(20, 200, 0)
polygon([(x-1.3*h,y+1.5*h),(x-2.1*h,y+2.5*h),(x-1.2*h, y+2.1*h)])
brushColor('white')
penColor('white')
ellipsee(x,y,int(2*h),h,0)
brushColor('orange')
penColor('orange')
polygon([(x+h/7,y-7*h/6),(x+h/7,y+7*h/6),(x,y+14*h/7),(x-h/2,y+17*h/7),(x-5*h/6,y+10*h/7)])
brushColor('orange')
penColor('orange')
circle(x-h/8,y+2*h/3-h/8,h/4)
polygon([(x,y+2*h/3),(x,y-2*h/3),(x-h,y-1.5*h),(x-2*h,y-2*h/3),(x-2*h, y+5*h/6)])
ellipsee(x-(h/2+5*h/6)/2, y+(27*h/7)/2, int(1.2*h/2), int(h/2), 12*3.14/180)
ellipsee(x, y, int(h/4), int(2*h/3), 0)
ellipsee(x-h/2, y-(1.5*h+2*h/3)/2, int(h/4), int(2*h/3+h/10), -40)
ellipsee(x-1.5*h, y-(1.5*h+2*h/3)/2, int(h/4), int(2*h/3), 40)
ellipsee(x-2*h, y-(2*h/3-5*h/6)/2, int(h/4), int(2*h/3+h/7), 0)
ellipsee(x-h, y+(5*h/6+2*h/3)/2, int(h/4), int(2*h/3+h/3), -88*3.14/180)
circle(x-h-h/10, y+h/3-2*h/10, h/3)
ellipseee(x-2*h, y+h/3-1.5*h/5, int(h/4), int(h/3), 0 )
ellipseee(x-2*h+h/10, y+h-h/5, int(h/3), int(h/4), 0 )
brushColor('black')
ellipseee(x-2*h+h/10, y-(5*h/6+2*h/3)/2-h/3, int(h/4), int(h/3+h/3), -40*3.14/180)
ellipseee(x, y-(5*h/6+2*h/3)/2-h/15, int(h/4), int(h/3+h/3), 30*3.14/180)
circle(x-1.1*h,y+0.25*h,h/4)
ellipseee(x+1.2*h,y+1.3*h,int(1.3*h),int(0.5*h), 60*3.14/180)
ellipseee(x+1.6*h,y-1.1*h,int(1.3*h),int(0.3*h), 30)
polyline([(195, 270),(220, 260), (245, 240), (270, 260), (295, 270)])
line(245, 240, 260, 140)
byket2(260, 140)
family(185, 270, 25)
ellipse(600, 400, 50, 25)
ellipse(500, 400, 50, 25)
byket1(650, 420)
woman(650, 200)
line(660,240, 660+35, 50+240)
line(640,240, 640+35, 50+240)
kit(680,270,15)
penColor('yellow')
brushColor('yellow')
circle(720, 0, 150)
#ellipse(500, 300, 50,20)
run()
|
920fd8f4c1712108a2e4e7e8c87de594f8f0569e | ZhiyuSun/leetcode-practice | /301-500/435_无重叠区间.py | 1,479 | 3.6875 | 4 | """
给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。
注意:
可以认为区间的终点总是大于它的起点。
区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。
示例 1:
输入: [ [1,2], [2,3], [3,4], [1,3] ]
输出: 1
解释: 移除 [1,3] 后,剩下的区间没有重叠。
示例 2:
输入: [ [1,2], [1,2], [1,2] ]
输出: 2
解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
示例 3:
输入: [ [1,2], [2,3] ]
输出: 0
解释: 你不需要移除任何区间,因为它们已经是无重叠的了。
"""
# 有点难度,后面再去理解一下
from typing import List
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
n = len(intervals)
if n == 0: return 0
dp = [1] * n
ans = 1
intervals.sort(key=lambda a: a[1])
for i in range(len(intervals)):
for j in range(i - 1, -1, -1):
if intervals[i][0] >= intervals[j][1]:
dp[i] = max(dp[i], dp[j] + 1)
# 由于我事先进行了排序,因此倒着找的时候,找到的第一个一定是最大的数,因此不用往前继续找了。
# 这也是为什么我按照结束时间排序的原因。
break
dp[i] = max(dp[i], dp[i - 1])
ans = max(ans, dp[i])
return n - ans
|
789653e393b86d5541f2baa87422b8688a76f8b4 | firdausraginda/python-beginner-to-advance | /zero-level/zero-level-#1-variables-data-types.py | 1,050 | 4.3125 | 4 | # USER INPUT
# user_says = input("Please enter the string you want to print: ")
# print(user_says)
# ----------------------------------------------------------
# VARIABLES
# 1. should start w/ a letter (can't start with a number)
# 2. can't include spaces
# 3. can't use symbols other than underscore (_)
# 4. Hyphens are not permitted
# 5. variable names are case sensitive
# how to assign multiple variables
# a = b = c = 10
# a, b, c = 1, 2, 3
# print(c)
# check pointer
# a = 10
# b = 10
# var a & b have the same location on memory bc both are pointing the same value
# python keyword that can't be variable: https://docs.python.org/3/reference/lexical_analysis.html#keywords
# ----------------------------------------------------------
# DATA TYPE
# strings, numbers, booleans, lists, sets, frozensets, tuples, ranges, dictionaries, None
# mutability = data type that can be modified after creation (lists, dictionaries, & sets)
# immutability = data type that CANNOT be modified after creation (strings, numbers, tuples, & frozensets) |
03bc8b2025ca7584a2846770abecb5da4cb154da | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/njschafi/Lesson08/test_circle.py | 2,977 | 4.0625 | 4 | """test code for circle.py"""
# NEIMA SCHAFI, LESSON 8 Assignment - Circle Class
import pytest
import math
from circle import *
########
# Step 1 & 2
########
def test_init():
"""
This tests if a proper numeric circle isinstance
is created and then checks for correct
radius and diameters
"""
c = Circle(4)
assert(c.radius == 4)
assert(c.diameter == 8)
c = Circle(4.5)
assert(c.radius == 4.5)
assert(c.diameter == 9)
########
# Step 3
########
"""tests if diameter setter properly works"""
def test_diameter():
c = Circle(5)
c.diameter = 6
assert(c.radius == 3)
assert(c.diameter == 6)
c.diameter = 'string'
########
# Step 4
########
"""tests if area setter properly works"""
def test_area():
c = Circle(5)
assert(round(c.area, 2) == 78.54)
########
# Step 5
########
"""tests if alternate constuctor works properly"""
def test_from_diameter():
c = Circle.from_diameter(8)
assert(c.radius == 4)
assert(c.diameter == 8)
########
# Step 6
########
def test_str():
"""Test proper string output of a circle"""
c = Circle(4)
assert(c.radius == 4)
assert(c.diameter == 8)
assert('Circle with radius: 4.000000' == c.__str__())
def test_repr():
"""Test representative value"""
c = Circle(4)
assert(c.radius == 4)
assert(c.diameter == 8)
assert('Circle(4)' == c.__repr__())
########
# Step 7
########
def test_add():
"""Test addition of circle radii"""
c1 = Circle(2)
c2 = Circle(4)
assert(c1 + c2 == Circle(6))
assert(c2 + c1 == Circle(6))
def test_mul():
"""Test multiplication of circle radius"""
c1 = Circle(2)
c2 = Circle(4)
assert((c1 * 3) == Circle(6))
assert((c2 * 3) != Circle(6))
assert((c2 * 3) == Circle(12))
def test_imul():
"""Test multiplication when object is on right hand side"""
c1 = Circle(2)
c2 = Circle(4)
assert((3 * c1) == Circle(6))
assert((3 * c2) != Circle(6))
assert((3 * c2) == Circle(12))
########
# Step 8
########
def test_gt():
"""Test > operator"""
c1 = Circle(2)
c2 = Circle(4)
assert(c2 > c1)
assert not(c1 > c2)
def test_lt():
"""Test < operator"""
c1 = Circle(2)
c2 = Circle(4)
assert(c1 < c2)
assert not(c2 < c1)
def test_eq():
"""Test < operator"""
c1 = Circle(2)
c2 = Circle(4)
c3 = Circle(2)
assert(c1 == c3)
assert(c1 * 3 == 3 * c1)
assert not(c2 == c1)
def test_sort():
"""Test to see if Circle class is sortable"""
circles = [Circle(3), Circle(6), Circle(2), Circle(1), Circle(8)]
circles.sort()
assert(circles == [Circle(1), Circle(2), Circle(3), Circle(6), Circle(8)])
def test_iadd():
"""Test augmented adding"""
c1 = Circle(2)
c2 = Circle(4)
c1 += c2
assert(c1.radius == 6)
def test_imul():
"""Test augmented multiplication"""
c1 = Circle(2)
c1 *= 2
assert(c1.radius == 4)
|
889cd91805cd44a62c240986866fcd7e972d1c8e | jithuraju/turbolab | /answer_2.py | 413 | 3.96875 | 4 | str1=input("enter the valid string of parenthesis:")
def remove_outer_layer(str1):
str2 =''
count=1
i = 1
while (i< len(str1)):
if (str1[i]=="("):
count = count+1
if count == 0:
i =i+2
count=count+1
continue
str2=str2+str1[i]
i=i+1
print (str2)
remove_outer_layer(str1)
|
6b92f9285e1756fc25e0797976c3f1c6952f94b4 | robertz23/code-samples | /python scripts and tools/list_intersection.py | 1,200 | 4.0625 | 4 | """
List intersection: Finds intersections between various lists
"""
def check_intersection(first_list, second_list):
#We use set builtin function to find the intersection between lists
return set(first_list).intersection(second_list)
def create_lists(line):
#receive a line from the file containing ascending numbers
#each line is of the form 'n,n,n;n,n,n' where n is a number
#and the semi-colon separates the lists
first, second = line.split(';')
#Make sure that we have a list of numbers and not numbers and commas
first = [x for x in first.split(',')]
second = [x for x in second.split(',')]
#look for the intersection
intersected_number = check_intersection(first, second)
if intersected_number:
intersected_numbers_sorted = [eachNumber for eachNumber in intersected_number]
intersected_numbers_sorted.sort()
print ','.join(intersected_numbers_sorted)
else:
print ""
#return 0
if __name__ == '__main__':
#l = ["1,2,3;3,4,5", "1,2,3;0,4,5", "7,8,9;8,9,10,11,12"]
l = ["1,2,3,4;4,5,6", "20,21,22;45,46,47", "7,8,9;8,9,10,11,12"]
for eachLine in l:
create_lists(eachLine)
|
40341bbf1b1099da8e9c539e42e557b385360404 | suyogpotnis/Leet_Code_Solved | /Longest_Common_Prefix.py | 862 | 4 | 4 | """
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
"""
class Solution:
def longestCommonPrefix(self, strs):
if len(strs) == 0 or len(strs[0]) == 0:
return ""
letter = strs[0][0]
dic = {letter: ""}
letterArray = []
for word in strs:
if len(word) == 0:
return ""
if word[0] not in dic:
return ""
else:
letterArray.append(word[1:])
return letter + self.longestCommonPrefix(letterArray)
|
ca17e71cea63b5914f0f45712d10df3a607c33cb | beminol/project_euler | /p23_non_abundant_sums.py | 543 | 3.671875 | 4 | def perfect_number(n):
all_list = range(n + 1)
all_list.remove(0)
divisor_list = list()
for i in all_list:
if n % i == 0:
divisor_list.append(i)
divisor_list.remove(n)
print divisor_list
print "Sum of all divisors:", sum(divisor_list)
if sum(divisor_list) == n:
print n, "IS A PERFECT NUMBER !"
elif sum(divisor_list) > n:
print n, "is a abundant number"
else:
print n, "is a deficient number"
return sum(divisor_list)
perfect_number(28122)
|
94656f65640d5a375c408b3ce464529ef87de528 | SavaTudor/StudentsLabsGrades | /validare/validatorLab.py | 2,610 | 3.609375 | 4 | from erori.exceptii import ValidError
class ValidatorLab(object):
def __validator_numar(self, s):
'''
:param s: a string representing the lab number and the problem number
:return: True if the string is valid, false otherwise
s must be of the format "LabNumber_ProblemNumber"
'''
if len(s) < 3:
return False
x = s.find('_')
if x == -1:
return False
c = ""
for i in range(0, x):
c = c + s[i]
try:
c = int(c)
if c < 0:
return False
except ValueError:
return False
c = ""
for i in range(x + 1, len(s)):
c = c + s[i]
try:
c = int(c)
if c < 0:
return False
except ValueError:
return False
return True
def __validator_deadline(self, string):
'''
:param string: a string representing the laboratory's deadline
:return: True if the string is valid, false otherwise
string must be of the format "DD.MM.YYYY"
'''
if len(string) < 8:
return False
x = string.split('.')
if len(x) != 3:
return False
for i in range(0, len(x)):
try:
x[i] = int(x[i])
except ValueError:
return False
for i in range(0, 3):
if i == 0:
if x[i] < 0 or x[i] > 31:
return False
if i == 1:
if x[i] < 0 or x[i] > 12:
return False
if i == 2:
if x[i] < 2020:
return False
return True
def valideaza(self, lab):
'''
:param lab: a Laborator object
Ridica ValidError cu mesajul "numar invalid!\n" sau "descriere invalida!\n" sau "deadline invalid!\n"
Raises ValidError with the message:
"numar invalid!\n" if the labNumber_problemNumber is invalid
"descriere invalida!\n" if the description is an empty string
"deadline invalid!\n" if the deadline is invalid
'''
erori = ""
if not self.__validator_numar(lab.get_nr()):
erori += "numar invalid!\n"
if lab.get_descriere() == "":
erori += "descriere invalida!\n"
if not self.__validator_deadline(lab.get_deadline()):
erori += "deadline invalid!\n"
if len(erori) > 0:
raise ValidError(erori)
else:
return True
|
253b3c33fc550949cd53066ca313ba444c5758e7 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_Another-One/Project Euler/Problem 03/sol2.py | 384 | 3.953125 | 4 | """
Problem:
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N?
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
"""
from __future__ import print_function
n = int(input())
prime = 1
i = 2
while i * i <= n:
while n % i == 0:
prime = i
n /= i
i += 1
if n > 1:
prime = n
print(prime)
|
ed080e4baa8b0ecd96a50f2e574576803bb027a6 | jaycoskey/IntroToPythonCourse | /PythonSrc/Unused/lunar_lander.py | 9,058 | 3.53125 | 4 | #!/usr/bin/env python3
# Lunar lander.
import argparse
import math
import sys
verbose = False
class Game:
DEFAULT_INITIAL_FUEL = 100
DEFAULT_INITIAL_HEIGHT = 300
DEFAULT_INITIAL_VELOCITY = 0
EPSILON = 0.01
GRAVITY = -5.0
MAX_BURN_RATE = 50
MIN_BURN_RATE = 0
SOFT_LANDING = -5
def __init__(self, player, fuel, height, velocity):
self.player = player
self.fuel = fuel
self.height = height
self.velocity = velocity
def get_contact_and_time(self, height, vel, acc, dt):
"""Determine if contact with the surface is made.
This function calls get_contact_and_time_exact.
Returns a pair (is_contact, contact_time)."""
is_contact = False
new_vel = vel + acc * dt
new_height = height + vel*dt + (0.5 * acc * dt**2)
if vel <= 0 or new_vel <= 0:
(is_contact, contact_time) = self.get_contact_and_time_exact(
height, vel, acc, dt)
return (is_contact, contact_time)
else:
self.player.vprint('get_contact_and_time: The lander is rising')
return (False, 0)
def get_contact_and_time_exact(self, height, vel, acc, dt):
"""If there is any contact, then we use the quadratic formula
to determine the exact moment of contact.
If contact is not made, this function returns (False, 0).
If contact is made, this function changes the value of the
timestep variable, dt, to the time into the current timestep
that contact took place, then returns (True, contact_time)."""
if Util.is_zero(acc):
# Solve for t in the equation x_0 + v_0 t = 0
contact_time = -height / vel
if contact_time > 0 and contact_time <= dt:
return (True, contact_time)
else:
return (False, 0)
else:
# Solve for t in the equation x_0 + v_0 t + (1/2) acc t^2 = 0
# Solution: t = (-v_0 +/- sqrt(v_0^2 - 2 acc x_0)) / acc
radicand = vel**2 - 2*acc*height
if radicand < 0:
return (False, 0)
sroot = math.sqrt(radicand)
contact_times = [ (-vel + which_root * sroot) / acc
for which_root in [-1, 1] ]
contact_time_min = min(contact_times)
contact_time_max = max(contact_times)
if contact_time_min > 0 and contact_time_min <= dt:
self.player.vprint('INFO: exact: contact_time={0:.2f}'
.format(contact_time_min))
return (True, contact_time_min)
elif contact_time_max > 0 and contact_time_max <= dt:
self.player.vprint('INFO: exact: contact_time={0:.2f}'
.format(contact_time_max))
return (True, contact_time_max)
else:
return (False, 0)
def play_game(self, fuel, height, vel):
has_fuel = True
has_landed = False
std_dt = 1
time = 0
while not has_landed:
self.player.show_state(time, fuel, height, vel)
dt = std_dt
if has_fuel:
burn_rate = self.player.get_burn_rate()
if burn_rate * std_dt > fuel:
# If all the fuel is being used,
# then set dt to time taken to burn the remaining fuel.
dt = fuel / burn_rate
self.player.vprint('INFO: play_game: Fuel-abridged dt={0}'
.format(dt))
else:
burn_rate = 0
acc = Game.GRAVITY + burn_rate
(has_landed, new_dt) = self.get_contact_and_time(
height, vel, acc, dt)
if has_landed:
dt = new_dt
time += dt
fuel -= burn_rate * dt
height += vel * dt + (0.5) * acc * dt**2
vel += acc * dt
# Landing
if has_landed or height < 0:
self.player.report_landing(time, vel, fuel)
return
# No landing
if has_fuel and Util.is_zero(fuel):
print('Out of fuel at t={0}.'.format(time))
has_fuel = False
fuel = 0
if dt < std_dt:
# Determine what happens after the fuel runs out
dt = std_dt - dt
self.player.vprint('INFO: Executing remaining dt={0:.2f}'
.format(dt))
acc = Game.GRAVITY
(has_landed2, new_dt) = self.get_contact_and_time(
height, vel, acc, dt)
if has_landed2:
dt = new_dt
time += dt
height += vel * dt + (0.5) * acc * dt**2
vel += acc * dt
if has_landed2:
report_landing(time, vel, fuel)
return
continue
def game_loop(self):
play_again = True
do_show_instructions = self.player.offer_boolean(
'\nShow instructions (y/n)? ')
if do_show_instructions:
self.player.show_instructions()
self.player.print_newline()
while play_again:
self.play_game(
fuel=args.fuel, height=args.height, vel=args.velocity)
play_again = self.player.offer_boolean('\nPlay again (y/n)? ')
self.player.print_newline()
class Player:
def farewell(self):
print('Bye!')
sys.exit(0)
def get_burn_rate(self):
burn_rate = -1.0
while burn_rate < Game.MIN_BURN_RATE or burn_rate > Game.MAX_BURN_RATE:
try:
response = input('\tBurn rate? ')
if response.lower().startswith("q"):
sys.exit(0)
burn_rate = float(response)
except KeyboardInterrupt:
self.farewell()
except:
pass
return burn_rate
def offer_boolean(self, prompt):
response = input(prompt)
letter = response[0].lower()
if letter == 'q':
farewell()
elif letter == 'n':
return False
else:
return True
def print_newline(self):
print()
def report_landing(self, time, vel, fuel):
event = "landed safely" if vel >= Game.SOFT_LANDING else "crashed"
print('At t={0:.2f}, you {1:s}.'.format(time, event))
print('\tLanding speed = {0:.2f}'.format(math.fabs(vel)))
if Util.is_zero(fuel):
print('\tNo fuel remaining')
else:
print('\tFuel remaining = {0:.2f}'.format(fuel))
def show_instructions(self):
print('Attempt to land softly on the moon.')
print('The gravity on the moon is 5 ft/sec^2.')
print('Each second, set the burn rate between 0 and 50 fuel units.')
print('It takes 5 units of fuel per second to maintain your speed.')
print('Using more will cause you to accelerate upward.')
print('Using less will cause you to accelearate downward.')
print('A "soft" landing has a downward velocity of less than 5 ft/sec.')
def show_state(self, time, fuel, height, vel):
print('t={0:3.0f}: height:{1:7.2f}, velocity:{2:7.2f}, fuel:{3:7.2f}'
.format(time, height, vel, fuel))
def vprint(self, str):
if verbose:
print(str)
def welcome(self):
print("\n\t\t*** Welcome to Lunar Lander ***")
class Util:
def is_zero(x):
"""Tests to see if a number has magnitude less than EPSILON."""
return math.fabs(x) < Game.EPSILON
def sign(x):
return math.copysign(1, x)
def main(fuel, height, velocity):
player = Player()
game = Game(player, fuel, height, velocity)
game.game_loop()
player.farewell()
if __name__ == '__main__':
# Example invocation syntax:
# python lunar_lander.py --verbose=True --height=300 --fuel=200
parser = argparse.ArgumentParser(description='Play lunar lander!!!')
parser.add_argument(
'--fuel',
type=int,
default=Game.DEFAULT_INITIAL_FUEL,
help='Initial fuel')
parser.add_argument(
'--height',
type=int,
default=Game.DEFAULT_INITIAL_HEIGHT,
help='Initial height')
parser.add_argument(
'--velocity',
type=int,
default=Game.DEFAULT_INITIAL_VELOCITY,
help='Initial velocity')
parser.add_argument(
'--verbose',
type=bool,
default=False,
help='Whether or not to print out debugging information')
args = parser.parse_args()
verbose = args.verbose
main(args.fuel, args.height, args.velocity)
|
02938bc2492f97d074b7709a2079c8d8ed14943f | GIT-Ramteja/Projectwork | /CMD.py | 387 | 3.796875 | 4 | import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
def add(a,b):
sum=a+b
print("the sum",sum)
def sub(a,b):
sub=a-b
print("the sum",sub)
def mul(a,b):
mul=a*b
print("the sum",mul)
def div(a,b):
if b==0:
print("division not possible")
else:
div=a/b
print("the sum",div)
add(a,b)
sub(a,b)
mul(a,b)
div(a,b) |
7e6e4ea245490f268f98bd588846ed208628d174 | jadesym/interview | /leetcode/111.minimum-depth-of-binary-tree/solution.py | 789 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None: return 0
queue = deque([(root, 1)])
while len(queue) > 0:
node, level = queue.popleft()
if node.left is None and node.right is None:
return level
if node.left is not None:
queue.append((node.left, level + 1))
if node.right is not None:
queue.append((node.right, level + 1))
|
73e9c57a8706afb74b46a43d76f103287a87a500 | justindodson/PythonProjects | /CPR_Temps/resources/excel_extractor.py | 2,423 | 3.609375 | 4 | import openpyxl
from resources.date_processor import process_date
class ExcelData:
def __init__(self, class_size, exel_file_name, counter=1, ):
self.class_size = class_size
self.counter = counter
self.wb = openpyxl.load_workbook(exel_file_name)
self.sheet = self.wb.get_sheet_by_name('Sheet1')
# returns a dictionary of students as a key and a list of all the data in their
# corresponding row as the value.
def extract_data(self):
values = {}
while self.class_size >= self.counter:
student_info = self.row_data_group((self.counter + 2))
values['Student {}'.format(self.counter)] = student_info
self.counter += 1
return values
# Method to put each row's data into a list to be returned.
def row_data_group(self, row_number):
column_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']
data_list = []
for col in column_list:
data_list.append(self.sheet[col+str(row_number)])
return data_list
# this method will return the String value of a specific cell.
def extract_cell_data(self, col_name, row_number):
name = None
try:
if row_number > 2:
name = self.sheet['{}{}'.format(col_name, row_number)]
return name.value
except ValueError:
raise Exception("You cannot enter data from the top 2 rows. Must start at row 3!")
# This method is used to create a student. The method takes a row number
# and creates a list of that row's location data. It then iterates over the data list
# and removes any 'None' values and appends all the text values of the
# location values to a new list. The date cells are processed to a better format
# and then an ExcelStudent object is created and returned with the list values
def create_student(self, row_number):
row_data = self.row_data_group(row_number)
student_data = []
for cell in row_data:
if cell.value is None:
cell = ""
student_data.append(cell)
else:
student_data.append(cell.value)
student = (student_data[0], student_data[1], student_data[2],
student_data[3], student_data[4], student_data[5],
student_data[6], student_data[7])
return student
|
48cd5fb1aee8e9e9927dcf296def05596e618a49 | szabgab/slides | /python/examples/dictionary/legal_drinking.py | 1,717 | 3.71875 | 4 | legal_drinking_age = {
0 : ['Angola', 'Guinea-Bissau', 'Nigeria', 'Togo', 'Western Sahara', 'Haiti', 'Cambodia', 'Macau'],
15 : ['Central African Republic'],
16 : [
'Gambia',
'Morocco',
'Antigua and Barbuda',
'Barbados',
'British Virgin Islands',
'Cuba',
'Dominica',
'Grenada',
'Saint Lucia',
'Saint Vincent and the Grenadines',
'Palestinian Authority',
'Austria',
'Denmark',
'Germany',
'Gibraltar',
'Lichtenstein',
'Luxembourg',
'San Marino',
'Switzerland'
],
17 : ['Malta'],
19 : ['Canada', 'South Korea'],
20 : ['Benin', 'Paraguay', 'Japan', 'Thailand', 'Uzbekistan', 'Iceland', 'Sweden'],
21 : [
'Cameroon',
'Egypt',
'Equatorial Guinea',
'Bahrain', 'Indonesia',
'Kazakhstan',
'Malaysia',
'Mongolia',
'Oman',
'Qatar',
'Sri Lanka',
'Turkmenistan',
'United Arab Emirates',
'American Samoa',
'Northern Mariana Islands',
'Palau',
'Samoa',
'Solomon Islands'
],
25 : ['USA'],
200 : ['Lybia', 'Somalia', 'Sudan', 'Afghanistan', 'Brunei', 'Iran', 'Iraq', 'Kuwait', 'Pakistan', 'Saudi Arabia', 'Yemen'],
}
age = int(input('Please enter your age in number of years: '))
country = input('Please enter the country of your location: ')
for k in legal_drinking_age:
if country in legal_drinking_age[k]:
print('The minimum legal drinking age in your location is: {} years'.format(k))
if age >= k:
exit('You are allowed to consume alcohol in your location')
else:
exit('You are not permitted to consume alcohol currently in your location.')
print('The minimum legal drinking age in your location is: 18 years')
if age >= 18:
exit('You are allowed to consume alcohol in your location')
else:
exit('You are not permitted to consume alcohol currently in your location.')
|
35e4a987b8f607c92c80be5b07403948215e94e2 | penroselearning/pystart | /Fast Five Car Rental.py | 1,524 | 4.25 | 4 | cars = [('Honda', 'Accord', 'Blue', 2019),
('Nissan', 'Patrol', 'Black', 2018),
('Infiniti', 'QX60', 'Silver', 2018)]
action = int(input('''Would you like to:
1. Add a Car
2. Remove a Car
3. View Cars
4. Exit
---------------------
Please choose the number corresponding to the action of your choice.\n'''))
print()
if action == 1:
make = input("Enter a New Car Make:\n").title()
model = input("Enter The Car Model:\n").title()
color = input("Enter The Car Color:\n").title()
year = input("Enter The Car Year:\n").title()
print()
cars.append((make, model, color, year))
print(f'{"Make":20} {"Model":20} {"Color":20} {"Year":20}')
print('-' * 70)
for info in cars:
print(f'{info[0]:20} {info[1]:20} {info[2]:20} {info[3]}')
elif action == 2:
make = input("Enter the make of the car you wish to remove:\n").title()
print()
for x in range(len(cars)):
if make == cars[x][0]:
cars.pop(x)
break
else:
print("Not Found")
print(f'{"Make":20} {"Model":20} {"Color":20} {"Year":20}')
print('-' * 70)
for info in cars:
print(f'{info[0]:20} {info[1]:20} {info[2]:20} {info[3]}')
elif action == 3:
print(f'{"Make":20} {"Model":20} {"Color":20} {"Year":20}')
print('-' * 70)
for info in cars:
print(f'{info[0]:20} {info[1]:20} {info[2]:20} {info[3]}')
elif action == 4:
exit()
else:
print("Sorry that is an invalid response. Please choose a number between 1 and 4.") |
163bd525b712219462f9a84fbb5615404f39e608 | Warherolion/Final-Project | /Main.py | 43,645 | 3.546875 | 4 | # Name: Ranvir Singh
# Date: March 20th, 2019
# File Name: Main.py AKA Monopoly
# Description: This program allows for the user to play monopoly with as many different AI players as they want or with
# other human players taking turns on the terminal, the user can set their own difficulty settings, choose their own
# names, if playing against AI depending on the level of difficulty the AI will choose card sets and play different
# tactics to win against the human player, the user has access to all the typical parts of monopoly community chests,
# chance cards, buy properties and can even modify game rules from a set of different changes they can choose what to
# for example they can choose to add a upper limit to the amount of money earned and whoever reaches there first wins.
# todo
# add try and except to everything
# Create a hotel and apartments function
import time
import random
from collections import Counter
property = ["Go", "Mediterranean Ave", "Community Chest", "Baltic Ave", "Income Tax", "Reading Railroad",
"Oriental Ave", "Chance", "Vermont Ave", "Connecticut Ave", "jail/Just Visiting", "St. Charles Place",
"Electric Company", "States Ave", "Virginia Ave", "Pennsylvania Railroad", "St. James Place",
"Community Chest", "Tennessee Ave", "New York Ave", "Free Parking", "Kentucky Ave", "Chance",
"Indiana Ave", "Illinois Ave", "B. & O. Railroad", "Atlantic Ave", "Ventnor Ave", "Water Works",
"Marvin Gardens", "Go to Jail", "Pacific Ave", "North Carolina Ave", "Community Chest",
"Pennsylvania Ave", "Short Line Railroad", "Chance", "Park Place", "Luxury Tax", "Boardwalk"]
propertyPrice= [
200, 60, 0, 60,100, 200, 100, 0, 100, 120, 0, 140, 150, 140, 160,200, 180, 0,180, 200, 0, 220, 0, 220, 240,
200, 260, 260, 150, 280, 0, 300, 300, 0, 320, 200, 0, 350, 300, 400
]
propertyColor = [
"None", "Brown", "None", "Brown", "None", "None", "Navy", "None", "Navy", "Navy", "None", "Pink", "None", "Pink", "Pink", "None", "Orange",
"None", "Orange", "Orange", "None", "Red", "None", "Red", "Red", "None", "Yellow", "Yellow", "None", "Yellow", "None", "Green", "Green", "None",
"Green", "None", "None", "Blue", "None", "Blue"
]
Color=["Brown", "Navy", "Pink", "Orange", "Red", "Yellow", "Green", "Blue"]
chanceCards = ["Advance to Go (Collect $200)", "Advance to Illinois Ave",
"Advance to St. Charles Place – If you pass Go, collect $200", "Bank pays you dividend of $50", "Get Out of Jail Free", "Go Back 3 Spaces",
"Go to Jail","Pay poor tax of $15", "Take a trip to Reading Railroad",
"Take a walk on the Boardwalk", "You have been elected Chairman of the "
"Board–Pay each player $50",
"Your building and loan matures—Collect $150", "You have won a crossword competition—Collect $100"]
CommunityChest = ["Advance to Go (Collect $200)", "Bank error in your favor—Collect $200", "Doctor's fee—Pay $50",
"From sale of stock you get $50", "Get Out of Jail Free", "Go to Jail–Go directly to jail–Do "
"not pass Go–Do not collect $200",
"Grand Opera Night—Collect $50 from every player for opening night seats", "Holiday Fund matures—"
"Receive $100",
"Income tax refund–Collect $20", "It is your birthday—Collect $10", "Life insurance matures–Collect "
"$100",
"Pay hospital fees of $100", "Pay school fees of $150", "Receive $25 consultancy fee",
"You have won second prize in "
"a beauty contest–Collect $10",
"You inherit $100"]
players = []
playerMoveCount = []
# Allows for access to the settings file and drops values into a list
settings = []
with open("settings.txt") as file:
for line in file:
line = line.split(":")
line = line[1]
line = line.rstrip("\n")
line = line[1:]
line = line.split(" ")
try:
for x in range(len(line)):
line[x] = int(line[x])
line = (line[0], line[1])
except:
line = line[0]
settings.append(line)
file.close()
# Error checking for inputs file stored as a function
def inputs(line, typeinp=None, start=None, end=None):
while True:
string = input(line)
if typeinp != None:
try:
if typeinp == "string":
string = str(string)
elif typeinp == "integer":
string = int(string)
if start != None and end != None:
while not (string >= start and string <= end):
print("Please input a number between", str(start) + "-" + str(end))
string = int(input(line))
break
except:
print("Please input a", typeinp)
else:
break
return string
def chance_community():
if property[player_update] == "Chance":
if chanceCards.index(ChanceCardPick) == 0:
players[PlayerTurn]["PlayerLocation"] = 0
money = int(players[PlayerTurn]["money"])
money += 200
players[PlayerTurn]["money"] = money
print("You were moved back to go and gained $200")
elif chanceCards.index(ChanceCardPick) == 1:
ill = property.index("Illinois Ave")
players[PlayerTurn]["PlayerLocation"] = ill
print("You are now on Illinois Ave")
elif chanceCards.index(ChanceCardPick) == 2:
cill = property.index("St. Charles Place")
players[PlayerTurn]["PlayerLocation"] = ill
print("You are now on St. Charles Place")
elif chanceCards.index(ChanceCardPick) == 3:
money = int(players[PlayerTurn]["money"])
money += 50
players[PlayerTurn]["money"] = money
print("You earned $50")
elif chanceCards.index(ChanceCardPick) == 4:
if players[PlayerTurn]["Getoutajail"] == True:
print("You already have a get outa jail free card so no more for you..")
elif players[PlayerTurn]["Getoutajail"] == False:
players[PlayerTurn]["Getoutajail"] == True
print("You now own a get out of jail free card")
elif chanceCards.index(ChanceCardPick) == 5:
players[PlayerTurn]["PLayerLocation"] -= 3
print("You Got moved back 3 spaces")
elif chanceCards.index(ChanceCardPick) == 6:
players[PlayerTurn]["inJail"]= True
players[PlayerTurn]["PlayerLocation"] = 10
print("Oh no you are now in jail")
elif chanceCards.index(ChanceCardPick) == 7:
money = int(players[PlayerTurn]["money"])
money -= 15
players[PlayerTurn]["money"] = money
elif chanceCards.index(ChanceCardPick) == 8:
players[PlayerTurn]["PlayerLocation"] = 5
print("You went to reading railroad")
elif chanceCards.index(ChanceCardPick) == 9:
bord = property.index("Boardwalk")
players[PlayerTurn]["PlayerLocation"] = bord
print("You went to Boardwalk")
elif chanceCards.index(ChanceCardPick) == 10:
count = 0
for pp in range(len(players)):
money = players[pp]["money"]
money +=50
count +=1
moneylost = (50 * count) -50
players[PlayerTurn]["money"] -= moneylost
print("You paid everyone $50")
elif chanceCards.index(ChanceCardPick) == 11:
money = players[PlayerTurn]["money"]
money +=150
players[PlayerTurn]["money"] = money
print("You made $150")
elif chanceCards.index(ChanceCardPick) == 12:
money = players[PlayerTurn]["money"]
money +=100
players[PlayerTurn]["money"] = money
print("You made $100")
elif property[player_update] == "Community Chest":
if CommunityChest.index(ChanceCardPick) == 0:
players[PlayerTurn]["PlayerLocation"] = 0
money = int(players[PlayerTurn]["money"])
money += 200
players[PlayerTurn]["money"] = money
print("You were moved back to go and gained $200")
elif CommunityChest.index(ChanceCardPick) == 1:
money = int(players[PlayerTurn]["money"])
money += 200
print("You made $200")
players[PlayerTurn]["money"] = money
elif CommunityChest.index(ChanceCardPick) == 2:
money = int(players[PlayerTurn]["money"])
money += 50
players[PlayerTurn]["money"] = money
print("You paid $50")
elif CommunityChest.index(ChanceCardPick) == 3:
money = int(players[PlayerTurn]["money"])
money += 50
players[PlayerTurn]["money"] = money
print("You earned $50")
elif CommunityChest.index(ChanceCardPick) == 4:
if players[PlayerTurn]["Getoutajail"] == True:
print("You already have a get outa jail free card so no more for you..")
elif players[PlayerTurn]["Getoutajail"] == False:
players[PlayerTurn]["Getoutajail"] == True
print("You now own a get out of jail free card")
elif CommunityChest.index(ChanceCardPick) == 5:
players[PlayerTurn]["inJail"]= True
players[PlayerTurn]["PlayerLocation"] = 10
print("Oh no you are now in jail")
elif CommunityChest.index(ChanceCardPick) == 6:
count = 0
for pp in range(len(players)):
money = players[pp]["money"]
money -=50
count +=1
moneyGain = (50 * count) +50
players[PlayerTurn]["money"] -= moneyGain
print("You got $50 from everyone")
elif CommunityChest.index(ChanceCardPick) == 7:
money = int(players[PlayerTurn]["money"])
money += 100
print("You made $100")
players[PlayerTurn]["money"] = money
elif CommunityChest.index(ChanceCardPick) == 8:
money = int(players[PlayerTurn]["money"])
money += 20
print("You made $20")
players[PlayerTurn]["money"] = money
elif CommunityChest.index(ChanceCardPick) == 9:
money = int(players[PlayerTurn]["money"])
money += 10
print("You made $10")
players[PlayerTurn]["money"] = money
elif CommunityChest.index(ChanceCardPick) == 10:
money = int(players[PlayerTurn]["money"])
money += 100
print("You made $100")
players[PlayerTurn]["money"] = money
money = players[PlayerTurn]["money"]
elif CommunityChest.index(ChanceCardPick) == 11:
money -=150
print("You paid $150")
players[PlayerTurn]["money"] = money
elif CommunityChest.index(ChanceCardPick) == 12:
money = players[PlayerTurn]["money"]
money +=25
print("You made $25")
players[PlayerTurn]["money"] = money
elif CommunityChest.index(ChanceCardPick) == 13:
money = players[PlayerTurn]["money"]
money +=10
print("You made $10")
players[PlayerTurn]["money"] = money
elif CommunityChest.index(ChanceCardPick) == 14:
money = players[PlayerTurn]["money"]
money +=100
print("You made $100")
players[PlayerTurn]["money"] = money
def playerChange():
print("Next Player")
print("***************************************")
print("*")
print("*")
print("*")
print("*")
print("***************************************")
return
# Settings file, if user chooses to run setup this is all the setup questions
def gameSettingsSetup():
settingsCheck = open("settings.txt", "r")
print("Lets setup")
# Int Setup questions
numPlayers = str(inputs('How many real players are playing: ', "intger"))
numAIplayers = str(inputs('How many AI players will be playing?: ', "integer"))
if numAIplayers != "0":
AILevel = str(inputs("What AI difficulty level would you like? (Easy, Normal, Hard): "))
while True:
if AILevel == "Easy" or AILevel == "Normal" or AILevel == "Hard":
startingMoney = str(inputs("How much money does everyone start with? Max: 10 000 (Keep in mind "
"this does not affect the property prices) ", "integer", 100, 10000))
for i in range(int(numPlayers)):
name = input("What is the players name? ")
players.append({"playerName": name, "money":startingMoney, "properties": [], "railroads": []})
break
else:
print("Please enter a valid input (make sure to capitalize the first letter)")
AILevel = str(inputs("What AI difficulty level would you like? (Easy, Normal, Hard): "))
elif numAIplayers == "0":
startingMoney = str(inputs("How much money does everyone start with? Max: 10 000 (Keep in mind "
"this does not affect the property prices) ", "integer", 100, 10000))
for i in range(int(numPlayers)):
name = input("What is the players name? ")
players.append(name)
print("Alright the setup is complete, Your game will start now....")
time.sleep(1)
# sends over the settings into the text file as well as monoset check
if "MonoSet1-1" in settingsCheck.read():
with open("settings.txt", "w") as file:
file.write("MonoSet1-1: true" + "\n")
file.write("numPlayer: " + numPlayers + "\n")
file.write("numAIplayer: " + numAIplayers + "\n")
file.write("AI Level: " + AILevel + "\n")
file.write("startingMoney: " + startingMoney + "\n")
file.close()
return settingsCheck, players
# Picks a random card from the chance lists
def chancePickUp():
cardPick = random.randint(0, 12)
return chanceCards[cardPick]
# Picks a random card from the community chest lists
def communityPickUp():
cardPick = random.randint(0, 13)
return CommunityChest[cardPick]
# emmulates the dice roll
def dice_roll():
snakeEyes = False
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
if die1 == die2:
snakeEyes = True
total = die1 + die2
return die1, die2, total, snakeEyes
def is_property_owned(property_name):
for p in players:
if property_name in p['properties']:
return p['playerName'] # Returns the owner of property
else:
for a in aiPlayerList:
if property_name in a['properties']:
return a['AiName'] # Returns the owner of property
return None
# Decides weather or not to buy the property
def buy_rand():
buyEasy = random.randint(0, 1)
return buyEasy
# AI EASY FULL PROGRAM
aiPlayerList = []
propLoc = 0
for PlayerAi in range(settings[2]):
aiPlayerList.append(
{
"AiName": PlayerAi,
"money": settings[4],
"properties": [],
"railroads": [],
"inJail": False,
"PlayerLocation": propLoc,
"Getoutajail": False
}
)
# AI EASY
def Ai_easy():
ChanceCardPick = chancePickUp()
CommunityCardPick = communityPickUp()
print("The Ai is going now please wait....")
time.sleep(1)
BigBoi = "(ง ͠° ͟ل͜ ͡°)ง"
for a in range(settings[2]):
money = int(aiPlayerList[0]["money"])
if money > 50:
buyEasy = buy_rand()
die1, die2, total, snakeEyes = dice_roll()
AiLoc = propLoc + total
AD = property.index(property[total])
aiPlayerList[0]["PlayerLocation"] += AD
AiUpdate = aiPlayerList[0]["PlayerLocation"]
propertycheck = is_property_owned(property[AiUpdate])
if property[total] != "Chance":
if property[total] != "Community Chest":
if property[total] != "jail/Just Visiting":
if buyEasy == 1:
if propertycheck == None:
aiPlayerList[a]["properties"] = property[AiLoc]
aiPlayerList[a]["PlayerLocation"] = AiLoc
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc], "and bought it")
if snakeEyes == True:
print("The computer also got Snake eyes! and gets to roll again")
die1, die2, total1, snakeEyes = dice_roll()
if buyEasy == 1:
if propertycheck == None:
aiPlayerList[a]["properties"] = property[AiLoc]
aiPlayerList[a]["PlayerLocation"] = AiLoc
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc+ total1], "and bought it")
elif propertycheck != None:
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc + total1], "which is owned by", propertycheck)
for i in range(len(players)):
if propertycheck in players[i]["playerName"]:
propOwn = players[i]
rentValue = propertyPrice[player_update] * 0.60
money = int(players[PlayerTurn]["money"])
money -= rentValue
players[PlayerTurn]["money"] = int(money)
moneyErn = int(propOwn["money"])
moneyErn +=rentValue
propOwn["money"] = int(moneyErn)
print("You paid rent to", propertycheck, "for a total of", rentValue)
print(players)
elif buyEasy == 0:
aiPlayerList[0]["PlayerLocation"] = AiLoc
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc], "and did not buy it")
elif propertycheck != None:
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc], "which is owned by", propertycheck)
elif buyEasy == 0:
aiPlayerList[a]["PlayerLocation"] = AiLoc
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc], "and did not buy it")
elif property[total] == "jail/Just Visiting":
print("The Bot landed on Jail/ Just Visiting")
elif property[total] == "Community Chest":
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc], "the card states", CommunityCardPick)
elif property[total] == "Income Tax":
print("The Computer rolled a", die1,"and a", die2, "landed on", property[AiLoc], "and had to pay", propertyPrice[AiLoc])
money = int(aiPlayerList[a]["money"])
money -= propertyPrice[total]
elif property[total] == "Chance":
print("The Computer rolled a", die1,"and a", die2, "and landed on", property[AiLoc], "the card states", CommunityCardPick)
elif money < 50:
print("The Ai ran out of money and is forfiting")
aiPlayerList.remove(0)
# A summary of all the player information
def playerInfo():
print("\nName:", players[PlayerTurn]["playerName"] )
print("Money:", players[PlayerTurn]["money"])
print("Properties:")
for u in range(len(players[PlayerTurn]["properties"])):
print(u+1, players[PlayerTurn]["properties"][u])
if players[PlayerTurn]["inJail"]:
print("You are in jail")
else:
print("You are not in jail")
if players[PlayerTurn]["Getoutajail"]:
print("You have a Get out of jail card")
else:
print("you have no get out of jail card \n")
# Intro
settingsCheck = open("settings.txt", "r")
print("Hello! Welcome to the game of monopoly, Terminal version before we can start we have to make sure "
"everything is set up properly... \n")
time.sleep(2)
# Settings check, checks if a settings file exists and if so checks if the user wants to use them. s
importSetyn = input("You have saved settings in you setting file, would you like to use them? (y or n): ")
if "MonoSet1-1" in settingsCheck.read():
while True:
if importSetyn == "y" or importSetyn == "Y":
print("Alright lets start your game... ")
time.sleep(1)
players = []
for i in range(int(settings[1])):
name = input("What is the players name? ")
players.append(
{
"playerName": name,
"money": settings[4],
"properties": ["Mediterranean Ave", "Baltic Ave"],
"Colors": ["Brown", "Brown", "Blue", "Blue", "Blue"],
"APTS": [],
"Hotels": [],
"inJail": False,
"PlayerLocation": 0,
"Getoutajail": False
}
)
break
elif importSetyn == "n" or importSetyn == "N":
time.sleep(1)
gameSettingsSetup()
break
else:
print("Invalid Input")
importSetyn = input("You have saved settings in you setting file, would you like to use them? "
"(y or n): ")
elif "" in settingsCheck.read(1):
print("You dont have any saved settings lets fix that.....")
gameSettingsSetup()
else:
print("Your setting file seems to be corrupted please either remove any random text or delete the file...")
# Main code, a for loop for all the real players
PlayerTurn = 0
while True:
money = int(players[PlayerTurn]["money"])
if money > 50:
playerInfo()
print("It is now", players[PlayerTurn]["playerName"]+ "'s", "turn \n")
print("1. Roll (rolls the dice)")
print("2. Skip (skips turn to the next person)")
print("3. Place Apartment (only works once a full card set is owned)")
print("4. Place Hotel (only works if 4 apartments are placed on a property)")
print("5. Mortgage Property (Mortgage the property to get some money back)")
print("6. Post Bail (only works if you are in jail and have the money to pay)")
print("7. Quit game")
playerAction = inputs("Please enter your action: ", "integer", 1, 7)
if playerAction == 1 :
while True:
if players[PlayerTurn]["inJail"] == False:
die1, die2, total, snakeEyes = dice_roll()
# Calls either chance or community function to pick a random card and give it to the player
ChanceCardPick = chancePickUp()
CommunityCardPick = communityPickUp()
# property owned check, sees if anyone owns the property and returns either none or the playerName
time.sleep(1)
#pd = property.index(property[total])
pd = 30
if pd > 40:
newLoop = pd - 40
pd = 0 + newLoop
players[PlayerTurn]["PlayerLocation"] += pd
player_update = players[PlayerTurn]["PlayerLocation"]
print("You passed go and collected $200")
money = int(players[PlayerTurn]["money"])
money += 200
players[PlayerTurn]["money"] = money
elif pd < 40:
print("Hello")
players[PlayerTurn]["PlayerLocation"] += pd
player_update = players[PlayerTurn]["PlayerLocation"]
print("You rolled a", die1, "and a", die2, "you move forward",total, "steps \n")
time.sleep(1)
print(player_update)
print("You landed on", property[player_update] + "\n")
time.sleep(1)
if property[player_update] == "Community Chest" or property[player_update] == "Chance":
if property[player_update] == "Community Chest":
print(CommunityChest.index(CommunityCardPick))
print("The card you picked states", CommunityCardPick, "\n")
chance_community()
elif property[player_update] == "Chance":
print(chanceCards.index(ChanceCardPick))
print("The card you picked states", ChanceCardPick)
chance_community()
else:
print("Something went wrong, sorry")
elif property[player_update] != "Community Chest":
# checks if the user landed on income tax and will deduct it from their money
if property[player_update] == "Income Tax":
print("You have to pay", propertyPrice[player_update])
money = int(players[PlayerTurn]["money"])
money -= propertyPrice[player_update]
players[PlayerTurn]["money"] = money
print("You now have", money, "dollars \n")
elif property[player_update] != "Income Tax":
if property[player_update] != "Chance":
# Checks if any one owns the property
propertycheck = is_property_owned(property[player_update])
# if the property check results in a player name it will state that name
if propertycheck != None:
# Property Check and rent
print("This property is owned by", propertycheck, "and you now need to pay a rent")
##########
# rent original value * 0.20 and for each apt og value + 20% hotel 200% of inital value
#########
for i in range(len(players)):
if propertycheck in players[i]["playerName"]:
propOwn = players[i]
rentValue = propertyPrice[player_update] * 0.60
money = int(players[PlayerTurn]["money"])
money -= rentValue
players[PlayerTurn]["money"] = int(money)
moneyErn = int(propOwn["money"])
moneyErn +=rentValue
propOwn["money"] = int(moneyErn)
print("You paid rent to", propertycheck, "for a total of", rentValue)
print(players)
# checks if no one owns the property and is not on jail
elif propertycheck == None and property[player_update] != "jail/Just Visiting":
# prints the price of the property as long as it costs more than 0
if propertyPrice[player_update] > 0:
print("It costs " + str(propertyPrice[player_update]) + " dollars ")
propertyBuyChoice = str(input("Do you want to buy this property? " + "\n"))
if propertyBuyChoice == "y" or propertyBuyChoice == "Y":
if int(players[PlayerTurn]["money"]) > propertyPrice[player_update]:
print("You have", players[PlayerTurn]["money"], "dollars \n")
buyCheck = input("You have enough money to buy this property, are you sure you want to buy it?: \n")
if buyCheck == "y" or buyCheck == "Y":
money = int(players[PlayerTurn]["money"])
players[PlayerTurn]["money"] -= int(propertyPrice[player_update])
players[PlayerTurn]["properties"].append(property[player_update])
players[PlayerTurn]["Colors"].append(propertyColor[player_update])
print("You now own", property[player_update] + "\n")
time.sleep(2)
elif buyCheck == "n" or buyCheck == "N":
print("Ok Buy canceled... \n")
else:
print("Please enter either a n or y ")
elif players[PlayerTurn]["money"] < propertyPrice[player_update]:
print("You do not have enough money to buy this property")
playerChange()
elif players[PlayerTurn]["money"] == 0:
print("Boi you are broke, you can't buy anything \n")
playerChange()
elif propertyBuyChoice == "n" or propertyBuyChoice == "N":
print("Alright buy canceled")
else:
print("Please input either y or n")
propertyBuyChoice = str(input("Do you want to buy this property? " + "\n"))
if PlayerTurn == settings[1]-1:
print("It is now the Ai's turn")
playerChange()
Ai_easy()
PlayerTurn = 0
elif PlayerTurn < settings[1]:
PlayerTurn +=1
playerChange()
elif property[player_update] == "jail/Just Visiting":
print("Don't worry you are just visiting")
time.sleep(2)
# If the player lands on the GO TO JAIL property, sets the players jail setting to true and moves them back to jail
elif property[player_update] == "Go to Jail":
print("You are being sent to jail")
players[PlayerTurn]["inJail"] = True
player_update = property[10]
if PlayerTurn == settings[1]-1:
print("It is now the Ai's turn")
playerChange()
Ai_easy()
PlayerTurn = 0
elif PlayerTurn != settings[1]:
PlayerTurn +=1
playerChange()
# Snake eyes for players
if snakeEyes == False:
break
else:
print("You got snake eyes and get to roll again")
elif playerAction == 2:
print("Alright next player is going now..")
if PlayerTurn == settings[1]-1:
print("It is now the Ai's turn")
playerChange()
Ai_easy()
PlayerTurn = 0
elif PlayerTurn < settings[1]:
PlayerTurn +=1
playerChange()
"""
elif playerAction == 3:
PropColors = []
for pp in range(len(propertyColor)):
PropColors.append(propertyColor[pp])
if players[PlayerTurn]["Colors"].count("Blue") == 2:
ColValues= []
for p in range(len(players[])):
PropColIndex = propertyColor.index("Brown")
del PropColors[PropColIndex]
ColValues.append(property[p])
for up in range (len(ColValues)):
print(up, ColValues[up])
BuildChoice = inputs("Which Property would you like to build on?(Note that whenever a player lands on the property the rent will be increased by 20% for each apt): ", "integer", 0, len(ColValues))
hotelnums = inputs("How many hotels would you like?: ", "integer", 1, 4)
players[PlayerTurn]["APTS"].append(BuildChoice,hotelnums)
print(players)
elif players[PlayerTurn]["Colors"].count("Brown") == 2:
ColValues= []
for p in range(len(propertyColor)):
PropColIndex = propertyColor.index("Brown")
del PropColors[PropColIndex]
ColValues.append(property[p])
for up in range (len(ColValues)):
print(up, ColValues[up])
BuildChoice = inputs("Which Property would you like to build on?(Note that whenever a player lands on the property the rent will be increased by 20% for each apt): ", "integer", 0, len(ColValues))
hotelnums = inputs("How many hotels would you like?: ", "integer", 1, 4)
players[PlayerTurn]["APTS"].append(BuildChoice,hotelnums)
print(players)
#elif propCount == 3:
# pass
elif playerAction == 4:
pass
"""
elif playerAction == 5:
if len(players[PlayerTurn]["properties"]) == 0:
print("You have no properties")
print("It is now", players[PlayerTurn]["playerName"]+ "'s", "turn \n")
print("1. Roll (rolls the dice)")
print("2. Skip (skips turn to the next person)")
print("3. Place Apartment (only works once a full card set is owned)")
print("4. Place Hotel (only works if 4 apartments are placed on a property)")
print("5. Mortgage Property (Mortgage the property to get some money back)")
print("6. Post Bail (only works if you are in jail and have the money to pay)")
print("7. Save Game (Save the current state of the game)")
print("8. Quit game")
playerAction = inputs("Please enter your action: ", "integer", 1, 6)
elif len(players[PlayerTurn]["properties"]) > 0:
print("Warning Mortgaging a property will remove it from your pack and will be on the open market again")
choice = input("Do you want to continue?: ")
while True:
if choice == "Y" or "y":
for prop in range(len(players[PlayerTurn]["properties"])):
print(prop, players[PlayerTurn]["properties"][0+prop])
mortChoice = inputs("Which property would you like to mortgage: ", "integer", 0, len(players[PlayerTurn]["properties"]))
PropChoiceMort = property.index(players[PlayerTurn]["properties"][mortChoice])
propPriceMort = propertyPrice[PropChoiceMort]
mortValue = int(propPriceMort *0.55)
money = int(players[PlayerTurn]["money"])
money += mortValue
players[PlayerTurn]["money"] = money
players[PlayerTurn]["properties"].remove(players[PlayerTurn]["properties"][mortChoice])
players[PlayerTurn]["Colors"].remove(players[PlayerTurn]["Colors"][mortChoice])
print("Your property is now mortgaged and you made", mortValue, "dollers")
break
elif choice == "N" or "n":
print("Alright")
print("It is now", players[PlayerTurn]["playerName"]+ "'s", "turn \n")
print("1. Roll (rolls the dice)")
print("2. Skip (skips turn to the next person)")
print("3. Place Apartment (only works once a full card set is owned)")
print("4. Place Hotel (only works if 4 apartments are placed on a property)")
print("5. Mortgage Property (Mortgage the property to get some money back)")
print("6. Post Bail (only works if you are in jail and have the money to pay)")
print("7. Save Game (Save the current state of the game)")
print("8. Quit game")
playerAction = inputs("Please enter your action: ", "integer", 1, 6)
break
else:
print("Please enter either y or n")
choice = input("Do you want to continue?")
elif playerAction == 6:
if players[PlayerTurn]["inJail"] == True:
while True:
bailChoice = input("The price of bail is $300, would you like to pay it?: ")
if bailChoice == "y" or "Y":
money = int(players[PlayerTurn]["money"])
money -= 300
players[PlayerTurn]["money"] = money
players[PlayerTurn]["inJail"] = False
print("You now have", players[PlayerTurn]["money"], "dollars")
if PlayerTurn == settings[1]-1:
print("It is now the Ai's turn")
playerChange()
Ai_easy()
PlayerTurn = 0
elif PlayerTurn < settings[1]:
PlayerTurn +=1
playerChange()
break
elif bailChoice == "n" or "N":
print("Alright")
if PlayerTurn == settings[1]-1:
print("It is now the Ai's turn")
playerChange()
Ai_easy()
PlayerTurn = 0
elif PlayerTurn < settings[1]:
PlayerTurn +=1
playerChange()
break
else:
print("Please enter either y or n")
bailChoice = input("The price of bail is $300, would you like to pay it?: ")
elif players[PlayerTurn]["inJail"] == False:
print("You are not in jail")
elif playerAction == 7:
print("Good bye")
break
else:
print("Please enter a valid integer")
playerAction = inputs("Please enter your action: ", "integer", 1, 6)
elif money < 50:
if len(players[PlayerTurn]["properties"]) > 0:
print("You do not have enough money to play please do one of the following: ")
print("1. Forfit Game (You will lose)")
print("2. Mortgage a property")
playChoice = input("Please enter one of the options: ", "integer", 1, 2)
elif len(players[PlayerTurn]["properties"]) == 0:
print("You do not have enough money to play")
print("You dont have any properties, your only choice is to forfit... Sorry")
time.sleep(1)
print("Sorry to see this end so soon... ")
players.remove(players[PlayerTurn])
time.sleep(1)
if len(players) == 1:
print("Congrats", players[0]["playerName"], "You WON!!!!!!!!!!!")
print("*\n"*6)
print("You won!")
break
|
cedc6a2de3e6b79658b49baad032956ad1c2573a | MattBroe/Python-Graph-Algorithms | /Edge.py | 1,469 | 3.875 | 4 | #This class is used to represent a weighted edge of a graph. If e_1, e_2 are
#two instances of Edge, then e_1 < e_2, e_1 > e_2, e_1 == e_2 are all evaluated
#according to the respective weights of e_1 and e_2. This allows you to create
#a minHeap full of Edge objects sorted by weight, which is a helpful data
#structure in several important graph algorithms.
#It is also possible to compare Edge objects to ints and floats,
#where the result is again determined by the weight of the edge,
class Edge:
def __init__(self, source, target, weight = 1):
self.source = source
self.target = target
self.weight = weight
def __eq__(self, other):
if isinstance(other, Edge):
return self.weight == other.weight
if isinstance(other, float):
return self.weight == other
if isinstance(other, int):
return self.weight == other
def __lt__(self, other):
if isinstance(other, Edge):
return self.weight < other.weight
if isinstance(other, float):
return self.weight < other
if isinstance(other, int):
return self.weight < other
def __gt__(self, other):
if isinstance(other, Edge):
return self.weight > other.weight
if isinstance(other, float):
return self.weight > other
if isinstance(other, int):
return self.weight > other
|
68b645dfd7954c91f6dd06ab0bdf2fb1b4c8b57a | mohmmadnoorjebreen/data-structures-and-algorithms | /python/stack-queue-pseudo/stack_queue_pseudo/stack_queue_pseudo.py | 1,708 | 4.03125 | 4 | class Node:
def __init__(self,data=''):
self.data= data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self,value):
node = Node(value)
node.next = self.top
self.top = node
def pop(self):
if not self.top:
raise Exception ( 'empty stack')
temp = self.top
self.top = self.top.next
temp.next = None
return temp.data
def peek(self):
if not self.top:
raise Exception ( 'empty stack')
return self.top.data
def is_empty(self):
return not self.top
def __str__(self) -> str:
string = ''
temp = self.top
while temp:
string += f'{temp.data}->'
temp = temp.next
return string
class PseudoQueue:
def __init__(self):
self.s1 = Stack()
self.s2 = Stack()
def enqueue(self,value):
self.s1.push(value)
def dequeue(self):
if self.s2.top:
value_remove =self.s2.pop()
else:
while self.s1.top:
top = self.s1.pop()
self.s2.push(top)
value_remove =self.s2.pop()
return value_remove
def __str__(self) -> str:
string = ''
if self.s1.top:
temp = self.s1.top
else:
temp = self.s2.top
while temp:
string += f'{temp.data}->'
temp = temp.next
return string
# if __name__ == '__main__':
# x = PseudoQueue()
# x.enqueue(10)
# x.enqueue(15)
# x.enqueue(20)
# x.enqueue(5)
# print(x)
# print(x.dequeue())
# print(x)
|
1c5b9b3bc4a64c3071a1b745096c2e59c147abe7 | kwaiman/Image-Downloader | /Image_Downloaders.py | 1,060 | 3.609375 | 4 | import requests
import os
def image_dl():
urlName = input('Please provide the URL name.\n')
r = requests.get(urlName, stream = True)
r.raw.decode_content = True
pathAnswer = 0
while pathAnswer != 1 and pathAnswer != 2:
pathAnswer = int(input('Do you want to save the images on (1) Desktop, or (2) Downloads folder?\nPlease return 1 or 2\n'))
if pathAnswer == 1:
pathName = 'Desktop'
break
elif pathAnswer == 2:
pathName = 'Downloads'
break
print('Please enter 1 or 2.\n')
fileName = input('Please enter the file name you want to be saved.\n') + '.jpeg'
fullPathName = pathName + '/' + fileName
# Change the directory to the user's home directory
homeDir = os.path.expanduser('~')
os.chdir(homeDir)
# download the image(file) to the selected path
with open(fullPathName,'wb') as f:
f.write(r.content)
# URL for testing: https://cdn.cdnparenting.com/articles/2018/06/27181318/lord-shiva-1800672_1280-696x464.jpg
image_dl()
|
d26ad3fbeb864557edb32b2ad4398977d3db81b9 | pocketgroovy/MachineLearningProj1 | /qlearning_robot/ReversePriorityQueue.py | 295 | 3.6875 | 4 | from Queue import PriorityQueue
class ReversePriorityQueue(PriorityQueue):
def put(self, tup):
newtup = tup[0] * -1, tup[1]
PriorityQueue.put(self, newtup)
def get(self):
tup = PriorityQueue.get(self)
newtup = tup[0] * -1, tup[1]
return newtup |
9a8c2e71714d5345fa7a0aab241fda4769d382e3 | bwood9/Portilla-Intro_ML | /PY/Groupby.py | 1,169 | 4.3125 | 4 | # Groupby is a function common to SQL that allows user to group rows together
# based off of a column and perform an aggregate (e.g. sum, mean, sd, etc.) function on them.
import pandas as pd
# create dictionary containing the data
data = {'Company':['GOOG', 'GOOG', 'MSFT', 'MSFT', 'FB', 'FB'],
'Person':['Same', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'],
'Sales':[200, 120, 340, 124, 243, 350]}
# read in data as dataframe
df = pd.DataFrame(data)
print df
byComp = df.groupby('Company')
print byComp
# groupby will ignore any aggregating col that is non-numeric
print byComp.mean()
print byComp.std()
print df.groupby('Company').sum()
# separate
print ''
# groupby for only FB (count number of instances
print df.groupby('Company').count().loc['FB']
print ''
# min will print first in alphabetical order for strings
print df.groupby('Company').min().loc['GOOG']
# print various aggregation functions in one line of code
print df.groupby('Company').describe()
# transpose describe print
print df.groupby('Company').describe().transpose()
# print for only FB
print df.groupby('Company').describe().transpose()['FB'] |
dbd2e0b8c5cf47f6e29c804ffba824c48af7d443 | vprusso/toqito | /toqito/states/chessboard.py | 3,195 | 3.546875 | 4 | """Chessboard state."""
import numpy as np
def chessboard(mat_params: list[float], s_param: float = None, t_param: float = None) -> np.ndarray:
r"""
Produce a chessboard state [BP00]_.
Generates the chessboard state defined in [BP00]_. Note that, for certain choices of
:code:`s_param` and :code:`t_param`, this state will not have positive partial transpose, and
thus may not be bound entangled.
Examples
==========
The standard chessboard state can be invoked using :code:`toqito` as
>>> from toqito.states import chessboard
>>> chessboard([1, 2, 3, 4, 5, 6], 7, 8)
[[ 0.22592593, 0. , 0.12962963, 0. , 0. ,
0. , 0.17777778, 0. , 0. ],
[ 0. , 0.01851852, 0. , 0. , 0. ,
0.01111111, 0. , 0.02962963, 0. ],
[ 0.12962963, 0. , 0.18148148, 0. , 0.15555556,
0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0.01851852, 0. ,
0.02222222, 0. , -0.01481481, 0. ],
[ 0. , 0. , 0.15555556, 0. , 0.22592593,
0. , -0.14814815, 0. , 0. ],
[ 0. , 0.01111111, 0. , 0.02222222, 0. ,
0.03333333, 0. , 0. , 0. ],
[ 0.17777778, 0. , 0. , 0. , -0.14814815,
0. , 0.23703704, 0. , 0. ],
[ 0. , 0.02962963, 0. , -0.01481481, 0. ,
0. , 0. , 0.05925926, 0. ],
[ 0. , 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. ]]
See Also
========
chessboard
References
==========
.. [BP00] Three qubits can be entangled in two inequivalent ways.
D. Bruss and A. Peres
Phys. Rev. A, 61:30301(R), 2000
arXiv: 991.1056
:param mat_params: Parameters of the chessboard state as defined in [BP00]_.
:param s_param: Default is :code:`np.conj(mat_params[2]) / np.conj(mat_params[5])`.
:param t_param: Default is :code:`t_param = mat_params[0] * mat_params[3] / mat_params[4]`.
:return: A chessboard state.
"""
if s_param is None:
s_param = np.conj(mat_params[2]) / np.conj(mat_params[5])
if t_param is None:
t_param = mat_params[0] * mat_params[3] / mat_params[4]
v_1 = np.array([[mat_params[4], 0, s_param, 0, mat_params[5], 0, 0, 0, 0]])
v_2 = np.array([[0, mat_params[0], 0, mat_params[1], 0, mat_params[2], 0, 0, 0]])
v_3 = np.array([[np.conj(mat_params[5]), 0, 0, 0, -np.conj(mat_params[4]), 0, t_param, 0, 0]])
v_4 = np.array(
[
[
0,
np.conj(mat_params[1]),
0,
-np.conj(mat_params[0]),
0,
0,
0,
mat_params[3],
0,
]
]
)
rho = v_1.conj().T * v_1 + v_2.conj().T * v_2 + v_3.conj().T * v_3 + v_4.conj().T * v_4
return rho / np.trace(rho)
|
9cda78d105193a8a51cb4a869c41dfd69108342c | kvntma/coding-practice | /codecadamy/Towers_of_Hanoi/tower_of_hanoi.py | 3,014 | 4.09375 | 4 | from stack import Stack
print("\nLet's play Towers of Hanoi!!")
# Create the Stacks - Global Scope, can be changed to reduce pollution if needed.
left_stack, middle_stack, right_stack = Stack(
"Left"), Stack("Middle"), Stack("Right")
stacks = [left_stack, middle_stack, right_stack]
# Set up the Game
def initializeDisk(num_disks):
for disk in range(num_disks, 0, -1):
left_stack.push(disk)
return left_stack
# Get User Input
def userInput(num_disks):
if num_disks < 3:
return errorValue()
return 0
def getInput():
choices = [stack.get_name()[0].lower() for stack in stacks]
while True:
for i in range(len(stacks)):
name = stacks[i].get_name()
letter = choices[i]
print("Enter {0} for {1}".format(letter.upper(), name))
user_input = input("").lower()
if user_input in choices:
for i in range(len(stacks)):
if user_input == choices[i]:
return stacks[i]
# Play the Game
def playGame(stacks, num_disks):
num_users_moves = 0
def showStacks(stacks):
print("\n\n...Current Stacks...")
for stack in stacks:
stack.print_items()
return stacks
while right_stack.get_size() != num_disks:
print("Moves so far: {0}".format(num_users_moves))
showStacks(stacks)
while True:
print("\nWhich stack do you want to move from?\n")
from_stack = getInput()
if from_stack.get_size() == 0:
print("\nInvalid Move.. Please enter a valid move.")
showStacks(stacks)
continue
print("\nWhich stack do you want to move to?\n")
to_stack = getInput()
if to_stack.get_size() == 0 or from_stack.peek() < to_stack.peek():
disk = from_stack.pop()
to_stack.push(disk)
num_users_moves += 1
break
else:
print("\nInvalid Move.. please enter a valid move.")
showStacks(stacks)
return num_users_moves
# Helper Functions
def errorValue():
print("Enter a number greater than or equal to 3.\n")
return 1
# main calls
def main():
while True:
try:
num_disks = int(
input("\nHow many disks do you want to play with?\n"))
except ValueError:
errorValue()
continue
if userInput(num_disks) == 1:
continue
num_optimal_moves = (2 ** num_disks) - 1
initializeDisk(num_disks)
print("By the way, the fastest you can solve this problem is in {0} moves.".format(
num_optimal_moves))
num_user_moves = playGame(stacks, num_disks)
print("\nCongratulations! You completed the game in {0} amount of moves and the optimal amount is {1}.".format(
num_user_moves, num_optimal_moves))
break
if __name__ == '__main__':
main()
|
15970afc8a6f0b21b16231d145e6470cd3e43b8a | Peett2/infoshare | /day_12/test_example.py | 698 | 3.90625 | 4 | from unittest import TestCase
from day_12.example import super_sum
class TestExample(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_sum_one_plus_two_equals_three(self):
# given
a = 1
b = 2
expected = 3
result = super_sum(a, b)
self.assertEqual(result, expected)
def test_sum_raises_valueerr_for_int_and_str(self):
a = 'abc'
b = 3
with self.assertRaises(TypeError):
super_sum(a, b)
def test_sum_adds_any_number_of_numbers(self):
data = [1, 2, 3]
expected = 6
result = super_sum(*data)
self.assertEqual(result, expected)
|
a734780940b6f24974b40623a325a0a2860eda36 | AdventurousDream/Top-100-Liked-Questions-by-python | /45 Jump Game II.py | 879 | 3.5 | 4 | from typing import List
class Solution:
def jump(self, nums: List[int]) -> int:
arr_len = len(nums)
if arr_len == 1:
return 0
ans = 0
curIdx = 0
maxPos = -1
nextIdx = -1
while True:
if curIdx + nums[curIdx] >= arr_len - 1:
return ans+1
curMaxPos = -1
for step in range(1,nums[curIdx]+1):
j = curIdx + step
if j >= arr_len:
break
if nums[j] + j > curMaxPos:
curMaxPos = nums[j] + j
nextIdx = j
curIdx = nextIdx
ans += 1
if curIdx >= arr_len - 1:
return ans
if __name__ == '__main__':
solveObj = Solution()
print(solveObj.jump([2,3,1,2,4,2,3])) |
e10a24ac8ed8a646dca9ac5587afc7c6ef3f686a | Gorsitho/PythonDocumentation | /Practica/P_01_ListasTuplasDiccionarios.py | 2,728 | 4.375 | 4 |
"""Listas
-Se pueden utilizar los operadores matematicos en ella
-Se pueden agregar, eliminar, mirar cualquier objeto.
-Admite cualquier tipo de valor en ellas.
"""
listaMascotas=[ "Pelusa","Mechis","Lulu",True,False,5.4,2 ]*2
listaMascotas.append("Juanchito") #Agrega un nuevo objeto al final de la lista.
listaMascotas.insert(2,"Tomas") #Agrega el objeto en la posicion deseada.
listaMascotas.extend(["lalala,lolololo"]) # Se extiende la lista con nuevos objetos.
listaMascotas.remove("Mechis") #Remueve el objeto de la lista.
listaMascotas.pop() #Elimina el ultimo objeto de la lista.
print(listaMascotas.index("Tomas")) #Nos da el indice del objeto en la lista.
print(listaMascotas[:]) #Imprime todo el objeto lista.
print(listaMascotas[1:3]) #Imprime entre los rangos de indice 1 y 3.
print(listaMascotas[2]) #Imprime el objeto del indice 2
print(listaMascotas[-2]) #Muestra el segundo objeto de izquierda a derecha, sin empezar desde 0.
print("Daniel" in listaMascotas) #Comrpueba si el objeto esta en la lista
""" LAS TUPLAS
- Son inmutables, es decir que no cambian durante la ejecuacion.
- Si permite extraer una porcion de la tupla, sin embargo, crea una nueva tupla.
- Si permite comprobar un objeto.
- Mas rapidas.
-Menor espacio.
- Pueden utilizarse como claves en un diccionario.
- nombreTupla=(n1,n2,n3) <- los parentesis son opcionales.
"""
miTupla=("Daniel","Natalia")
milista=list(miTupla) # Convierta la tupla en lista. tuple(milista) <- de lista a tupla.
novio,novia=miTupla#Desempaquetado de Tuplas.Similar a clave,valor.
print(novio) # Imprime el valor de la variable.
print(novia)
print(miTupla.count("Daniel")) #Cuantas veces aparece ese objeto.
print(len(miTupla)) # Length en Python
"""Diccionarios
- Estructura de datos.
- Se asocian clave:valor.
- No estan ordenados.
- No pueden existir dos claves con el mismo nombre, se remplezan siendo asi.
"""
# Los diccionarios pueden tener diccionarios,tuplas, listas, etc. Dentro de ellos.
midiccionario={"Colombia":"Bogota","Mexico":"CDMexico","One piece":("Luffy","Zoro","Nami")}
midiccionario["España"]="Madrid" # Se agrega el objeto si no existe, si no, lo remplaza.
del midiccionario["Mexico"] # Elimina ese indice.
#diccionarioTupla={miTupla(0):"jeje",miTupla(1):"jojojo"}
#print(diccionarioTupla)
print(midiccionario.keys()) # Todas las claves del diccionario
print(midiccionario.values()) # Todas los valores del diccionario
print(midiccionario)
print(midiccionario["Colombia"]) # Muestra el valor de la clave Colombia
"""------------Despedida ----------------"""
mensajeDespedida=input("Escribe un mensaje de despedida")
|
54ae5cef6dfec7dccc04cadcf204b215c5b8ea2d | bd52622020/appSpaceDanish | /Task 1 -Python coding challenges/Q2 - pascals triangle.py | 374 | 3.890625 | 4 | #!/usr/bin/env python
def pastriangle(num = 5):
for i in range(1, num+1):
for j in range(1, num-i+1):
print(" ", end="")
for j in range(i,0,-1):
print(j, end="")
for j in range(2,i+1):
print(j,end="")
print()
if __name__ == "__main__":
x = input("Enter number of rows: ")
pastriangle(x)
|
88f1e0a8076352f71af684260fcaa18f41e85ada | apoorvasindhuja/sindhuja473 | /naveen.py | 80 | 3.9375 | 4 | x=input("enter string")
if x[-1]==x[-2]:
print(x+x[-1])
else:
print(x)
|
680008d15a0e4bb1f4c2cbc6502fd270b413ed6b | hunterkun/leetcode | /数据结构与算法/数据结构/链表.py | 16,207 | 3.90625 | 4 | #coding=utf8
class Node:
def __init__(self,e, node_next=None):
self.e = e
self.next = node_next
class LinkedList():
def __init__(self):
# 虚拟头节点,(头节点的前一个节点)
self.dummyHead = Node(None, None)
self.size = 0
def getSize(self):
return self.size
def isEmpty(self):
return self.size == 0
# 在索引处插入元素e
def add(self, index, e):
count = 0
prev = self.dummyHead
while count < index:
prev = prev.next
count += 1
# node = Node(e)
# node.next = prev.next
# prev.next = node
prev.next = Node(e, prev.next)
self.size += 1
# 在链表头插入元素
def addFirst(self, e):
# 不用虚拟头节点,单独处理头节点
# node = Node(e)
# node.next = head
# head = node
# self.head = Node(e, self.head)
# self.size += 1
self.add(0, e)
def addLast(self, e):
self.add(self.size, e)
def travel(self):
cur = self.dummyHead
for i in range(self.size):
print(cur.next.e, end='->')
cur = cur.next
print('NULL')
def getter(self, index):
cur=self.dummyHead.next
for _ in range(index):
cur = cur.next
return cur.e
def getFirst(self):
return self.getter(0)
def getLast(self):
return self.getter(self.size-1)
def setter(self, index, e):
cur=self.dummyHead.next
for _ in range(index):
cur = cur.next
cur.e = e
def contains(self, e):
cur = self.dummyHead.next
while cur is not None:
if cur.e == e:
return True
cur = cur.next
return False
def remove(self, index):
prev = self.dummyHead
for i in range(index):
prev = prev.next
node = prev.next
prev.next = node.next
node.next = None
self.size -= 1
return node.e
def removeFirst(self):
return self.remove(0)
def removeLast(self):
return self.remove(self.size - 1)
# 栈顶就是链表头节点
class Stack:
def __init__(self):
self._list = LinkedList()
def getSize(self):
return self._list.getSize()
def isEmpty(self):
return self._list.isEmpty()
def push(self,e):
self._list.addFirst(e)
def pop(self):
return self._list.removeFirst()
def peek(self):
return self._list.getFirst()
def travel(self):
print("Stack: top",end=' ')
self._list.travel()
# 链表实现队列
# 使用头指针作为队首负责删除元素,尾指针作为队尾负责插入元素
class Queue:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def getSize(self):
return self.size
def isEmpty(self):
return self.size == 0
def enqueue(self, e):
if self.tail:
self.tail.next = Node(e)
self.tail = self.tail.next
else:
self.head = Node(e)
self.tail = self.head
self.size += 1
def dequeue(self):
retNode = self.head
self.head = self.head.next
if not self.head:
self.tail = None
self.size -= 1
retNode.next = None
return retNode.e
def getFront(self):
if not self.isEmpty():
return self.head.e
def travel(self):
print("Queue: front",end=' ')
cur = self.head
while cur:
print(cur.e, end='->')
cur = cur.next
print("NULL tail")
###################################################
#LeetCode专题#
###################################################
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
'''
203. Remove all elements from a linked list of integers
that have value val.
'''
def removeElements(head: ListNode, val: int):
# 头节点单独处理,因为没有prev
while (head is not None and head.val == val):
node = head
head = head.next
node.next = None
if (head is None):
return None
prev=head
while (prev.next is not None):
if (prev.next.val == val):
node = prev.next
prev.next = node.next
node.next = None
else:
prev = prev.next
return head
# 使用虚拟头节点
def removeElements2(self, head: ListNode, val: int) -> ListNode:
dummyHead = ListNode(-1)
dummyHead.next=head
prev = dummyHead
while (prev.next is not None):
if (prev.next.val == val):
node = prev.next
prev.next = node.next
node.next = None
else:
prev = prev.next
return head
# 使用递归求解
def removeElements3(self, head, val):
if head is None:
return None
head.next = self.removeElements3(head.next, val)
return head.next if head.val==val else head
'''
206.反转链表
'''
# 经分析可知需要三个指针prev, cur, next
def reverseList(head: ListNode) -> ListNode:
prev = None
cur = head
# nex = head.next
while (cur):
nex = cur.next
cur.next = prev
prev = cur
cur = nex
return prev
# 递归法
def reverseList2(head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
rhead = reverseList2(head.next)
head.next.next = head
head.next = None
return rhead
'''
92. 反转链表II
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明: 1 ≤ m ≤ n ≤ 链表长度。
'''
def reverseBetween(head: ListNode, m: int, n: int) -> ListNode:
prev = None
cur = head
for _ in range(m - 1):
prev = cur
cur = cur.next
node1 = prev
node2 = cur
prev = cur
cur = cur.next
for _ in range(n - m):
nex = cur.next
cur.next = prev
prev = cur
cur = nex
if node1:
node1.next = prev
if node2:
node2.next = cur
return head if node1 else prev
def reverseBetween2(head: ListNode, m: int, n: int) -> ListNode:
dummyHead = ListNode(-1)
dummyHead.next=head
prev = dummyHead
for _ in range(m - 1):
prev = prev.next
tail = prev.next
prev.next = reverse(prev.next, n - m)
tail.next = left
ret = dummyHead.next
del dummyHead
return ret
def reverse(head, index):
if index == 0:
global left
left = head.next
return head
ret = reverse(head.next, index - 1)
head.next.next = head
return ret
def reverseBetween2(head: ListNode, m: int, n: int) -> ListNode:
dummyHead = ListNode(-1)
dummyHead.next=head
prev = dummyHead
for _ in range(m - 1):
prev = prev.next
tail = prev.next
left = tail
prev.next = reverse2(prev.next, n - m)
if (tail != left):
tail.next = left
ret = dummyHead.next
del dummyHead
return ret
def reverse2(head, index):
global left
if (head is None or head.next is None or index==0):
return head
prev = head
cur = head.next
while (index):
nex = cur.next
cur.next = prev
prev = cur
cur = nex
index -= 1
left = cur
return prev
'''
82. Remove Duplicates from Sorted ListII
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中
没有重复出现的数字。
'''
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummyHead = ListNode(-1)
dummyHead.next = head
prev = dummyHead
cur = head
while (cur):
num = 0
p = cur
while (p and p.val == cur.val):
num += 1
p = p.next
if (num > 1):
prev.next = p
else:
prev = cur
cur = p
return dummyHead.next
'''
83. Remove Duplicates from Sorted List
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次
'''
def deleteDuplicates2(self, head):
cur = head
while (cur):
num = 0
p = cur
while (p and p.val == cur.val):
num += 1
p = p.next
if (num > 1):
cur.next = p
cur = p
return head
'''
86. Partition List
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x
的节点之前。
'''
def partition(self, head: ListNode, x: int) -> ListNode:
dummyHead1 = ListNode(-1)
dummyHead2 = ListNode(-1)
cur = head
p1 = dummyHead1
p2 = dummyHead2
while (cur):
if (cur.val < x):
p1.next = cur
cur = cur.next
p1 = p1.next
else:
p2.next = cur
cur = cur.next
p2 = p2.next
p2.next = None
p1.next = dummyHead2.next
ret = dummyHead1.next
return ret
'''
328. Odd Even Linked List
'''
def oddEvenList(head):
if head is None or head.next is None or head.next.next is None:
return head
dummyHead1 = ListNode(-1)
dummyHead2 = ListNode(-2)
p1 = dummyHead1
p2 = dummyHead2
p = head
i = 0
while p:
if i % 2==0:
p1.next = p
p = p.next
p1 = p1.next
else:
p2.next = p
p = p.next
p2 = p2.next
i += 1
p1.next = None
p2.next = None
p1.next = dummyHead2.next
ret = dummyHead1.next
del dummyHead1
del dummyHead2
return ret
'''
一个链表,奇数位升序,偶数位降序,让链表变成升序的
'''
def merge2(a, b):
dummyHead = ListNode(-1)
p1 = a
p2 = b
p = dummyHead
while (p1 and p2):
if (p1.val < p2.val):
p.next = p1
p1 = p1.next
p = p.next
p.next = None
else:
p.next = p2
p2 = p2.next
p = p.next
p.next = None
if p1:
p.next = p1
if p2:
p.next = p2
ret = dummyHead.next
del dummyHead
return ret
def splitOddEven(head):
if head is None or head.next is None or head.next.next is None:
return head
dummyHead1 = ListNode(-1)
dummyHead2 = ListNode(-2)
p1 = dummyHead1
p2 = dummyHead2
p = head
i = 0
while p:
if i % 2==0:
p1.next = p
p = p.next
p1 = p1.next
else:
p2.next = p
p = p.next
p2 = p2.next
i += 1
p1.next = None
p2.next = None
return dummyHead1.next, dummyHead2.next
def reverseList3(head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
rhead = reverseList3(head.next)
head.next.next = head
head.next = None
return rhead
def OddIncreaseEvenDecrease(head):
head1,head2 = splitOddEven(head)
head2 = reverse3(head2)
head = merge(head1, head2)
return head
'''
Given a singly linked list, determine if it is a palindrome.
'''
def isPalindrome(head):
if (head is None or head.next is None):
return True
slow, fast = head, head
while (fast.next and fast.next.next):
slow = slow.next
fast = fast.next.next
slow = reverse3(slow.next)
cur = head
while (slow):
if cur.val != slow.val:
return False
else:
slow = slow.next
cur = cur.next
return True
def reverse3(head):
if head is None or head.next is None:
return head
prev = None
cur = head
while (cur):
nex = cur.next
cur.next = prev
prev = cur
cur = nex
return prev
'''
141. Given a linked list, determine if it has a cycle in it. To represent a
cycle in the given linked list, we use an integer pos which represents the
position (0 - indexed) in the linked list where tail connects to. If pos
is - 1, then there is no cycle in the linked list.
'''
#就是检测有没有重复值
def hasCycle(head):
if head is None:
return False
table = set()
cur = head
while cur:
if cur in table:
return True
else:
table.append(cur)
cur = cur.next
return False
'''
142. Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which
represents the position (0-indexed) in the linked list where tail connects to.
If pos is -1, then there is no cycle in the linked list. Note: Do not modify the linked list.
'''
def detectCycle(head):
if head is None:
return None
records = set()
cur = head
while cur:
if cur in table:
return cur
else:
records.add(cur)
cur = cur.next
return None
'''
Sort List
'''
# 归并排序
def sortList(head):
if head is None or head.next is None:
return head
slow = head
fast = head
while (fast.next and fast.next.next):
slow = slow.next
fast = fast.next.next
head2 = slow.next
slow.next = None
head=sortList(head)
head2=sortList(head2)
return merge(head, head2)
def merge(a, b):
dummyHead = ListNode(-1)
p1 = a
p2 = b
p = dummyHead
while (p1 and p2):
if (p1.val < p2.val):
p.next = p1
p1 = p1.next
p = p.next
p.next = None
else:
p.next = p2
p2 = p2.next
p = p.next
p.next = None
if p1:
p.next = p1
if p2:
p.next = p2
ret = dummyHead.next
del dummyHead
return ret
def creatLinkedList(arr) -> ListNode:
n = len(arr)
if n == 0:
return None
dummyHead = ListNode(-1)
prev = dummyHead
for i in range(n):
node = ListNode(arr[i])
prev.next = node
prev = prev.next
return dummyHead.next
def printLinkedList(head):
cur = head
while cur:
print(cur.val, end=' -> ')
cur = cur.next
print("NULL")
return
def deleteLinkedList(head):
cur = head
while cur:
delNode = cur
cur = cur.next
del delNode
# 对链表进行测试
if __name__=="__main__":
# l = Stack()
# for i in range(5):
# l.push(i)
# l.travel()
# l.pop()
# l.travel()
# l.add(2, 666)
# l.travel()
# l.remove(2)
# l.travel()
# l.removeFirst()
# l.travel()
# l.removeLast()
# l.travel()
# q = Queue()
# for i in range(10):
# q.enqueue(i)
# q.travel()
# if (i % 3 == 2):
# q.dequeue()
# q.travel()
# 根据数组创建链表进行测试
arr = [1,8,3,6,5,4,7,2,9]
head = creatLinkedList(arr)
# printLinkedList(head)
ret=OddIncreaseEvenDecrease(head)
printLinkedList(ret)
# print(isPalindrome(head))
# rhead = reverseBetween2(head,2,4)
# rethead= reverseList2(head)
# printLinkedList(rhead)
|
3876ad8420b7a719f9b96ed54a1d9f421eac62d6 | kses1010/algorithm | /nadongbin/chapter07-binarySearch/chapter15-binarySearch-solution/find_fixed_point.py | 453 | 3.6875 | 4 | # 고정점 찾기
def solution(arr):
start, end = 0, len(arr) - 1
while start <= end:
mid = (start + end) // 2
if arr[mid] == mid:
return mid
elif arr[mid] < mid:
start = mid + 1
else:
end = mid - 1
return -1
arr1 = [-15, -6, 1, 3, 7]
arr2 = [-15, -4, 2, 8, 9, 13, 15]
arr3 = [-15, -4, 3, 8, 9, 13, 15]
print(solution(arr1))
print(solution(arr2))
print(solution(arr3))
|
e18cc65f83326c5f592047646d3752eb2a362597 | zimingding/data_structure | /10_array_stack.py | 932 | 3.84375 | 4 | class ListStack:
def __init__(self):
self._data = []
def pop(self):
return self._data.pop(-1)
def push(self, item):
self._data.append(item)
def print(self):
print(self._data)
class ArrayStack:
def __init__(self, capacity: int):
self._capacity = capacity
self._size = 0
self._data = [None] * capacity
def push(self, item) -> bool:
if self._size == self._capacity:
return False
self._data[self._size] = item
self._size += 1
return True
def pop(self):
if self._size == 0:
return None
val = self._data[self._size-1]
self._size -= 1
return val
def print(self):
print('current size: ' + str(self._size))
print(self._data)
stack = ArrayStack(5)
stack.push('bob')
stack.push('alice')
stack.push('daniel')
stack.print()
print(stack.pop())
|
e71343ab011d7d2e49fd588b198f4b3ee8c8d098 | ziqizhang/msm4phi | /code/python/src/util/produce_feature_files.py | 2,067 | 3.546875 | 4 | # Used to produce a new file with selected features
# feature_columns needs to be changed accordingly
# first argument is the name of the file with features
import sys
import pandas as pd
feature_file = sys.argv[1]
# read annotated data file
# Read the file with annotated data
annotated_df = pd.read_csv("merged_output.csv")
# feature columns
feature_columns = ['user_statuses_count', 'user_friends_count',
'user_favorites_count','user_retweeted_count',
'user_retweet_count', 'user_followers_count',
'user_listed_count', 'user_newtweet_count', 'user_favorited_count',
'user_entities_hashtag', 'user_entities_url',
'user_entities_user_mention', 'user_entities_media_url']
col_names = ['twitter_id'] + feature_columns
# read features file
features_df = pd.read_csv(feature_file)
# select required features
features_df = features_df[col_names]
col_names = col_names + ['label']
output_df = pd.DataFrame(columns = col_names)
# iterate through the annotate users
for row in range(len(annotated_df)):
label_value = annotated_df.label[row]
if label_value == "" :
label_value = "Other"
print("empty")
current_id = annotated_df.twitter_id[row]
features = pd.DataFrame(columns = col_names)
#print("columns are: " + str(list(features.columns.values)))
#features['twitter_id'] = current_id
#features['label'] = label_value
# get row from features with this twitter id
feature_row = features_df.loc[features_df['twitter_id'] == current_id]
features[feature_columns] = feature_row[feature_columns]
# add the feature vector into the new file
output_df.loc[row] = features.iloc[0]
output_df.twitter_id[row] = current_id
output_df.label[row] = label_value
# add the label
#output_df.label[row] = label
#output_df = pd.to_numeric(output_df[feature_columns], errors='coerce')
output_df[feature_columns] = output_df[feature_columns].apply(pd.to_numeric)
output_df = output_df.fillna("Other")
output_df.to_csv("output_features.csv", index = False) |
86fd8bd90a7461362881a18fa1ae7eb8120e8d12 | pedrogomez2019upb/Taller_PracticaProgramacion | /44.py | 496 | 3.921875 | 4 | #Escribe un algoritmo que, dados dos números, verifique si ambos están entre 0 y 5 o retorne false sino es cierto. Por ejemplo 1 y 2 ---> true ; 1 y 8 ---> false
#Primero hay que recibir los valores a analizar
a=int(input("Bienvenido! Por favor ingresa el primer número: "))
b=int(input("Por favor ingresa el segundo valor: "))
#Ponemos condicionales para analizar los valores
if (a<5 and a>0)and(b<5 and b>0):
print("True")
else:
print("False")
#Desarrollado por Pedro Gómez / ID:000396221 |
ad774a79994021d2ffd2ff0865ced5c4459203d1 | Kaiquenakao/Python | /Variáveis e Tipos de Dados em Python/Exercicio3.py | 326 | 3.9375 | 4 | """
3 - Peça ao usuário para digitar três valores inteiros e imprima soma deles
"""
num1 = int(input("Insira o seu primeiro valor para somar:"))
num2 = int(input("Insira o seu segundo valor para somar"))
num3 = int(input("Insira o seu terceiro valor para somar"))
print(f"O resultado da soma é {num1 + num2 + num3}") |
85a71bddeefa23891a8ca8c083057875d28eba05 | crispinpigla/Mcgyver | /mcgyver/objramasse.py | 923 | 3.734375 | 4 | """ La classe des objets à ramasser est créee dans ce fichier """
import random
class ObjetRamasse:
""" Cette classe est celle des objets que le heros doit ramasser pour endormir le gardien """
def __init__(self, plateau, nom_de_lobjet):
random.shuffle(plateau.place_potenti_objet_ramass)
self._position = plateau.place_potenti_objet_ramass[-1]
plateau.place_potenti_objet_ramass.pop()
self._nom_objet = nom_de_lobjet
def ramassage(self):
""" Enlève l'objet ramassé du plateau """
self._position = (-1, -1)
# setters
@property
def position(self):
return self._position
@property
def nom_objet(self):
return self._nom_objet
# getters
@position.setter
def position(self, valeur):
self._position = valeur
@nom_objet.setter
def nom_objet(self, valeur):
self._nom_objet = valeur
|
9127af71c0ee9dfadbf63b8a7c5934bbaed407d8 | gabriellaec/desoft-analise-exercicios | /backup/user_158/ch164_2020_06_22_03_29_20_149516.py | 193 | 3.59375 | 4 | def traduz(lista,dic):
traducao = []
for i in lista:
for palavara in dic:
if lista[i] == palavara:
traducao.append(dic[palavara])
return traducao |
475d97304e797b85c141fe8c18519b3acd3f8a11 | garimatuli/Udacity-Coding-and-Projects | /Python-Programs/polygons.py | 446 | 4.0625 | 4 | import turtle
jack = turtle.Turtle()
jack.color("yellow")
def draw_polygon(length, color, sides):
for side in range(sides):
jack.color(color)
jack.forward(length)
jack.right(360 / sides)
jack.penup()
jack.backward(100)
jack.pendown()
draw_polygon(120, "cyan", 8)
draw_polygon(100, "magenta", 7)
draw_polygon(80, "yellow", 6)
draw_polygon(60, "orange", 5)
draw_polygon(50, "pink", 4)
draw_polygon(30, "green", 3)
|
02eaa88c970d3bbe9af9a8526ff8cd894ca10268 | countone/exercism-python | /triangle.py | 617 | 3.78125 | 4 | def is_equilateral(sides):
if is_valid(sides):
return len(set(sides))==1
else:
return is_valid(sides)
def is_isosceles(sides):
if is_valid(sides):
return len(set(sides))<=2
else:
return is_valid(sides)
def is_scalene(sides):
if is_valid(sides):
return len(set(sides))==3
else:
return is_valid(sides)
def is_valid(sides):
if len(sides)==3:
if sides[0]+sides[1]<=sides[2]:
is_valid=False
elif sides[0]+sides[2]<=sides[1]:
is_valid=False
elif sides[1]+sides[2]<=sides[0]:
is_valid=False
else:
is_valid=True
return is_valid |
bfcab6e46db9462479f113e66c96ab2509d05912 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2310/60636/245056.py | 801 | 3.609375 | 4 | n_root=input().split(" ")
n=int(n_root[0])
root=int(n_root[1])
lists=[]
for i in range(pow(2,n)):
lists.append("*")
sources=[]
try:
while(True):
x=input().split(" ")
source=[]
source.append(int(x[0]))
source.append(int(x[1]))
source.append(int(x[2]))
sources.append(source)
except(EOFError):
pass
print(sources)
lists[0]=sources[0][0]
for i in sources:
for a in range(len(lists)):
if(lists[a]==i[0]):
if(i[1]!=0):
lists[2*a+1]=i[1]
if(i[2]!=0):
lists[2*a+2]=i[2]
print(lists)
|
7fdb758e37942cd07910b7b798cfa495c43a6102 | jimmyodonnell/banzai | /scripts/dereplication/derep_fasta.py | 4,671 | 3.71875 | 4 | #!/usr/bin/env python
'''
Authors: Walter Sessions, Jimmy O'Donnell
Find and remove duplicate DNA sequences from a fasta file
usage: python ./this_script.py infile.fasta 'ID1_' derep.fasta derep.map
'''
import os
from collections import Counter
import fileinput
import itertools
import argparse
import hashlib
parser = argparse.ArgumentParser(
description = 'Remove and count duplicate sequences in a fasta file',
)
parser.add_argument('-i', '--fasta_in',
help = 'File path for input file. Must be a fasta file with *no* wrapped lines!',
required = True)
parser.add_argument('-s', '--sample_prefix',
help = 'First part of string identifying samples (e.g. "ID1=").',
required = True)
parser.add_argument('-f', '--fasta_out',
help = 'File path for output fasta.',
required = True)
parser.add_argument('-m', '--mapfile',
help = 'File path for output mapfile.',
required = True)
parser.add_argument('-H', '--hash',
help = 'Use hash output (SHA1) of sequence to name sequences?',
choices = ["YES", "NO"],
default = "NO",
required = False)
args = vars(parser.parse_args())
infile = args['fasta_in']
sample_id_start = args['sample_prefix']
outfasta = args['fasta_out']
outmap = args['mapfile']
hash_arg = args['hash']
#############################################################################_80
#_main_#########################################################################
################################################################################
def run_main(fname, sampleID, out_f, out_m, hash_id):
#_open input file
f = fileinput.input(fname)
list_id = []
dict_uniqseq = {}
# sample_pattern = re.compile(samplestringID + "(.*)", re.flags)
#_loop over two lines of input
for line0, line1 in itertools.izip_longest(f,f):
seq_id = line0.replace('\n','').replace('>','')#_don't .strip()
sample_id = sampleID + '{0:s}'.format(seq_id.split(sampleID)[1])
dna_str = line1.strip()
#_build list of unique ids
idx_id = len(list_id) #_get current id index
list_id.append(sample_id) # seq_id
#_build dictionary of
if dna_str in dict_uniqseq:
dict_uniqseq[dna_str].append(idx_id)
else:
dict_uniqseq[dna_str] = [idx_id]
keys_by_length = sorted(dict_uniqseq,
key=lambda k: len(dict_uniqseq[k]), reverse = True)
if hash_id == 'YES':
write_fasta_hash(dict_uniqseq, keys_by_length, out_f)
write_map_hash(list_id, dict_uniqseq, keys_by_length, out_m)
else:
write_fasta(dict_uniqseq, keys_by_length, out_f)
write_map(list_id, dict_uniqseq, keys_by_length, out_m)
#_close input
f.close()
#############################################################################_80
#_end_main_#####################################################################
################################################################################
def write_fasta(dna_dict, sorted_keys, fasta_output = 'fasta_output.file'):
''' write fasta file of unique sequences '''
with open(fasta_output, 'w') as f:
for index, key in enumerate(sorted_keys):
f.write('>DUP_{0:n}'.format(index+1) +
';size={0:n}\n'.format(len(dna_dict[key])) +
'{0:s}\n'.format(key))
def write_fasta_hash(dna_dict, sorted_keys, fasta_output = 'fasta_output.file'):
''' write fasta file of unique sequences using hash as sequence id'''
with open(fasta_output, 'w') as f:
for index, key in enumerate(sorted_keys):
f.write('>SHA1={0:s}'.format(hashlib.sha1(key).hexdigest()) +
';size={0:n}\n'.format(len(dna_dict[key])) +
'{0:s}\n'.format(key))
def write_map(id_list, dna_dict, sorted_keys, map_output = 'map_output.file'):
'''write two column file of sequence name from input and sequence name in output'''
with open(map_output, 'w') as f:
for index, key in enumerate(sorted_keys):
count_per_sample = Counter([id_list[i] for i in dna_dict[key]]).most_common()
f.write('\n'.join([
'DUP_{0:n}'.format(index+1) + '\t' +
'{0:s}'.format(k) + '\t' +
'{0:n}'.format(v)
for k, v in count_per_sample]) + '\n')
def write_map_hash(id_list, dna_dict, sorted_keys, map_output = 'map_output.file'):
'''write two column file of sequence name from input and sequence name in output'''
with open(map_output, 'w') as f:
for index, key in enumerate(sorted_keys):
count_per_sample = Counter([id_list[i] for i in dna_dict[key]]).most_common()
f.write('\n'.join([
'SHA1={0:s}'.format(hashlib.sha1(key).hexdigest()) + '\t' +
'{0:s}'.format(k) + '\t' +
'{0:n}'.format(v)
for k, v in count_per_sample]) + '\n')
if __name__ == '__main__':
run_main(fname = infile, sampleID = sample_id_start, out_f = outfasta, out_m = outmap, hash_id = hash_arg)
|
64db558fc4c1a0236e424570c07b20cebe707325 | luohuaizhi/test | /kwargs.py | 538 | 3.546875 | 4 |
def test(a, b, c, d):
print a, b, c, d
return "->".join([str(a), str(b), str(c), str(d)])
def test1(a, b, c, d):
print a, b, c, d
return "->".join([str(a), str(b), str(c), str(d)])
def test2(*args, **kwargs):
print "args: " + str(args)
print "kwargs: " + str(kwargs)
def main():
param = [1,2,3,4]
param1 = {
"a":1,
"b":2,
"c":3,
"d":4,
}
print test(*param)
print test1(**param1)
print test2(*param, **param1)
if __name__ == '__main__':
main() |
9acc2846f4270a634ea8417e96c79b4b9e97a8fd | qmnguyenw/python_py4e | /geeksforgeeks/algorithm/medium_algo/9_6.py | 9,041 | 3.90625 | 4 | Iterative Letter Combinations of a Phone Number
Given an integer array containing digits from **[0, 9]** , the task is to
print all possible letter combinations that the numbers could represent.
A mapping of digit to letters (just like on the telephone buttons) is being
followed. **Note** that **0** and **1** do not map to any letters. All the
mapping are shown in the image below:

**Example:**
> **Input:** arr[] = {2, 3}
> **Output:** ad ae af bd be bf cd ce cf
>
> **Input:** arr[] = {9}
> **Output:** w x y z
>
>
>
>
>
>
Recommended: Please try your approach on _**_{IDE}_**_ first, before moving on
to the solution.
**Approach:** Now let us think how we would approach this problem without
doing it in an iterative way. A recursive solution is intuitive and common. We
keep adding each possible letter recursively and this will generate all the
possible strings.
Let us think about how we can build an iterative solution using the recursive
one. Recursion is possible through the use of a stack. So if we use a stack
instead of a recursive function will that be an iterative solution? One could
say so speaking technically but we then aren’t really doing anything different
in terms of logic.
A Stack is a LIFO DS. Can we use another Data structure? What will be the
difference if we use a FIFO DS? Let’s say a queue. Since BFS is done by queue
and DFS by stack is there any difference between the two?
The difference between DFS and BFS is similar to this question. In DFS we will
find each path possible in the tree one by one. It will perform all steps for
a path first whereas BFS will build all paths together one step at a time.
So, a queue would work perfectly for this question. The only difference
between the two algorithms using queue and stack will be the way in which they
are formed. Stack will form all strings completely one by one whereas the
queue will form all the strings together i.e. after x number of passes all the
strings will have a length of x.
**For example:**
If the given number is "23",
then using **queue** , the letter combinations
obtained will be:
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
and using **stack** , the letter combinations obtained will
be:
["cf","ce","cd","bf","be","bd","af","ae","ad"].
Below is the implementation of the above approach:
## C++
__
__
__
__
__
__
__
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return a vector that contains
// all the generated letter combinations
vector<string> letterCombinationsUtil(const int number[],
int n,
const string table[])
{
// To store the generated letter combinations
vector<string> list;
queue<string> q;
q.push("");
while (!q.empty()) {
string s = q.front();
q.pop();
// If complete word is generated
// push it in the list
if (s.length() == n)
list.push_back(s);
else
// Try all possible letters for current digit
// in number[]
for (auto letter : table[number[s.length()]])
q.push(s + letter);
}
// Return the generated list
return list;
}
// Function that creates the mapping and
// calls letterCombinationsUtil
void letterCombinations(const int number[], int n)
{
// table[i] stores all characters that
// corresponds to ith digit in phone
string table[10]
= { "0", "1", "abc", "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> list
= letterCombinationsUtil(number, n, table);
// Print the contents of the vector
for (auto word : list)
cout << word << " ";
return;
}
// Driver code
int main()
{
int number[] = { 2, 3 };
int n = sizeof(number) / sizeof(number[0]);
// Function call
letterCombinations(number, n);
return 0;
}
---
__
__
## Java
__
__
__
__
__
__
__
// Java implementation of the approach
import java.io.*;
import java.util.*;
class GFG {
// Function to return a vector that contains
// all the generated letter combinations
static ArrayList<String>
letterCombinationsUtil(int[] number, int n,
String[] table)
{
// To store the generated letter combinations
ArrayList<String> list = new ArrayList<>();
Queue<String> q = new LinkedList<>();
q.add("");
while (!q.isEmpty()) {
String s = q.remove();
// If complete word is generated
// push it in the list
if (s.length() == n)
list.add(s);
else {
String val = table[number[s.length()]];
for (int i = 0; i < val.length(); i++)
{
q.add(s + val.charAt(i));
}
}
}
return list;
}
// Function that creates the mapping and
// calls letterCombinationsUtil
static void letterCombinations(int[] number, int n)
{
// table[i] stores all characters that
// corresponds to ith digit in phone
String[] table
= { "0", "1", "abc", "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz" };
ArrayList<String> list
= letterCombinationsUtil(number, n, table);
// Print the contents of the list
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
// Driver code
public static void main(String args[])
{
int[] number = { 2, 3 };
int n = number.length;
// Funciton call
letterCombinations(number, n);
}
}
// This code is contributed by rachana soma
---
__
__
## Python
__
__
__
__
__
__
__
# Python3 implementation of the approach
from collections import deque
# Function to return a list that contains
# all the generated letter combinations
def letterCombinationsUtil(number, n, table):
list = []
q = deque()
q.append("")
while len(q) != 0:
s = q.pop()
# If complete word is generated
# push it in the list
if len(s) == n:
list.append(s)
else:
# Try all possible letters for current digit
# in number[]
for letter in table[number[len(s)]]:
q.append(s + letter)
# Return the generated list
return list
# Function that creates the mapping and
# calls letterCombinationsUtil
def letterCombinations(number, n):
# table[i] stores all characters that
# corresponds to ith digit in phone
table = ["0", "1", "abc", "def", "ghi",
"jkl",
"mno", "pqrs", "tuv", "wxyz"]
list = letterCombinationsUtil(number, n, table)
s = ""
for word in list:
s += word + " "
print(s)
return
# Driver code
number = [2, 3]
n = len(number)
# Function call
letterCombinations(number, n)
---
__
__
## C#
__
__
__
__
__
__
__
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG {
// Function to return a vector that contains
// all the generated letter combinations
static List<String>
letterCombinationsUtil(int[] number, int n,
String[] table)
{
// To store the generated letter combinations
List<String> list = new List<String>();
Queue<String> q = new Queue<String>();
q.Enqueue("");
while (q.Count != 0) {
String s = q.Dequeue();
// If complete word is generated
// push it in the list
if (s.Length == n)
list.Add(s);
else {
String val = table[number[s.Length]];
for (int i = 0; i < val.Length; i++) {
q.Enqueue(s + val[i]);
}
}
}
return list;
}
// Function that creates the mapping and
// calls letterCombinationsUtil
static void letterCombinations(int[] number, int n)
{
// table[i] stores all characters that
// corresponds to ith digit in phone
String[] table
= { "0", "1", "abc", "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz" };
List<String> list
= letterCombinationsUtil(number, n, table);
// Print the contents of the list
for (int i = 0; i < list.Count; i++) {
Console.Write(list[i] + " ");
}
}
// Driver code
public static void Main(String[] args)
{
int[] number = { 2, 3 };
int n = number.Length;
// Function call
letterCombinations(number, n);
}
}
// This code is contributed by Princi Singh
---
__
__
**Output**
ad ae af bd be bf cd ce cf
Attention reader! Don’t stop learning now. Get hold of all the important DSA
concepts with the **DSA Self Paced Course** at a student-friendly price and
become industry ready. To complete your preparation from learning a language
to DS Algo and many more, please refer **Complete Interview Preparation
Course** **.**
My Personal Notes _arrow_drop_up_
Save
|
a4b22cfa66b445d1b6edab1b8a744c2b29a49d13 | avrudik/easy_it | /course_tasks/and/hmw_1/task_3.py | 379 | 3.96875 | 4 | def do_it(data, sub):
data = data[data.find(sub) + len(sub):]
return 1, data
input_str = input('Input some string: ')
sub_str = input('Input a sub-string: ')
answer = 0
while input_str and sub_str in input_str:
sum, input_str = do_it(input_str, sub_str)
answer += sum
else:
print('String is over or there is no sub-string in initial string.')
print(answer)
|
faa9043e9f9d5b99b7edcfd2b76bc9cd680ca4e7 | biswajit2506/python | /shop_check_print.py | 778 | 3.84375 | 4 | def search(s):
list=["apple","orange","kiwi"]
avl=[]
navl=[]
nval=0;
s=s.split(",")
#print(s)
#print(type(s))
for j in s:
nval=0;
for i in list:
if j==i:
#print(j," Avaiable in our Shop.")
avl.append(j)
break;
else:
nval=nval+1;
#print(nval)
if nval==len(list):
navl.append(j)
#print(j," Is not avaiable in our Shop.")
avl.insert(0,"Avaiavle List")
navl.insert(0,"Not Avaiavle List")#print(avl)
#print(navl)
return avl,navl
s=input("Enter the Fruits U Want to Search - ")
#print(search(s))
x,y=search(s)
print("---------",x[0],"--------")
for i in x:
if i!='Avaiavle List':
print(i)
print("---------",y[0],"--------")
for j in y:
if j!='Not Avaiavle List':
print(j)
|
d5d397472354e64350ffd6eb0ab2efe4e2e44e07 | xiaohuilangss/modeng_research | /test/tf_new_version_test/test1.py | 20,155 | 3.953125 | 4 | # encoding=utf-8
"""
测试最新版本TensorFlow
测试TensorFlow 2.3.0版本官网有关rnn的案例代码
"""
"""
## Setup
"""
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
if __name__ == '__main__':
"""
Title: Working with RNNs
Authors: Scott Zhu, Francois Chollet
Date created: 2019/07/08
Last modified: 2020/04/14
Description: Complete guide to using & customizing RNN layers.
"""
"""
## Built-in RNN layers: a simple example
"""
"""----------------------------------------------- 第一部分 -----------------------------------------------"""
model = keras.Sequential()
# 添加一层,输入维度1000, 输出维度64
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# 添加一个128单元的lstm层
model.add(layers.LSTM(128))
# Add a Dense layer with 10 units.
model.add(layers.Dense(10))
model.summary()
"""
Built-in RNNs support a number of useful features:
- Recurrent dropout, via the `dropout` and `recurrent_dropout` arguments
- Ability to process an input sequence in reverse, via the `go_backwards` argument
- Loop unrolling (which can lead to a large speedup when processing short sequences on
CPU), via the `unroll` argument
- ...and more.
For more information, see the
[RNN API documentation](https://keras.io/api/layers/recurrent_layers/).
"""
"""
## Outputs and states
By default, the output of a RNN layer contains a single vector per sample. This vector
is the RNN cell output corresponding to the last timestep, containing information
about the entire input sequence. The shape of this output is `(batch_size, units)`
where `units` corresponds to the `units` argument passed to the layer's constructor.
A RNN layer can also return the entire sequence of outputs for each sample (one vector
per timestep per sample), if you set `return_sequences=True`. The shape of this output
is `(batch_size, timesteps, units)`.
"""
"""----------------------------------------------- 第二部分 -----------------------------------------------"""
model = keras.Sequential()
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256)
model.add(layers.GRU(256, return_sequences=True))
# The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128)
model.add(layers.SimpleRNN(128))
model.add(layers.Dense(10))
model.summary()
"""
In addition, a RNN layer can return its final internal state(s). The returned states
can be used to resume the RNN execution later, or
[to initialize another RNN](https://arxiv.org/abs/1409.3215).
This setting is commonly used in the
encoder-decoder sequence-to-sequence model, where the encoder final state is used as
the initial state of the decoder.
To configure a RNN layer to return its internal state, set the `return_state` parameter
to `True` when creating the layer. Note that `LSTM` has 2 state tensors, but `GRU`
only has one.
To configure the initial state of the layer, just call the layer with additional
keyword argument `initial_state`.
Note that the shape of the state needs to match the unit size of the layer, like in the
example below.
"""
"""----------------------------------------------- 第三部分 -----------------------------------------------"""
encoder_vocab = 1000
decoder_vocab = 2000
encoder_input = layers.Input(shape=(None,))
encoder_embedded = layers.Embedding(input_dim=encoder_vocab, output_dim=64)(
encoder_input
)
# Return states in addition to output
output, state_h, state_c = layers.LSTM(64, return_state=True, name="encoder")(
encoder_embedded
)
encoder_state = [state_h, state_c]
decoder_input = layers.Input(shape=(None,))
decoder_embedded = layers.Embedding(input_dim=decoder_vocab, output_dim=64)(
decoder_input
)
# Pass the 2 states to a new LSTM layer, as initial state
decoder_output = layers.LSTM(64, name="decoder")(
decoder_embedded, initial_state=encoder_state
)
output = layers.Dense(10)(decoder_output)
model = keras.Model([encoder_input, decoder_input], output)
model.summary()
"""----------------------------------------------- 第四部分 -----------------------------------------------"""
"""
## RNN layers and RNN cells
In addition to the built-in RNN layers, the RNN API also provides cell-level APIs.
Unlike RNN layers, which processes whole batches of input sequences, the RNN cell only
processes a single timestep.
除了内建的rnn层,rnn api也提供cell级别的api。不同于rnn层处理整个批次的输入序列,rnn cell只处理单个时间步。
cell实际上存在于rnn层for循环当中,
The cell is the inside of the `for` loop of a RNN layer. Wrapping a cell inside a
`keras.layers.RNN` layer gives you a layer capable of processing batches of
sequences, e.g. `RNN(LSTMCell(10))`.
从数学上讲,`RNN(LSTMCell(10))`与`LSTM(10)`生成的效果是一样的,但是`LSTM(10)`可以使用gpu加速。
有三种 built-in RNN cells, 对应三种 RNN 层
- `keras.layers.SimpleRNNCell` corresponds to the `SimpleRNN` layer.
- `keras.layers.GRUCell` corresponds to the `GRU` layer.
- `keras.layers.LSTMCell` corresponds to the `LSTM` layer.
"""
"""
## Cross-batch statefulness
When processing very long sequences (possibly infinite), you may want to use the
pattern of **cross-batch statefulness**.
Normally, the internal state of a RNN layer is reset every time it sees a new batch
(i.e. every sample seen by the layer is assumed to be independent of the past). The
layer will only maintain a state while processing a given sample.
If you have very long sequences though, it is useful to break them into shorter
sequences, and to feed these shorter sequences sequentially into a RNN layer without
resetting the layer's state. That way, the layer can retain information about the
entirety of the sequence, even though it's only seeing one sub-sequence at a time.
You can do this by setting `stateful=True` in the constructor.
If you have a sequence `s = [t0, t1, ... t1546, t1547]`, you would split it into e.g.
```
s1 = [t0, t1, ... t100]
s2 = [t101, ... t201]
...
s16 = [t1501, ... t1547]
```
Then you would process it via:
```python
lstm_layer = layers.LSTM(64, stateful=True)
for s in sub_sequences:
output = lstm_layer(s)
```
When you want to clear the state, you can use `layer.reset_states()`.
> Note: In this setup, sample `i` in a given batch is assumed to be the continuation of
sample `i` in the previous batch. This means that all batches should contain the same
number of samples (batch size). E.g. if a batch contains `[sequence_A_from_t0_to_t100,
sequence_B_from_t0_to_t100]`, the next batch should contain
`[sequence_A_from_t101_to_t200, sequence_B_from_t101_to_t200]`.
Here is a complete example:
"""
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
output = lstm_layer(paragraph3)
# reset_states() will reset the cached state to the original initial_state.
# If no initial_state was provided, zero-states will be used by default.
lstm_layer.reset_states()
"""
### RNN State Reuse
<a id="rnn_state_reuse"></a>
"""
"""
The recorded states of the RNN layer are not included in the `layer.weights()`. If you
would like to reuse the state from a RNN layer, you can retrieve the states value by
`layer.states` and use it as the
initial state for a new layer via the Keras functional API like `new_layer(inputs,
initial_state=layer.states)`, or model subclassing.
Please also note that sequential model might not be used in this case since it only
supports layers with single input and output, the extra input of initial state makes
it impossible to use here.
"""
paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
existing_state = lstm_layer.states
new_lstm_layer = layers.LSTM(64)
new_output = new_lstm_layer(paragraph3, initial_state=existing_state)
"""
## Bidirectional RNNs
For sequences other than time series (e.g. text), it is often the case that a RNN model
can perform better if it not only processes sequence from start to end, but also
backwards. For example, to predict the next word in a sentence, it is often useful to
have the context around the word, not only just the words that come before it.
Keras provides an easy API for you to build such bidirectional RNNs: the
`keras.layers.Bidirectional` wrapper.
"""
model = keras.Sequential()
model.add(
layers.Bidirectional(layers.LSTM(64, return_sequences=True), input_shape=(5, 10))
)
model.add(layers.Bidirectional(layers.LSTM(32)))
model.add(layers.Dense(10))
model.summary()
"""----------------------------------------------- 第五部分 -----------------------------------------------"""
"""
Under the hood, `Bidirectional` will copy the RNN layer passed in, and flip the
`go_backwards` field of the newly copied layer, so that it will process the inputs in
reverse order.
The output of the `Bidirectional` RNN will be, by default, the sum of the forward layer
output and the backward layer output. If you need a different merging behavior, e.g.
concatenation, change the `merge_mode` parameter in the `Bidirectional` wrapper
constructor. For more details about `Bidirectional`, please check
[the API docs](https://keras.io/api/layers/recurrent_layers/bidirectional/).
"""
"""
## Performance optimization and CuDNN kernels
In TensorFlow 2.0, the built-in LSTM and GRU layers have been updated to leverage CuDNN
kernels by default when a GPU is available. With this change, the prior
`keras.layers.CuDNNLSTM/CuDNNGRU` layers have been deprecated, and you can build your
model without worrying about the hardware it will run on.
Since the CuDNN kernel is built with certain assumptions, this means the layer **will
not be able to use the CuDNN kernel if you change the defaults of the built-in LSTM or
GRU layers**. E.g.:
- Changing the `activation` function from `tanh` to something else.
- Changing the `recurrent_activation` function from `sigmoid` to something else.
- Using `recurrent_dropout` > 0.
- Setting `unroll` to True, which forces LSTM/GRU to decompose the inner
`tf.while_loop` into an unrolled `for` loop.
- Setting `use_bias` to False.
- Using masking when the input data is not strictly right padded (if the mask
corresponds to strictly right padded data, CuDNN can still be used. This is the most
common case).
For the detailed list of constraints, please see the documentation for the
[LSTM](https://keras.io/api/layers/recurrent_layers/lstm/) and
[GRU](https://keras.io/api/layers/recurrent_layers/gru/) layers.
"""
"""
### Using CuDNN kernels when available
Let's build a simple LSTM model to demonstrate the performance difference.
We'll use as input sequences the sequence of rows of MNIST digits (treating each row of
pixels as a timestep), and we'll predict the digit's label.
"""
batch_size = 64
# Each MNIST image batch is a tensor of shape (batch_size, 28, 28).
# Each input sequence will be of size (28, 28) (height is treated like time).
input_dim = 28
units = 64
output_size = 10 # labels are from 0 to 9
# Build the RNN model
def build_model(allow_cudnn_kernel=True):
# CuDNN is only available at the layer level, and not at the cell level.
# This means `LSTM(units)` will use the CuDNN kernel,
# while RNN(LSTMCell(units)) will run on non-CuDNN kernel.
if allow_cudnn_kernel:
# The LSTM layer with default options uses CuDNN.
lstm_layer = keras.layers.LSTM(units, input_shape=(None, input_dim))
else:
# Wrapping a LSTMCell in a RNN layer will not use CuDNN.
lstm_layer = keras.layers.RNN(
keras.layers.LSTMCell(units), input_shape=(None, input_dim)
)
model = keras.models.Sequential(
[
lstm_layer,
keras.layers.BatchNormalization(),
keras.layers.Dense(output_size),
]
)
return model
"""
Let's load the MNIST dataset:
"""
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
sample, sample_label = x_train[0], y_train[0]
"""
Let's create a model instance and train it.
We choose `sparse_categorical_crossentropy` as the loss function for the model. The
output of the model has shape of `[batch_size, 10]`. The target for the model is an
integer vector, each of the integer is in the range of 0 to 9.
"""
model = build_model(allow_cudnn_kernel=True)
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1
)
"""
Now, let's compare to a model that does not use the CuDNN kernel:
"""
noncudnn_model = build_model(allow_cudnn_kernel=False)
noncudnn_model.set_weights(model.get_weights())
noncudnn_model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
noncudnn_model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1
)
"""
When running on a machine with a NVIDIA GPU and CuDNN installed,
the model built with CuDNN is much faster to train compared to the
model that uses the regular TensorFlow kernel.
The same CuDNN-enabled model can also be used to run inference in a CPU-only
environment. The `tf.device` annotation below is just forcing the device placement.
The model will run on CPU by default if no GPU is available.
You simply don't have to worry about the hardware you're running on anymore. Isn't that
pretty cool?
"""
import matplotlib.pyplot as plt
with tf.device("CPU:0"):
cpu_model = build_model(allow_cudnn_kernel=True)
cpu_model.set_weights(model.get_weights())
result = tf.argmax(cpu_model.predict_on_batch(tf.expand_dims(sample, 0)), axis=1)
print(
"Predicted result is: %s, target result is: %s" % (result.numpy(), sample_label)
)
plt.imshow(sample, cmap=plt.get_cmap("gray"))
"""
## RNNs with list/dict inputs, or nested inputs
Nested structures allow implementers to include more information within a single
timestep. For example, a video frame could have audio and video input at the same
time. The data shape in this case could be:
`[batch, timestep, {"video": [height, width, channel], "audio": [frequency]}]`
In another example, handwriting data could have both coordinates x and y for the
current position of the pen, as well as pressure information. So the data
representation could be:
`[batch, timestep, {"location": [x, y], "pressure": [force]}]`
The following code provides an example of how to build a custom RNN cell that accepts
such structured inputs.
"""
"""
### Define a custom cell that supports nested input/output
"""
"""
See [Making new Layers & Models via subclassing](/guides/making_new_layers_and_models_via_subclassing/)
for details on writing your own layers.
"""
class NestedCell(keras.layers.Layer):
def __init__(self, unit_1, unit_2, unit_3, **kwargs):
self.unit_1 = unit_1
self.unit_2 = unit_2
self.unit_3 = unit_3
self.state_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]
self.output_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]
super(NestedCell, self).__init__(**kwargs)
def build(self, input_shapes):
# expect input_shape to contain 2 items, [(batch, i1), (batch, i2, i3)]
i1 = input_shapes[0][1]
i2 = input_shapes[1][1]
i3 = input_shapes[1][2]
self.kernel_1 = self.add_weight(
shape=(i1, self.unit_1), initializer="uniform", name="kernel_1"
)
self.kernel_2_3 = self.add_weight(
shape=(i2, i3, self.unit_2, self.unit_3),
initializer="uniform",
name="kernel_2_3",
)
def call(self, inputs, states):
# inputs should be in [(batch, input_1), (batch, input_2, input_3)]
# state should be in shape [(batch, unit_1), (batch, unit_2, unit_3)]
input_1, input_2 = tf.nest.flatten(inputs)
s1, s2 = states
output_1 = tf.matmul(input_1, self.kernel_1)
output_2_3 = tf.einsum("bij,ijkl->bkl", input_2, self.kernel_2_3)
state_1 = s1 + output_1
state_2_3 = s2 + output_2_3
output = (output_1, output_2_3)
new_states = (state_1, state_2_3)
return output, new_states
def get_config(self):
return {"unit_1": self.unit_1, "unit_2": unit_2, "unit_3": self.unit_3}
"""
### Build a RNN model with nested input/output
Let's build a Keras model that uses a `keras.layers.RNN` layer and the custom cell
we just defined.
"""
unit_1 = 10
unit_2 = 20
unit_3 = 30
i1 = 32
i2 = 64
i3 = 32
batch_size = 64
num_batches = 10
timestep = 50
cell = NestedCell(unit_1, unit_2, unit_3)
rnn = keras.layers.RNN(cell)
input_1 = keras.Input((None, i1))
input_2 = keras.Input((None, i2, i3))
outputs = rnn((input_1, input_2))
model = keras.models.Model([input_1, input_2], outputs)
model.compile(optimizer="adam", loss="mse", metrics=["accuracy"])
"""
### Train the model with randomly generated data
Since there isn't a good candidate dataset for this model, we use random Numpy data for
demonstration.
"""
input_1_data = np.random.random((batch_size * num_batches, timestep, i1))
input_2_data = np.random.random((batch_size * num_batches, timestep, i2, i3))
target_1_data = np.random.random((batch_size * num_batches, unit_1))
target_2_data = np.random.random((batch_size * num_batches, unit_2, unit_3))
input_data = [input_1_data, input_2_data]
target_data = [target_1_data, target_2_data]
model.fit(input_data, target_data, batch_size=batch_size)
"""
With the Keras `keras.layers.RNN` layer, You are only expected to define the math
logic for individual step within the sequence, and the `keras.layers.RNN` layer
will handle the sequence iteration for you. It's an incredibly powerful way to quickly
prototype new kinds of RNNs (e.g. a LSTM variant).
For more details, please visit the [API docs](https://keras.io/api/layers/recurrent_layers/rnn/).
""" |
35634eb26c5597a3535d16cbfb5d3c124f861f57 | geuben/adafruit-pi-lcd-plate | /menu_framework/menu.py | 1,989 | 3.609375 | 4 | class Menu(object):
def __init__(self, items):
self._items = items
self._items.append(Back())
self._pos = 0
self._active = True
def items(self):
return self._items
def num_items(self):
return len(self._items)
def message(self):
if self._active:
return self._message()
else:
return self._items[self._pos].message()
def _message(self):
if self._pos == (self.num_items() - 1):
return "> " + self._items[self._pos].text
else:
return "> " + self._items[self._pos].text + "\n- " + self._items[self._pos+1].text
def up(self):
if self._active:
self._up()
else:
self._items[self._pos].up()
def down(self):
if self._active:
self._down()
else:
self._items[self._pos].down()
def select(self, lcd_control):
lcd_control.clear()
if self._active:
return self._select(lcd_control)
else:
if not self._items[self._pos].select(lcd_control):
self._active = True
return False
else:
return True
def _down(self):
if self._pos < (len(self._items) - 1):
self._pos += 1
def _up(self):
if self._pos > 0:
self._pos -= 1
def _select(self, lcd_control):
if isinstance(self._items[self._pos], Menu):
self._active = False
return True
elif isinstance(self._items[self._pos], Back):
return False
else:
self._items[self._pos].select(lcd_control)
return True
class MenuItem(object):
TEXT = "NOT DEFINED"
def __init__(self):
pass
def select(self, lcd_control):
print "NOT IMPLEMENTED"
return True
@property
def text(self):
return self.TEXT
class Back(MenuItem):
TEXT = "Back"
|
7f07e66c94da1f249a95645900f1140a1d7bf596 | jdk1997/CP | /HR/digfac.py | 228 | 3.5 | 4 | from math import factorial
t = int(input())
for _ in range(t):
n = int(input())
for i in range(len(s_num)):
tmp = factorial(n)
ans = 0
s_num = str(tmp)
ans += int(s_num[i])
print(ans) |
4eccdcb14d1e43c307069c789a2c21a7fcb4f8cd | Journey99/Algorithm | /Topic3/chapter4/example14.py | 549 | 3.640625 | 4 | # 최소 동전으로 거슬러 주기
def min_coin_count(value, coin_list):
min_coin = 0
coin_list = sorted(coin_list, reverse= True)
for i in range(len(coin_list)):
coin = value // coin_list[i]
min_coin += coin
value = value - coin*coin_list[i]
return min_coin
# 테스트
default_coin_list = [100, 500, 10, 50]
print(min_coin_count(1440, default_coin_list))
print(min_coin_count(1700, default_coin_list))
print(min_coin_count(23520, default_coin_list))
print(min_coin_count(32590, default_coin_list)) |
84c5c4e35d9aa28b09ebad22c38a53abe48d20cc | roblivesinottawa/studies_and_projects | /PYTHON_BOOTCAMP/CONDITIONALS/one.py | 268 | 4.15625 | 4 | temperature = int(input("enter temperature between 0 and 40: "))
if temperature > 30:
print("it's hot out")
elif temperature > 15 and temperature < 30:
print("it's nice out")
elif temperature < 15:
print("it's chilly out")
else:
print("it's freezing") |
ef245082a7d5d140f754a8af7e022dd860319df8 | guillox/Practica_python | /2013/tp1/tp1ej9.py | 583 | 4.125 | 4 | """9.- a) Implemente una calculadora simple, en donde se ingrese (por entrada estandar) dos operandos y
el operador(+,-,*, /) e imprima el valor de la operacion resultante(por el momento no tenga en cuenta errores
de tipos, ej: que el operando no sea numero o que el operador no sea los enumerados).
Nota: No codifique con condicionales (if, elif, etc) ni bucles (while, for, etc)"""
var_ent1= int(raw_input("ingrese un valor entero"))
var_ent2= int(raw_input("ingrese un valor entero"))
var_oper= raw_input("ingrese un valor del operando")
eval("var_ent1 var_oper var_ent2")
|
055742f2d5fad1611f40a6009eedf6300e1c7ca5 | cross-sky/sicp | /c1_2_6.py | 347 | 3.703125 | 4 | def divides(a, b):
return b % a == 0
def smallest_divisor(n):
return find_divisor(n, 2)
def square(n):
return n * n
def find_divisor(n, test_divisor):
if square(test_divisor) > n:
return n
if divides(test_divisor, n):
return test_divisor
else:
return find_divisor(n, test_divisor + 1)
def prime(n):
return n == smallest_divisor(n)
|
ef1d4df052d0f2a4a71224915fc0c60d40cd7af7 | jacindaz/algos_practice | /algos/dynamic_programming.py | 1,135 | 3.578125 | 4 | def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
def fib_dynamic_programming(n):
a, b = 0, 1
for step in range(n):
a, b = a + b, a
return a
def num_paths(height, width):
if height == 0 and width == 0:
return 0
if height == 0 or width == 0:
return 1
return num_paths(height-1, width) + num_paths(height, width-1)
def num_paths_dp(height, width):
memoized_values = []
for current_height in range(height+1):
height_values = []
for current_width in range(width+1):
if current_height == 0 or current_width == 0:
height_values.append(1)
memoized_values.append(height_values)
for current_height in range(height+1):
height_values = []
for current_width in range(width+1):
if current_height != 0 and current_width != 0:
up = memoized_values[current_height-1][current_width]
left = memoized_values[current_height][current_width-1]
memoized_values[current_height].append(up + left)
return memoized_values[height][width]
|
24b27ecce9485366a73d933f4f48debf2c5f16f6 | xerprobe/LeetCodeAnswer | /141. 环形链表/pythonCode.py | 1,215 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if(head == None or head.next == None):
return False
quickHead = head.next
while(quickHead != None):
if(quickHead == head):
return True
if(quickHead.next == None):
break
quickHead = quickHead.next.next
head = head.next
return False
'''
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
''' |
3d4bc69f9f43db87d2b476096442eb0241f99a3d | ouedraogoboukary/starter-kit-datascience | /arthur-ouaknine/Lesson 1/wordcount.py | 3,065 | 4.25 | 4 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Wordcount exercise
Google's Python class
The main() below is already defined and complete. It calls print_words()
and print_top() functions which you write.
1. For the --count flag, implement a print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
...
Print the above list in order sorted by word (python will sort punctuation to
come before letters -- that's fine). Store all the words as lowercase,
so 'The' and 'the' count as the same word.
2. For the --topcount flag, implement a print_top(filename) which is similar
to print_words() but which prints just the top 20 most common words sorted
so the most common word is first, then the next most common, and so on.
Use str.split() (no arguments) to split on all whitespace.
Workflow: don't build the whole program at once. Get it to an intermediate
milestone and print your data structure and sys.exit(0).
When that's working, try for the next milestone.
Optional: define a helper function to avoid code duplication inside
print_words() and print_top().
"""
import sys
import operator
import collections
def buildDict(filename):
dictionnary = {}
file = open(filename,"r")
#file = filename.split("\n")
for line in file:
words = line.split()
for word in words:
word = word.lower()
if word in dictionnary:
dictionnary[word] += 1
else:
dictionnary[word] = 1
return dictionnary
def print_words(filename):
dico = buildDict(filename)
wordsSorted = collections.OrderedDict(sorted(dico.items()))
for key,value in wordsSorted.items():
print(key,value)
def print_top(filename):
dico = buildDict(filename)
dicoSorted = sorted(dico.items(), key=operator.itemgetter(1), reverse=True) #transforme en liste !
cpt = 1
while cpt <= 20:
print(dicoSorted[cpt][0],dicoSorted[cpt][-1])
cpt += 1
# +++your code here+++
# Define print_words(filename) and print_top(filename) functions.
# You could write a helper utility function that reads a file
# and builds and returns a word/count dict for it.
# Then print_words() and print_top() can just call the utility function.
###
# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
option = input("count or topcount : ")
filename = input("File name : ")
if option == 'count':
print_words(filename)
elif option == 'topcount':
print_top(filename)
else:
print('unknown option: ' + option)
sys.exit(1)
if __name__ == '__main__':
main()
#txt = "We are not what we should be \n We are not what we need to be \n But at least we are not what we used to be \n -- Football Coach " |
0d4f470ef24ddf2f531b95e9fda5c37207ed21a3 | gabriellaec/desoft-analise-exercicios | /backup/user_221/ch149_2020_04_13_21_19_33_037376.py | 891 | 3.921875 | 4 | salario = float(input('Qual o seu salário bruto? '))
dependentes = int(input('Qual o número de dependentes? '))
if salario <= 1045:
contribuicao = salario*0.075
elif 1045.01 <= salario <= 2089.60:
contribuicao = salario*0.09
elif 2089.61 <= salario <= 3134.40:
contribuicao = salario*0.012
elif 3134.41 <= salario <= 6101.06:
contribuicao = salario*0.14
elif salario > 6101.06:
contribuicao = 671.12
base_de_calculo = salario - contribuicao - dependentes*189.59
if base_de_calculo <= 1903.98:
irrf = base_de_calculo*0 - 0
elif 1903.99 <= base_de_calculo <= 2826.65:
irrf = base_de_calculo*0.075 - 142.80
elif 2826.66 <= base_de_calculo <= 3751.05:
irrf = base_de_calculo*0.15 - 354.80
elif 3751.06 <= base_de_calculo <= 4664.68:
irrf = base_de_calculo*0.225 - 636.13
elif base_de_calculo > 4664.68:
irrf = base_de_calculo*0.275 - 869.36
print(irrf) |
4f444b251ffc8af652e7d386c6b363e43a6d6030 | Jerrydepon/LeetCode | /3_tree/medium/98. Validate Binary Search Tree.py | 691 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# traverse through tree and check the valid range for each node in the tree
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.traverseTree(root, -float("inf"), float("inf"))
def traverseTree(self, node, l_range, r_range):
if not node:
return True
if not(l_range < node.val < r_range):
return False
l = self.traverseTree(node.left, l_range, node.val)
r = self.traverseTree(node.right, node.val, r_range)
return l and r |
c79507344fa6d0e8afbe294b6c9d28f59d36a3ce | SvetlaGeorgieva/HackBulgaria-Programming101 | /week0/week0day1/11_count_substrings/solution.py | 850 | 4.125 | 4 | def count_substrings(haystack, needle):
index = haystack.find(needle, 0)
if (index == -1):
return 0
else:
count = 0
needle_length = len(needle)
while (index < len(haystack) + 1):
if (haystack.find(needle, index) != -1):
index1 = haystack.find(needle, index)
count += 1
index = index1 + needle_length
else:
break
return count
def main():
print (count_substrings("This is a test string", "is"))
print (count_substrings("babababa", "baba"))
print (count_substrings("Python is an awesome language to program in!", "o"))
print (count_substrings("We have nothing in common!", "really?"))
print (count_substrings("This is this and that is this", "this"))
if __name__ == '__main__':
main()
|
d87c22fafc405dc867a71f884f8f52b92186c5c2 | MichaelCurrin/daylio-csv-parser | /dayliopy/mood_report.py | 1,665 | 3.890625 | 4 | #!/usr/bin/env python
"""
Mood report application file.
"""
import pandas as pd
from .lib.config import AppConf
conf = AppConf()
def print_aggregate_stats(df: pd.DataFrame, column_name: str) -> None:
"""
Print aggregate stats for a given DataFrame and column name.
:param df: Data to work on.
:param column_name: Name of column to use in `df`. Also used to print a
heading.
"""
print(column_name)
values = df[column_name]
stats = {
"mean": values.mean(),
"median": values.median(),
}
for k, v in stats.items():
print("{k}: {v:3.2f}".format(k=k, v=v))
def get_mood_counts(df: pd.DataFrame):
"""
Combine configured mood score with actual counts and return.
:param df: Data that was read in from cleaned CSV.
:return: DataFrame with index as 'mood_label' and columns as
['mood_score', 'count'].
"""
config_df = pd.DataFrame.from_dict(
conf.MOODS, orient="index", columns=["mood_score"]
)
config_df.sort_values("mood_score", inplace=True)
return df["mood_label"].value_counts()
def make_report(csv_in_path: str) -> None:
"""
Make report from input CSV and show.
:param: csv_in_path: Path to cleaned CSV, as generated by clean_csv.py
application.
:return: None
"""
df = pd.read_csv(csv_in_path, usecols=["mood_label", "mood_score"])
print_aggregate_stats(df, "mood_score")
print()
print(get_mood_counts(df))
def main():
"""
Command-line entry-point.
"""
csv_in_path = conf.get("data", "cleaned_csv")
make_report(csv_in_path)
if __name__ == "__main__":
main()
|
ab9f3bd9474d7dd1cbed403a0b58b9da43562de4 | chrisbubernak/ProjectEulerChallenges | /46_GoldbachsOtherConjecture.py | 1,288 | 4 | 4 | # It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
# 9 = 7 + 2×1^2
# 15 = 7 + 2×2^2
# 21 = 3 + 2×3^2
# 25 = 7 + 2×3^2
# 27 = 19 + 2×2^2
# 33 = 31 + 2×1^2
# It turns out that the conjecture was false.
# What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
import math
# store found primes here to make things quicker
primes = []
# whether a number can be written as the sum of a prime and twice a square
# basically we iterate through all the primes we've seen so far and check
# if the remainder is 2x a perfect square. if it is, return true, if none
# are the number doesn't meet the condition
def meetsCondition(n):
for p in primes:
remainder = n - p
if (remainder % 2 == 0):
root = math.sqrt(remainder / 2)
if ((int(root) * int(root)) == (remainder / 2)):
return True
return False
def isPrime(n):
i = int(math.sqrt(n))
while(i > 1):
if (n%i == 0):
return False
i = i - 1
primes.append(n)
return True
def isOdd(n):
return n % 2 == 1
def solve():
i = 1
while(True):
if (not(isPrime(i)) and isOdd(i)):
if (not(meetsCondition(i))):
return i
i = i + 1
return 0
print(solve()) |
8a860d5c64cda470cb724d40eaadbbc309e8528f | ic3top/KPI-labs | /Python-Gui-Labs/Sem_1/CPC_3/Task_18.py | 201 | 3.90625 | 4 | k1 = int(input("The length of the first leg of the right triangle: "))
k2 = int(input("The length of the second leg of the right triangle: "))
s = (k1*k2)/2
print(f'The area of the triangle: {s:^10}')
|
198f5ee48709be0c9c0520e785551c7eaf2fb34f | mustard-seed/graph_algo | /test_digraph_topological_order.py | 1,299 | 3.734375 | 4 | from digraph.digraph import *
if __name__ == '__main__':
numV = 13
edges = [
[0, 1], [0, 5], [0, 6],
[2, 0], [2, 3],
[3, 5],
[4, 6],
[5, 4], [5, 9],
[6, 7], [6, 9],
[7, 8],
[9, 10], [9, 11], [9, 12],
[11, 12]
]
def checkOrder(order, graph: Digraph):
hasSeen = [False] * graph.v
if isinstance(order, list):
if len(order) < graph.v:
return False
for v in order:
hasSeen[v] = True
adjList = graph.adj(v)
for d in adjList:
""" If there is an edge pointing to a vertex earlier in the order,
then this order is not topological """
if hasSeen[d] is True:
return False
return True
graph = Digraph(numV, edges)
topologicalOrderFinder = DigraphTopological(graph)
order = topologicalOrderFinder.toplogicalOrder
if order:
print('Topological order: ', order)
isOrder = checkOrder(order, graph)
if isOrder is False:
print ('The proposed topological order failed the test!')
else:
print('The graph is not a DAG, hence it does not contain a topological order')
|
384bea6bdc6515f50e2c07416532efaacdfaf173 | saishg/codesnippets | /codeeval/towers.py | 1,249 | 3.53125 | 4 | #!/bin/python
import sys
class Tower:
def __init__(self, line):
self._blocks = map(int, line.split())
self._sum = sum(self._blocks)
def sum(self):
return self._sum
def pop(self, height):
while self._sum > height:
self._sum -= self._blocks.pop(0)
def blocks(self):
return len(self._blocks)
def compare(self, t):
height_difference = self.sum() - t.sum()
if height_difference == 0:
for block1, block2 in zip(self._blocks, t._blocks):
if block1 != block2:
return block1 - block2
return self.blocks() - t.blocks()
else:
return height_difference
n1,n2,n3 = raw_input().strip().split(' ')
n1,n2,n3 = [int(n1),int(n2),int(n3)]
h1 = Tower(raw_input())
h2 = Tower(raw_input())
h3 = Tower(raw_input())
def compare_towers(t1, t2):
return t1.compare(t2)
while True:
if 0 in [h1.sum(), h2.sum(), h2.sum()]:
print 0
break
if h1.sum() == h2.sum() == h3.sum():
print h1.sum()
break
h1, h2, h3 = sorted([h1, h2, h3], cmp=compare_towers, reverse=True)
# print sum(h1), sum(h2), sum(h3)
h1.pop(h3.sum())
|
3231452f80eed353eaca1b39db9b78b7970fa713 | Peter-Gr/MLPositionExtrapolator | /simple2.py | 1,248 | 3.6875 | 4 | import numpy as np
# sigmoid function
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
# input dataset
# The pattern is - doulbe the first column other columns are irrelevant
X = np.array([ [2,3,4],
[3,2,60],
[4,9,12],
[5,5,332] ])
# output dataset
y = np.array([[4,6,8,10]]).T
# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)
# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1
for iter in range(200000):
# forward propagation
l0 = X
dotProd = np.dot(l0,syn0)
l1 = nonlin(dotProd)
# how much did we miss?
l1_error = y - l1
# multiply how much we missed by the
# slope of the sigmoid at the values in l1
l1_delta = l1_error * nonlin(l1,True)
# update weights
syn0 += np.dot(l0.T,l1_delta)
print ("Output After Training ")
print ("L1")
print (l1)
print ("Last Syn0")
print (syn0)
print ("Last Dot Product")
print (dotProd)
print ("Prediction - hoping for 12")
l0 = np.array([[6,12,57]])
dotProd = np.dot(l0,syn0)
l1 = nonlin(dotProd)
print ("L1")
print (l1)
print ("Dot Product")
print (dotProd)
|
362d7e4a070f686f0b73adac8b2fc1762a9458c0 | TAHURASFRY/older-homeworks | /RPS.py | 2,350 | 4.0625 | 4 | import random
items = ["ROCK","PAPER","SCISSOR","EXIT"]
computer_score = 0
user_score = 0
computer_choice = random.choice(items)
print("0-ROCK")
print("1-PAPER")
print("2-SCISSOR")
print("3-EXIT")
while True:
user_choice_index = int(input())
user_choice = items[user_choice_index]
if user_choice == 3:
break
elif computer_choice == "ROCK" and user_choice == "SCISSOR":
print("computer wins")
computer_score +=1
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
elif computer_choice == "ROCK" and user_choice == "PAPER":
print("user wins")
user_score +=1
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
elif computer_choice == "ROCK" and user_choice == "ROCK":
print("equal")
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTR")
elif computer_choice == "PAPER" and user_choice == "ROCK":
print("user wins")
user_score +=1
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
elif computer_choice == "PAPER" and user_choice == "PAPER":
print("equal")
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
elif computer_choice == "PAPER" and user_choice == "SCISSOR":
print("computer wins")
computer_score +=1
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
elif computer_choice == "SCISSOR" and user_choice == "ROCK":
print("user wins")
user_score +=1
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
elif computer_choice == "SCISSOR" and user_choice == "PAPER":
print("computer wins")
computer_score +=1
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
elif computer_choice == "SCISSOR" and user_choice == "SCISSOR":
print("equal")
print(computer_choice)
print(user_score, "USER")
print(computer_score, "COMPUTER")
|
b952ea3f79d505379ecf7c4e99e53cadc86fe4ad | olaruandreea/KattisProblems | /grandpabernie.py | 383 | 3.625 | 4 | def createDictionary():
n = input()
i = 0
d = {}
while i < n:
tokens = raw_input().split()
if tokens[0] not in d:
d[tokens[0]] = [tokens[1]]
else:
d[tokens[0]].append(tokens[1])
i+=1
n2 = input()
i = 0
l = []
while i < n2:
tokens = raw_input().split()
l.append(sorted(d[tokens[0]])[int(tokens[1])-1])
i+=1
return "\n".join(l)
print createDictionary()
|
a91ea6afeb939f35606871c8d36cdf58fc3387c7 | xyzrlee/LeetCode | /530. Minimum Absolute Difference in BST/530v2.py | 1,188 | 3.65625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
last, min = None, None
def dfs(root):
nonlocal last, min
if root is None:
return
dfs(root.left)
if last is not None:
x = abs(root.val - last)
if min is None or min > x:
min = x
last = root.val
dfs(root.right)
dfs(root)
return min
if __name__ == '__main__':
nodeList = []
for i in range(10):
node = TreeNode(i)
nodeList.append(node)
nodeList[6].left = nodeList[2]
nodeList[6].right = nodeList[8]
nodeList[2].left = nodeList[0]
nodeList[2].right = nodeList[4]
nodeList[4].left = nodeList[3]
nodeList[4].right = nodeList[5]
nodeList[8].left = nodeList[7]
nodeList[8].right = nodeList[9]
root = nodeList[6]
sol = Solution()
print(sol.getMinimumDifference(root))
|
2b3eed20b9c8f9039824249c030c082eff21be2a | BlAcAnNy/kpk_33_0201 | /180921/electronics_store.py | 2,193 | 3.5 | 4 | class Electronics:
def __init__(self, name, characteristic, guarantee, producing_country, price):
self.name = name
self.characteristic = characteristic
self.guarantee = guarantee
self.producing_country = producing_country
self.price = price
def __str__(self):
return f'Электроника: {self.name}, ({self.characteristic}), {self.guarantee} мес, {self.producing_country}, {self.price} руб.'
@classmethod
def import_from_file(cls, file_name):
items_source = open(file_name, 'r', encoding='utf-8').readlines()
items_source = list(map(lambda x: x.replace('\n', '').split(', '), items_source))
items_schema = items_source.pop(0)
items_source_as_dict = list(map(lambda x: dict(zip(items_schema, x)), items_source))
items = []
for item_dict in items_source_as_dict:
_item = cls(**item_dict)
items.append(_item)
return items
class Smartphone(Electronics):
def __init__(self, name, characteristic, guarantee, producing_country, price, *args, **kwargs):
super().__init__(name, characteristic, guarantee, producing_country, price, *args, **kwargs)
def __str__(self):
return f'Смартфоны: {self.name}, ({self.characteristic}), {self.guarantee} мес, {self.producing_country}, {self.price} руб.'
class Laptop(Electronics):
def __init__(self, name, characteristic, guarantee, producing_country, price, *args, **kwargs):
super().__init__(name, characteristic, guarantee, producing_country, price, *args, **kwargs)
def __str__(self):
return f'Ноутбуки: {self.name}, ({self.characteristic}), {self.guarantee} мес, {self.producing_country}, {self.price} руб.'
class TV(Electronics):
def __init__(self, name, characteristic, guarantee, producing_country, price, *args, **kwargs):
super().__init__(name, characteristic, guarantee, producing_country, price, *args, **kwargs)
def __str__(self):
return f'Телевизоры: {self.name}, ({self.characteristic}), {self.guarantee} мес, {self.producing_country}, {self.price} руб.'
|
a0ab2fd77f10aa0a74757f05d6ec0c6aa028bc41 | mcelroa/Python-GUI | /main.py | 2,290 | 3.9375 | 4 | import tkinter as tk
from tkinter import filedialog, Text
import os
root = tk.Tk()
apps = []
#If this is not the first time using the GUI then this code block will
#add previously opened apps to the screen on start up.
if os.path.isfile("save.txt"):
with open("save.txt", "r") as f:
tempApps = f.read()
tempApps = tempApps.split(",")
apps = [x for x in tempApps if x.strip()]
#Function that handles the event of a user adding an app to the app list
def addApp():
#remove current selections when adding a new app. Prevents duplications
for widget in frame.winfo_children():
widget.destroy()
#Opens a windows file explorer dialog to allow users to select files to be opened
#Contains a filter feature to filter by executables only or all file types.
fileName = filedialog.askopenfilename(initialdir="/", title="Select File",
filetypes=(("executables", "*.exe"), ("all files", "*.*")))
apps.append(fileName)
print(fileName)
#Post current selected files to be opened on screen for user
for app in apps:
label = tk.Label(frame, text=app, bg="gray")
label.pack()
#Function that handles button click to run all selected apps.
def runApps():
for app in apps:
os.startfile(app)
#Set Up the window where the GUI will be contained
canvas = tk.Canvas(root, height=700, width=700, bg="#263D42")
canvas.pack()
#Set up a frame inside the larger window
frame = tk.Frame(root, bg="white")
frame.place(relheight=0.8, relwidth=0.8, relx=0.1, rely=0.1)
#The open file button
openFile = tk.Button(root, text="Open File", padx=10, pady=5, foreground="white",
bg="#263D42", command=addApp)
openFile.pack()
#The run apps button
runApps = tk.Button(root, text="Run Apps", padx=10, pady=5, foreground="white", bg="#263D42", command=runApps)
runApps.pack()
for app in apps:
label = tk.Label(frame, text=app)
label.pack()
root.mainloop()
#Write currently selected apps to be opened into a file for reusability.
#The apps path will be written to this file and can thus be opened immediately
#the next time the user uses the app
with open("save.txt", "w") as f:
for app in apps:
f.write(app + ",") |
12994e12df90c5506fed6820154f820005f32dc4 | BeeverFeever/Tic-Tac-Toe | /Tic_Tac_Toe-Python/Tic_Tac_Toe.py | 1,804 | 3.84375 | 4 | board = ["-", "-", "-", "-", "-", "-", "-", "-", "-",]
winner = None
def GenerateBoard():
print(f"""{board[0]}|{board[1]}|{board[2]}
{board[3]}|{board[4]}|{board[5]}
{board[6]}|{board[7]}|{board[8]}""")
def GetInput(player):
position = int(input(f"'{player}' Turn, where would you like to place your piece (0-9): "))
position -= 1
run = True
#adds piece to the board - with error checking
while(run == True):
if board[position] == '-':
if player == 'O':
board[position] = 'O'
run = False
if player == 'X':
board[position] = 'X'
run = False
else:
position = int(input("Please enter a valid position, 1-9: "))
position -= 1
def CheckWin(piece):
global winner
#check vertical wins
for i in range(3):
if board[i] == piece and board[i + 3] == piece and board[i + 6] == piece:
winner = piece
#check horizontal wins
for i in range(0, 8, 4):
if board[i] == piece and board[i + 1] == piece and board[i + 2] == piece:
winner = piece
#check diagonal wins
if board[0] == piece and board[4] == piece and board[8] == piece:
winner = piece
if board[i] == piece and board[2] == piece and board[4] == piece:
winner = piece
#check tie
for i in range(len(board)):
if board[i] != 'X' or 'O':
return
elif i == 8:
winner = 'Tie'
def MainGameLoop(isWinner):
while isWinner == None:
#X's turn
GenerateBoard()
GetInput('X')
CheckWin('X')
CheckWin('O')
#O's turn
GenerateBoard()
GetInput('O')
CheckWin('O')
CheckWin('X')
#display who won
if isWinner == 'Tie':
GenerateBoard()
print(f"It is a Tie.")
elif isWinner == 'X' or 'O':
GenerateBoard()
print(f"{isWinner} is the winner.")
MainGameLoop(winner) |
cc9a91f14323ed854da9b86f4251e48b5d6cc3f1 | ThomasLeonardo/Intro-to-CS | /guess_num.py | 686 | 4.15625 | 4 | # -*- coding: utf-8 -*-
guess = 50
min_num = 0
max_num = 100
print("Please think of a number between 0 and 100!")
while(True):
print("Is your secret number", str(guess) + "?")
i = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
last_guess = guess
if(i == 'h'):
guess = (guess + min_num) // 2
max_num = last_guess
elif(i == 'l'):
guess = (guess + max_num) // 2
min_num = last_guess
elif(i == 'c'):
print("Game over. Your secret number was:", guess)
break
else:
print("Sorry, I did not understand your input.")
|
ddee0144eb4b138ff6641ce9796a1291b0add1ee | fanyCaz/discrete-math | /exampleSets.py | 621 | 3.65625 | 4 | U = 191
F = 65
N = 76
M = 63
sets = []
print("Of the group of 191")
print("Will you add a set? y/n")
ans = input()
while(ans == 'y'):
print("Insert number of students, then after commas, the subject they're into : students,F,N,M")
x = input()
x = x.split(',',1)
sets.append([x[1],int(x[0])])
print("Will you add a set? y/n")
ans = input()
FrenchSets = [i[1] for i in sets if 'F' in i[0]]
MusicSets = [i[1] for i in sets if 'M' in i[0]]
BusinessSets = [i[1] for i in sets if 'N' in i[0]]
onlyFrench = F - sum(FrenchSets)
print("People who only take French {}".format(onlyFrench))
print(FrenchSets) |
137275479f2d2488bf9b142328b4632b7307abc2 | bala4rtraining/python_programming | /python-programming-workshop/def/tuple_args_great_super.py | 534 | 4.625 | 5 |
#Tuple argument. A method in Python can receive any number of arguments stored in a
#tuple. This requires the single-star syntax. A formal parameter of name *t can be
#used as a tuple.
#Tip: The tuple in this program, of identifier t, can be used in the same way as any tuple.
#Python that receives tuple argument
def display(*t):
# Print tuple.
print(t)
# Loop over tuple items.
for item in t:
print(item)
# Pass parameters.
display("San Francisco", "Los Angeles", "Sacramento")
display(2, 0, 1, 4)
|
49c4904fb4e4f5110ffade1cb1a42940f312cc2a | hhahhahhahha/python | /第一次上机/01.py | 421 | 3.5625 | 4 | #e1.1TempConvert.py
TempTstr = eval(input("请输入温度值:"))
s = input("请输入F或C以此选择温度类型(华氏温度: F,摄氏温度:C):")
#print(TempTstr)
if s in ['F','f']:
C = (TempTstr-32)/1.8
print("转换后的温度{:.2f}C".format(int(C)))
elif s in ['c','C']:
F =1.8*TempTstr+32
print("转换后的温度是{:.2f}F".format(int(F)))
else:
print("输入格式错误")
|
c12aa498cc01e6099f1af676a36fb538dfac1da9 | NathanMuniz/Exercises-Python | /Desafio/ex061.py | 537 | 3.796875 | 4 | print('Gerar Pa')
print('-=' *10)
first = int(input('Primeiro Termo'))
reason = int(input('Rasão da PA'))
term = first
cont = 1
while cont <= 10:
print('{}'.format(term), end='')
print(' → 'if cont <= 9 else '', end='')
term = term + reason
cont = cont + 1
'''print('Gerar Pa')
print('-='*10)
first = int(input('Primeiro Termo'))
reason = int(input('Rasão sa PA'))
term = first
for c in range(10 , 0, -1):
print('{}'.format(term), end='')
print(' → 'if c <= 10 else '',end='')
term = term + reason'''
|
e5c116184f8ab10f218f70a5b86afb9251e3349a | ayk-dev/python-basics | /drawing/butterfly.py | 734 | 3.921875 | 4 | n = int(input())
# ширина 2 * n - 1 колони
# height 2 * (n - 2) + 1
# Лявата и дясната ѝ част са широки n - 1
middle = n - 1
s = (n - 1) - 1
dash = ''
r = 2 * (n - 2) + 1 # range = height
spaces = n - 1
for row in range(1, r + 1):
if row == middle:
print(' ' * spaces + '@' + ' ' * spaces)
elif row < middle:
if row % 2 != 0:
print('*' * s + '\\' + ' ' + '/' + '*' * s)
elif row % 2 == 0:
print('-' * s + '\\' + ' ' + '/' + '-' * s)
else:
if row % 2 != 0:
print('*' * s + '/' + ' ' + '\\' + '*' * s)
elif row % 2 == 0:
print('-' * s + '/' + ' ' + '\\' + '-' * s)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.