blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
b20e6a3e61c832ca4dfecdd2bb5506083c7f24fa | adkhune/aditya-codes | /pythonscripts/recursion/factorial1.py | 291 | 3.75 | 4 | import pandas
import timeit
def main():
print("find of a factorial of n: n!")
n = 6
timeit
print("fctorial of {} is {}".format(n,factorial(n)))
def factorial(n):
if n == 1 or n == 0:
return 1
return n * factorial(n-1)
if __name__=="__main__": main()
|
f3cfe542f2d63141c0e0f6e0360d372899ce344b | adkhune/aditya-codes | /pythonscripts/dictionaries/sorting.py | 577 | 3.78125 | 4 | import operator
def main():
print('Let us see how to sort in dictionaries')
dict1 = {'aa':1, 'pp':4, 'cc':2, 'tt':3}
print('this is our dict1=', dict1)
sorted_dict1 = sorted(dict1.items(), key=operator.itemgetter(1))
print('after sorting it acc to values=',sorted_dict1)
sorted_dict2 = sorted(dict1.items(), key=operator.itemgetter(0))
print('sorting it acc to keys=',sorted_dict2)
print('these were list of tuples\nif we want dictionary then..')
print(dict(sorted_dict1))
print(dict(sorted_dict2))
if __name__=="__main__": main()
|
bd541d380c68c3ed9a5efbbec118b69d9a35feca | adkhune/aditya-codes | /pythonscripts/insertionsort.py | 394 | 4.09375 | 4 | def main():
list = [2,5,0,6,7]
print("sorted numbers=",insertionSort(list))
def insertionSort(numbers):
for i in range(0,len(numbers)):
current = numbers[i]
j = i-1
while numbers[j] > current and j>=0:
numbers[j+1] = numbers[j]
j=j-1
numbers[j+1] = current
return numbers
if __name__=="__main__": main()
|
80077e9e5324d70914a79967097e0f58e1161b72 | evespiration/Webscraping-Udemy | /WebScrapingA.py | 6,989 | 3.578125 | 4 | import time # to use sleep function to allow website to load
from selenium import webdriver # to connect to a browser and access an URL
from bs4 import BeautifulSoup # to remove HTML tags from HTML content
from selenium.webdriver.common.keys import Keys # so I can press the Enter Key in the search fields
import pandas as pd
class Course:
courseTitle = ""
courseDescription = ""
courseInstructor = ""
courseRating = ""
courseTotalRates = ""
courseLength = ""
courseNumberOfLectures = ""
courseLevel = ""
coursePrice = ""
def __init__(self, courseTitle, courseDescription, courseInstructor, courseRating,
courseTotalRates, courseLength, courseNumberOfLectures, courseLevel, coursePrice):
self.courseTitle = courseTitle
self.courseDescription = courseDescription
self.courseInstructor = courseInstructor
self.courseRating = courseRating
self.courseTotalRates = courseTotalRates
self.courseLength = courseLength
self.courseNumberOfLectures = courseNumberOfLectures
self.courseLevel = courseLevel
self.coursePrice = coursePrice
def showDetails(self):
print("Title: " + self.courseTitle)
print("Description: " + self.courseDescription)
print("Instructor: " + self.courseInstructor)
print("Rating: " + self.courseRating)
print("Rates: " + self.courseTotalRates)
print("Length: " + self.courseLength)
print("Lectures: " + self.courseNumberOfLectures)
print("Level: " + self.courseLevel)
print("Price: " + self.coursePrice)
print("")
def HTMLtoText(HTMLelement):
textContent = HTMLelement.get_attribute('innerHTML')
# Beautiful soup removes HTML tags from content, if it exists.
soup = BeautifulSoup(textContent, features="lxml")
rawString = soup.get_text().strip() # Leading and trailing whitespaces are removed
return rawString
# Connect to Browser
DRIVER_PATH = "C:/Users/filip/Documents/PythonFiles/chromedriver"
browser = webdriver.Chrome(DRIVER_PATH)
URL = "https://www.udemy.com"
# Access website
browser.get(URL)
# Give the browser time to load all content.
time.sleep(5)
# searches to be passed to search field
SEARCH_TERM = ["Python", "Data Analytics"]
courseList = []
# Create dataframe with named columns.
df = pd.DataFrame(columns=['courseTitle', 'courseDescription', 'courseInstructor', 'courseRating', 'courseTotalRates',
'courseLength', 'courseNumberOfLectures', 'courseLevel', 'coursePrice'])
# Navigate through 2 pages
for i in range(0,2):
# Locate search field
search = browser.find_element_by_css_selector(".js-header-search-field")
# Clear search field
search.clear()
# Pass search text to search field
search.send_keys(SEARCH_TERM[i])
# Press enter key after typing search text
search.send_keys(Keys.RETURN)
# Give the browser time to load all content.
time.sleep(3)
# content = browser.find_elements_by_css_selector(".course-card--has-price-text--1Ikr0")
# Couldn't use like this as resulting text had no spaces, so couldn't split contents dynamically.
# Store website content.
courseTitleLIST = browser.find_elements_by_css_selector\
(".popper--popper-hover--4YJ5J .course-card--course-title--2f7tE")
courseDescriptionLIST = browser.find_elements_by_css_selector\
(".course-card--course-headline--yIrRk")
courseInstructorLIST = browser.find_elements_by_css_selector\
(".popper--popper-hover--4YJ5J .course-card--instructor-list--lIA4f")
courseRatingLIST = browser.find_elements_by_css_selector\
(".popper--popper-hover--4YJ5J .star-rating--rating-number--3lVe8")
courseTotalRatesLIST = browser.find_elements_by_css_selector\
(".popper--popper-hover--4YJ5J .course-card--reviews-text--12UpL")
courseLengthLIST = browser.find_elements_by_css_selector\
(".course-card--large--1BVxY .course-card--row--1OMjg:nth-child(1)")
courseNumberOfLecturesLIST = browser.find_elements_by_css_selector\
(".course-card--large--1BVxY .course-card--row--1OMjg:nth-child(2)")
courseLevelLIST = browser.find_elements_by_css_selector\
(".course-card--large--1BVxY .course-card--row--1OMjg~ .course-card--row--1OMjg+ .course-card--row--1OMjg")
coursePriceLIST = browser.find_elements_by_css_selector\
(".course-card--price-text-container--2sb8G")
# Read and store each course details in a courseLIST.
for j in range(len(courseTitleLIST)):
title = HTMLtoText(courseTitleLIST[j])
description = HTMLtoText(courseDescriptionLIST[j])
instructor = HTMLtoText(courseInstructorLIST[j])
rating = HTMLtoText(courseRatingLIST[j])
totalRates = HTMLtoText(courseTotalRatesLIST[j])
length = HTMLtoText(courseLengthLIST[j])
numberOfLect = HTMLtoText(courseNumberOfLecturesLIST[j])
try:
level = HTMLtoText(courseLevelLIST[j])
except Exception as e:
level = "N/A"
# price needs further manipulation:
# treating for when price is null
try:
price = HTMLtoText(coursePriceLIST[j])
startIndex = price.index('R$') # starts reading from this point
cutOffIndex = price.index('O') # cuts the string at [O]riginal Price
price = price[startIndex:cutOffIndex]
except Exception as e:
# print("Price not available")
price = "Price not available"
# adding one course info into a dictionary
courseDict = {'courseTitle': title, 'courseDescription': description,
'courseInstructor': instructor, 'courseRating': rating,
'courseTotalRates': totalRates, 'courseLength': length,
'courseNumberOfLectures': numberOfLect, 'courseLevel': level,
'coursePrice': price}
# appending course by course into a DataFrame
df = df.append(courseDict, ignore_index=True)
# Creating course objects
course = Course(title, description, instructor,
rating,totalRates, length,
numberOfLect,level, price)
# appending course by course into an Object's List.
courseList.append(course)
# Print all courses found
for c in courseList:
c.showDetails()
# Save DataFrame into a CSV File
PATH = "C:/Users/filip/Documents/PythonFiles/"
CSV_FILE = "UdemyCourses.csv"
df.to_csv(PATH+CSV_FILE, sep=',')
# Set up DataFrame printing options
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
pd.set_option("display.colheader_justify","left")
# Read CSV file and print first and last two rows
readCsv = pd.read_csv(PATH+CSV_FILE, sep=',')
print("First two rows: \n", readCsv.head(2), "\n\nLast two rows: \n", readCsv.tail(2))
|
dfb2a28ed745af251dc85d8d24f8e8006cf897ff | amani021/100DaysOfPython | /Day_6.py | 1,584 | 4.09375 | 4 | # -------- DAY 6 "FizzBuzz" --------
# Goal: Check an input if it is divisible by (3 and 5) or (3 or 5) or none of them.
from tkinter import *
root = Tk()
root.title('100 Days Of Python - Day 6')
root.configure(background='#B3E5FC')
# --------------- CREATE A FRAME ---------------
frame = LabelFrame(root, text=' FizzBuzz ', bg='#B3E5FC', fg='#1A237E', font=15, padx=75, pady=75)
frame.pack(padx=20, pady=20)
info = Label(frame, text='Enter a number:', bg='#B3E5FC', font=.5)
info.grid(row=0, column=0, pady=5)
e_num = Entry(frame, width=21, borderwidth=3, font=7)
e_num.grid(row=1, column=0, columnspan=2, padx=3)
# --------------- FUNCTIONS ---------------
def fizz_buzz():
try:
if int(e_num.get()) % 3 == 0 and int(e_num.get()) % 5 == 0:
txt.config(text='FizzBuzz')
elif int(e_num.get()) % 3 == 0 or int(e_num.get()) % 5 == 0:
txt.config(text='Fizz')
else:
txt.config(text=e_num.get())
except ValueError:
txt.config(text='That is NOT a number!!', bg='#B3E5FC', fg='#BF360C')
def clear():
e_num.delete(0, END)
# --------------- BUTTONS & LABEL FOR ANSWERS ---------------
button = Button(frame, text="Check Number", bg='#F48FB1', height=2, command=fizz_buzz)
button.grid(row=2, column=0, sticky='snew', padx=2, pady=21)
button = Button(frame, text="Clear", bg='#E0E0E0', height=2, command=clear)
button.grid(row=2, column=1, sticky='snew', padx=2, pady=21)
txt = Label(frame, text='', bg='#B3E5FC', font=.5, pady=15)
txt.grid(row=3, column=0, columnspan=2)
root.mainloop()
|
50384540ecb37dca4f55a9ef395a8e480296176a | amani021/100DaysOfPython | /Day_2.py | 334 | 3.984375 | 4 | # -------- DAY 2 "Basic Info" --------
# Goal: Learn more about the day 1's goal.
print('Welcome to iPython Supermarket')
bill = float(input('How much is your bill? ... '))
tax = bill*(15/100)
print(f'TAX is 15%\nBill is {bill}')
print(f'~~~~~~~~~~~~\nThe total including the TAX is {bill+tax}$')
print('THANK YOU, SEE YOU AGAIN ^-^') |
2e0d0c56a3dbd4baf528ec145887b3dd355d8196 | mon0theist/Automate-The-Boring-Stuff | /Chapter 12/update_produce.py | 924 | 3.578125 | 4 | #! /usr/bin/python
#
# ATBS Chapter 12 - Updating a Spreadsheet
# produceSales.xlsx
#
# Update the following prices:
# Celery - 1.19
# Garlic - 3.07
# Lemon - 1.27
import openpyxl
wb = openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.get_sheet_by_name('Sheet')
# The produce types and their updated prices
# If any future price updates are required, you can just update this dictionary
# whereas a hard-coded solution would require you to change the whole code, which
# could introduce new bugs
PRICE_UPDATES = {
'Garlic': 3.07,
'Celery': 1.19,
'Lemon': 1.27
}
# TODO: Loop through the rows and update the prices
for rowNum in range(2, sheet.max_row): # skip the first row since first row is column names
produceName = sheet.cell(row=rowNum, column=1).value
if produceName in PRICE_UPDATES:
sheet.cell(row=rowNum, column=2).value = PRICE_UPDATES[produceName]
wb.save('updated_produce_sales.xlsx')
|
936db64e955730755cc244be94cf280e25051ef2 | mon0theist/Automate-The-Boring-Stuff | /Chapter 04/characterPictureGrid1.py | 2,631 | 3.796875 | 4 | # Character Picture Grid
#
# Say you have a list of lists where each value in the inner lists is a one-character string, like this:
#
#
# grid = [['.', '.', '.', '.', '.', '.'],
# ['.', 'O', 'O', '.', '.', '.'],
# ['O', 'O', 'O', 'O', '.', '.'],
# ['O', 'O', 'O', 'O', 'O', '.'],
# ['.', 'O', 'O', 'O', 'O', 'O'],
# ['O', 'O', 'O', 'O', 'O', '.'],
# ['O', 'O', 'O', 'O', '.', '.'],
# ['.', 'O', 'O', '.', '.', '.'],
# ['.', '.', '.', '.', '.', '.']]
#
# You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The (0, 0) origin will be in the upper-left corner, the x-coordinates increase going right, and the y-coordinates increase going down.
# >>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
# >>> spam[0]
# ['cat', 'bat']
# >>> spam[0][1]
# 'bat'
# >>> spam[1][4]
# 50
# The first index dictates which list value to use, and the second indicates the value within the list value. For example, spam[0][1] prints 'bat', the second value in the first list. If you only use one index, the program will print the full list value at that index.
# based on this it seems that in grid[y][x] is more accurate...
# Copy the previous grid value, and write code that uses it to print the image.
#
# ..OO.OO..
# .OOOOOOO.
# .OOOOOOO.
# ..OOOOO..
# ...OOO...
# ....O....
# This is the above image sideways
# Hint: You will need to use a loop in a loop in order to print grid[0][0], then grid[1][0], then grid[2][0], and so on, up to grid[8][0]. This will finish the first row, so then print a newline. Then your program should print grid[0][1], then grid[1][1], then grid[2][1], and so on. The last thing your program will print is grid[8][5].
# Also, remember to pass the end keyword argument to print() if you don’t want a newline printed automatically after each print() call.
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
for j in range(len(grid[0])): # this is basically functioning as the Y axis?
for i in range(0, len(grid)): # this is basically functioning as the X axis?
print(grid[i][j], end='') # keyword=end prevents a newline after every print()
print()
# I don't follow this at all.... :'(
|
981c2e7984813e752f26a37f85ca2bec74470b40 | mon0theist/Automate-The-Boring-Stuff | /Chapter 04/commaCode2.py | 1,183 | 4.375 | 4 | # Ch 4 Practice Project - Comma Code
# second attempt
#
# Say you have a list value like this:
# spam = ['apples', 'bananas', 'tofu', 'cats']
#
# Write a function that takes a list value as an argument and returns a string
# with all the items separated by a comma and a space, with and inserted before
# the last item. For example, passing the previous spam list to the function
# would return 'apples, bananas, tofu, and cats'. But your function should be
# able to work with any list value passed to it.
#
# Couldn't figure this out on my own, had to look at the solution from my last attempt,
# which I'm also pretty sure I didn't figure out on my own, pretty sure I
# copy+pasted from somewhere
#
# I can read it and understand why it works, but writing it from scratch is a whole
# different thing :'(
def commaList(listValue):
counter = 0
newString = ''
while counter < len(listValue)-1:
newString += str(listValue[counter]) + ', '
counter += 1
print(newString + 'and ' + str(listValue[counter])) # print for testing
return newString + 'and ' + str(listValue[counter])
spamList = ['apples', 'bananas', 'tofu', 'cats']
commaList(spamList)
|
e8e5b4e8b4fde7a877ee26d8a064985293531427 | mon0theist/Automate-The-Boring-Stuff | /Chapter 05/fantasyGameInventory_l2d2.py | 1,119 | 3.796875 | 4 | # ATBS Chatper 5 Practice Project - Fantasy Game Inventory List to Dictionary
# 2nd attempt for revision/review
# No looking at past solutions!
#
# Some of the code is already given in the problem, just need to fill it in
# Display Inventory function from previous exercise
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
# FILL IN THE CODE HERE
print(v, k)
item_total += v
print("Total number of items: " + str(item_total))
# new Add To Inventory function
def addToInventory(inventory, addedItems):
# your code goes here
# check to see if "new" item exists in inventory - .get() method?
# or maybe .setdefault()
# if it does, increment by 1
# if it doesn't, create it and set to 1
for i in range(len(addedItems)):
inv.setdefault(addedItems[i], 0)
item_added = addedItems[i]
inv[item_added] += 1
return inv
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
|
3c2f7e0a16640fdb7e72795f10824fcce5370199 | mon0theist/Automate-The-Boring-Stuff | /Chapter 07/strongPassword.py | 1,249 | 4.375 | 4 | #! /usr/bin/python3
# ATBS Chapter 7 Practice Project
# Strong Password Detection
# Write a function that uses regular expressions to make sure the password
# string it is passed is strong.
# A strong password has:
# at least 8 chars - .{8,}
# both uppercase and lowercase chars - [a-zA-Z]
# test that BOTH exist, not just simply re.IGNORECASE
# at least one digit - \d+
# You may need to test the string against multiple regex patterns to validate its strength.
# NOTES
# Order shouldn't matter, & operator?
# Test: if regex search/findall != None
# seperate Regex for reach requirement?
import re
def pwStrength(pw):
if eightChars.search(pw) and oneUpper.search(pw) and oneLower.search(pw) and oneDigit.search(pw) != None:
print('Your password meets the requirements.')
else:
print('Your password does not meet the requirements.')
eightChars = re.compile(r'.{8,}') # tests for 8 or more chars
oneUpper = re.compile(r'[A-Z]+') # test for 1+ upper
oneLower = re.compile(r'[a-z]+') # test for 1+ lower
oneDigit = re.compile(r'\d+') # test for 1+ digit
# Wanted to combine all into single Regex if possible but can't figure it out
password = input('Please enter the password you want to test: ')
pwStrength(password)
|
c3450d7b24260189e3599c6e79f11d00e7636b60 | mon0theist/Automate-The-Boring-Stuff | /Chapter 10/debugging_coin_toss.py | 1,773 | 4.09375 | 4 | #!/usr/bin/python
# ATBS Chapter 10
# The following program is meant to be a simple coin toss guessing game. The
# player gets two guesses (it’s an easy game). However, the program has several
# bugs in it. Run through the program a few times to find the bugs that keep the
# program from working correctly.
# I didn't really use the debugging tools, just ran the program a couple times
# and then started looking at the code and fixing it
# import needed modules
import random, logging, traceback
# set logging level (copied from Chapter 10 example_)
logging.basicConfig(level = logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# disables logging, comment out the following line to re-enable debugging
logging.disable(logging.CRITICAL)
# commented out = logging/debugging ENABLED
# debug start
logging.debug('Start of program')
def guess():
guess = ''
while guess != 'heads' and guess != 'tails' and guess != 'h' and guess != 't':
guess = str.lower(input('Guess the coin toss! Enter (h)eads or (t)ails: '))
if guess == 'h':
guess = 'heads'
elif guess == 't':
guess = 'tails'
return guess
def toss():
toss = random.randint(0, 1) # 0 is tails, 1 is heads
if toss == 0:
toss = 'tails'
elif toss == 1:
toss = 'heads'
return toss
def check():
tries = 2
user_guess = guess()
tries = tries - 1
coin_toss = toss()
while tries > 0:
if user_guess == coin_toss:
print('You got it!')
break
elif user_guess != coin_toss:
print('Nope! Guess again!')
tries = tries - 1
user_guess = guess()
if tries == 0:
print('Nope. There are only 2 choices...')
check()
|
9705306602423b9133baac671d04659de2336df9 | aaron22/ProjectEuler | /src/Problem3.py | 498 | 3.9375 | 4 | '''
Created on Apr 6, 2011
@author: aaron
'''
def solve():
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
num = 600851475143
# take care of 2; it's a special case
while (num % 2 == 0):
num /= 2
for i in range(3,600851475143,2):
while (num % i == 0):
num /= i
if num == 1:
return i
if __name__ == '__main__':
print(solve()) |
bda60753962f59bf11041338b0dfca3b0242d079 | dnlsyfq/py_centos | /pay_analysis.py | 524 | 3.5 | 4 | from csv import DictReader
employee_info = []
with open("employees.csv", newline="") as f:
reader = DictReader(f)
for row in reader:
row["age"] = int(row["age"])
row["salary"] = float(row["salary"])
employee_info.append(row)
# Example dictionary in employee_info
# {
# "id": "10",
# "first_name": "Marie-ann",
# "last_name": "Cargo",
# "email": "Marie-ann.Cargo@example.com",
# "gender": "Female",
# "age": 68,
# "salary": 54000.0,
# "job_title": "Human Resources Manager",
# }
|
7df5fbc8f66813f75584f8410da004809e37fcf9 | whobbes/l_systems | /solution/l_systems_solution.py | 2,948 | 3.96875 | 4 | import turtle
import random as rd
class L_systemDrawer():
'''Provide ways to build a L-system and draw it with a turtle'''
def __init__(self, instructions='F-G-G', iterations=5, distance=10, angle=120):
self.t = turtle.Turtle()
self.wn = turtle.Screen()
self.instructions = instructions
self.iterations = iterations
self.distance = distance
self.angle = angle
self._iterate_instructions()
self.t.pencolor((rd.random(), rd.random(), rd.random()))
self.t.speed('fastest')
self.t.shape("turtle")
def _iterate_instructions(self):
for _ in range(self.iterations):
next_instructions = ''
for instruction in self.instructions:
if instruction == 'F':
next_instructions += 'F-G+F+G-F'
elif instruction == 'G':
next_instructions += 'GG'
elif instruction == 'A':
next_instructions += 'B-A-B'
elif instruction == 'B':
next_instructions += 'A+B+A'
elif instruction == '1':
next_instructions += '1+2-11+1+11+12+11-2+11-1-11-12-111'
elif instruction == '2':
next_instructions += '222222'
if instruction == '3':
next_instructions += '3+3-3-3+3'
else:
next_instructions += instruction
self.instructions = next_instructions
print(self.instructions)
def draw(self):
for instruction in self.instructions:
self.t.pencolor((rd.random(), rd.random(), rd.random()))
if (instruction == 'F'
or instruction =='G'
or instruction =='A'
or instruction =='B'
or instruction =='1'
or instruction == '3'):
self.t.pendown()
self.t.forward(self.distance)
elif instruction == '-':
self.t.left(self.angle)
elif instruction == '+':
self.t.right(self.angle)
elif instruction == '2':
self.t.penup()
self.t.forward(self.distance)
def finish_and_wait(self):
self.t.up()
self.t.forward(100)
self.t.pencolor((0, 0.5, 0.5))
self.t.write("Job done :) ", True, font=("Arial", 24, "normal"))
self.wn.exitonclick() # keep window open until user click or close it
if __name__ == "__main__":
#l_sys = L_systemDrawer() # Task 1, 2, 3
#l_sys = L_systemDrawer(instructions='A', iterations=5, angle=60, distance=10) # Task 4
l_sys = L_systemDrawer(instructions='-3', iterations=3, angle=90, distance=15) # Optional Task
#l_sys = L_systemDrawer(instructions='1-1-1-1', iterations=2, angle=90, distance=10) # Task Z: Islands!
l_sys.draw()
l_sys.finish_and_wait() |
e444ca6c4052246efa10b95d11c61ee32ad8f33f | RiyaSingh15/data-structure | /array/maximum_sum(i x arr[i]).py | 829 | 3.65625 | 4 | # Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
class sum_maximum:
def __init__(self):
self.array_input()
def array_input(self):
length = int(input("Enter the number of elements: "))
input_array = []
for i in range(0, length):
input_array.append(int(input("Enter element into array: ")))
print("Input array: ", input_array)
self.maximum_sum(input_array)
def maximum_sum(self, array):
sum_array = []
for i in range(0, len(array)):
total = 0
for j in range(0, len(array)):
total = total + j * array[j]
sum_array.append(total)
array.insert(0, array.pop(len(array)-1))
print("Maximum sum we can get = ", max(sum_array))
sum_maximum()
|
589a0295445328ed89c44450ae9ff3066bd7c159 | RiyaSingh15/data-structure | /array/rearrange_positive_negative_alternatively.py | 1,451 | 4.09375 | 4 | # Rearrange array in alternating positive & negative items
class rearrange_positive_negative_alternatively:
def __init__(self):
self.array_input()
def array_input(self):
length = int(input("Enter number of elements in the array: "))
input_array = []
for i in range(length):
input_array.append(int(input("Enter element into array: ")))
print("Input array= ", input_array)
print("Output array= ", self.array_reposition(input_array))
def array_reposition(self, array):
sorted_array = sorted(array)
output_array = []
if(len(sorted_array) % 2 != 0):
first_half = sorted_array[0: int(len(sorted_array)/2)+1]
second_half = sorted_array[int(
len(sorted_array)/2)+1: len(sorted_array)]
for i in range(int(len(sorted_array)/2)):
output_array.append(first_half[i])
output_array.append(second_half[i])
output_array.append(first_half[len(first_half)-1])
else:
first_half = sorted_array[0: int(len(sorted_array)/2)]
second_half = sorted_array[int(
len(sorted_array)/2): len(sorted_array)]
for i in range(int(len(sorted_array)/2)):
output_array.append(first_half[i])
output_array.append(second_half[i])
return output_array
rearrange_positive_negative_alternatively()
|
b3d152ca85b7cf29fa67753bcf587cad14a9911b | iguyking/adventofcode | /2020/day4/others/aoc2040.py | 1,792 | 3.59375 | 4 | import re
#check ranges if they apply to a field
#expect the ruleset in either one of these two formats:
# cm:150-193,in:59-76
# 1920-2002
def check_ranges(ranges,data):
if ":" in ranges: #determine range to use if there are multiple units
ranges=dict([x.split(":") for x in ranges.split(",")])[re.search("(\D+)",data).group()]
num=int(re.search("(\d+)",data).group())
(min,max)=ranges.split("-")
return int(min)<=num<=int(max)
#print(check_ranges2("99-150","1111"))
#print(check_ranges2("cm:150-193,in:59-76","66cm"))
#given a ruleset, a rule name and a person(as dict) check the rule
def check_rule(rs,rule,data):
if(rule in data):#see if the field exists in the passport data
if(re.search("^"+rs[rule][0]+"$",data[rule])): #regex validation
if len(rs[rule]) > 1: #check range if at a range rule exists
return check_ranges(rs[rule][1],data[rule])
else:
return True #regex passed and there is no range check
else:
return False #rule failed because no field exists in the passport
#given a ruleset and text related to a person, check the passport
#expect mulitline input
def is_passport_valid(person,ruleset):
fields=dict([x.split(":") for x in re.split("\n| ",person.rstrip())])
return all(check_rule(ruleset,rule,fields) for rule in ruleset)
#read in the ruleset and a batch of passports
#calls is_valid function for each passport
def count_valid_passports(input_file,ruleset_file):
ruleset = dict([ [re.split(" ",x)[0],re.split(" ",x)[1:]] for x in open(ruleset_file,"r").read().splitlines()])
return sum([1 for p in open(input_file,"r").read().split("\n\n") if is_passport_valid(p,ruleset)])
print(count_valid_passports("input.txt","rules.txt"))
|
6250b682331f1f64e54494d173e54aa53780a21a | ZYSLLZYSLL/Python | /代码/code/day14/Demo02_time.py | 1,209 | 3.59375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/19 15:01
# @Author : ZY
# @File : Demo02_time.py
# @Project : code
import time
# 时间戳
a = time.time()
print(a)
# 结构化时间 东八区时间(北京时间)
c = time.localtime()
print(c)
# UTC时间,国际时间,和北京时间差八个小时
d = time.gmtime()
print(d)
# 格式化时间 结构转格式
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# 格式转结构
print(time.strptime("2021-01-19 15:12:44", "%Y-%m-%d %H:%M:%S"))
# 结构转时间戳
print(time.mktime(time.localtime()))
# 系统强制休眠
# for i in range(10):
# print(i)
# time.sleep(2)
# 需求:计算从出生到现在经过了多少秒
# 1,先算出出生时间的时间戳
aa = time.strptime("1998-08-09 00:00:00", "%Y-%m-%d %H:%M:%S")
aa1 = time.strptime("2000-01-14 00:00:00", "%Y-%m-%d %H:%M:%S")
dd = time.mktime(aa)
dd1 = time.mktime(aa1)
# 2,算出当前时间戳
bb = time.time()
# 3,求差
print(f'宝宝出生了 {bb - dd} 秒')
print(f'周宇出生了 {bb - dd1} 秒')
print(f'宝宝比我大了 {(bb - dd)-(bb - dd1)} 秒\n{((bb - dd)-(bb - dd1))/86400} 天\n{(((bb - dd)-(bb - dd1))/86400)/365} 年')
|
d19ad2bd766829f6cd179101b3615d8ede6425a7 | ZYSLLZYSLL/Python | /代码/code/eg/一行代码计算1到100的和.py | 265 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/27 9:05
# @Author : ZY
# @File : 一行代码计算1到100的和.py
# @Project : code
print(sum([i for i in range(1, 101)]))
print((lambda i: sum(i))(i for i in range(1, 101)))
print(sum(range(1, 101)))
|
f950540f7fd7e20c033f7b562a41156f5c43a1f2 | ZYSLLZYSLL/Python | /代码/code/day06/Demo07_列表常用操作_修改_复制.py | 1,104 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/11 15:35
# @Author : ZY
# @File : Demo07_列表常用操作_修改_复制.py
# @Project : code
# 修改指定位置的数据
# a = [1, [1, 2, 3], 1.23, 'abc']
# a[1] = '周宇'
# print(a)
# 逆置:reverse()
# a = [1, [1, 2, 3], 1.23, 'abc']
# a.reverse()
# print(a)
# # print(a[::-1])
# 排序 sort() 默认升序
# a = [1, 3, 5, 8, 0, 3]
# a.sort()
# print(a)
# 降序
# a = [1, 3, 5, 8, 0, 3]
# a.sort(reverse = True)
# print(a)
# copy() 复制,浅复制
# a = [1, [1, 2, 3], 1.23, 'abc']
# b = a.copy()
# print(b)
# print(id(a[1]))
# print(id(b[1]))
# print(id(a[0]))
# print(id(b[0]))
# 二维数组
# a = [1, [1, 2, 3], 1.23, 'abc']
# print(a[1][2])
# 深复制:
# from copy import deepcopy
# a = [1, [1, 2, 3], 1.23, 'abc']
# b = deepcopy(a)
# print(id(a[1]))
# print(id(b[1]))
# print(id(a[0]))
# print(id(b[0]))
a = [1, [1, 2, 3], 1.23, 'abc']
b = a.copy()
b[1] = a[1].copy()
print(id(a[1]))
print(id(b[1]))
print(id(a))
print(id(b))
'''
浅复制:对于可变类型没有完全复制
深复制:全部复制
'''
|
88e3452998a093ef0737ee0aed0c8c41861411dc | ZYSLLZYSLL/Python | /代码/code/eg/Demo12_.py | 4,627 | 3.640625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/13 14:45
# @Author : ZY
# @File : Demo12_.py
# @Project : code
"""
需求:进入系统显示系统功能页面,功能如下:
添加学员
删除学员
修改学员信息
查询学员信息
显示所有学员信息
退出系统
系统共6个功能,用户根据自己需求选取。
步骤分析
1.显示功能界面
2.用户输入功能序号
3.根据用户输入的功能序号,执行不同的功能(函数)
3.1 定义函数
3.2 调用函数
"""
change_name = '' # 修改学员信息时用到的
a = '' # 命令界面使用
xinXi = []
def inIt():
global a
print('\n\n')
print('*-' * 50, '-')
print(' ' * 30, end='')
print('---欢迎登陆博文智生2011届学员管理系统---\n')
print(' ' * 40, end='')
print('1:添加学员')
print(' ' * 40, end='')
print('2:删除学员')
print(' ' * 40, end='')
print('3:修改学员信息')
print(' ' * 40, end='')
print('4:查询学员信息')
print(' ' * 40, end='')
print('5:显示所有学员信息')
print(' ' * 40, end='')
print('6:退出系统')
a = input('请输入对应的序号来选择你要操作的功能:')
print('-')
def no1():
"""本函数添加学员的基本信息"""
add_name = input('请输入姓名:')
add_gender = input('请输入性别:')
add_age = input('请输入年龄:')
global xinXi
for i in xinXi:
if add_name == i['name']:
print(f' {add_name} 学员的信息已经存在,请勿重新添加')
return
add_xin_xi = {}
add_xin_xi['name'] = add_name
add_xin_xi['gender'] = add_gender
add_xin_xi['age'] = add_age
xinXi.append(add_xin_xi)
print(f'成功添加 {add_name} 学员的信息')
print(xinXi)
def no2():
"""本函数删除学员的基本信息"""
del_name = input('请输入你要删除学员的姓名:')
for j in xinXi:
if del_name == j['name']:
print(f"{del_name} 学员信息为:{j}")
for i in xinXi:
if del_name == i['name']:
xinXi.remove(i)
print(f'成功删除 {del_name} 学员的信息')
print(xinXi)
return
else:
print(f"{del_name} 学员不存在,请确认后再删除")
def change():
global change_name
change_name = input('请输入你要修改学员的姓名:')
project = input('请输入你要修改学员的那一部分信息(name,gender,age):')
change_value = input('请输入你要修改的新内容:')
for i in xinXi:
if change_name == i['name']:
i[project] = change_value
def no3():
"""本函数修改学员的基本信息"""
global change_name
change_name = input('请输入你要修改学员的姓名:')
for i in xinXi:
if change_name == i['name']:
print(f"{change_name} 学员信息为:{i}")
a = input('您是要修改几个内容呢?(1,2,3)')
if a == '1':
change()
elif a == '2':
change()
change()
elif a == '3':
print('修改三个信息你不会删除重新添加啊,啥也不是')
if a != '3':
print(f'成功修改 {change_name} 学员的信息')
print(xinXi)
return
else:
print(f"{change_name} 学员不存在,请确认后再修改")
def no4():
"""本函数查询学员的基本信息"""
Inquire_name = input('请输入你要修改学员的姓名:')
for i in xinXi:
if Inquire_name == i['name']:
print(f"{Inquire_name} 学员信息为:{i}")
return
else:
print(f"{Inquire_name} 学员不存在,请确认后再查询")
def no5():
"""本函数显示所有学员的基本信息"""
print('name', ' gender', ' age')
for k in range(len(xinXi)):
print(xinXi[k]['name'], end='\t\t')
print(xinXi[k]['gender'], end='\t\t')
print(xinXi[k]['age'], end='\t\t\n')
def student():
while True:
global a
inIt()
if a == '1':
no1()
elif a == '2':
no2()
elif a == '3':
no3()
elif a == '4':
no4()
elif a == '5':
no5()
elif a == '6':
a = input('您确定退出程序吗?(Y/N)')
if a == 'Y' or a == 'y':
break
|
73eb8edd0464520f902279c952bc1949343722c7 | ZYSLLZYSLL/Python | /代码/code/day18/111.py | 238 | 3.734375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/29 13:19
# @Author : ZY
# @File : 111.py
# @Project : code
s = '*'
for i in range(1, 8, 2):
print((s * i).center(7))
for i in range(5, 0, -2):
print((s * i).center(7))
|
e6d51bc9001f005cd5e3868d990f300f720ac019 | ZYSLLZYSLL/Python | /代码/code/day06/Demo02_列表.py | 504 | 3.9375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/11 10:23
# @Author : ZY
# @File : Demo02_列表.py
# @Project : code
"""
列表(list,数组):以中括号为边界,以逗号隔开的数据(各种类型)
特点:
1,有序的
2,可变的
3,支持索引
4,支持切片
"""
a = [1, True, None, [1, 2, 3], 'abc', (1, 2, 3), {'a': 1}, {1, 2, 3}, 1.23]
for i in a:
print(f'{type(i)}-->{i}')
# 索引
print(a[3])
# 切片
print(a[::-1])
|
e742395c74a60bfbf6bb75fe3fbb72ae989c573b | ZYSLLZYSLL/Python | /代码/code/eg/Demo03_质数之和.py | 863 | 3.625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/11 19:02
# @Author : ZY
# @File : Demo03_质数之和.py
# @Project : code
# 质数之和 质数 只能被自己和1整除的数叫质数 ts:2 3 5 7 11 13 17
# for
a = 0
b = 0
for i in range(2, 101):
for j in range(2, i):
if i % j == 0:
a = 1
if a == 0:
b += i
else:
a = 0
print('for_100以内所有质数的和为', b)
print('-' * 100)
# while
a = b = 0
i = 1
while i < 100:
i += 1
j = 2
while j < i:
if i % j == 0:
a = 1
j += 1
if a == 0:
b += i
else:
a = 0
print('while_100以内所有质数的和为', b)
b = 0
for i in range(2, 101):
for j in range(2, i):
if i % j == 0:
break
else:
b += i
print('for_100以内所有质数的和为', b)
|
a9b80c05ba415f16cb1c0e92baec6cca38860dc2 | ZYSLLZYSLL/Python | /代码/code/eg/Demo06_判断三角形.py | 1,157 | 3.96875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/11 19:23
# @Author : ZY
# @File : Demo06_判断三角形.py
# @Project : code
# 需求:根据边判断三角形,直角,锐角,钝角
# a = int(input('请输入三角形的第一条边:'))
# b = int(input('请输入三角形的第二条边:'))
# c = int(input('请输入三角形的第三条边:'))
#
# if c < a:
# a,c = c,a
# if c < b:
# a,b = b,a
# if b < a:
# a,b = b,a
#
# if a + b <= c:
# print('啥都不是')
# else:
# if (a ** 2 + b ** 2) == (c ** 2):
# print('直角三角形')
# elif (a ** 2 + b ** 2) < (c ** 2):
# print('钝角三角形')
# else:
# print('锐角三角形')
z = input("请输入三角形三边长,数据用逗号','(英文)隔开:")
z = z.split(',')
a = int(z[0])
b = int(z[1])
c = int(z[2])
if c < a:
a, c = c, a
if c < b:
a, b = b, a
if b < a:
a, b = b, a
if a + b <= c:
print('啥都不是')
else:
if (a ** 2 + b ** 2) == (c ** 2):
print('直角三角形')
elif (a ** 2 + b ** 2) < (c ** 2):
print('钝角三角形')
else:
print('锐角三角形')
|
6dd3477022671fa8652ca9626a92b55496543767 | ZYSLLZYSLL/Python | /代码/code/day08/Demo07_文件操作_读_写.py | 1,939 | 3.78125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/13 15:25
# @Author : ZY
# @File : Demo07_文件操作_读_写.py
# @Project : code
"""
写入文件
"""
# encoding 可以把文件类型变成utf-8
# a = open("a.txt", "w", encoding="utf_8") # 打开文件设置权限
# a.write('hello world\n') # 默认不会换行 写入文件内容
# a.write('hello world\n')
# a.write('hello world\n')
# a.write('周宇\n')
# a.close() # 关闭并保存文件
# 需求:将数字1-100写入文档中,并换行
# a = open("a.txt", "w", encoding="utf_8")
# for i in range(101):
# a.write(f'{i}\n')
# a.close()
# 需求:99乘法表写入文档中
# a = open('a.txt', 'w', encoding='utf-8')
# for i in range(1, 10):
# for j in range(1, i + 1):
# a.write(f'{j}*{i}={j * i}\t')
# a.write('\n')
# a.close()
"""
读
"""
# 读文件,相对路径
# f = open('a.txt', 'r', encoding='utf-8')
# print(f.read())
# f.close()
# 读文件,觉对路径
# f = open('E:\\新\\软件测试\\5.第五阶段\\代码\\code\\day08\\a.txt', 'r', encoding='utf-8')
# print(f.read())
# f.close()
# 读文件,将特殊字符变为原生字符串 r""
# f = open(r'E:\新\软件测试\5.第五阶段\代码\code\day08\a.txt', 'r', encoding='utf-8')
# # f.read() 将文件中所有内容以字符串的形式读出来
# print(f.read())
# # f.readline() 将文件中所有内容以列表的形式读出来
# print(f.readline())
# # f.readline() 以字符串读出一行内容
# print(f.readline())
# f.close()
# 需求:统计文件中含有#开头的行和空行总共有多少行
count = 0
a = open('a.txt', 'r', encoding='utf-8')
for i in a.readlines():
if i.startswith('#') or i == '\n':
count += 1
print(count)
a.close()
count = 0
a = open('a.txt', 'r', encoding='utf-8')
b = a.readlines()
for i in range(len(b)):
if b[i].startswith('#') or b[i] == '\n':
count += 1
print(count)
a.close()
|
33b4d7d80b3701c9593c590d65a327ff69a002a4 | ZYSLLZYSLL/Python | /代码/hei_ma/Demo07_while...else.py | 601 | 3.84375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/8 19:48
# @Author : ZY
# @File : Demo07_while...else.py
# @Project : code
# i = 0
# while i < 5:
# i += 1
# print("hello world")
# else:
# print("输出五次了")
# while不正常结束时,else里的内容不执行
i = 0
while i < 5:
i += 1
if i == 3:
break
print("hello world")
else:
print("输出五次了")
print("*"*20)
# while正常结束时,else里的内容执行
i = 0
while i < 5:
i += 1
if i == 3:
continue
print("hello world")
else:
print("输出五次了")
|
8c0310c63b76fb2d8bdc439201e66a22273f4077 | ZYSLLZYSLL/Python | /代码/hei_ma/Demo05_while应用.py | 473 | 3.671875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/7 16:41
# @Author : ZY
# @File : Demo05_while应用.py
# @Project : code
# 需求:1-100 累加和
i = 0
count = 1
while count <= 100:
i += count
count += 1
print(i)
# 1-100里偶数的累加和,即2+4+6+8……,
i = 0
count = 1
while count <= 100:
if count % 2 == 0:
i += count
count += 1
print(i)
i = 0
count = 2
while count <= 100:
i += count
count += 2
print(i)
|
c0a45d0c65e6eb7b403a299b0cf6086e13bab296 | ZYSLLZYSLL/Python | /代码/code/day11/Demo06_类属性和类方法.py | 871 | 4.09375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/16 16:02
# @Author : ZY
# @File : Demo06_类属性和类方法.py
# @Project : code
"""
类属性
"""
# class A():
# # 类属性
# name = 'A'
#
# # 成员属性
# def __init__(self):
# self.age = 23
#
# def printInfo(self):
# print(A.name)
#
#
# a = A()
# print(a.age)
# a.name = '周宇'
# print(a.name)
# A.name = '博文'
# print(A.name)
#
# b = A()
# print(b.age)
# # b.name = '周宇'
# print(b.name)
# # A.name = '博文'
# print(A.name)
# b.printInfo()
"""
类方法
"""
class A():
# 类属性
name = 'A'
# 成员属性
def __init__(self):
self.age = 23
def printInfo(self):
print(A.name)
# 类方法
@classmethod
def a(cls):
print(cls.name)
print('类方法')
a = A()
a.a()
A.a()
b = A()
b.a()
|
9817da4716a09b2aef31e84d4db409d06f03a02d | ZYSLLZYSLL/Python | /代码/code/day10/Demo06_搬家具.py | 1,109 | 3.9375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/1/15 17:37
# @Author : ZY
# @File : Demo06_搬家具.py
# @Project : code
# 房子类
class House():
def __init__(self, addr, area):
self.addr = addr
self.area = area
self.free = self.area
self.funcList = []
def __str__(self):
result = f"当前位置:{self.addr}\n"
result += f"总面积:{self.area}平方米\n"
result += f"剩余面积:{self.free}平方米\n"
b = ""
if len(self.funcList) == 0:
b = "无"
else:
b = ','.join(self.funcList)
result += f"当前房子家具列表:{b}\n"
return result
def banJiaJu(self, fo):
c = fo.area
if c > self.free or c < 0:
print("剩余面积不够了或输入错误")
else:
self.free -= c
self.funcList.append(fo.name)
# 家具类
class Func():
def __init__(self, name, area):
self.name = name
self.area = area
h = House("北京", 120)
bed = Func("床", 10)
h.banJiaJu(bed)
print(h)
|
19803babdb60c45644620079e296c27bdc014815 | petcsclub/python-projects | /battleship/battleship_single.py | 14,232 | 3.796875 | 4 | # imports
from random import randint, choice
from operator import add, mul
from time import sleep
def setPlayerShips(shipNames, shipLength, playerShipAliveCoords, playerGrid, directionMap):
'''Get and set the ship placements of the player'''
print('Set the position of your ships!')
printGrid(playerGrid, True)
# Loops through ships
for i in range(len(shipNames)):
while True:
print('Set the position of your ' +
shipNames[i] + ' of length ' + str(shipLength[i]) + '.')
# Get start coordinate and check validity
start = input('Coordinate for the start of your ' +
shipNames[i] + '? ')
startCoords = convert(start)
if startCoords is None:
print(
'Invalid input. Examples of proper coordinates: a0, B9, c2. Please try again.')
continue
# Get direction
direction = input('Direction for your ' +
shipNames[i] + '? ([w/a/s/d] for up, left, down, right) ')
if direction not in ['w', 'a', 's', 'd']:
print(
"Invalid input. Please enter either 'w', 'a', 's', or 'd'. Please try again.")
continue
# Adds appropriate direction to startCoords to get endCoords
endCoords = tuple(
map(add, startCoords, tuple(map(mul, directionMap[direction], (shipLength[i]-1, shipLength[i]-1)))))
# Ensures endCoords is in the grid
if endCoords[0] < 0 or endCoords[0] > 9 or endCoords[1] < 0 or endCoords[1] > 9:
print('Ship is out of bounds. Please try again.')
continue
# Check validity of ship placement
if checkShipPlacement(startCoords, endCoords, i, playerShipAliveCoords, playerGrid):
printGrid(playerGrid, True)
break
else:
print('Ships cannot intersect. Please try again.')
continue
print("Ships successfully set!")
sleep(2)
print("--------------------------------------------------")
print("START GAME\n")
sleep(2)
def setComputerShips(shipNames, shipLength, computerShipAliveCoords):
'''Set the ship placements of the computer'''
# Loops through ships
for i in range(len(shipNames)):
while True:
# Get random start coordinate
startCoords = (randint(0, 9), randint(0, 9))
# Get random end coordinate from start coordinate to ensure proper ship length
endCoords = tuple(map(add, startCoords, choice(
[(0, shipLength[i]-1), (shipLength[i]-1, 0)])))
# Ensure end coordinate is on the grid
if endCoords[0] < 0 or endCoords[0] > 9 or endCoords[1] < 0 or endCoords[1] > 9:
continue
# Check validity of ship placement
if checkShipPlacement(startCoords, endCoords, i, computerShipAliveCoords):
break
else:
continue
def playerTurn(shipNames, computerGrid, computerShipsAlive, computerShipAliveCoords, computerShipSunkCoords):
'''Execute player turn'''
print("YOUR TURN!")
printGrid(computerGrid, False)
sunkShip = False
# Player input and logic
while True:
# Get attack coordinate and check validity
attack = input('Coordinate for your attack this turn? ')
attackCoords = convert(attack)
if attackCoords is None:
print(
'Invalid input. Examples of proper coordinates: a0, B9, c2. Please try again.')
continue
elif computerGrid[attackCoords[0]][attackCoords[1]] != ' ':
print('You have already attacked this coordinate. Please try again.')
continue
# Check if attack hit a ship and update grid
shipIndex = hitShip(attackCoords, computerShipAliveCoords)
if shipIndex == -1:
print("Miss!")
computerGrid[attackCoords[0]][attackCoords[1]] = '-'
break
else:
print("Hit!")
computerGrid[attackCoords[0]][attackCoords[1]] = 'o'
# Remove attack coordinate from alive set to sunk set
computerShipAliveCoords[shipIndex].remove(attackCoords)
computerShipSunkCoords[shipIndex].add(attackCoords)
# Check if alive set is empty (meaning ship is sunk)
if len(computerShipAliveCoords[shipIndex]) == 0:
sunkShip = True
print("You have sunk the computer's " +
shipNames[shipIndex] + "!")
computerShipsAlive -= 1
for coords in computerShipSunkCoords[shipIndex]:
computerGrid[coords[0]][coords[1]] = 'x'
break
# Print grid again if ship was sunk
if sunkShip:
printGrid(computerGrid, False)
print("END TURN!")
print("--------------------------------------------------")
if sunkShip:
sleep(3)
sleep(2)
return computerShipsAlive
def computerTurn(shipNames, playerGrid, playerShipsAlive, playerShipAliveCoords, playerShipSunkCoords, computerAvailableAttacks):
'''Execute computer turn'''
print("COMPUTER TURN!")
printGrid(playerGrid, True)
sleep(2)
# Get random attack coordinate from available attacks set
attackCoords = choice(tuple(computerAvailableAttacks))
computerAvailableAttacks.remove(attackCoords)
sunkShip = False
print('The computer attacked coordinate ' +
chr(attackCoords[0]+65) + str(attackCoords[1]) + '.')
shipIndex = hitShip(attackCoords, playerShipAliveCoords)
# Check if attack hit a ship and update grid
if shipIndex == -1:
print("Miss!")
playerGrid[attackCoords[0]][attackCoords[1]] = '-'
else:
print("Hit!")
playerGrid[attackCoords[0]][attackCoords[1]] = 'o'
# Remove attack coordinate from alive set to sunk set
playerShipAliveCoords[shipIndex].remove(attackCoords)
playerShipSunkCoords[shipIndex].add(attackCoords)
# Check if alive set is empty (meaning ship is sunk)
if len(playerShipAliveCoords[shipIndex]) == 0:
sunkShip = True
print("The computer sunk your " +
shipNames[shipIndex] + "!")
playerShipsAlive -= 1
for coords in playerShipSunkCoords[shipIndex]:
playerGrid[coords[0]][coords[1]] = 'x'
# Print grid again if ship was sunk
if sunkShip:
printGrid(playerGrid, True)
print("END TURN!")
print("--------------------------------------------------")
if sunkShip:
sleep(3)
sleep(2)
return playerShipsAlive
def printGrid(grid, isPlayerGrid):
'''Print the specified grid'''
# Set title based on isPlayerGrid
if isPlayerGrid:
print("\n YOUR SHIPS")
else:
print("\n YOUR ATTACKS")
# Print grid
for i in range(-1, 10):
for j in range(-1, 10):
# Print first row of letters
if i == -1:
if j == -1:
print(" ", end=" ")
elif j == 9:
print(j)
else:
print(j, end=" ")
else:
# Print first column on numbers
if j == -1:
print(chr(i+65), end=" ")
# Print grid
elif j == 9:
print(grid[i][j])
else:
print(grid[i][j], end=" ")
print("Legend: ' ' = empty | '-' = miss | 'o' = hit | 'x' = sunk | 's' = ship\nNote: you cannot see the position of the computer's ships until the game is finished\n")
def checkShipPlacement(startCoords, endCoords, shipIndex, shipCoords, grid=None):
'''Check validity of ship placement and return True if placement is valid, false if not'''
# Check validity
if startCoords[0] == endCoords[0]:
# first coordinate is the same
if startCoords[1] > endCoords[1]:
startCoords, endCoords = endCoords, startCoords
# check validity to ensure coordinate doesn't already contain another ship
for i in range(startCoords[1], endCoords[1]+1):
if hitShip((startCoords[0], i), shipCoords, shipIndex) >= 0:
return False
# input ships and add to set
for i in range(startCoords[1], endCoords[1]+1):
shipCoords[shipIndex].add((startCoords[0], i))
# Print grid if specified (from player)
if grid != None:
grid[startCoords[0]][i] = 's'
return True
else:
# second coordinate is the same
if startCoords[0] > endCoords[0]:
startCoords, endCoords = endCoords, startCoords
# check validity to ensure coordinate doesn't already contain another ship
for i in range(startCoords[0], endCoords[0]+1):
if hitShip((i, startCoords[1]), shipCoords, shipIndex) >= 0:
return False
# input ships and add to set
for i in range(startCoords[0], endCoords[0]+1):
shipCoords[shipIndex].add((i, startCoords[1]))
# Print grid if specified (from player)
if grid != None:
grid[i][startCoords[1]] = 's'
return True
def convert(coords):
'''Convert coords in the correct form to the 2D array coordinates'''
# Check correct length
if len(coords) == 2:
# Convert to ASCII
first = ord(coords[0].upper())
second = ord(coords[1])
# Check validity of coordinates
firstValid = first >= 65 and first <= 74
secondValid = second >= 48 and second <= 57
if firstValid and secondValid:
# Return appropriate tuple
return(first-65, second-48)
def hitShip(coords, shipCoords, shipIndex=5):
'''Check if coordinate intersects with existing ship, and return the index of the ship if it does. If not, return -1'''
# Loop through ships
for i in range(shipIndex):
# Check if coordinate is in the set for specified ship
if coords in shipCoords[i]:
return i
return -1
def runBattleshipSingle():
'''Overarching game loop'''
# Declare const variables
shipNames = ['Carrier', 'Battleship', 'Cruiser', 'Submarine', 'Destroyer']
shipLength = [5, 4, 3, 3, 2]
directionMap = {
'w': (-1, 0),
'a': (0, -1),
's': (1, 0),
'd': (0, 1),
}
# Full game loop
while True:
# player view of player's grid, initialize with 10x10 grid of ' '
playerGrid = [[' ' for i in range(10)] for j in range(10)]
# player view of computer's grid, initialize with 10x10 grid of ' '
computerGrid = [[' ' for i in range(10)] for j in range(10)]
# Keep track of ships alive for player and computer to determine when to end the game
playerShipsAlive = 5
computerShipsAlive = 5
gameLength = 0
# Track coordinates for ships alive and sunk for both player and computer in order to update char from 'o' to 'x' when the entire ship is sunk. Each index represents 1 ship.
playerShipAliveCoords = [set() for i in range(5)]
playerShipSunkCoords = [set() for i in range(5)]
computerShipAliveCoords = [set() for i in range(5)]
computerShipSunkCoords = [set() for i in range(5)]
# Set of all computer available attacks
computerAvailableAttacks = set()
for i in range(10):
for j in range(10):
computerAvailableAttacks.add((i, j))
print('Welcome to Battleship!')
print("--------------------------------------------------")
sleep(2)
# Set ships for computer and player
setComputerShips(shipNames, shipLength, computerShipAliveCoords)
setPlayerShips(shipNames, shipLength, playerShipAliveCoords,
playerGrid, directionMap)
# Game loop
while True:
gameLength += 1
# Player turn
computerShipsAlive = playerTurn(shipNames, computerGrid, computerShipsAlive, computerShipAliveCoords,
computerShipSunkCoords)
# Check if game over
if computerShipsAlive == 0 and playerShipsAlive > 1:
break
# Computer turn
playerShipsAlive = computerTurn(shipNames, playerGrid, playerShipsAlive,
playerShipAliveCoords, playerShipSunkCoords, computerAvailableAttacks)
# Check if game over
if computerShipsAlive == 0 or playerShipsAlive == 0:
break
if playerShipsAlive == 0 and computerShipsAlive == 0:
print('TIE!')
printGrid(playerGrid, True)
printGrid(computerGrid, False)
elif computerShipsAlive == 0:
# Player won
print("YOU WON IN {} MOVES!".format(gameLength))
printGrid(playerGrid, True)
printGrid(computerGrid, False)
else:
# Computer won
print("YOU LOST!")
printGrid(playerGrid, True)
# Populate computer grid with positions of un hit ship coordinates
for ship in computerShipAliveCoords:
for coords in ship:
computerGrid[coords[0]][coords[1]] = 's'
printGrid(computerGrid, False)
sleep(5)
print("Thanks for playing!")
# Check if player wants to play again
playAgain = ''
while True:
playAgain = input("Would you like to play again? [y/n] ")
playAgain = playAgain.lower()
if playAgain == 'y' or playAgain == 'n':
break
else:
print("Invalid input. Please enter either 'y' or 'n'. Please try again.")
if playAgain == 'y':
continue
elif playAgain == 'n':
break
# Play game
if __name__ == "__main__":
runBattleshipSingle()
|
d2dc37941832c97787f4dd0ecc7c2fe9574f6988 | petcsclub/python-projects | /battleship/battleship_multi.py | 12,724 | 3.921875 | 4 | # imports
from random import randint, choice
from operator import add, mul
from time import sleep
import os
def setPlayerShips(shipNames, shipLength, playerShipAliveCoords, playerGrid, playerNumber, directionMap):
'''Get and set the ship placements of the player'''
# Get player name
print("Hello Player " + str(playerNumber))
playerName = input("What is your name? ").upper()
print('Set the position of your ships! Tell your opponent to look away from the computer screen.')
sleep(5)
printGrid(playerGrid, True, playerName)
# Loops through ships
for i in range(len(shipNames)):
while True:
print('Set the position of your ' +
shipNames[i] + ' of length ' + str(shipLength[i]) + '.')
# Get start coordinate and check validity
start = input('Coordinate for the start of your ' +
shipNames[i] + '? ')
startCoords = convert(start)
if startCoords is None:
print(
'Invalid input. Examples of proper coordinates: a0, B9, c2. Please try again.')
continue
# Get direction
direction = input('Direction for your ' +
shipNames[i] + '? ([w/a/s/d] for up, left, down, right) ')
if direction not in ['w', 'a', 's', 'd']:
print(
"Invalid input. Please enter either 'w', 'a', 's', or 'd'. Please try again.")
continue
# Adds appropriate direction to startCoords to get endCoords
endCoords = tuple(
map(add, startCoords, tuple(map(mul, directionMap[direction], (shipLength[i]-1, shipLength[i]-1)))))
# Ensures endCoords is in the grid
if endCoords[0] < 0 or endCoords[0] > 9 or endCoords[1] < 0 or endCoords[1] > 9:
print('Ship is out of bounds. Please try again.')
continue
# Check validity of ship placement
if checkShipPlacement(startCoords, endCoords, i, playerShipAliveCoords, playerGrid):
printGrid(playerGrid, True, playerName)
break
else:
print('Ships cannot intersect. Please try again.')
continue
# Remove ships ('s') from the grid
for i in range(5):
for coords in playerShipAliveCoords[i]:
playerGrid[coords[0]][coords[1]] = ' '
print("Ships successfully set! You won't be able to see the position of your ships again until the end of the game. Tell your opponent to return as soon as the output is cleared.")
sleep(5)
# Clear system output
os.system('cls' if os.name == 'nt' else 'clear')
return playerName
def playerTurn(shipNames, opponentGrid, opponentShipsAlive, opponentShipAliveCoords, opponentShipSunkCoords, playerName):
'''Execute player turn'''
print("{}'S TURN!".format(playerName))
printGrid(opponentGrid, False, playerName)
sunkShip = False
# Player input and logic
while True:
# Get attack coordinate and check validity
attack = input('Coordinate for your attack this turn? ')
attackCoords = convert(attack)
if attackCoords is None:
print(
'Invalid input. Examples of proper coordinates: a0, B9, c2. Please try again.')
continue
elif opponentGrid[attackCoords[0]][attackCoords[1]] != ' ':
print('You have already attacked this coordinate. Please try again.')
continue
# Check if attack hit a ship and update grid
shipIndex = hitShip(attackCoords, opponentShipAliveCoords)
if shipIndex == -1:
print("Miss!")
opponentGrid[attackCoords[0]][attackCoords[1]] = '-'
break
else:
print("Hit!")
opponentGrid[attackCoords[0]][attackCoords[1]] = 'o'
# Remove attack coordinate from alive set to sunk set
opponentShipAliveCoords[shipIndex].remove(attackCoords)
opponentShipSunkCoords[shipIndex].add(attackCoords)
# Check if alive set is empty (meaning ship is sunk)
if len(opponentShipAliveCoords[shipIndex]) == 0:
sunkShip = True
print("You have sunk your opponent's " +
shipNames[shipIndex] + "!")
opponentShipsAlive -= 1
for coords in opponentShipSunkCoords[shipIndex]:
opponentGrid[coords[0]][coords[1]] = 'x'
break
# Print grid again if ship was sunk
if sunkShip:
printGrid(opponentGrid, False, playerName)
print("END TURN!")
print("--------------------------------------------------")
if sunkShip:
sleep(3)
sleep(2)
return opponentShipsAlive
def printGrid(grid, showShips, playerName):
'''Print the specified grid'''
# Set title based on isPlayerGrid
if showShips:
print("\n{}'S SHIPS".format(playerName))
else:
print("\n{}'S ATTACKS".format(playerName))
# Print grid
for i in range(-1, 10):
for j in range(-1, 10):
# Print first row of letters
if i == -1:
if j == -1:
print(" ", end=" ")
elif j == 9:
print(j)
else:
print(j, end=" ")
else:
# Print first column on numbers
if j == -1:
print(chr(i+65), end=" ")
# Print grid
elif j == 9:
print(grid[i][j])
else:
print(grid[i][j], end=" ")
print("Legend: ' ' = empty | '-' = miss | 'o' = hit | 'x' = sunk | 's' = ship\nNote: you cannot see the position of your opponent's ships until the game is finished\n")
def checkShipPlacement(startCoords, endCoords, shipIndex, shipCoords, grid=None):
'''Check validity of ship placement and return True if placement is valid, false if not'''
# Check validity
if startCoords[0] == endCoords[0]:
# first coordinate is the same
if startCoords[1] > endCoords[1]:
startCoords, endCoords = endCoords, startCoords
# check validity to ensure coordinate doesn't already contain another ship
for i in range(startCoords[1], endCoords[1]+1):
if hitShip((startCoords[0], i), shipCoords, shipIndex) >= 0:
return False
# input ships and add to set
for i in range(startCoords[1], endCoords[1]+1):
shipCoords[shipIndex].add((startCoords[0], i))
# Print grid if specified (from player)
if grid != None:
grid[startCoords[0]][i] = 's'
return True
else:
# second coordinate is the same
if startCoords[0] > endCoords[0]:
startCoords, endCoords = endCoords, startCoords
# check validity to ensure coordinate doesn't already contain another ship
for i in range(startCoords[0], endCoords[0]+1):
if hitShip((i, startCoords[1]), shipCoords, shipIndex) >= 0:
return False
# input ships and add to set
for i in range(startCoords[0], endCoords[0]+1):
shipCoords[shipIndex].add((i, startCoords[1]))
# Print grid if specified (from player)
if grid != None:
grid[i][startCoords[1]] = 's'
return True
def convert(coords):
'''Convert coords in the correct form to the 2D array coordinates'''
# Check correct length
if len(coords) == 2:
# Convert to ASCII
first = ord(coords[0].upper())
second = ord(coords[1])
# Check validity of coordinates
firstValid = first >= 65 and first <= 74
secondValid = second >= 48 and second <= 57
if firstValid and secondValid:
# Return appropriate tuple
return(first-65, second-48)
def hitShip(coords, shipCoords, shipIndex=5):
'''Check if coordinate intersects with existing ship, and return the index of the ship if it does. If not, return -1'''
# Loop through ships
for i in range(shipIndex):
# Check if coordinate is in the set for specified ship
if coords in shipCoords[i]:
return i
return -1
def runBattleshipMulti():
'''Overarching game loop'''
# Declare const variables
shipNames = ['Carrier', 'Battleship', 'Cruiser', 'Submarine', 'Destroyer']
shipLength = [5, 4, 3, 3, 2]
directionMap = {
'w': (-1, 0),
'a': (0, -1),
's': (1, 0),
'd': (0, 1),
}
# Full game loop
while True:
# player2 view of player1's grid, initialize with 10x10 grid of ' '
playerOneGrid = [[' ' for i in range(10)] for j in range(10)]
# player1 view of player2's grid, initialize with 10x10 grid of ' '
playerTwoGrid = [[' ' for i in range(10)] for j in range(10)]
# Keep track of ships alive for player1 and player2 to determine when to end the game
playerOneShipsAlive = 5
playerTwoShipsAlive = 5
gameLength = 0
# Track coordinates for ships alive and sunk for both players in order to update char from 'o' to 'x' when the entire ship is sunk. Each index represents 1 ship.
playerOneShipAliveCoords = [set() for i in range(5)]
playerOneShipSunkCoords = [set() for i in range(5)]
playerTwoShipAliveCoords = [set() for i in range(5)]
playerTwoShipSunkCoords = [set() for i in range(5)]
print('Welcome to Battleship!')
print("--------------------------------------------------")
# Set ships for both players
playerOneName = setPlayerShips(shipNames, shipLength,
playerOneShipAliveCoords, playerOneGrid, 1, directionMap)
playerTwoName = setPlayerShips(shipNames, shipLength,
playerTwoShipAliveCoords, playerTwoGrid, 2, directionMap)
print("START GAME\n")
sleep(2)
# Game loop
while True:
gameLength += 1
# Player1 turn
playerTwoShipsAlive = playerTurn(shipNames, playerTwoGrid, playerTwoShipsAlive, playerTwoShipAliveCoords,
playerTwoShipSunkCoords, playerOneName)
# Check if game over
if playerTwoShipsAlive == 0 and playerOneShipsAlive > 1:
break
# Player turn
playerOneShipsAlive = playerTurn(
shipNames, playerOneGrid, playerOneShipsAlive, playerOneShipAliveCoords, playerOneShipSunkCoords, playerTwoName)
# Check if game over
if playerOneShipsAlive == 0 or playerTwoShipsAlive == 0:
break
if playerOneShipsAlive == 0 and playerTwoShipsAlive == 0:
print('TIE!')
printGrid(playerTwoGrid, True, playerTwoName)
printGrid(playerOneGrid, True, playerOneName)
elif playerOneShipsAlive == 0:
# Player2 won
print("{} WON IN {} MOVES!".format(playerTwoName, gameLength))
# Populate player2 grid with positions of un hit ship coordinates
for ship in playerTwoShipAliveCoords:
for coords in ship:
playerTwoGrid[coords[0]][coords[1]] = 's'
# Print ships grids
printGrid(playerTwoGrid, True, playerTwoName)
printGrid(playerOneGrid, True, playerOneName)
else:
# Player1 won
print("{} WON IN {} MOVES!".format(playerOneName, gameLength))
# Populate player1 grid with positions of un hit ship coordinates
for ship in playerOneShipAliveCoords:
for coords in ship:
playerOneGrid[coords[0]][coords[1]] = 's'
# Print ships grids
printGrid(playerOneGrid, True, playerOneName)
printGrid(playerTwoGrid, True, playerTwoName)
sleep(5)
print("Thanks for playing!")
# Check if players want to play again
playAgain = ''
while True:
playAgain = input("Would you like to play again? [y/n] ")
playAgain = playAgain.lower()
if playAgain == 'y' or playAgain == 'n':
break
else:
print("Invalid input. Please enter either 'y' or 'n'. Please try again.")
if playAgain == 'y':
continue
elif playAgain == 'n':
break
# Play game
if __name__ == "__main__":
runBattleshipMulti()
|
cf1e3aa630ec34233b352168bd4b0818565883cb | sofianguy/skills-dictionaries | /test-find-common-items.py | 1,040 | 4.5 | 4 | def find_common_items(list1, list2):
"""Produce the set of common items in two lists.
Given two lists, return a list of the common items shared between
the lists.
IMPORTANT: you may not not 'if ___ in ___' or the method 'index'.
For example:
>>> sorted(find_common_items([1, 2, 3, 4], [1, 2]))
[1, 2]
If an item appears more than once in both lists, return it each
time:
>>> sorted(find_common_items([1, 2, 3, 4], [1, 1, 2, 2]))
[1, 1, 2, 2]
(And the order of which has the multiples shouldn't matter, either):
>>> sorted(find_common_items([1, 1, 2, 2], [1, 2, 3, 4]))
[1, 1, 2, 2]
"""
common_items_list = []
for item1 in list1:
for item2 in list2:
if item1 == item2:
common_items_list.append(item1) #add item1 to new list
return common_items_list
print find_common_items([1, 2, 3, 4], [1, 2])
print find_common_items([1, 2, 3, 4], [1, 1, 2, 2])
print find_common_items([1, 1, 2, 2], [1, 2, 3, 4]) |
ea326d20c18ed1933aa011c844859f5292e9e636 | KlubInformatycznyLearnIT/Programistyczne-Puzzle | /Python/stoLat.py | 752 | 4.09375 | 4 | def stoLat():
wiek = int(input("Podaj swój wiek: "))
rokKiedy100Lat = (2018-wiek)+100
kiedy100Lat = rokKiedy100Lat-2018
print("Lat potrzebnych do osiągnięcia wieku 100 lat: {}".format(kiedy100Lat))
print("Rok osiągnięcia wieku 100 lat: {}".format(rokKiedy100Lat))
stoLat()
def stoLatUzytkownika():
wiek = int(input("Podaj swój wiek: "))
pozadanyWiek = int(input("Ile chcesz mieć lat?: "))
rokKiedyPozadanyWiek = (2018 - wiek) + pozadanyWiek
kiedyPozadanyWiek = rokKiedyPozadanyWiek - 2018
print("Lat potrzebnych do osiągnięcia wieku {} lat: {}".format(pozadanyWiek, kiedyPozadanyWiek))
print("Rok osiągnięcia wieku 100 lat: {}".format(rokKiedyPozadanyWiek))
stoLatUzytkownika() |
33ed3a85ac7ec37e390aab5d7f4a7330facf6d29 | KlubInformatycznyLearnIT/Programistyczne-Puzzle | /Python/odwrocone_zdanie.py | 603 | 3.84375 | 4 | # metoda nr1
def odwrocZdanie1(x):
y = x.split()
result = []
for word in y:
result.insert(0, word)
return " ".join(result)
# metoda nr2
def odwrocZdanie2(x):
y = x.split()
return " ".join(y[::-1])
# metoda nr3
def odwrocZdanie3(x):
y = x.split()
return " ".join(reversed(y))
# metoda nr4
def odwrocZdanie4(x):
y = x.split()
y.reverse()
return " ".join(y)
# test code
test1 = input("Wpisz zdanie: ")
print(odwrocZdanie1(test1))
print(odwrocZdanie2(test1))
print(odwrocZdanie3(test1))
print(odwrocZdanie4(test1)) |
c2dd84d87e72965c1b301061093ec5a5b3759b0a | kevinmu/xwgen | /square.py | 1,898 | 3.5625 | 4 | """Class representing the a single square in the crossword grid."""
from dataclasses import dataclass
from typing import Optional
@dataclass
class Square:
is_black: bool = False
letter: Optional[str] = None
index: Optional[int] = None
starts_down_word: bool = False
starts_across_word: bool = False
across_entry_parent: Optional[str] = None
down_entry_parent: Optional[str] = None
# Example of one square rendered:
# +—————+
# |129 |
# | A |
# +—————+
# Example of five squares rendered next to each other,
# with the left-most square being a black square:
# +—————++—————++—————++—————++—————+
# |█████||129 || || || |
# |█████|| A || B || _ || A |
# +—————++—————++—————++—————++—————+
def get_render_str(self):
border_str = "+—————+"
if self.is_black:
# top-border
render_str = f"{border_str}\n"
# first row - fill w/ big black rectangles
render_str += "|\u2588\u2588\u2588\u2588\u2588|\n"
# second row - fill w/ big black rectangles
render_str += "|\u2588\u2588\u2588\u2588\u2588|\n"
# bottom-border
render_str += border_str
return render_str
# top-border
render_str = f"{border_str}\n"
# second row with index
render_str += "|"
render_str += " " if self.index is None else "{:<3d}".format(self.index)
render_str += " |\n"
# third row with letter
render_str += "| "
render_str += "_" if self.letter is None else self.letter
render_str += " |\n"
# bottom-border
render_str += border_str
return render_str
|
974719c9fd09762406b5eb26d07582ec10256f12 | jrm2k6/pytanque | /src/models/Game.py | 1,577 | 3.578125 | 4 | import math
class Score(object):
def __init__(self, nb_teams_playing, winning_score=13):
self.winning_score = winning_score
self.nb_teams_playing = nb_teams_playing
self.scores = [0] * nb_teams_playing
def __str__(self):
return 'Scores : [ ' + ','.join(str(x) for x in self.scores) + ']'
def add_points(self, nb_points, num_team):
if num_team <= self.nb_teams_playing:
self.scores[num_team - 1] += nb_points
print self.scores
def check_for_win(self, num_team, nb_points):
if nb_points >= self.winning_score:
if self.no_close_team(num_team - 1):
self.show_win_message(num_team)
else:
pass
else:
pass
def no_close_team(self, num_team):
if num_team == 0:
list_to_check = self.scores[1:]
elif num_team == (len(self.scores)):
list_to_check = self.scores[0: num_team -2]
else:
list_to_check = self.scores[0: num_team] + self.scores[num_team:]
print list_to_check
result = True
for elem in list_to_check:
if math.fabs(elem - self.scores[num_team]) < 2:
result = False
return result
def show_win_message(self, num_team):
return "Congrats " + num_team +', you won the game'
class Shoot(object):
def __init__(self, angle, strength):
self.angle = angle
self.strength = strength
|
a47d242c90902ccb969ca515885dd8f229d0261f | charliecheng/LeetCodeOJ | /MedianofTwoSortedArrays.py | 1,379 | 3.53125 | 4 | class Solution:
# @return a float
'''
It is said that it is better not to use recursion in python.
By default Only 1000 times recursion is allowed
sys.setrecursionlimit(10000)
'''
def findMedianSortedArrays(self, A, B):
m=len(A)
n=len(B)
if (m+n)%2==1:
return float(self.findKthSmallest(A, m, B, n, (m+n+1)/2))
else:
a=float(self.findKthSmallest(A, m, B, n, (m+n)/2))
b=float(self.findKthSmallest(A, m, B, n, (m+n+2)/2))
return (a+b)/2
return
def findKthSmallest(self,A,m,B,n,k):
if m>n:
return self.findKthSmallest(B, n, A, m, k)
if m==0:
return B[k-1]
if k==1:
if A[0]>B[0]:
return B[0]
else:
return A[0]
if k/2<m:
i=k/2
else:
i=m
j=k-i
if A[i-1]<B[j-1]:
return self.findKthSmallest(A[i:m+1], m-i, B[0:j], j, k-i)
elif A[i-1]>B[j-1]:
return self.findKthSmallest(A[0:i], i, B[j:n+1], n-j, k-j)
else:
return A[i-1]
#Edge cases is extremely difficult to consider.
#Thus, need to find right place to start divide-conquer algorithm, which is the value of i an j.
#First find the Kth smalest in two sorted arrays.
|
f3ffd8b106b118377428818d3fade0a24aa0fdb7 | Vibhu1024/Python-tkinter | /messegeme.py | 850 | 3.6875 | 4 | import tkinter
import tkinter.messagebox
root = tkinter.Tk()
def display_and_print():
tkinter.messagebox.showinfo("Info","Just so you know")
tkinter.messagebox.showwarning("Warning","Better be careful")
tkinter.messagebox.showerror("Error","Something went wrong")
okcancel = tkinter.messagebox.askokcancel("What do you think?","Should we go ahead?")
print(okcancel)
yesno = tkinter.messagebox.askyesno("What do you think?","Please decide")
print(yesno)
retrycancel = tkinter.messagebox.askretrycancel("What do you think?","Should we try again?")
print(retrycancel)
answer = tkinter.messagebox.askquestion("What do you think?","What's your answer?")
print(answer)
b1 = tkinter.Button(root, text='Display dialogs', command=display_and_print)
b1.pack(fill='x')
root.mainloop() |
f203168252fea12f76058bbe861c6ccf1c718672 | zhaokang555/Developer | /Python3/201508/11-__getattr__And__call__-Creative.py | 614 | 3.671875 | 4 | class Chain(object):
def __init__(self, path = ''):
self._path = path
def __getattr__(self, path):
# 返回的是一个对象,而不是一个方法!!!!
return Chain('%s/%s' % (self._path, path))
def __call__(self, path = ''):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
def main():
# 不利用__call__来输出
print( Chain().users.michael.repos )
# 利用__call__来输出
print( (Chain().users)('michael').repos )
# 也可以去掉括号,即
print( Chain().users('michael').repos )
if __name__ == '__main__':
main()
|
07afcb0856341565e6b894945ff7a63d8aa58634 | Gogulaanand/100DaysOfCode | /LeetCode problems/Four-Divisors.py | 766 | 3.71875 | 4 | # Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors.
# If there is no such integer in the array, return 0.
# Example 1:
# Input: nums = [21,4,7]
# Output: 32
# Explanation:
# 21 has 4 divisors: 1, 3, 7, 21
# 4 has 3 divisors: 1, 2, 4
# 7 has 2 divisors: 1, 7
# The answer is the sum of divisors of 21 only.
from functools import reduce
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
def factor(n):
return set(reduce(list.__add__, [[i, n//i] for i in range(1, int(n**0.5)+1) if not n%i]))
total = 0
for num in nums:
f = factor(num)
if len(f)==4:
total += sum(f)
return total |
ec4172cb48ea9126cbc746455b807f6b9ee29106 | Gogulaanand/100DaysOfCode | /LeetCode problems/leafSimilarTrees.py | 521 | 3.625 | 4 | # Leaf-Similar Trees
# https://leetcode.com/problems/leaf-similar-trees/
#Sol 1: DFS
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
def dfs(node: TreeNode, l: List) -> bool:
if node is None:
return
if node.left is None and node.right is None:
l.append(node.val)
return l
dfs(node.left, l)
dfs(node.right, l)
return l
return dfs(root1, []) == dfs(root2, []) |
8350e4ff2c7442c4c2b685ece638b1e30a5756b2 | Capping-CPCA/Surveys | /test2.py | 710 | 3.53125 | 4 | import csv
#connects to the web server on a port
#conn = cpcapep.connect(connection,port here)
#Allows Python code to execute PostgreSQL command in a database session.
#cursor = conn.cursor()
csvfile = open("r2.csv","rb")
#Loop that goes through each row and creates an insert statement
reader = csv.reader(csvfile)
for row in reader:
#print "ROW: %s ---- " % row
query = "INSERT INTO answers (Q1, Q2, Q3) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);" % (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16])
print " "
#cursor.execute(query, data)
print query
(csvfile).close
|
5efe6e27964e98c49ae15c3f572152a6efba648b | vtombou/python_par_la_pratique_101_exercices_corriges | /exercices/debutant/exercice020.py | 346 | 3.78125 | 4 | """Récuperer des éléments communs à deux listes
"""
liste_01 = [1, 5, 6, 7, 9, 10, 11]
liste_02 = [2, 3, 5, 7, 8, 10, 12]
liste_commun = [i for i in liste_01 if i in liste_02]
print(liste_commun)
#Solution Formateur
sliste_01 = set(liste_01)
sliste_02 = set(liste_02)
intersect = sliste_01.intersection(sliste_02)
print(list(intersect)) |
d267475569338b2eb07a3c11b873f336af0bafbc | vtombou/python_par_la_pratique_101_exercices_corriges | /exercices/debutant/exercice009.py | 181 | 3.5625 | 4 | """Ordonner une chiane de caractère
"""
chaine = "Pierre, Julien, Anne, Marie, Lucien"
chaine = chaine.split(", ")
chaine = sorted(chaine)
chaine = ", ".join(chaine)
print(chaine) |
3035c5c5578e0d60d57be62f9a5767c074d57973 | vtombou/python_par_la_pratique_101_exercices_corriges | /exercices/avancer/exercice089.py | 403 | 3.65625 | 4 | def recuperer_item(liste, indice):
if abs(indice)>=0 and abs(indice)<len(liste):
return liste[indice]
elif indice < 0 and abs(indice) == len(liste):
return liste[indice]
else :
return "Index {i} hors de la liste".format(i=indice)
liste = ["Julien", "Marie", "Pierre"]
print(recuperer_item(liste, 0))
print(recuperer_item(liste, 5))
print(recuperer_item(liste, -13)) |
7e7a96a194384485ae8273f118e65dc898e832de | vtombou/python_par_la_pratique_101_exercices_corriges | /exercices/debutant/exercice038.py | 371 | 3.515625 | 4 | a = 4
b = 6
c = 2
ens = {a,b,c}
min_1 = min(ens)
ens.discard(min_1)
min_2 = min(ens)
ens.discard(min_2)
min_3 = min(ens)
print("Les nombres dans l'ordre sont {}, {} et {}".format(min_1, min_2, min_3))
#Solution Formateur, very nice
a1 = min(a, b, c)
a3 = max(a, b, c)
a2 = (a + b + c) - a1 - a3
print("Les nombres dans l'ordre sont {}, {} et {}".format(a1, a2, a3)) |
c8c423d8d764a4b66645cb5000aa3e9c92381ae1 | caiocanic/MIT-OCW-6.000 | /6.0001/Hangman/hangman.py | 11,854 | 4.15625 | 4 | # Hangman Game
# -----------------------------------
import random
import string
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the letters of secret_word are in
letters_guessed; False otherwise
'''
for char in secret_word:
if char not in letters_guessed:
return False
return True
def get_guessed_word(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing
letters_guessed: list (of letters), which letters have been guessed so far
returns: string, comprised of letters, underscores (_), and spaces that
represents which letters in secret_word have been guessed so far.
'''
guessed_letters=""
for char in secret_word:
if char in letters_guessed:
guessed_letters += char
else:
guessed_letters += "_ "
return guessed_letters
def get_available_letters(letters_guessed):
'''
letters_guessed: list (of letters), which letters have been guessed so far
returns: string (of letters), comprised of letters that represents which
letters have not yet been guessed.
'''
available_letters = list(string.ascii_lowercase)
for char in letters_guessed:
available_letters.remove(char)
return ''.join(available_letters)
def hangman(secret_word):
'''
secret_word: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.
* The user should start with 6 guesses
* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.
* Ask the user to supply one guess per round. Remember to make
sure that the user puts in a letter!
* The user should receive feedback immediately after each guess
about whether their guess appears in the computer's word.
* After each guess, you should display to the user the
partially guessed word so far.
Follows the other limitations detailed in the problem write-up.
'''
guesses_remaining = 6
warnings_remaining = 3
letters_guessed = []
print("Welcome to the game Hangman!")
print("I am thinking of a word that is", len(secret_word), "letters long.")
print("You have", warnings_remaining, "warnings left.")
while (not is_word_guessed(secret_word, letters_guessed) and
guesses_remaining > 0):
print("-------------")
print("You have", guesses_remaining, "guesses left.")
print("Available letters:", get_available_letters(letters_guessed))
letter = input("Please guess a letter:")
#Check if is a invalid letter
if not letter.isalpha():
if warnings_remaining > 0:
warnings_remaining -= 1
print("Oops! That is not a valid letter. You have",
warnings_remaining, "warnings left:",
get_guessed_word(secret_word, letters_guessed))
else:
guesses_remaining -= 1
print("Oops! That is not a valid letter. You have no warnings "
"left so you lose one guess:",
get_guessed_word(secret_word, letters_guessed))
#Check if the letter has alreday beed guessed
elif letter in letters_guessed:
if warnings_remaining > 0:
warnings_remaining -= 1
print("Oops! You've already guessed that letter. You have",
warnings_remaining, "warnings left:",
get_guessed_word(secret_word, letters_guessed))
else:
guesses_remaining -= 1
print("Oops! You've already guessed that letter. You have no "
"warnings left so you lose one guess:",
get_guessed_word(secret_word, letters_guessed))
#If a valid letter, add it to the letters_guessed
else:
letters_guessed.append(letter.lower())
if letter in secret_word:
print("Good guess:", get_guessed_word(secret_word,
letters_guessed))
else:
#Check if it's a vowel
if letter in ["a", "e", "i", "o", "u"]:
guesses_remaining -= 2
else:
guesses_remaining -= 1
print("Oops! That letter is not in my word:",
get_guessed_word(secret_word, letters_guessed))
print("-------------")
#You win if the word was guessed
if is_word_guessed(secret_word, letters_guessed):
print("Congratulations, you won!")
print("Your total score for this game is:",
len(set(secret_word)) * guesses_remaining)
#Else you loose
else:
print("Sorry, you ran out of guesses. The word was", secret_word)
# -----------------------------------
def match_with_gaps(my_word, other_word):
'''
my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special
symbol _ , and my_word and other_word are of the same length;
False otherwise:
'''
my_word = my_word.replace(" ","")
if len(my_word) == len(other_word):
for i in range(0,len(my_word)):
if my_word[i] != "_" and my_word[i] != other_word[i]:
return False
elif my_word[i] == "_" and other_word[i] in my_word:
return False
else:
return False
return True
def show_possible_matches(my_word):
'''
my_word: string with _ characters, current guess of secret word
returns: nothing, but should print out every word in wordlist that matches
my_word
Keep in mind that in hangman when a letter is guessed, all the positions at
which that letter occurs in the secret word are revealed. Therefore, the
hidden letter(_ ) cannot be one of the letters in the word that has
already been revealed.
'''
possible_matches = []
for other_word in wordlist:
if match_with_gaps(my_word, other_word):
possible_matches.append(other_word)
if possible_matches == []:
print("No matches found")
else:
print(" ".join(possible_matches))
def hangman_with_hints(secret_word):
'''
secret_word: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secret_word contains and how many guesses s/he starts with.
* The user should start with 6 guesses
* Before each round, you should display to the user how many guesses
s/he has left and the letters that the user has not yet guessed.
* Ask the user to supply one guess per round. Make sure to check that the
user guesses a letter
* The user should receive feedback immediately after each guess
about whether their guess appears in the computer's word.
* After each guess, you should display to the user the
partially guessed word so far.
* If the guess is the symbol *, print out all words in wordlist that
matches the current guessed word.
Follows the other limitations detailed in the problem write-up.
'''
guesses_remaining = 6
warnings_remaining = 3
letters_guessed = []
print("Welcome to the game Hangman!")
print("I am thinking of a word that is", len(secret_word), "letters long.")
print("You have", warnings_remaining, "warnings left.")
while (not is_word_guessed(secret_word, letters_guessed) and
guesses_remaining > 0):
print("-------------")
print("You have", guesses_remaining, "guesses left.")
print("Available letters:", get_available_letters(letters_guessed))
letter = input("Please guess a letter:")
#Check to print possible words
if letter == "*":
print("Possible word matches are:")
show_possible_matches(get_guessed_word(secret_word,
letters_guessed))
#Check if is a invalid letter
elif not letter.isalpha():
if warnings_remaining > 0:
warnings_remaining -= 1
print("Oops! That is not a valid letter. You have",
warnings_remaining, "warnings left:",
get_guessed_word(secret_word, letters_guessed))
else:
guesses_remaining -= 1
print("Oops! That is not a valid letter. You have no warnings "
"left so you lose one guess:",
get_guessed_word(secret_word, letters_guessed))
#Check if the letter has alreday beed guessed
elif letter in letters_guessed:
if warnings_remaining > 0:
warnings_remaining -= 1
print("Oops! You've already guessed that letter. You have",
warnings_remaining, "warnings left:",
get_guessed_word(secret_word, letters_guessed))
else:
guesses_remaining -= 1
print("Oops! You've already guessed that letter. You have no "
"warnings left so you lose one guess:",
get_guessed_word(secret_word, letters_guessed))
#If a valid letter, add it to the letters_guessed
else:
letters_guessed.append(letter.lower())
if letter in secret_word:
print("Good guess:", get_guessed_word(secret_word,
letters_guessed))
else:
#Check if it's a vowel
if letter in ["a", "e", "i", "o", "u"]:
guesses_remaining -= 2
else:
guesses_remaining -= 1
print("Oops! That letter is not in my word:",
get_guessed_word(secret_word, letters_guessed))
print("-------------")
#You win if the word was guessed
if is_word_guessed(secret_word, letters_guessed):
print("Congratulations, you won!")
print("Your total score for this game is:",
len(set(secret_word)) * guesses_remaining)
#Else you loose
else:
print("Sorry, you ran out of guesses. The word was", secret_word)
WORDLIST_FILENAME = "words.txt"
wordlist = load_words()
secret_word = choose_word(wordlist)
#hangman(secret_word)
hangman_with_hints(secret_word) |
bb080ba26c9453f545c0d4fad561e1c15673be7f | sieradzkidamian/pythonSubapps | /menuModules/numberChecker.py | 1,157 | 3.8125 | 4 | def checkNumbers():
numbers = []
userNumber = 'x'
sumOfNumbers = {
'lessThan': 0,
'biggerThan': 0,
'equalTo': 0
}
print('Wpisz liczby do porówniania, jeśli chcesz zakończyć wpisywanie użyj klawisza enter')
while(userNumber != ''):
userNumber = input('Podaj liczbę: ')
checkIfInt = userNumber.isnumeric()
if(checkIfInt):
numbers.append(userNumber)
print(numbers)
elif(userNumber == ''):
break
elif(not checkIfInt):
print('To nie jest liczba!')
for x in numbers:
if str(x) < '10':
sumOfNumbers['lessThan'] = sumOfNumbers.get('lessThan', 0) +1
elif str(x) > '10':
sumOfNumbers['biggerThan'] = sumOfNumbers.get('biggerThan', 0) +1
else:
sumOfNumbers['equalTo'] = sumOfNumbers.get('equalTo', 0) +1
print('Liczb mniejszych od 10 jest: ' + str(sumOfNumbers['lessThan']))
print('Liczb większych od 10 jest: ' + str(sumOfNumbers['biggerThan']))
print('Liczb równych zero jest: ' + str(sumOfNumbers['equalTo'])) |
80def11f9a59bf9eb55afb739c2e2176c0e0448e | marianaamaralarruda/MAC110 | /Aulas/Aula 13.03.py | 1,363 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 08:31:25 2018
@author: mariana.frasson
Problema
Dado um inteiro positivo n, imprimir os n primeiros naturais ímpares.
Exemplo: para n = 4, o programa deve exibir 1 3 5 7.
"""
def main():
n = int(input("Digite n: "))
impar = 1
while impar <= (2*n -1):
print(impar)
impar += 2
def main2():
n = int(input("Digite n: "))
impar = 1
i = 0
while i != n:
print(impar)
impar = impar + 2
i = i +1
"""
Problema
Dados números inteiros n e k, k >= 0, determinar n**k. Por exemplo,
dados os números 3 e 4, o seu programa deve escrever 81.
"""
def func():
n = int(input("Digite n: "))
k = int(input("Digite expoente: "))
if k >= 0:
result = n**k
print(result)
def funcProf():
n = int(input("Digite n: "))
k = int(input("Digite expoente: "))
prod = 1
i = 0
while i < k:
prod = prod * n
i = i + 1
print(n, " elevado a ", k, " = ", prod)
"""
Problema
Dado um inteiro n, n>=0, determinar n!.
"""
def func3():
n = int(input("Digite um inteiro: "))
result = 1
nsaldo = n
while n > 0:
result *= n
n -= 1
print(nsaldo, "fatorial= ", result)
if __name__ == "__func3__":
func3()
|
7f5565fb5c2c4b451c72e2b8bfc781439002c8c4 | marianaamaralarruda/MAC110 | /Aulas/Aula 03.04.py | 2,585 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 08:01:33 2018
@author: mariana.frasson
"""
"""
Dados n pontos (x,y) para cada ponto, determinar se (x,y) pertence a
região H.
"""
def main1():
n = int(input("Digite n:"))
count = 0
while count < n:
x = float(input("Digite x:"))
y = float(input("Digite y:"))
if x*x + y*y < 1:
if x > 0:
if y > 0:
print("O ponto (", x, ",", y, ") pertence à região H.")
else:
print("O ponto (", x, ",", y, ") não pertence à região H.")
else:
print("O ponto (", x, ",", y, ") não pertence à região H.")
else:
print("O ponto (", x, ",", y, ") não pertence à região H.")
count += 1
def main2():
n = int(input("Digite n:"))
count = 0
while count < n:
x = float(input("Digite x:"))
y = float(input("Digite y:"))
if x*x + y*y < 1 and x > 0 and y < 0:
print("O ponto (", x, ",", y, ") pertence à região H.")
else:
print("O ponto (", x, ",", y, ") não pertence à região H.")
count += 1
"""
Operadores lógicos
Existem três operadores lógicos:
and, or, not
Exemplo
2 < 3 and -5 < 0: True
2 > 3 and -5 < 0: False
2 < 3 or -5 < 0: True
Prioridades
( )
**
* /
+ -
< > <= >=
not
and
or
"""
"""
Problema
Dado um inteiro n, n > 0 e uma sequência com n números inteiros,
verificar se a sequência é estritamente crescente.
Exemplo
7 -6 0 12 15 37 101 201 resp SIM
7 -6 0 17 15 37 101 201 resp NÃO
"""
def main3():
n = int(input("Digite n:"))
contador = 1
anterior = int(input("Digite um inteiro: "))
d = 1
while contador < n:
atual = int(input("Digite um inteiro: "))
if anterior >= atual:
d = 0
anterior = atual
contador += 1
if d == 1:
print("É crescente.")
else:
print("Não é crescente.")
"""
Problema
Dado um número n > 0 verificar se n contém dois dígitos adjacentes
iguais.
Exemplo
1 2 3 4 3 2 1 resposta NÃO
1 2 3 4 5 5 6 resposta SIM
"""
def main4():
n = int(input("Digite n: "))
tem = False
dig_ant = n % 10
n = n // 10
while n > 0:
dig_atual = n % 10
if dig_ant <= dig_atual:
tem = True
dig_ant = dig_atual
if tem == True:
print("Tem dígitos adjacentes iguais.")
else:
print("Não tem dígitos adjacentes iguais.")
|
956b1da44ab5987ca8c4c82b78067f75861a9eb4 | alee1412/projects | /python-challenge/PyBank/main.py | 2,398 | 3.875 | 4 | import os
import csv
filepath = os.path.join("budget_data_1.csv")
#Total Months
with open(filepath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
print("Financial Analysis")
print("**************************************")
total_months = []
for row in csvreader:
total_months.append(row[0])
months = (len(total_months) - 1)
print("Total Months: " + str(months) + " Months")
#Total Revenue
with open(filepath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
total_revenue = 0
for revenue in csvreader:
if revenue[1] != "Revenue":
total_revenue = total_revenue + int(revenue[1])
print("Total Revenue: " + "$" + str(total_revenue))
#Average Change in revenue
with open(filepath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
average_change = []
for row in csvreader:
average_change.append(row[1])
average_change.pop(0)
average_change = list(map(int, average_change))
#print(average_change)
new_change = []
change = 0
for items in range(len(average_change)-1):
new_change.append(average_change[change + 1] - average_change[change])
change = change + 1
#print(new_change)
average_monthly_change = sum(new_change)/len(new_change)
print("Average Revenue Change: " + "$" + str(average_monthly_change))
#Greatest increase in revenue (date and month)
#print(new_change)
i = len(new_change)
def largest(new_change, i):
return max(new_change)
print("Greatest Increase in Revenue: " + "$" + str(largest(new_change, i)))
#Greatest decrease in revenue (date and month)
#print(new_change)
d = len(new_change)
def lowest(new_change, d):
return min(new_change)
print("Greatest Decrease in Revenue: " + "$" + str(lowest(new_change, d)))
#Exporting to txt file
text_file = open("Main.txt", "w")
text_file.write("Financial Analysis \n")
text_file.write("**************************** \n")
text_file.write("Total Months: " + str(months) + " Months \n")
text_file.write("Average Revenue Change: " + "$" + str(average_monthly_change) + " \n")
text_file.write("Greatest Increase in Revenue: " + "$" + str(largest(new_change, i)) + " \n")
text_file.write("Greatest Decrease in Revenue: " + "$" + str(lowest(new_change, d))) |
cc90a2abad5545744475f0f0066dce42e9ac32ad | pabhd3/Coding-Challenges | /adventofcode/2015/13 - Knights of the Dinner Table/arrange.py | 1,857 | 3.59375 | 4 | from itertools import permutations
from json import dumps
def findHappyness(people):
print("People:", people)
total = len(list(permutations(people, len(people))))
count = 0
# Loop through seating combinations
best = {"arrangement": None, "happyness": 0}
for combo in permutations(people, len(people)):
happyness = 0
for i in range(0, len(combo)):
if(i == 0):
happyness += happy[combo[i]][combo[i+1]] + happy[combo[i]][combo[len(combo)-1]]
elif(i == len(combo)-1):
happyness += happy[combo[i]][combo[0]] + happy[combo[i]][combo[i-1]]
else:
happyness += happy[combo[i]][combo[i+1]] + happy[combo[i]][combo[i-1]]
if(happyness > best["happyness"]):
best = {"arrangement": combo, "happyness": happyness}
count += 1
print("Arrangements Checked: {}/{}".format(count, total), end="\r")
print("")
return best
if __name__ == "__main__":
# Read the instruction data
with open("input.txt", "r") as r:
data = r.read()
r.close()
# Parse the Data
happy = {}
for instruction in data.split("\n"):
# print(instruction.split())
a, _, net, val, _, _, _, _, _, _, b = instruction.split()
if(not happy.get(a)):
happy[a] = {}
if(not happy[a].get(b)):
happy[a][b.replace(".", "")] = int(val) if net == "gain" else 0-int(val)
print("Happyness Values\n{}".format(dumps(happy, indent=4)))
people = [p for p in happy]
# Part 1 - Find arrangement with "me"
print("\nPart 1 - Best Arrangement with 'Me'")
print(findHappyness(people=people))
# Part 2 - Find arrangement without "me"
print("\nPart 2 - Best Arrangement without 'Me'")
people.remove("Me")
print(findHappyness(people=people)) |
8875ce74923a7f3f2aa47a4de4bbc6caa1e80fc2 | pabhd3/Coding-Challenges | /adventofcode/2015/05 - Doesn't He Have Intern-Elves For This/niceList.py | 1,909 | 3.59375 | 4 | if __name__ == "__main__":
# Get data from flatfile
with open("input.txt", "r") as r:
data = r.read()
r.close()
niceCountSetA, niceCountSetB = 0, 0
for name in data.split():
# Make a list of every two letters
everyTwoLetters = [name[i] + name[i + 1] for i in range(0, len(name) - 1)]
# Part 1 - Nice if part 1 rules all met
# Check if Vowel Count > 2
vowelCount = True if sum([name.count(vowel) for vowel in ["a", "e", "i", "o", "u"]]) > 2 else False
# Check if there is repeated letter
repeatedLetter = True if True in [pair[0] == pair[1] for pair in everyTwoLetters] else False
# Check if not allowed in name
notAllowed = True if True not in [sub in name for sub in ["ab", "cd", "pq", "xy"]] else False
niceCountSetA += 1 if vowelCount and repeatedLetter and notAllowed else 0
# Part 2 - Nice if part 2 rules all met
# Check if not shared pair repeat occurs
repeatPair = False
# print(name)
# print(everyTwoLetters)
for i in range(0, len(everyTwoLetters) - 2):
# print(everyTwoLetters[i])
for j in range(i + 2, len(everyTwoLetters)):
# print(" ", everyTwoLetters[j])
if(everyTwoLetters[i] == everyTwoLetters[j]):
repeatPair = True
break
if(repeatPair):
break
# Check if letter repeats with 1 letter between
repeatSandwich = False
for i in range(0, len(name) - 2):
if(name[i] == name[i + 2]):
repeatSandwich = True
break
niceCountSetB += 1 if repeatPair and repeatSandwich else 0
print("Nice name count under Rule Set 1: {count}".format(count=niceCountSetA))
print("Nice name count under Rule Set 2: {count}".format(count=niceCountSetB))
|
d093a437bb9d08605f63ea0a9d81d4f2b8fcf1f2 | pabhd3/Coding-Challenges | /adventofcode/2019/04 - Secure Container/password.py | 1,615 | 3.796875 | 4 | def findPassword(pRange):
start, end = pRange.split("-")
possibilities = []
for p in range(int(start), int(end)+1):
# Check if 6 digit number
if(len(str(p)) != 6):
continue
# Check for at 1 pair of adjacent same numbers
double = False
strP = str(p)
for i in range(0, 5):
if(strP[i] == strP[i+1]):
double = True
break
if(not double):
continue
#Check for never decreasing
decrease = False
for i in range(0, 5):
if(int(strP[i]) > int(strP[i+1])):
decrease = True
break
if(decrease):
continue
possibilities.append(p)
return possibilities
def noLargerSets(possibilities):
newPoss = []
for p in possibilities:
strP = str(p)
temp = {}
for i in strP:
try:
temp[i] += 1
except:
temp[i] = 1
if(2 not in [temp[i] for i in temp]):
continue
newPoss.append(p)
return newPoss
if __name__ == "__main__":
# Read input
with open("input.txt", "r") as f:
data = f.read()
# Part 1 - Find password
possibilities = findPassword(pRange=data)
print(f"Part 1 - Find Password Possibilities")
print(f" Possiblities: {len(possibilities)}")
# Part 2 - No Larger Sets
newPossibilities = noLargerSets(possibilities=possibilities)
print(f"Part 2 - \"No Larger Sets Rule\" Possibilities")
print(f" Possibilties: {len(newPossibilities)}")
|
18d450fe88c4c6df2456c0b93fd666c1a5a2fdae | Golden-cobra-bjj/itstep | /lesson3/welcome.py | 59 | 3.640625 | 4 | name = input("What is your name?")
print('"Hello, Neo :)"') |
1c1cebceb7f945f2d9488a911c45b868a05ceb3c | Dhyaneshwaran-Vaitheswaran/Calculator | /Calculator_tkinter.py | 3,549 | 3.953125 | 4 | from tkinter import *
###main()
window = Tk()
window.title("Calculator")
window.configure()
operator=""
text_input=StringVar()
#Entry
num = Entry(window, font="arial 20 normal",width=20, borderwidth=5, textvariable=text_input, bd=30, insertwidth=3, bg="powderblue")
num.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
#Definie button
#==================================================================================================================================================#
def button_click(numbers):
global operator
operator=operator + str(numbers)
text_input.set(operator)
def button_clear():
global operator
operator=""
text_input.set("")
def button_equals():
global operator
sumup=str(eval(operator))
text_input.set(sumup)
operator=""
#==================================================================================================================================
#buttons
button_1 = Button(window, bg="powderblue", bd=8, font="15", text="1", padx=45, pady=20, command=lambda:button_click(1))
button_2 = Button(window, bg="powderblue", bd=8,font="15",text="2", padx=45, pady=20, command=lambda:button_click(2))
button_3 = Button(window, bg="powderblue", bd=8,font="15",text="3", padx=45, pady=20, command=lambda:button_click(3))
button_4 = Button(window, bg="powderblue", bd=8,font="15",text="4", padx=45, pady=20, command=lambda:button_click(4))
button_5 = Button(window, bg="powderblue", bd=8,font="15",text="5", padx=45, pady=20, command=lambda:button_click(5))
button_6 = Button(window, bg="powderblue", bd=8,font="15",text="6", padx=45, pady=20, command=lambda:button_click(6))
button_7 = Button(window, bg="powderblue", bd=8,font="15",text="7", padx=45, pady=20, command=lambda:button_click(7))
button_8 = Button(window, bg="powderblue", bd=8,font="15",text="8", padx=45, pady=20, command=lambda:button_click(8))
button_9 = Button(window, bg="powderblue", bd=8,font="15",text="9", padx=45, pady=20, command=lambda:button_click(9))
button_0 = Button(window, bg="powderblue", bd=8,font="15",text="0", padx=45, pady=20, command=lambda:button_click(0))
button_add = Button(window, bg="powderblue", bd=8,font="15",text="+", padx=45, pady=20, command=lambda:button_click("+"))
button_equal = Button(window, bg="powderblue", bd=8,font="15",text="=", padx=174, pady=20, command=button_equals)
button_clear = Button(window, bg="powderblue", bd=8,font="15",text="C", padx=45, pady=20, command=button_clear)
button_sub = Button(window, bg="powderblue", bd=8,font="15",text="-", padx=45, pady=20, command=lambda:button_click("-"))
button_multi = Button(window, bg="powderblue", bd=8,font="15",text="x", padx=45, pady=20, command=lambda:button_click("*"))
button_div = Button(window, bg="powderblue", bd=8,font="15",text="÷", padx=45, pady=20, command=lambda:button_click("/"
""))
#grids
button_1.grid(row=1, column=0)
button_2.grid(row=1, column=1)
button_3.grid(row=1, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=3, column=0)
button_8.grid(row=3, column=1)
button_9.grid(row=3, column=2)
button_sub.grid(row=5, column=0)
button_multi.grid(row=5, column=1)
button_div.grid(row=5, column=2)
button_0.grid(row=4, column=1)
button_add.grid(row=4, column=0)
button_equal.grid(row=6, column=0, columnspan=3)
button_clear.grid(row=4, column=2)
##loops
window.mainloop()
|
acd1c76acbeb71338fa504768fff792701a7e3a4 | jimtoGXYZ/scrapy_spiders_repository | /cd_lianjia_spider-centOS/data_analysis/c_gen_area_mean_price_pic.py | 1,409 | 3.6875 | 4 | """
2020年2月17日15:44:53
按照不同的小区进行分类并计算小区总价平均值
使用plt进行数据展示
"""
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文
plt.rcParams['axes.unicode_minus'] = False # 显示负号
from_path = "..\\doc\\processed_data\\cd_lianjia-v3_ed.csv"
to_path = "..\\doc\\pic\\area_mean_price.png"
# 读取数据 类型dataframe
df = pd.read_csv(from_path)
# 设置所在区域为大索引
df.set_index(['所在区域'], inplace=True)
# 根据所在区域做聚集操作
groupby_obj = df.groupby("所在区域")
# 根据所在区域算出总价的平均值
total_list = groupby_obj.mean()["总价"]
print(total_list)
# 取出索引作为标签
total_index_list = total_list.index
print(total_list, total_index_list)
# 设置刻度
y_ticks = range(len(total_index_list))
x_ticks = range(0, 260, 10)
# 打开画布
plt.figure(figsize=(20, 9), dpi=80)
# 设置柱子
plt.barh(y=y_ticks, width=total_list, height=0.2, color='orange')
# 设置y轴刻度
plt.yticks(ticks=y_ticks, labels=total_index_list)
# 设置x轴刻度
plt.xticks(ticks=x_ticks)
# 增加标签
plt.xlabel("区域平均价格(单位:万元)")
plt.ylabel("区域名称")
plt.title("成都2020年2月份各区平均房价一览图")
# 打开网格
plt.grid()
# 保存图片
plt.savefig(to_path)
# 展示图片
plt.show()
|
f69ef00c44a9f5cc889a67bd509786ea306bcf0e | bhavesh-09/addskilleetcode | /WEEK2/Sorting/mergetwoll.py | 902 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head=ListNode(0)
ptr=head
while head:
if l1 is None and l2 is None:
break
elif l1 is None:
ptr.next=l2
break
elif l2 is None:
ptr.next=l1
break
else:
sv=0
if l1.val < l2.val:
sv=l1.val
l1=l1.next
else:
sv=l2.val
l2=l2.next
new=ListNode(sv)
ptr.next=new
ptr=ptr.next
return head.next
|
be522a17498e9c460579c7558b4fbf25061ef593 | lwbrooke/dailyprogrammer | /easy/2017-06-12_challenge-319-condensing-sentences/solutions/condense.py | 753 | 3.90625 | 4 | #!/usr/bin/env python3
def main():
with open('input.txt') as f_in:
for line in f_in.readlines():
print(condense(line.strip()))
def condense(sentence):
condensed = []
tokens = list(reversed(sentence.split(' ')))
while len(tokens) > 1:
first, second = tokens.pop(), tokens.pop()
similarity = max(
(i for i in range(1, min(len(first), len(second)) + 1) if second.startswith(first[-i:])),
default=0)
if similarity:
tokens.append('{}{}'.format(first, second[similarity:]))
else:
condensed.append(first)
tokens.append(second)
condensed.extend(tokens)
return ' '.join(condensed)
if __name__ == '__main__':
main()
|
f14f50012773c003f4d5d3f89942189ed1071f08 | FlyingBirdSwim/Python | /other_code/max_of_sum.py | 924 | 3.609375 | 4 | #!usr/bin/env python
# coding=utf-8
# 输入:列表list
# 输出:list的子列表中,和最大的子列表(最少为一个元素)以及sum值
# 1.常规实现 2.尽量优化(未完成)
import time
from memory_profiler import profile
data = [-1, -2, -1, 1, -2, 3, -1, 2, -3, 2]
@profile()
def max_1(lt):
max_sum = 0
max_list = []
for i in range(len(lt)):
for j in range(len(lt) + 1):
# list[i: j]遍历所有子列表,但是有较多空集
if lt[i: j] == []:
continue
if sum(lt[i: j]) > max_sum:
max_sum = sum(lt[i: j])
max_list = lt[i: j]
print('最大的和为 %d' % max_sum + ',列表为 %s' % max_list)
if __name__ == '__main__':
start = time.process_time()
max_1(data)
end = time.process_time()
print('运行时间为 %f' % (end-start))
|
30aa6513cd0eb7965abcba481995614d613c3c1b | mnxtr/Leetcode | /Arrays/First_Missing_Positive.py | 1,147 | 3.703125 | 4 | # Given an unsorted integer array nums, find the smallest missing positive integer.
# Example 1:
# Input: nums = [1,2,0]
# Output: 3
# Example 2:
# Input: nums = [3,4,-1,1]
# Output: 2
# Leetcode 41: https://leetcode.com/problems/first-missing-positive/
# Difficulty: Hard
# Solution: Sort the list as you iterate through it by placing the elements in its index + 1 position
# Realize that the answer must be within the range of 0 to the length of the list + 1
def firstMissingPositive(self, nums: List[int]) -> int:
i, j = 0, len(nums)
while i < j:
# Element is already in the right position - do nothing
if nums[i] == i + 1:
i += 1
# If the number is within our range (0, j) and the number is not in its nth + 1 position then swap
elif nums[i] > 0 and nums[i] <= j and nums[nums[i] - 1] != nums[i]:
nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
# Outsite our range or a duplicate, swap to the end of list
else:
j -= 1
nums[j], nums[i] = nums[i], nums[j]
return j + 1
# Time Complexity: O(N)
# Space Complexity: O(1)
|
a27ecb0e07e8cb284ee3226b6f63d954b1aae65f | mnxtr/Leetcode | /Arrays/Two_Sum_Sorted.py | 1,126 | 4 | 4 | # Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
# Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
# You may assume that each input would have exactly one solution and you may not use the same element twice.
# Example 1:
# Input: numbers = [2,7,11,15], target = 9
# Output: [1,2]
# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
# Leetcode 167: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
# Difficulty: Easy
# Solution: Modify left and right pointers based on the size of the target relative to the sum of nums[l] and nums[r]
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l, r = 0, len(numbers) - 1
while l < r:
if numbers[l] + numbers[r] == target:
return [l + 1, r + 1]
elif numbers[l] + numbers[r] > target:
r -= 1
else:
l += 1
return []
# Time Complexity: O(N)
# Space Complexity: O(1)
|
6afbd8e0f14f30d194df6f42b4e432d84eb579d3 | mnxtr/Leetcode | /Arrays/Find_Pivot_Index.py | 1,159 | 4.0625 | 4 | # Given an array of integers nums, calculate the pivot index of this array.
# The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
# If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
# Return the leftmost pivot index. If no such index exists, return -1.
# Example 1:
# Input: nums = [1,7,3,6,5,6]
# Output: 3
# Explanation:
# The pivot index is 3.
# Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
# Right sum = nums[4] + nums[5] = 5 + 6 = 11
# Leetcode 724: https://leetcode.com/problems/find-pivot-index/
# Difficulty: Easy
def pivotIndex(self, nums: List[int]) -> int:
# Initialize variables to keep track of the sum strictly to the left and right of the current index we are at
leftSum, rightSum = 0, sum(nums)
for i, v in enumerate(nums):
rightSum -= v
if leftSum == rightSum:
return i
leftSum += v
return -1
# Time Complexity: O(N)
# Space Complexity: O(1)
|
2c13bb164982403cd2bdc5017d65d4b62dfe6a75 | jhutar/RedBot | /plan.py | 14,425 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import os.path
PATHS = ['|', '/', '-', '\\']
def is_edge(coords):
return coords[0] % 2 == 1 or coords[1] % 2 == 1
def is_vertex(coords):
return coords[0] % 2 == 0 and coords[1] % 2 == 0
def can_put(c, coords):
if c == '#':
return True
if c not in PATHS:
return False
if is_vertex(coords):
return False
if coords[0] % 2 == 1 and coords[1] % 2 == 0:
return c == '-'
if coords[0] % 2 == 1 and coords[1] % 2 == 1:
return c == '/' or c == '\\'
if coords[0] % 2 == 0 and coords[1] % 2 == 1:
return c == '|'
class PlanColumn():
"""Helper object to implement Plan[x][y] type of access"""
def __init__(self, playfield, x):
self.x = x
self.column = []
for line in playfield:
self.column.append(line[self.x])
###print ">>> self.column:", self.column
def __getitem__(self, y):
return self.column[y]
def __setitem__(self, y, value):
"""Put some item (like stone or path) to given cell.
If adding a path (e.g. "{'\': stratID}"), then just add it to whatever is already in the cell"""
###print ">>> Setting [%s,%s] to '%s'" % (self.x, y, value)
assert len(value) == 1 # only one item can be placed in one time (this is limitation of this method implementation only)
k = value.keys()[0]
v = value.values()[0]
assert 0 <= v <= 3 # value is strategy ID
if k == '#': # lets place stone
# If there is already a stone on the field, do not replace its owner,
# just silently ignore the action
if '#' not in self.column[y]:
self.column[y][k] = v
elif k in PATHS: # lets add some path to the field
assert is_edge([self.x, y])
if '#' not in self.column[y]: # only place new path on the fields without stone
if k not in self.column[y]: # only place new path on the field if same path is not already there
# If there is already path of a given type on the field,
# do not replace its owner, just silently ignore the action
# Note: If you were allowed to build given type of the path on given
# coords, no harm is done if we ignore your request because
# there already is same path, because that means that that
# path is actually co-owned by you
self.column[y][k] = v
else:
raise Exception("Do not know how to set this value (%s, %s, %s)" % (self.x, y, value))
class Plan():
"""Object to hold data about game plan. it can be adressed by x and y coordinates and [0,0] is in bottom left corner"""
def __init__(self, dat):
assert type(dat) is list
assert len(dat) > 0
self.dat = dat
self.columns = {}
self.columns_count = self.dat[0].count(',') + 1
self.rows_count = len(self.dat)
self.plan = []
assert self.columns_count == self.rows_count
for line in self.dat[::-1]:
# Line looks like: "A:3;B:3,,A:1,-:1,,,H:1,-:2,G:3;H:3"
assert self.columns_count == line.count(',') + 1
l = []
for cell in line.split(','):
# Cell looks like: "A:3;B:3"
c = {}
for item in cell.split(';'):
# Item looks like "A:3"
if item != '':
key, val = item.split(':')
assert key not in c
c[key] = int(val)
l.append(c)
self.plan.append(l)
###print ">>> self.plan:", self.plan
pass
def __getitem__(self, x):
if x not in self.columns:
self.columns[x] = PlanColumn(self.plan, x)
return self.columns[x]
def __str__(self):
out = ''
for y in range(len(self.dat)-1, -1, -1):
on_row = []
for x in range(len(self.dat)):
on_cell = []
for k, v in self[x][y].iteritems():
on_cell.append("%s:%s" % (k, v))
on_row.append(';'.join(on_cell))
out += ','.join(on_row)
out += "\n"
return out
def __eq__(self, other):
return self.plan == other.plan
def __add_if_valid(self, what, to):
"""Returns 'to' with 'what' apended if 'what' are valid coords"""
if 0 <= what[0] <= self.columns_count-1 and 0 <= what[1] <= self.rows_count-1:
###print ">>> __add_if_valid: Adding %s to the list as it is valid coord" % what
to.append(what)
else:
###print ">>> __add_if_valid: Not adding %s to the list as it is not valid coord" % what
pass
return to
def use_ingredient(self, ingredient, coord, count):
assert is_vertex(coord)
current = self[coord[0]][coord[1]] # remember this is just a refference, so any change into this variable will make it back into that self[x][y]
assert ingredient in current
###print ">>> use_ingredient: There is %s on %s, but decreasing %s by %s" % (current, coord, ingredient, count)
assert current[ingredient] >= count
current[ingredient] -= count
if current[ingredient] == 0:
del(current[ingredient])
###print ">>> use_ingredient: This was left there: %s" % self[coord[0]][coord[1]]
def get_connected_cells(self, coords, cells):
"""Return list of cells which are one one path where given coords are
part of. Employs recursion so even long paths are discovered.
'cells' is a lit of cells we already know about."""
###print ">>> get_connected_cells: Entering function with %s and %s" % (coords, cells)
if coords not in cells: # add starting coords to the output set
cells.append(coords)
if is_edge(coords):
# Find cells on the plan this coords connects (there might be more paths
# on one coords)
for item in self.get_continuing_cells(coords):
if item not in cells:
cells.append(item)
if "#" not in self[item[0]][item[1]]:
###print ">>> get_connected_cells: get_continuing_cells returned new cell %s, investigating" % item
cells = self.get_connected_cells(item, cells)
else: # this is vertex
# Now we should check if there are more paths comming from this
# vertex, but only if there is no stone on it
if "#" not in self[coords[0]][coords[1]]:
for item in self.get_connecting_edges(coords):
# If we have not seen that edge, discover vertexes connected to it
# and add it to output set
if item not in cells and "#" not in self[item[0]][item[1]]:
###print ">>> get_connected_cells: get_connecting_edges returned new edge %s, investigating" % item
cells = self.get_connected_cells(item, cells)
###print ">>> get_connected_cells: Returning %s" % cells
return cells
def __get_continuing_cells(self, coords, what):
"""Return list of edges and vertexes connected by given type of path on
given coords"""
assert is_edge(coords)
candidates = []
###print ">>> __get_continuing_cells: Considering %s on %s" % (what, coords)
if what == '|':
candidates = self.__add_if_valid((coords[0], coords[1]-1), candidates)
candidates = self.__add_if_valid((coords[0], coords[1]+1), candidates)
if what == '/':
candidates = self.__add_if_valid((coords[0]+1, coords[1]+1), candidates)
candidates = self.__add_if_valid((coords[0]-1, coords[1]-1), candidates)
if what == '-':
candidates = self.__add_if_valid((coords[0]-1, coords[1]), candidates)
candidates = self.__add_if_valid((coords[0]+1, coords[1]), candidates)
if what == '\\':
candidates = self.__add_if_valid((coords[0]-1, coords[1]+1), candidates)
candidates = self.__add_if_valid((coords[0]+1, coords[1]-1), candidates)
###print ">>> __get_continuing_cells: Returning:", candidates
return candidates
def get_continuing_cells(self, coords):
"""Return paths/edges or vertexes attached to given path"""
candidates = []
for k, v in self[coords[0]][coords[1]].iteritems():
candidates += self.__get_continuing_cells(coords, k)
###print ">>> get_continuing_cells: Found cells continuing from given edge: %s" % candidates
return candidates
def get_connecting_edges(self, coords):
"""Return paths/edges connected to this vertex"""
assert is_vertex(coords) # make sure this is vertex
x_modif = [0]
if coords[0] != 0:
x_modif.append(-1)
if coords[0] != self.columns_count - 1:
x_modif.append(1)
y_modif = [0]
if coords[1] != 0:
y_modif.append(-1)
if coords[1] != self.rows_count - 1:
y_modif.append(1)
###print ">>> get_connecting_edges: Considering these x:%s and y:%s coordinates modificators for %s" % (x_modif, y_modif, coords)
out = []
for x_mod in x_modif:
for y_mod in y_modif:
x = coords[0] + x_mod
y = coords[1] + y_mod
if x_mod == 0 and y_mod == 1: # up
if '|' in self[x][y]:
out.append((x, y))
if x_mod == 1 and y_mod == 1: # up right
if '/' in self[x][y]:
out.append((x, y))
if x_mod == 1 and y_mod == 0: # right
if '-' in self[x][y]:
out.append((x, y))
if x_mod == 1 and y_mod == -1: # down right
if '\\' in self[x][y]:
out.append((x, y))
if x_mod == 0 and y_mod == -1: # down
if '|' in self[x][y]:
out.append((x, y))
if x_mod == -1 and y_mod == -1: # down left
if '/' in self[x][y]:
out.append((x, y))
if x_mod == -1 and y_mod == 0: # left
if '-' in self[x][y]:
out.append((x, y))
if x_mod == -1 and y_mod == 1: # up left
if '\\' in self[x][y]:
out.append((x, y))
###print ">>> get_connecting_edges: Found connected edges on these coords %s" % out
return out
def list_paths_for_strat(self, strat):
"""Return list of coords of all paths built directly by given strategy"""
paths = []
for x in range(self.columns_count):
for y in range(self.rows_count):
for k, v in self[x][y].items():
if k in PATHS and v == strat:
paths.append((x, y))
###print ">>> list_paths_for_strat: Paths created by strategy %s: %s" % (strat, paths)
return paths
def get_paths_for_strat(self, strat):
"""Return lists of all cells connected by given strategy. There can be
multiple lists, because one path can be divided by stone."""
paths = []
# For every path/edge coords built by given strategy
# if there is no stone on it
list_paths_for_strat = filter(lambda crd: "#" not in self[crd[0]][crd[1]], self.list_paths_for_strat(strat))
for coords in list_paths_for_strat:
###print ">>> get_paths_for_strat: Considering %s for %s" % (coords, strat)
processed = False
# If we already have these coords in some path for this strategy
for path in paths:
if coords in path:
###print ">>> get_paths_for_strat: Coords %s already known" % coords
processed = True
break
# If these coords are not part of this strategy
if not processed:
###print ">>> get_paths_for_strat: Coords not in any of the paths, computing additional path"
# Compute path these coords are part of
path = self.get_connected_cells(coords, [])
path.sort()
# And if this path is not known already, add it
assert path not in paths # we are checking using that 'processed' before
###print ">>> get_paths_for_strat: This new path (%s) is not know yet, adding it among other paths" % path
paths.append(path)
###print ">>> get_paths_for_strat: Returning:", paths
return paths
def get_all_ingredients(self):
"""Return list of all ingredients which can be found on the map"""
ingredients = []
for x in range(self.columns_count):
for y in range(self.rows_count):
if is_vertex([x, y]):
for i in self[x][y]:
if i not in PATHS and i != '#':
if i not in ingredients:
ingredients.append(i)
ingredients.sort()
###print ">>> get_all_ingredients: Returning", ingredients
return ingredients
def put(self, what, who, coord):
"""Build stone or path (param 'what') to given coords (param 'coord').
When building path, it have to be connected with paths of this strategy
(given by 'who')."""
assert what in PATHS + ['#']
###print ">>> put: Going to build '%s' for strategy '%s' on %s" % (what, who, coord)
# If we are building path, we have to check if that is connected to
# this strategy's path already
if what in PATHS:
assert can_put(what, coord)
paths = self.get_paths_for_strat(who)
if len(paths) != 0: # do not check neighbours if this is our first path
###print ">>> put: Found these path (co)owned by strategy %s: %s" % (who, paths)
neighbours = self.__get_continuing_cells(coord, what)
###print ">>> put: Building %s on %s would connect: %s" % (what, coord, neighbours)
found = False
for neighbour in neighbours:
for path in paths:
if neighbour in path:
found = True
break
if not found:
raise Exception("Path %s on %s would not connect to any path (co)owned by strategy %s" % (what, coord, who))
# Finally put stone or build the path
self[coord[0]][coord[1]] = {what: who}
def dump_for_strat(self, round, who):
"""Dump map customized for given strategy as 'playfield.txt' to where directory"""
fp = open(os.path.join(who.stratwd, 'playfield.txt'), 'w')
fp.write("Kolo: %s\n" % round)
fp.write("Bodu: %s\n" % who.points)
fp.write("Kamenu: %s\n" % who.stones)
if not who.potion_done:
fp.write("Hlavni: %s\n" % ''.join(who.potion))
fp.write("Kucharka:\n")
for p in who.cookbook:
fp.write("%s\n" % ''.join(p))
fp.write("Mapa:\n")
fp.write(str(self))
fp.close()
def dump_globaly(self, where, round, strats, cookbook):
"""Dump map customized for given strategy as 'playfield.txt' to where directory"""
fp = open(where, 'w')
fp.write("Kolo: %s\n" % round)
for s in strats:
s_dat = ','.join([str(s.points), str(s.stones), ''.join(s.potion), '1' if s.potion_done else '0'])
fp.write("Strategie%s: %s\n" % (s.id, s_dat))
fp.write("Kucharka:\n")
for p in cookbook:
fp.write("%s\n" % ''.join(p))
fp.write("Mapa:\n")
fp.write(str(self))
fp.close()
|
102fb4b9db411b63dcceca6d381a771fec65b0c2 | 121910314010/10B14-Lab-Assignment | /L13- Binarytree.py | 218 | 3.734375 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def DispTree(self):
print(self.data)
root = Node(15)
root.DispTree()
Output:-
15
|
35eb58c9c2f9d6f431225606b12b0f414ea7a6c4 | SSudhashu/ModelAuto | /ModelAuto/ModelSelection.py | 6,261 | 3.53125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Regression Model Selection
def Regress_model(x_train,y_train,x_test=None,y_test=None,degree=2,test_size=0.1):
"""[summary]
DESCRIPTION :-
Regressin Model selection.
This Model will compare all the different Regression models, and will return model with highest Rsq value.
It also shows performance graph comaring the models.
PARAMETERS :-
x_train,x_test,y_train,y_test = are the data after tain test split
test_size = 10 % of original data is used for testing
degree = degree of polinomial regresoin (default = 2)
Returns:
Model with heighest Rsq.
Along with model compaing plot.
"""
print('Regression Model Selection...')
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.svm import SVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
if x_test is None or y_test is None:
x_train,x_test,y_train,y_test = train_test_split(x_train,y_train,random_state=0,test_size=test_size)
print('\nLinear Regression ...')
lr=LinearRegression()
lr.fit(x_train,y_train)
y_pred_lir = lr.predict(x_test)
lr_pred=r2_score(y_test, y_pred_lir)
print('Rsq :',lr_pred )
print('\nPolinomial Regression ...')
polr=PolynomialFeatures(degree)
x_polr=polr.fit_transform(x_train)
polr.fit(x_polr,y_train)
lr.fit(x_polr,y_train)
y_pred_poly=lr.predict(polr.fit_transform(x_test))
poly_pred=r2_score(y_pred_poly,y_test)
print('Rsq :',poly_pred )
print('\nSVM Model ...')
regressor = SVR(kernel = 'rbf')
regressor.fit(x_train, y_train)
y_pred=regressor.predict(x_test)
svr_pred=r2_score(y_test,y_pred)
print('Rsq :',svr_pred)
print('\nDesision Tree ...')
d_tree=DecisionTreeRegressor(random_state=1)
d_tree.fit(x_train,y_train)
y_pred=d_tree.predict(x_test)
d_tree_acc=r2_score(y_test,y_pred)
print('Rsq : ',d_tree_acc)
print('\nRandom Forest ...')
rand = RandomForestRegressor(n_estimators = 100, random_state = 1)
rand.fit(x_train,y_train)
y_pred=rand.predict(x_test)
ran_for_acc=r2_score(y_test,y_pred)
print('Rsq :',ran_for_acc)
l=[lr_pred,poly_pred,svr_pred,d_tree_acc,ran_for_acc]
x_label=['Lin_Reg','Poly_Reg','Svm','Des_Tr','Rand_For']
ma=l.index(max(l))
if ma==0:
model=lr
elif(ma==1):
model=polr
elif(ma==2):
model=regressor
elif(ma==3):
model=d_tree
else:
model=rand
xx=np.arange(0,5)
plt.plot(xx,l)
plt.ylabel('Rsq')
plt.title('Regression Models')
plt. xticks(xx,x_label)
plt.show()
return model
# Classification Model Selection
def Classi_model(x_train,x_test,y_train,y_test):
"""[summary]
DESCRIPTION :-
Classification model selection.
This Model will compare all the different Classification models, and will return model with highest Accuracy value.
It also shows performance graph comaring the models.
PARAMETERS :-
x_train,x_test,y_train,y_test = are the data after tain test split
Returns:
Model with heighest Accuracy.
Along with model compaing plot.
"""
print('Classification Model Selection...')
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
print('LOGISTIC REGRESSIN...\n')
classifier_log =LogisticRegression(C=1,random_state=0)
classifier_log.fit(x_train,y_train)
y_pred = classifier_log.predict(x_test)
y_pred_log=accuracy_score(y_test, y_pred)
print('ACCURACY : ',y_pred_log )
print('\nKNN...\n')
classifier_knn = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)
classifier_knn.fit(x_train, y_train)
y_pred = classifier_knn.predict(x_test)
y_pred_knn=accuracy_score(y_test, y_pred)
print('ACCURACY : ',y_pred_knn )
print('\nSVM_LINEAR...\n')
regressor_svmlinear = SVC(kernel = 'linear')
regressor_svmlinear.fit(x_train, y_train)
y_pred= regressor_svmlinear.predict(x_test)
y_pred_svmlin=accuracy_score(y_test,y_pred)
print('ACCURACY : ',y_pred_svmlin)
print('\nSVM_NonLinear...\n')
regressor_svmnon = SVC(kernel = 'rbf')
regressor_svmnon.fit(x_train, y_train)
y_pred=regressor_svmnon.predict(x_test)
y_pred_svmnon=accuracy_score(y_test,y_pred)
print('ACCURACY : ',y_pred_svmnon)
print('\nDecision Tree...\n')
d_tree=DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
d_tree.fit(x_train,y_train)
y_pred=d_tree.predict(x_test)
y_pred_dt=accuracy_score(y_test,y_pred)
print('ACCURACY : ',y_pred_dt)
print('\nRANDOM FOREST...\n')
regressor_rf = RandomForestClassifier(n_estimators = 50,random_state = 0,criterion = 'entropy')
regressor_rf.fit(x_train,y_train)
y_pred=regressor_rf.predict(x_test)
y_pred_rf=accuracy_score(y_test,y_pred)
print('ACCURACY : ',y_pred_rf)
l=[y_pred_log,y_pred_knn,y_pred_svmlin,y_pred_svmnon,y_pred_dt,y_pred_rf]
xx=np.arange(0,6)
plt.plot(xx,l)
ma=l.index(max(l))
x_label=['Log_Reg','KNN','Svm_Lin','Svm_Nonlin','RandF','DeciTree']
plt.ylabel('Accuracy')
plt. xticks(xx,x_label)
plt.title('Classification Models')
plt.show()
if ma==0:
model=classifier_log
elif(ma==1):
model=classifier_knn
elif(ma==2):
model=regressor_svmlinear
elif(ma==3):
model=regressor_svmnon
elif(ma==4):
model=d_tree
else:
model=regressor_rf
return model
|
a8bf8c4ea895e621812b82a880cd9b62cff97eb1 | Nadine278/design-patterns_wsb | /dp1.py | 1,463 | 3.5625 | 4 | # Language Translator
# Adaptee: Incompatible interface # 1
class English:
def Greeting(self):
return "Hello!"
def Farewell(self):
return "Good byee."
# Adapter Class, which takes functionality provided by English, morphs it into functionality expected by the polish person.
class Translator:
_English = None
_engphrases = {
"Hello!": "CZEŚĆ",
"Good byee.": "Do widzenia"
}
def __init__(self, English):
self._English = English
# polish speaker: Incompatible interface # 2
class polish_p:
_englToPolish = None
def __init__(self, englToPolish):
self._englToPolish = englToPolish
def exchangeGreetings(self):
print("Hello!")
print( self._englToPolish._engphrases[ self._englToPolish._English.Greeting() ] )
def exchangeFarewell(self):
print("Good bye!")
print( self._englToPolish._engphrases[ self._englToPolish._English.Farewell() ] )
# Create an English Speaking person
English = English()
# Create a translator with popular english phrases
englToPolish = Translator(English)
# The polish Person can now get responses in polish
polish = polish_p(englToPolish)
# Two-way conversation in Polish
polish.exchangeGreetings()
polish.exchangeFarewell()
|
709fc9d07868898643a74f008b9107d0ec391eec | Sandyky/pdftojson | /pypdf_text_generator.py | 699 | 3.5625 | 4 | # pypdf_text_generator.py
# importing required modules
import PyPDF2
def extract_text_by_page(pdf_path):
# creating a pdf file object
pdfFileObj = open(pdf_path, 'rb') # pdfFileObj = open('Test for json (2) (1).pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# printing number of pages in pdf file
print(pdfReader.numPages)
# creating a page object
for pageNumber in range(0,pdfReader.numPages):
pageObj = pdfReader.getPage(pageNumber)
# extracting text from page
text = pageObj.extractText()
yield text
# closing the pdf file object
pdfFileObj.close()
|
f2585c3c300b3dece289d3eddf8e4b8e0270e4e1 | jaredad7/CSC_BACKUPS | /university/CSC325/Homework/HW4.py | 151 | 3.828125 | 4 | #Search an unordered array
def search(x, arr):
for i in range(len(arr)):
if x == arr[i]:
return i
return -1
print(search(1, [2,4,9,5,8,1,0]))4
|
9abe35cda5b6d4d7a3460cdee7a2a368893fa37b | jaredad7/CSC_BACKUPS | /university/CSC325/Homework/HW5.py | 336 | 4.03125 | 4 | #Write a binary search
def binSearch(arr, first, last, K):
if last < first:
index = -1
else:
mid = int((first+last)/2)
if K == arr[mid]:
index = mid
elif K < arr[mid]:
index = binSearch(arr, first, mid-1, K)
else:
index = binSearch(arr, mid+1, last, K)
return index
print(binSearch([1,2,3,4,5,6,7,8,9], 0, 8, 6))
|
bf2a05fff10cf1fa6a2d0e5591da851b22069a78 | adamny14/LoadTest | /test/as2/p4.py | 219 | 4.125 | 4 | #------------------------------
# Adam Hussain
# print a square of stars for n
#------------------------------
n = input("Enter number n: ");
counter = 1;
while counter <= n:
print("*"*counter);
counter = counter +1;
|
c76fb61d59cc8b7be29675d495bac11a645d34c1 | echo750/python | /python_test/高阶函数.py | 976 | 3.6875 | 4 | #1淶Ӣĸ
def normalize(name):
return name[0].upper()+name[1:].lower()
# :
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
#2reduce()
def prod(L):
def f1(x,y):
return x*y
return reduce(f1,L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('Գɹ!')
else:
print('ʧ!')
#3ַ'123.456'תɸ123.456
from functools import reduce
def str2float(s):
def fn(s):
d={'.':'.','1':1,'2':2,'3':3,'4':4,'5':5,'6':6}
return d[s]
def fm(x,y):
return x*10+y
n=0
for index,value in enumerate(s):
if value=='.':
n=index;
return reduce(fm,map(fn,s[0:n]))+(0.1**len(s[n+1:]))*(reduce(fm,map(fn,s[n+1:])))
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('Գɹ!')
else:
print('ʧ!') |
c94cd9920eef06a3e26a5880252c4b2058c01669 | KlippRid/codepub | /Workshop/step1.py | 556 | 3.5625 | 4 | import random
import radio
from microbit import button_a, Image, display, sleep
# Create an array with the three prepicked images (HEART, PITCHFORK and PACMAN) to
# use instead of stone, rock, scissor. By terminology we call these "tools"
# tools = <write array here>
random.seed(463473567345343)
my_id = 'foo'
tool = 0
while True:
if button_a.was_pressed():
tool = random.randrange(3)
display.clear()
sleep(1000)
# Show the randomly chosen tool on the Micro:bit
display.show(tools[tool])
sleep(10) |
4b7cee3fbbb50e5bad5d7a439daaf8b001d8f2e6 | fmbdti/Projeto-02 | /idade_anos_cachorro.py | 160 | 3.71875 | 4 | idade = int(input("Quantos anos você tem?"))
print(f'Se você fosse um cachorro, você teria {idade * 7} anos!! \n')
print(" '0'____' ")
print(" |||| ")
|
b8307df493ecd72dc573304ae500e81fdd531dc9 | Flip-SG/python-code | /Memory-Test/memory_test_function.py | 340 | 3.875 | 4 | # -*- encoding: utf-8 -*-
"""
Memory Usage Test using Function and List
"""
# Defining a Function
def fibonacci_fun(max):
nums = []
a, b = 0, 1
while len(nums) < max:
nums.append(b)
a, b = b, a + b
return nums
# Calling the Function
for n in fibonacci_fun(100000):
print(n)
# Usage: 1,120 MB of memory
|
69d9f24c6cb5b375c1cd4533a1479221c4dfb813 | Jeevanantham13/programizprograms | /swappingvaraibleswithouttemp.py | 268 | 4.0625 | 4 | #swapping variables without using temporary variable
a = int(input("enter the value of a:"))
b = int(input("enter the value of b:"))
print("the values of a and b are:",a,b)
a = a+b
b = a-b
a = a-b
print("the swapped varaibles of a and b are:",a,b) |
bc4d287f92a9c8fc88b40f9a44f29bba615efc41 | Jeevanantham13/programizprograms | /celciustofarenheit.py | 185 | 4.3125 | 4 | #coverting celsius into farenheit
celcius = int(input("enter the celcius rate:"))
farenheit = celcius * 32
print("the farenheit of the given celcius is:",farenheit,'farenheit') |
25be821b8a8dcfde4e0e43f5b6f8321cb32d1717 | ercas/scripts | /isopen.py | 5,734 | 3.734375 | 4 | #!/usr/bin/env python3
import datetime
import json
import math
WEEKDAYS = [ "mon", "tue", "wed", "thu", "fri", "sat", "sun" ]
FORMATS = [ "%I:%M %p", "%H:%M", "%I %p", "%H" ]
CLOSED = "\x1b[31mClosed\x1b[0m"
OPEN = "\x1b[32mOpen\x1b[0m"
def parse_time(time_string):
""" Attempt to convert a time string into a datetime, using a format
specified in FORMATS
Args:
time_string: The string to be converted.
Returns:
A datetime.datetime object. Returns LookupError if the string could not
be converted.
"""
for _format in FORMATS:
try:
return datetime.datetime.strptime(time_string, _format)
except:
pass
raise LookupError
def second_of_day(datetime):
""" Convert a datetime into the number of seconds since 12:00 am
Args:
datetime: A datetime.datetime object.
Returns:
The number of seconds since 12:00 am.
"""
return datetime.second + datetime.minute*60 + datetime.hour*3600
def time_diff(start_datetime, end_datetime):
""" Show the difference between two times
Args:
start_datetime, end_datetime: The datetime.datetime objects that the
difference will be calculated from.
Returns:
A string describing the difference in time of day.
"""
seconds = abs(
(end_datetime.second - start_datetime.second)
+ (end_datetime.minute - start_datetime.minute) * 60
+ (end_datetime.hour - start_datetime.hour) * 3600
)
minutes = math.floor(seconds/60)
hours = math.floor(seconds/3600)
if (hours > 1):
return "%d hours" % hours
elif (minutes == 60):
return "1 hour"
elif (hours == 1):
return "1 hour and %d minutes" % (minutes - 60)
elif (minutes > 1):
return "%d minutes" % minutes
elif (seconds == 60):
return "1 minute"
elif (minutes == 1):
return "1 minute and %d seconds" % (seconds - 60)
else:
return "%d seconds" % seconds
def main(times_json, relative, absolute):
""" Prints if locations are opened or closed
Args:
times: A string containing a path to a JSON of locations and hours.
Sample JSON:
[
{
"name": "Boston Public Library",
"hours": {
"sun": ["1:00 pm", "5:00 pm"],
"mon": ["9:00 am", "9:00 pm"],
"tue": ["9:00 am", "9:00 pm"],
"wed": ["9:00 am", "9:00 pm"],
"thu": ["9:00 am", "9:00 pm"],
"fri": ["9:00 am", "5:00 pm"],
"sat": ["9:00 am", "5:00 pm"]
}
},
{
"name": "Only Thursdays",
"hours": {
"thu": ["9:00 am", "9:00 pm"],
}
}
]
Times must be in one of the formats defined in the FORMATS array.
For example, 1:00 pm, 1 pm, 13:00, and 13 are all valid. If a venue
is closed for the whole day, that day can be ommitted.
relative: A bool describing whether or not opening and closing times
should be given in relation to the current time or not.
"""
with open(times_json, "r") as f:
locations = json.load(f)
now = datetime.datetime.now()
today = WEEKDAYS[now.weekday()]
now_sod = second_of_day(now)
for location in locations:
description = []
_open = False
if (today in location["hours"]):
hours = location["hours"][today]
start = parse_time(hours[0])
end = parse_time(hours[1])
start_sod = second_of_day(start)
end_sod = second_of_day(end)
if (now_sod > start_sod) and (now_sod < end_sod):
_open = True
if (relative):
description.append("Open until %s" % hours[1])
if (absolute):
description.append("Closes in %s" % time_diff(now, end))
elif (now_sod >= end_sod):
if (relative):
description.append("Closed for the day")
if (absolute):
description.append("Closed %s ago" % time_diff(now, end))
else:
if (relative):
description.append("Closed until %s" % hours[0])
if (absolute):
description.append("Opens in %s" % time_diff(now, start))
elif (absolute):
description.append("Closed today")
print("%s: %s" % (location["name"], _open and OPEN or CLOSED))
if (len(description) > 0):
print("\n".join(description))
#print("%d < %d < %d %s" % (start_sod, now_sod, end_sod, _open))
print("")
if (__name__ == "__main__"):
import optparse
parser = optparse.OptionParser()
parser.add_option("-f", "--file", dest = "file", help = "The JSON to use",
metavar = "FILE", default = "isopen.json")
parser.add_option("-a", "--abs", "--absolute", dest = "relative",
help = "Toggle absolute time output", default = False,
action = "store_true")
parser.add_option("-r", "--rel", "--relative", dest = "absolute",
help = "Toggle absolute time output", default = False,
action = "store_true")
(options, args) = parser.parse_args()
main(options.file, options.relative, options.absolute)
|
62a3e0306d82ddce02ba9f471c7b0d1f3ffa9199 | wangtao666666/Data-structure-Algorithm | /Sort/2-sort.py | 492 | 3.546875 | 4 | #encoding='utf-8'
"""
短冒泡排序
"""
def shortBubbleSort(alist):
exchanges = True
item = len(alist) - 1
while item > 0 and exchanges:
exchanges = False
for i in range(item):
if alist[i] > alist[i+1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
item = item -1
return alist
print(shortBubbleSort([20,30,40,90,50,60,70,80,100,110])) |
d00c727795694f3d0386699e15afeb5cb4484f89 | VictoriaAlvess/LP-Python | /exercicio5.py | 565 | 4.40625 | 4 | ''' 5) Escreva um programa que receba três números quaisquer e apresente:
a) a soma dos quadrados dos três números;
b) o quadrado da soma dos três números.'''
import math
print("Digite o primeiro número: ")
num1 = float(input())
print("Digite o segundo número: ")
num2 = float(input())
print("Digite o terceiro número: ")
num3 = float(input())
somaA = math.pow(num1,2)+ math.pow(num2,2)+ math.pow(num3, 2)
print("A soma dos quadrados dos três números é: ", somaA)
somaB = math.pow(somaA,2)
print("O quadrado da soma dos três números é: ", somaB)
|
4ac46568573edf2b5528846c93b19a864a0b903c | KrzysztofNyrek/strip_exponentiation | /rozbierz_potegowanie.py | 1,056 | 3.546875 | 4 | # coding: UTF-8
def rozb_pot(liczba, potega):
liczba = str(liczba)
i = 1
a = liczba
b = liczba
pot = potega
lic = int(liczba)
lista =[]
#Exceptions
if lic == 0:
return '1'
elif pot == 0:
return '1'
elif pot == 1:
return b
elif lic == 1:
return '1'
elif pot < 0:
return "Ten program obsługuje tylko potęgi należące do zbioru liczb naturalnych"
elif lic < 0:
return "Ten program obsługuje tylko liczby należące do zbioru liczb naturalnych"
#calculations
else:
while i < pot:
a = a + "*" + liczba
i += 1
i = 1
lista.append(a)
while i < lic:
b = b + "+" + liczba
i += 1
i = 1
if pot > 2:
c = b
k = lic ** (pot - 2)
while i < k:
c = c + "+" + b
i += 1
lista.append(c)
else:
lista.append(b)
return lista
|
aa24f9c6c050d9da74ee0fdb271cbcf1d28a5f40 | Laishuxin/python | /3.web服务器/1.正则表达式/7.re高级用法.py | 531 | 3.65625 | 4 | import re
# search 不从开始匹配,只匹配一次
ret = re.search(r"\d+", "阅读次数:9999, 点赞:888")
# 返回一个列表,不需要用group()
ret1 = re.findall(r"\d+", "阅读次数:9999, 点赞:888")
# 将匹配到的所有!!内容替换 然后返回整个内容
ret2 = re.sub(r"\d+", "7777", "阅读次数:9999, 点赞:888")
# 切割字符串, 返回一个列表
ret3 = re.split(r":| ", "info:1111 小米 guangdong")
print(ret.group())
print(ret1)
print(ret2)
print(ret3) |
d77e3f0c1b69178d36d43f767e4e12aed8a821da | Laishuxin/python | /2.thread/3.协程/6.create_generator_send启动.py | 742 | 4.3125 | 4 | # 生成器是特殊的迭代器
# 生成器可以让一个函数暂停,想执行的时候执行
def fibonacci(length):
"""创建一个financci的生成器"""
a, b = 0, 1
current_num = 0
while current_num < length:
# 函数中由yield 则这个不是简单的函数,而是一个生成器模板
print("111")
ret = yield a
print("222")
print(">>>>ret>>>>", ret)
a, b = b, a+b
# print(a, end=",")
current_num += 1
obj = fibonacci(10)
ret = next(obj)
print(ret)
ret = next(obj)
print(ret)
# 第一次最好不用send启动
# ret = obj.send("hhhhh") # send里面的参数当作结论传递给 yield的返回值
# print(ret)
|
51f77bec87dafe67de8cd09bcc1413bb200fd55b | Laishuxin/python | /6.web_mini框架/6.装饰器/4.装饰器-调用参数的函数.py | 512 | 3.9375 | 4 | """
装饰器是在原来函数不修改的前提下,对函数整体加功能
"""
def set_func(func):
def call_func(a): # 注意这里也需要传入参数
print("-----这是权限验证1------")
print("-----这是权限验证2------")
func(a) # 注意这里也需要传入参数
return call_func
@set_func
def test1(num):
print("这是test1函数 %d" % num)
@set_func
def test2(num):
print("这是test2222函数 %d" % num)
test1(100)
test2(2000) |
16734679a66a28546fc4707d5f508a2ecb98b873 | Laishuxin/python | /2.thread/1.线程/4.多线程共享全局变量-互斥锁.py | 959 | 3.8125 | 4 | import threading
import time
g_num = 0
def test1(num):
global g_num
# 上锁,如果之前没上锁,此时上锁成功
# 如果上锁之前,已经被上锁,那么此时会堵塞在这里,直到锁被解开为止
mutex.acquire()
for i in range(num):
g_num += 1
# 解锁
mutex.release()
print("------in test11111 g_num = {}".format(g_num))
def test2(num):
global g_num
mutex.acquire()
for i in range(num):
g_num += 1
mutex.release()
print("-------in test2 g_nums = {}".format(str(g_num)))
# 创建一个互斥锁,默认不上锁
mutex = threading.Lock()
def main():
t1 = threading.Thread(target=test1, args=(10000,))
t2 = threading.Thread(target=test2, args=(10000,))
t1.start()
print("")
t2.start()
time.sleep(2)
print("main -----g_num = {}".format(g_num))
if __name__ == "__main__":
main() |
9ea09bff31a3f8612de32e1c48afd0a7de7782ab | prathyushaVV/algoexpert | /TwoNumberSum.py | 705 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 30 23:39:55 2020
@author: Prathyusha Vaigandla
"""
array = [9, 10, 11, 0, -4 ,-5, -6, -1]
count = 0
target = 0
triplets = []
array.sort()
for i in range(len(array)-3):
for j in range(i+1,len(array)-2):
left = j+1
right = len(array)-1
while left<right:
cn = array[i]+array[j]+array[left]+array[right]
if cn == target:
triplets.append([array[i],array[j],array[left],array[right]])
left += 1
right -= 1
count += 1
elif cn<target:
left += 1
elif cn > target:
right -= 1
print(count)
print(triplets) |
1bb08f16176e0ef96228ec8696e9fcbf0fe4d7fc | prathyushaVV/algoexpert | /LargestRange.py | 799 | 3.796875 | 4 | def largestRange(array):
dupHash = {}
largeArray = []
longValue = 0
for i in array:
dupHash[i] = True
for i in array:
if not dupHash[i]:
continue
dupHash[i] = False
currentValue = 1
left = i-1
right = i+1
while left in dupHash:
dupHash[left] = False
currentValue += 1
left -= 1
while right in dupHash:
dupHash[right] = False
currentValue += 1
right += 1
if currentValue > longValue:
longValue = currentValue
largeArray = [left+1, right-1]
return largeArray
#time complexity is o(n) and space complexity is o(n)
array = [1,11,5, 3, 4, 8, 7, 2, 0, 6, 12, 14 , 15 , 20]
print(largestRange(array))
|
434328739627343a2181d5499073dc2e41a9bd1b | l3ouu4n9/LeetCode | /algorithms/840. Magic Squares In Grid.py | 2,652 | 4.09375 | 4 | """
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: [[4,3,8,4],
[9,5,1,9],
[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:
438
951
276
while this one is not:
384
519
762
In total, there is only one magic square inside the given grid.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
0 <= grid[i][j] <= 15
"""
class Solution(object):
def numMagicSquaresInside(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ret = 0
for i in range(0, len(grid) - 2):
l = []
for j in range(0, len(grid[0]) - 2):
if j == 0:
for ptr1 in range(i, i + 3):
for ptr2 in range(j, j + 3):
l.append(grid[ptr1][ptr2])
else:
for ptr1 in range(i, i + 3):
l.remove(grid[ptr1][j - 1])
l.append(grid[ptr1][j + 2])
# Check from 1 to 9
if 1 in l and 2 in l and 3 in l and 4 in l and 5 in l and 6 in l and 7 in l and 8 in l and 9 in l:
sum1 = 0
sum2 = 0
sum3 = 0
# row
for ptr2 in range(j, j + 3):
sum1 += grid[i][ptr2]
sum2 += grid[i + 1][ptr2]
sum3 += grid[i + 2][ptr2]
if sum1 == sum2 == sum3:
s = sum1
sum1 = 0
sum2 = 0
sum3 = 0
# column
for ptr1 in range(i, i + 3):
sum1 += grid[ptr1][j]
sum2 += grid[ptr1][j + 1]
sum3 += grid[ptr1][j + 2]
if s == sum1 == sum2 == sum3:
sum1 = 0
sum2 = 0
# diagonals
sum1 += grid[i][j] + grid[i + 1][j + 1] + grid[i + 2][j + 2]
sum2 += grid[i][j + 2] + grid[i + 1][j + 1] + grid[i + 2][j]
if s == sum1 == sum2:
print(s)
ret += 1
return ret
|
fbb4ce33a955eec2036211a7421950f027330a0b | l3ouu4n9/LeetCode | /algorithms/7. Reverse Integer.py | 860 | 4.125 | 4 | '''
Given a 32-bit signed integer, reverse digits of an integer.
E.g.
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
import sys
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = str(x)
if(s[0] == '-'):
s = '-' + s[1::][::-1]
else:
s = s[::-1]
while(len(s) > 1 and s[0] == '0'):
s = s[1::]
if(int(s) >= 2 ** 31 or int(s) < (-2) ** 31):
return 0
else:
return int(s)
|
74a739b7b55ef53fe62e892d468b8ee5b4d94e6f | l3ouu4n9/LeetCode | /algorithms/350. Intersection of Two Arrays II.py | 610 | 4 | 4 | """
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
"""
from collections import Counter
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list((Counter(nums1) & Counter(nums2)).elements())
|
e29e7c01ed08fc5cef0d2eeb50da36e3c86ffa25 | Ryuji-commit/AtCoder-Python | /ABC165/165_B.py | 163 | 3.515625 | 4 | import math
X = int(input())
now = 100
count = 0
while(True):
count += 1
now = math.floor(now * 1.01)
if now >= X:
print(count)
break
|
66c6394de9d7b855ff15d1c30686a4301a576d7e | Ryuji-commit/AtCoder-Python | /ABC173/173_C.py | 1,535 | 3.890625 | 4 | import copy
# ここら辺はライブラリで求めるのが正解
def combination(num):
result_combination = [[0]]
recursion([], 1, num, result_combination)
return result_combination
def recursion(combination_list, i, max_num, result_combination):
if i > max_num:
if len(combination_list) > 0:
result_combination.append(combination_list)
return
new_list = combination_list + [i]
recursion(new_list, i+1, max_num, result_combination)
recursion(combination_list, i+1, max_num, result_combination)
def fill_table(line_list, row_list, h, w, table):
count = 0
copied_table = copy.deepcopy(table)
for line in line_list:
if line == 0:
continue
for row in range(w):
copied_table[line-1][row] = '.'
for row in row_list:
if row == 0:
continue
for line in range(h):
copied_table[line][row-1] = '.'
for line in range(h):
for row in range(w):
if copied_table[line][row] == '#':
count += 1
return count
def main():
h, w, k = map(int, input().split())
table = []
for _ in range(h):
table.append(list(input()))
result = 0
combination_h = combination(h)
combination_w = combination(w)
for line_list in combination_h:
for row_list in combination_w:
if fill_table(line_list, row_list, h, w, table) == k:
result += 1
print(result)
if __name__ == '__main__':
main()
|
2a569c9d2f1d8065df49a6e5c32ed258772df51e | datsaloglou/100DaysPython | /Module1/Day14/challenge_completed_da.py | 1,749 | 3.65625 | 4 |
content = ["Wayne is the toughest guy in Letterkenny.", list(range(0,101,10)), ("Wayne", "Dan", "Katy", "Daryl"), 10.4]
for i in range(0, len(content)):
# if the object is immutable, print the type and advance to the next step.
if type(content[i]) is tuple:
print ("{} is a {}".format(content[i], type(content[i])))
# if the object is mutable and a string, add "Allegedly" to the end.
elif type(content[i]) is str:
content[i] += " Allegedly."
print(content[i])
# if the object is mutable and a number, take 10 % off (for an int) and overwrite the value in the existing position.
elif type(content[i]) is list:
new_list = content[i]
for j in range(0, len(new_list)):
if type(new_list[j]) is int:
new_list[j] -= new_list[j] * .1
# print the new value
# to 20 % off (for a float) and overwrite the value in the existing position.
elif type(new_list[j]) is float:
new_list[j] -= new_list[j] * .2
# print the new value
content[i] = new_list
print(new_list)
elif type(content[i]) is int:
content[i] -= content[i] * .1
# print the new value
print(content[i])
# to 20 % off (for a float) and overwrite the value in the existing position.
elif type(content[i]) is float:
content[i] -= content[i] * .2
# print the new value
print(content[i])
# If an object is not a string, number, or tuple end the program immediately
# while displaying the object and the type for review.
else:
print("{} is a {}, and nothing was done about it.".format(content[i], type(content[i])))
break
|
10eec44cfcbb285ef26963cb919db5b1c8fa4b78 | grigorescu/abalone | /server/gameState.py | 18,269 | 4.0625 | 4 | import copy
from ball import white, black, empty
import utils
class GameState:
"""Stores the state of the game at any given time."""
def __init__(self):
"""Start a new game."""
self.board = [
[black, black, black, black, black],
[black, black, black, black, black, black],
[empty, empty, black, black, black, empty, empty],
[empty, empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty, empty],
[empty, empty, white, white, white, empty, empty],
[white, white, white, white, white, white],
[white, white, white, white, white]
]
self.turn = black
self.black_marbles_removed = 0
self.white_marbles_removed = 0
def get_turn(self):
"""Get a text representation of who's turn it is."""
if self.turn == black:
return "black"
else:
return "white"
def proc_move(self, move, preview=False):
"""Process a move. If preview == True, it won't actually store the move, just return the board state that would
result.
Move notation:
In-line move:
Start and end position of the "pushing" marble. e.g. I5-H5
Broad-side move:
Start positions of the two extremities of the row followed by the end position of the first one. e.g.
I5-I7-H4
"""
black_count = self.black_marbles_removed
white_count = self.white_marbles_removed
if black_count >= 6:
raise EOFError("The game is over - white has won")
if white_count >= 6:
raise EOFError("The game is over - black has won")
if move.count("-") == 1:
result, marble_removed = self._proc_inline_move(move)
if marble_removed and self.turn == white:
black_count += 1
if marble_removed and self.turn == black:
white_count += 1
elif move.count("-") == 2:
result = self._proc_broadside_move(move)
else:
raise ValueError("Unknown move notation")
if preview:
return result, black_count, white_count
self.turn = utils.get_opposite_marble(self.turn)
self.black_marbles_removed = black_count
self.white_marbles_removed = white_count
self.board = result
return result, black_count, white_count
def _proc_inline_move(self, move):
"""Process an inline move, e.g. I5-H5.
Returns a tuple of: the new board position, T if a black marble was removed, T if a white marble was removed"""
#########
# Check 1 - Are we moving a distance of 1?
start, end = move.split('-')
start_row, start_col = utils.parse_position(start)
end_row, end_col = utils.parse_position(end)
direction, distance = utils.get_direction(start_row, start_col, end_row, end_col)
#print "Direction is", direction
if distance != 1:
raise ValueError("Invalid move - can only move a distance of 1")
marble = self.turn
#########
# Check 2 - Is there a matching marble in the starting position?
try:
if self._get_marble(start_row, start_col) != marble:
raise ValueError("Invalid move - start marble is not yours!")
#######
# Check 3 - If we're here, the starting position is not on the board.
except IndexError:
raise ValueError("Invalid move - start position is off the board")
#########
# Check 4 - The end position can't have a marble of the opposite color.
try:
if self._get_marble(end_row, end_col) == utils.get_opposite_marble(marble):
# Clearly illegal. Is this a pac, though?
if self._get_marble(start_row, start_col, direction, 2, True) == empty:
raise ValueError("Pac - 1 v 1")
else:
raise ValueError("Invalid move - don't have superior strength to push")
#######
# Check 5 - If we're here, the end position is not on the board.
except IndexError:
raise ValueError("Invalid move - end position is off the board")
# For documentation, we'll assume our marble is white
if self._get_marble(start_row, start_col, direction, 1) == empty:
# We're pushing one white into an empty space - Legal move
board = self._set_marble(start_row, start_col, empty)
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 1)
board = self._set_marble(r, c, marble, board)
return board, False
else:
# Two white marbles in a row. We dealt with black in check 4.
if self._get_marble(start_row, start_col, direction, 2) == empty:
# We're pushing two whites into an empty space - Legal move
board = self._set_marble(start_row, start_col, empty)
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 2)
board = self._set_marble(r, c, marble, board)
return board, False
elif self._get_marble(start_row, start_col, direction, 2) == utils.get_opposite_marble(marble):
# Two whites against one black. What's in the next space?
if self._get_marble(start_row, start_col, direction, 3, True) == empty:
# Two whites pushing one black into an empty space - Legal move
board = self._set_marble(start_row, start_col, empty)
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 2)
board = self._set_marble(r, c, marble, board)
try:
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 3)
board = self._set_marble(r, c, utils.get_opposite_marble(marble), board)
except IndexError:
# We just pushed a black off the edge
return board, True
return board, False
elif self._get_marble(start_row, start_col, direction, 3) == utils.get_opposite_marble(marble):
# Two whites against two blacks. Can't do this, but is this a pac or just an invalid move?
if self._get_marble(start_row, start_col, direction, 4) == empty:
# We're pushing two whites against two blacks followed by an empty space
raise ValueError("Pac - 2 v 2")
else:
# We're pushing two whites against two blacks and some other stuff
raise ValueError("Invalid move - blocked by other marbles behind it")
else:
# Two whites, one black, one white
raise ValueError("Invalid move - blocked by one of your marbles behind it")
else:
# Three white marbles in a row.
if self._get_marble(start_row, start_col, direction, 3) == empty:
# We're pushing three whites into an empty space - Legal move
board = self._set_marble(start_row, start_col, empty)
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 3)
board = self._set_marble(r, c, marble, board)
return board, False
elif self._get_marble(start_row, start_col, direction, 3) == utils.get_opposite_marble(marble):
# Three whites against one black. What's in the next space?
if self._get_marble(start_row, start_col, direction, 4, True) == empty:
# Three whites pushing one black into an empty space - Legal move
board = self._set_marble(start_row, start_col, empty)
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 3)
board = self._set_marble(r, c, marble, board)
try:
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 4)
board = self._set_marble(r, c, utils.get_opposite_marble(marble), board)
except IndexError:
# We just pushed a black off the edge
return board, True
return board, False
elif self._get_marble(start_row, start_col, direction, 4) == utils.get_opposite_marble(marble):
# Three whites against two blacks. What's in the next space?
if self._get_marble(start_row, start_col, direction, 5, True) == empty:
# Three whites pushing two blacks into an empty space - Legal move
board = self._set_marble(start_row, start_col, empty)
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 3)
board = self._set_marble(r, c, marble, board)
try:
r, c = utils.calc_position_at_distance(start_row, start_col, direction, 5)
board = self._set_marble(r, c, utils.get_opposite_marble(marble), board)
except IndexError:
# We just pushed a black off the edge
return board, True
return board, False
elif self._get_marble(start_row, start_col, direction, 5) == utils.get_opposite_marble(marble):
# Three whites against three blacks. Can't do this, but is this a pac or just an invalid move?
if self._get_marble(start_row, start_col, direction, 6) == empty:
# We're pushing three whites against three blacks followed by an empty space
raise ValueError("Pac - 3 v 3")
else:
# We're pushing three whites against three blacks and some other stuff
raise ValueError("Invalid move - blocked by other marbles behind it")
else:
# Three whites, two blacks, white
raise ValueError("Invalid move - blocked by your marble behind it")
else:
# Three whites, one black, white
raise ValueError("Invalid move - blocked by your marble behind it")
else:
# Four whites
raise ValueError("Invalid move - can't push 4 marbles")
def _proc_broadside_move(self, move):
"""Process an broadside move, e.g. I5-I7-H5"""
line_start, line_end, end = move.split('-')
line_start_row, line_start_col = utils.parse_position(line_start)
line_end_row, line_end_col = utils.parse_position(line_end)
end_row, end_col = utils.parse_position(end)
#########
# Check 1 - Is the line actually a line and <= 3 in length?
line_direction, line_distance = utils.get_direction(line_start_row, line_start_col, line_end_row, line_end_col)
if line_distance > 2:
raise ValueError("Invalid move - can only move 1, 2, or 3 marbles broadside")
if line_distance == 2:
# Direction:
# NE = 1, E = 2, SE = 3
# SW = 4, W = 5, NW = 6
# Col changes in all cases except for SE and NW
if line_direction not in (3, 6):
line_mid_col = max(line_start_col, line_end_col) - 1
else:
line_mid_col = line_start_col
# Row changes in all cases except for E and W
if line_direction not in (2, 5):
line_mid_row = max(line_start_row, line_end_row) - 1
else:
line_mid_row = line_start_row
if line_distance == 0:
# This is the same as an inline push of 1 marble
inline_result, inline_was_pushed = self._proc_inline_move(move[3:8])
return inline_result
marble = self.turn
#########
# Check 2 - Is there a matching marble in the line start position?
try:
if self._get_marble(line_start_row, line_start_col) != marble:
raise ValueError("Invalid move - line start marble is not yours!")
#######
# Check 3 - If we're here, the line start position is not on the board.
except IndexError:
raise ValueError("Invalid move - line start position is off the board")
#########
# Check 4 - Is there a matching marble in the line end position?
try:
if self._get_marble(line_end_row, line_end_col) != marble:
raise ValueError("Invalid move - line end marble is not yours!")
#######
# Check 5 - If we're here, the line end position is not on the board.
except IndexError:
raise ValueError("Invalid move - line end position is off the board")
#########
# Check 6 - If the line is of length 3, is there a matching marble in the middle position?
try:
if line_distance == 2 and self._get_marble(line_mid_row, line_mid_col) != marble:
raise ValueError("Invalid move - middle marble is not yours!")
#######
# Check 7 - If we're here, the middle position is not on the board... defying the laws of physics, somehow
except IndexError:
raise ValueError("Invalid move - middle marble position is off the board")
move_direction, move_distance = utils.get_direction(line_start_row, line_start_col, end_row, end_col)
if move_distance != 1:
raise ValueError("Invalid move - can only move a distance of 1")
######
# Check 8 - Is the end position of the first marble empty?
try:
if self._get_marble(end_row, end_col) != empty:
raise ValueError("Invalid move - end position of the first marble is not empty")
######
# Check 9 - If we're here, the end position of the first marble is not on the board.
except IndexError:
raise ValueError("Invalid move - end position of the first marble is off the board")
######
# Check 10 - Is the end position of the last marble empty?
try:
if self._get_marble(line_end_row, line_end_col, move_direction, 1) != empty:
raise ValueError("Invalid move - end position of the last marble is not empty")
######
# Check 11 - If we're here, the end position of the last marble is not on the board.
except IndexError:
raise ValueError("Invalid move - end position of the last marble is off the board")
if line_distance == 2:
######
# Check 14 - Is the end position of the middle marble empty?
try:
if self._get_marble(line_mid_row, line_mid_col, move_direction, 1) != empty:
raise ValueError("Invalid move - end position of the middle marble is not empty")
######
# Check 15 - If we're here, the end position of the middle marble is not on the board - somehow.
except IndexError:
raise ValueError("Invalid move - end position of the middle marble is off the board")
board = self._set_marble(line_start_row, line_start_col, empty)
board = self._set_marble(end_row, end_col, marble, board)
board = self._set_marble(line_end_row, line_end_col, empty, board)
r, c = utils.calc_position_at_distance(line_end_row, line_end_col, move_direction, 1)
board = self._set_marble(r, c, marble, board)
if line_distance == 2:
board = self._set_marble(line_mid_row, line_mid_col, empty, board)
r, c = utils.calc_position_at_distance(line_mid_row, line_mid_col, move_direction, 1)
board = self._set_marble(r, c, marble, board)
return board
def _get_marble(self, row, col, direction=0, hops=0, edge_is_empty=False):
"""For a given starting row & col (e.g. (1, 3)), a direction, and a number of "hops," return the marble in that
position.
If edge_is_empty=True, treat positions off the board as empty (this is useful for pushing when you
don't care if you're pushing off the board or not)."""
if row < 0 or col < 0:
raise IndexError("Negative position")
if hops > 0:
try:
r, c = utils.calc_position_at_distance(row, col, direction, hops)
except IndexError, e:
if edge_is_empty:
return empty
else:
raise IndexError(e)
else:
r, c = row, col
if r < 4:
#print "Marble at position", r, c, "is", self.board[r][c]
return self.board[r][c]
if c-(r-4) < 0:
raise IndexError("Negative position")
#print "Marble at upper position", r, c-(r-4), "is", self.board[r][c-(r-4)]
return self.board[r][c-(r-4)]
def _set_marble(self, row, col, marble, board=None):
"""Set the marble at (row, col)."""
if not 0 <= row <= 8:
raise IndexError("Row is off the board")
if not 0 <= col <= 8:
raise IndexError("Column is off the board")
if not board:
board = copy.deepcopy(self.board)
if row < 4:
board[row][col] = None
board[row][col] = marble
return board
board[row][col-(row-4)] = None
board[row][col-(row-4)] = marble
return board
|
4f85b8be417d4253520781c0f99e31af282d60b7 | sjtrimble/pythonCardGame | /cardgame.py | 2,811 | 4.21875 | 4 | # basic card game for Coding Dojo Python OOP module
# San Jose, CA
# 2016-12-06
import random # to be used below in the Deck class function
# Creating Card Class
class Card(object):
def __init__(self, value, suit):
self.value = value
self.suit = suit
def show(self):
print self.value + " " + self.suit
# Creating Deck Class
class Deck(object):
def __init__(self):
self.cards = []
self.get_cards() # running the get_card method defined below to initiate with a full set of cards as your deck
def get_cards(self):
suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
for suit in suits: # iterating through the suits
for value in values: # iterating through each value
newcard = Card(value, suit) # creating a newcard variable with the class Card and passing the iterations from the for loop
self.cards.append(newcard) # adding the newly created card of Card class and adding it to the cards variable within the deck class object/instance
def show(self):
for card in self.cards:
card.show() # calling the Card class' show method (see above in Card class section) - this is okay because the item it's iterating through it of the Card class
def shuffle(self):
random.shuffle(self.cards) # using random.shuffle method - import random above needs to be set before using
def deal(self):
return self.cards.pop() # returning the removed last value (a card of class Card) of the cards variable
# Creating Player Class
class Player(object):
def __init__(self, name):
self.hand = []
self.name = name
def draw_cards(self, number, deck): # also need to pass through the deck here so that the player can have cards deal to them from that deck of class Deck
if number < len(deck.cards):# to ensure that the amount of cards dealt do not exceed how many cards remain in a deck
for i in range (number): # iterating through the cards in the deck
self.hand.append(deck.deal()) # appending it to the player's hand variable set above
print "Sorry, the deck is out of cards"
def show(self):
for card in self.hand:
card.show() # calling the Card class' show method (see above in Card class section) - this is okay because the item it's iterating through it of the Card class
# Sample Order of Process
mydeck = Deck() # create a new deck with Deck class
mydeck.shuffle() # shuffle the deck
player1 = Player('Bob') # create a new player
player1.draw_cards(5, mydeck) # draw 5 card from the mydeck deck created
player1.show() # show the player's hand of cards that has been drawn |
1e6e66026c83ba3c859b919c7df9a344b2493847 | MikeThomson/Project-Euler-Python | /problem001.py | 116 | 3.734375 | 4 | #!/usr/bin/python
total = 0
for i in range(1,1000):
if ((i % 3) == 0) or ((i % 5) == 0):
total += i
print total
|
6e2fd2cc56821e6aeb9ac0beb5173a9d57c03f67 | ericd9799/PythonPractice | /year100.py | 421 | 4.125 | 4 | #! /usr/bin/python3
import datetime
now = datetime.datetime.now()
year = now.year
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
yearsToHundred = 100 - age
turnHundred = int(year) + yearsToHundred
message = name + " will turn 100 in the year "+ str(turnHundred)
print(message)
repeat = int(input("Please enter integer to repeat message: "))
print(repeat * (message + "\n"))
|
1b6d711b5078871fca2de4fcf0a12fc0989f96e4 | ericd9799/PythonPractice | /modCheck.py | 497 | 4.125 | 4 | #! /usr/bin/python3
modCheck = int(input("Please enter an integer: "))
if (modCheck % 4) == 0:
print(str(modCheck) + " is a multiple of 4")
elif (modCheck % 2) == 0:
print(str(modCheck) + " is even")
elif (modCheck % 2) != 0:
print(str(modCheck) + " is odd")
num, check = input("Enter 2 numbers:").split()
num = int(num)
check = int(check)
if num % check == 0:
print(str(check) + " divides evenly into " + str(num))
else:
print(str(check) + " does not divide evenly into " + str(num))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.