blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1184871d1e2bf1abe936750ab254bfb973f8b26e | DeepLenin/phns | /phns/utils/contractions.py | 6,413 | 3.703125 | 4 | """
Сочетания модификаторов:
- "to be" + not
- "to have" + not
- "to do" + not
- can + not
- will + not
- shall + not
- modal verbs + [have, not, not + have]
"""
MODAL_VERBS = ["could", "should", "would", "ought", "might", "must", "need"]
MODIFIERS = {
"am",
"is",
"are",
"was",
"were",
"have",
"has",
"had",
"does",
"did",
"could",
"will",
"would",
"shall",
"should",
"not",
}
ALIASES = {
("let", "us"): "let's",
("of", "course"): "'course",
("it", "was"): "'twas",
("it", "is"): "'tis",
}
def encode(word_idx, sentence):
word1 = sentence[word_idx].lower()
if "'" in word1:
return word1, 0
modifiers = [word1]
for word in sentence[word_idx + 1 :]:
word = word.lower()
if word in MODIFIERS and __compatible__(modifiers, word):
modifiers.append(word)
else:
if len(modifiers) == 1 and ALIASES.get((word1, word)):
modifiers.append(word)
break
return "^".join(modifiers), len(modifiers) - 1
def decode(word):
modifiers = word.split("^")
variants = [modifiers]
mod_len = len(modifiers)
alias = ALIASES.get((modifiers[0], modifiers[1]))
if alias:
variants.append([alias, *modifiers[2:]])
if mod_len == 2:
word1, word2 = modifiers
if word1 in MODAL_VERBS and word2 in ["not", "have"]:
if word2 == "not":
variants.append([word1 + "n't"])
elif word2 == "have":
variants.append([word1 + "'ve"])
elif word1 in MODIFIERS.union({"can", "do"}) and word2 == "not":
if word1 in ["was", "were", "had", "do", "did", "does"]:
variants.append([word1 + "n't"])
elif word1 == "shall":
# TODO: there is no shan't in CMU dict
variants.append(["shan't"])
elif word1 == "will":
variants.append(["won't"])
elif word1 == "can":
variants += [["can't"], ["cannot"]]
elif word1 in ("am", "is", "are", "has", "have"):
if word1 != "am":
variants.append([word1 + "n't"])
variants.append(["ain't"])
elif word1 == "dare":
variants.append(["daren't"])
else:
raise ValueError(word)
else:
if word2 == "am":
if word1 == "i":
variants.append(["i'm"])
else:
raise ValueError(word)
elif word2 in ["is", "has", "does", "was"]:
variants.append([word1 + "'s"])
elif word2 in ["are", "were"]:
variants.append([word1 + "'re"])
elif word2 in ["have"]:
variants.append([word1 + "'ve"])
elif word2 in ["will", "shall"]:
variants.append([word1 + "'ll"])
elif word2 in ["had", "did", "could", "would", "should"]:
variants.append([word1 + "'d"])
elif not alias:
raise ValueError(word)
# TODO: she'll've (she will have)
# TODO: he'd've (he would have)
elif mod_len == 3:
word1, word2, word3 = modifiers
if word2 in MODAL_VERBS and word3 == "have":
if word2 in ["should", "would", "could"]:
variants.append([word1 + "'d", word3])
variants.append([word1, word2 + "'ve"])
elif word3 == "not":
if word2 in ("am", "is", "are", "has", "have"):
variants.append([word1, "ain't"])
if (
word2
in [
"is",
"are",
"were",
"was",
"have",
"has",
"had",
"do",
"did",
"does",
]
+ MODAL_VERBS
):
variants.append([word1, word2 + "n't"])
elif word2 == "can":
variants += [[word1, "can't"], [word1, "cannot"]]
elif word2 == "will":
variants.append([word1, "won't"])
elif word2 == "shall":
variants.append([word1, "shan't"])
elif word2 != "am": # Already handled above
raise ValueError(word)
if word2 == "am":
if word1 == "i":
variants.append(["i'm", word3])
else:
raise ValueError(word)
elif word2 in ["is", "has", "does", "was"]:
variants.append([word1 + "'s", word3])
elif word2 in ["are", "were"]:
variants.append([word1 + "'re", word3])
elif word2 in ["have"]:
variants.append([word1 + "'ve", word3])
elif word2 in ["will", "shall"]:
variants.append([word1 + "'ll", word3])
elif word2 in ["had", "did", "could", "would", "should"]:
variants.append([word1 + "'d", word3])
elif word2 in ["do", "can"]:
pass
else:
raise ValueError(word)
else:
raise ValueError(word)
elif mod_len == 4:
word1, word2, word3, word4 = modifiers
if word2 in MODAL_VERBS and word3 == "not" and word4 == "have":
if word2 in ["should", "would", "could"]:
variants.append([word1 + "'d", word3, word4])
variants += [[word1, word2 + "n't", word4], [word1, word2 + "n't've"]]
else:
raise ValueError(word)
else:
raise ValueError(word)
return variants
def __compatible__(modifiers, modifier):
not_modifier = modifier == "not"
if modifier == "am" and modifiers != ["i"]:
return False
if len(modifiers) == 1 and modifiers[0] not in MODIFIERS.union({"can", "do"}):
return not (not_modifier)
if not_modifier:
return True
if modifier == "have":
if modifiers[-1] in MODAL_VERBS:
return True
if (
modifiers[-1] == "not"
and len(modifiers) > 1
and modifiers[-2] in MODAL_VERBS
):
return True
return False
|
db35a91cd01659407280f8a094d7733289be5721 | karendi/python | /excercise36.py | 1,090 | 3.765625 | 4 | from sys import exit
from sys import argv
script, username = argv
def red_ball() :
print("you have chosen a red ball")
pick_bat()
hit_ball()
def blue_ball() :
print("you have chosen a blue ball")
pick_bat()
hit_ball()
def green_ball() :
print("you have chosen a green ball")
pick_bat()
hit_ball()
def pick_bat():
bat = input("Please choose either a green blue or red bat?")
if bat == "green":
print("You can only use it to hit either the blue or red ball")
elif bat == "blue" :
print("You can use it to hit either the blue or green ball")
elif bat == "red" :
print("You can use it to hit either the blue or green ball")
else:
exit(0)
def hit_ball():
message = print("Congragulations you have hit the ball")
player = input("whats your name?")
print("okay %s welcome.." %player)
print("please pick a ball")
ball = input("please choose the ball you want")
if ball == "red":
red_ball()
elif ball == "blue":
blue_ball()
elif ball == "green":
green_ball()
else:
exit(0)
|
d02324dd69efea0b56139bc7b049f103e3b7f171 | peleduri/baby-steps | /baby steps/Learn_py/ex5.py | 522 | 3.765625 | 4 | my_name = 'Uri Peled'
my_age = 27
my_height = 165 # cn
my_weight = 65 # kg
my_eyes = 'brown'
my_teeth = 'White'
my_hair = 'Blonde'
print (f"Let's talk about {my_name}.")
print (f"He's {my_height} cn tall")
print (f"He's {my_weight} kg heavy")
print (f"Actually that's not too heavy.")
print (f"He's got {my_eyes} eyes and {my_hair} hair")
print (f"His teeth are usually {my_teeth} depending on the coffee")
total = [my_age] + [my_height] + [my_weight]
print(f"if I add {my_age}, {my_height}, and {my_weight} I get {total}")
|
dea484075682bce5707bc3cb61eef2c2d6bcfb72 | varun3108/Agent-Selector-based-on-issue | /AgentSelect.py | 5,430 | 3.65625 | 4 | import datetime
import random
agent_list= [1001, True, datetime.time(8, 0), 'Support', 1002, True, datetime.time(10, 0), 'Sales', 1003, True, datetime.time(11, 0), 'Spanish speaker', 1004, True, datetime.time(12, 0), 'Sales', 1005, True, datetime.time(11, 0), 'Support', 1006, True, datetime.time(12, 0), 'Spanish speaker', 1007, True, datetime.time(15, 0), 'Sales', 1008, True, datetime.time(16, 0), 'Spanish speaker', 1009, True, datetime.time(9, 0), 'Sales', 1010, True, datetime.time(16, 0), 'Support']
roles = ['Support', 'Sales', 'Spanish speaker']
"""
LIST OF AGENTS
The following code is to enter details of agents to create an agent list.
It also takes into consideration the types of roles by making a list of roles.
AGENT LIST CREATION (OPTIONAL)
i = 'Y'
agent_list = []
roles = []
while i == 'Y':
add_detail = input('Do you want to enter agent details (Y/N):')
if add_detail == 'Y':
agent_id = int(input('Agent ID:'))
is_available = bool(input('Agent Availablity (True/False):'))
available = input('specify time since agent is available in HH,MM format:')
available = available.split(',')
available_since = datetime.time(int(available[0]),int(available[1]))
role = str(input('Enter the Role:'))
agent_list.append(agent_id)
agent_list.append(is_available)
agent_list.append(available_since)
agent_list.append(role)
if role not in roles:
roles.append(role)
else:
break
"""
issues = [9001, 'Technical problems with the platform', datetime.time(13, 38), 'Support', 9002, 'Want to know about features in spanish language.', datetime.time(8, 49), 'Sales,Spanish speaker', 9003, 'Want an AI chatbot for my website', datetime.time(11, 39), 'Sales,Support', 9004, 'Want to know about features in Japanese Language', datetime.time(10, 40), 'Japanese speaker,Sales']
"""
LIST OF ISSUES
The following code is to enter the issue and the type of role/roles of agents related to the issue.
issues = []
j = 'Y'
while j == 'Y':
add_detail = input('Do you want to enter issues details (Y/N):')
if add_detail == 'Y':
issue_id = int(input('Issue ID:'))
issue_desp = input('Issue:')
role_issue = str(input('Enter the Roles involved separated by comma:'))
timenow = ((datetime.datetime.now()).strftime("%X")).split(":")
#timenow = timenow.split(":")
time_now = datetime.time(int(timenow[0]),int(timenow[1]))
issues.append(issue_id)
issues.append(issue_desp)
issues.append(time_now)
issues.append(role_issue)
else:
break
"""
print ('AGENT LIST: ',agent_list)
print ('AGENT ROLES: ',roles)
print ('ISSUES LIST: ',issues)
select_mode = ''
the_issue = []
def agent_select(agent_list,select_mode,the_issue):
agent_reqd = []
types_roles= (the_issue[3]).split(',')
for k in range(len(types_roles)):
for l in range(int(len(agent_list)/4)):
if types_roles[k] == agent_list[(4*l +3)]:
agent_reqd.append(agent_list[(4*l)])
agent_reqd.append(agent_list[(4*l+1)])
agent_reqd.append(agent_list[(4*l+2)])
agent_reqd.append(agent_list[(4*l+3)])
if types_roles[k] not in agent_list:
print ('The role '+ types_roles[k] + ' is not available')
# print('LIST OF AGENTS WITH ROLES RELATED TO THE ISSUE: ',agent_reqd)
if select_mode == 'All available':
print('For the issue:')
print(the_issue)
print('with selection mode:')
print(select_mode)
print('Here are the agents:')
print(agent_reqd)
if select_mode == 'Least busy':
o = 0
Diff = []
timeDiff = 0
for n in range(int(len(agent_reqd)/4)):
A = datetime.datetime.combine(datetime.date.today(), the_issue[2])
B = datetime.datetime.combine(datetime.date.today(), agent_reqd[(4*n+2)])
timeDiff = A-B
timeDiff = int(timeDiff.total_seconds())
Diff.append(agent_reqd[(4*n)])
Diff.append(timeDiff)
if timeDiff > o :
o = timeDiff
# print('HIGHEST TIME DIFFERENCE BETWEEN THE ISSUE AND AVAILABILITY OF THE AGENT: ',o)
# print('LIST OF TIME DIFFERENCES: ',Diff)
for p in range(int(len(Diff)/2)):
if o == Diff[2*p+1]:
agent_reqd = agent_reqd[(4*p):(4*p+4)]
print('For the issue:')
print(the_issue)
print('with selection mode:')
print(select_mode)
print('Here is the agent:')
if o >0:
print(agent_reqd)
else:
print('NIL')
if select_mode == 'Random':
q = random.randrange(int(len(agent_reqd)/4))
agent_reqd = agent_reqd[(4*q):(4*q+4)]
print('For the issue:')
print(the_issue)
print('with selection mode:')
print(select_mode)
print('Here is the agent:')
print(agent_reqd)
for m in range(int(len(issues)/4)):
the_issue = issues[(4*m):(4*m+4)]
print ('THE ISSUE: ',the_issue)
select_mode = input('Select a selection mode (All available/Least busy/Random):')
agent_select(agent_list,select_mode,the_issue)
|
b70203f198a4c07f9d567ff9397b9c485014da78 | Twest19/prg105 | /Final Project/YT_final_project.py | 19,150 | 4.4375 | 4 | """
Tim West, Programming Logic 105 - Final Project
What does it do?
Uses a tkinter GUI to get a users preferences on the random YouTube videos they want to see. It then uses those
preferences to pull the correct videos from the YouTube API. The videos are then opened in the users default
browser.
What does it NOT do?
It does not play play YouTube videos within the GUI, nor does it download videos. The videos are also not
necessarily random, rather they are pulled from the most popular videos in each category for the day. All
controls over the video like volume, playback speed, and quality will still be handled via YouTube itself.
This is just merely a video opener.
Requirements for use ----
pip install --upgrade google-api-python-client
pip install tk
You will also NEED to get your own YouTube API key. Without it the program will not work! It is completely
free, you just need to create a Google account. DO NOT SHARE YOUR API KEY! I have put mine in an environment
variable so that others can not access it. I would recommend you do so as well! There is also a limit per day
on the number of requests you can send to the YouTube API. The limit for free accounts is 10,000 quota a day.
This program only uses about 2-3 quota per use, so you should never hit that limit.
You can find out more about this here:
https://developers.google.com/youtube/v3/getting-started
and here:
https://developers.google.com/youtube/v3/quickstart/python
I would also like to recommend that you have a YouTube account. YouTube sometimes has age restrictions on
videos, thus requiring a YouTube account.
How to use it?
A simple graphical user interface window will appear. At the top of the window you will see a text label that
asks you to choose a video category and the number of videos you want to see. The categories are inside a drop
down menu, as are the number of videos. The number of videos option is just giving you the option to play
anywhere from 1 - 15 videos. Later on you will be able to select if you want the videos to open all at once,
or open via a next button. Make sure to hit enter to submit your choices, if you do not the program will go no
further! Also if you hit enter without making a choice in one of the boxes, it will pop up a message window
telling you to make a selection.
After you have hit enter a new set of drop down menus will appear. These menus will give you the option of how
you want the videos to appear. The first box that says "Randomize" has several options for what order the
videos should play in. "Randomize" will randomize the order, "Most Popular First" will play the most popular
video first, and "Least Popular First" will play the least most popular video first. The "Options" menu gives
you the choice of "Open All" which will open all the videos at once in your browser, or "Open on Click" which
will open the first video automatically and then consecutive videos will be opened by clicking the next button
or previous buttons.
Your videos should now have been opened in your default web browser. You will now have full control over them
just as if you were watching YouTube normally. Also if you choose the "Open All" option it may or may not play
the videos back in the correct order. This is can happen when one video is loaded into the browser faster than
another. Unfortunately there is not much that can be done about that, except for choosing "Open on Click".
Resources ---
YouTube API links/Resources:
https://developers.google.com/youtube
https://developers.google.com/youtube/v3/getting-started
https://developers.google.com/youtube/v3/quickstart/python
https://github.com/googleapis/google-api-python-client/blob/master/docs/start.md
https://github.com/googleapis/google-api-python-client/blob/master/docs/README.md
https://github.com/youtube/api-samples
https://github.com/youtube/api-samples/blob/master/python/README.md
Tutorials that helped me get started with the YouTube API:
Corey Schafer: Python YouTube API Tutorial: Getting Started
https://www.youtube.com/watch?v=th5_9woFJmk&list=RDCMUCCezIgC97PvUuR4_gbFUs5g&index=3
Corey Schafer: Python YouTube API Tutorial: Calculating the Duration of a Playlist
https://www.youtube.com/watch?v=coZbOM6E47I&list=RDCMUCCezIgC97PvUuR4_gbFUs5g&index=3
Tkinter GUI Resources:
freecodecamp.org Tkinter course
https://youtu.be/YXPyB4XeYLA
Webbrowser Python Resources:
https://docs.python.org/3/library/webbrowser.html
Python Random:
https://docs.python.org/3/library/random.html
Python os:
https://docs.python.org/3/library/os.html
"""
import os
from googleapiclient.discovery import build
from tkinter import *
from tkinter import messagebox
import webbrowser
import random
class RandomVid:
"""This class uses the YouTube API to open a top YouTube video given a category"""
def __init__(self, api_key):
# Initialize Api key
self.api_key = api_key
# Create frames
self.top_frame = Frame(root)
self.top_frame.configure(bg='gray')
self.mid_frame = Frame(root)
self.mid_frame.configure(bg='darkgray', padx=36)
self.play_frame = Frame(root)
self.play_frame.configure(bg='gray')
self.status_frame = Frame(root)
self.status_frame.configure(bg='darkgray', padx=36)
self.next_frame = Frame(root)
self.next_frame.configure(bg='gray')
self.bot_frame = Frame(root)
self.bot_frame.configure(bg='gray')
# Need to initialize buttons/ labels for later use
self.next_btn = Button(self.next_frame)
self.prev_btn = Button(self.next_frame)
self.status = Label(self.next_frame)
# Put frames on screen
self.top_frame.pack(side='top')
self.mid_frame.pack(side='top')
self.play_frame.pack(side='top')
self.status_frame.pack(side='top')
self.next_frame.pack(side='top')
self.bot_frame.pack(side='top')
# Call self.Category() to display buttons
self.category()
def category(self):
# This is where we will contact the YouTube API to get the category names and ids
youtube = build('youtube', 'v3', developerKey=self.api_key)
request = youtube.videoCategories().list(
part='snippet',
regionCode='US'
)
response_one = request.execute() # Execute the youtube api request for categories
# Add the categories and category ids to dictionary, should update if YouTube adds any new ones
my_dict = {}
for item in response_one['items']:
if item['snippet']['assignable'] is False:
pass
else:
tube_dict1 = item['snippet']['title']
tube_dict2 = item['id']
my_dict[tube_dict1] = tube_dict2
# The Trending category will need to be added manually here
my_dict['Trending'] = '0'
# The Travel category does not work, so needs to be removed
del my_dict['Travel & Events']
# Numbers could go up to 50, but I would advise to stick to at most 15
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# Set the default option of the drop down menu to "Categories" and the other to "Number Videos
clicked = StringVar()
clicked.set("Categories")
results = IntVar()
results.set("Number Videos")
# Tell the user how to begin
description_label = Label(self.top_frame,
text='Choose a category and the number of videos you wish to view:',
bg='gray', wraplength=300)
description_label.grid(row=0, column=0, sticky=W)
# Create a drop down menu to have user make a selection
category_drop = OptionMenu(self.mid_frame, clicked, *my_dict.keys())
category_drop.config(width=18, bg='gray', activebackground='gray')
num_videos = OptionMenu(self.mid_frame, results, *numbers)
num_videos.config(width=18, bg='gray', activebackground='gray')
enter_button = Button(self.mid_frame, text="Enter", command=lambda: self.get_link(my_dict, clicked, results),
bg='lightgreen', activebackground='lightgreen', width=18)
# Add option menus and enter button to mid frame
category_drop.grid(row=1, column=0, padx=10, pady=10)
num_videos.grid(row=2, column=0, padx=10, pady=10)
enter_button.grid(row=2, column=1, pady=10, padx=10)
def get_link(self, my_dict, click, num):
try:
result = num.get()
clicked_label = click.get()
youtube = build('youtube', 'v3', developerKey=self.api_key)
# Uses selected category to get video ids from the YouTube API
request = youtube.videos().list(
part='snippet,contentDetails,statistics',
chart='mostPopular',
regionCode='US',
videoCategoryId=my_dict[clicked_label],
maxResults=result
)
vid_list = []
response_two = request.execute()
for item in response_two['items']: # Saves video ids to a list
vid_list.append(item['id'])
except (KeyError, TclError):
messagebox.showwarning('Error', 'Please select from the drop down menus, then hit enter!')
else:
file = open('youtube_links.txt', 'w') # Writes the links to a file
for ids in vid_list:
vids = f'https://www.youtube.com/watch?v={ids}' # Inserts video ids into a youtube link
file.write(vids + '\n')
file.close()
self.vid_opener()
def vid_opener(self):
# Adds the youtube links from the file to a list
file_in = open('youtube_links.txt', 'r')
lines = file_in.readlines()
url_list = []
url_list2 = []
for url in lines:
url_list.append(url.strip('\n'))
url_list2.append(url.strip('\n'))
file_in.close()
options = ['Randomize', 'Most Popular First', 'Least Popular First']
selected = StringVar()
selected.set('Randomize')
# Label and menu button for video play back
play_label = Label(self.play_frame, text='Choose the order you want the videos played:', bg='gray')
play_label.grid(row=0, column=0)
playback_menu = OptionMenu(self.status_frame, selected, *options)
playback_menu.config(width=18, bg='gray', activebackground='gray')
playback_menu.grid(row=1, column=0, padx=10, pady=10)
options = StringVar()
options.set("Options")
option_list = ['Open All', 'Open on Click']
option_btn2 = OptionMenu(self.status_frame, options, *option_list)
option_btn2.config(width=18, bg='gray', activebackground='gray')
option_btn2.grid(row=2, column=0, padx=10, pady=10)
enter_button = Button(self.status_frame, text="Enter",
command=lambda: self.get_options(selected, url_list, options, url_list),
bg='lightgreen', activebackground='lightgreen', width=18)
enter_button.grid(row=2, column=1, pady=10, padx=10)
def get_options(self, select, urls, option, urls2): # Takes users selected options and continues depending on them
new = 0
choice = select.get()
options = option.get()
if options != 'Options':
if options == 'Open All':
self.next_btn.grid_forget()
self.prev_btn.grid_forget()
self.status.grid_forget()
# If you play on click the order the videos open is different than all at once
if choice == 'Randomize':
random.shuffle(urls2)
for links in urls2: # Need to use a different list here since it will shuffle the urls
webbrowser.open(links, new=new)
elif choice == 'Most Popular First' or 'Least Popular First':
if choice == 'Most Popular First':
urls = urls[::-1]
elif choice == 'Least Popular First':
pass
for links in urls: # Opens the links in default web browser
webbrowser.open(links, new=new)
elif options == 'Open on Click':
# If you play on click the order the videos open is different than all at once
if choice == 'Randomize':
random.shuffle(urls2)
webbrowser.open(urls2[0], new=new)
elif choice == 'Most Popular First' or 'Least Popular First':
if choice == 'Most Popular First':
pass
elif choice == 'Least Popular First':
urls = urls[::-1]
# Opens the links in default web browser
webbrowser.open(urls[0], new=new)
# Create next and previous buttons
self.next_btn = Button(self.next_frame, text='Next',
command=lambda: self.next_vid(urls, 1), bg='cyan', width=8)
# Do not want to go backwards at first video
if urls[0]:
self.prev_btn = Button(self.next_frame, text="Prev", state=DISABLED, bg='red', width=8)
else:
self.prev_btn = Button(self.next_frame, text='Prev',
command=lambda: self.prev_vid(urls, 1), bg='pink', width=8)
# Create a status bar to display what number video is playing
self.status = Label(self.next_frame, text='Video 1 of ' + str(len(urls)),
relief=SUNKEN, width=16)
# Put Buttons on the screen
self.next_btn.grid(row=4, column=2, sticky=E, pady=5, padx=10)
self.status.grid(row=4, column=1, sticky=E + W, padx=5, ipadx=4)
self.prev_btn.grid(row=4, column=0, sticky=W, pady=5, padx=10)
update_label = Label(self.bot_frame, text="Your videos will open shortly.", bg='gray')
notice_label = Label(self.bot_frame,
text='*Please note that the "Open All" option may not open all of the videos in '
'the correct order. '
'This is due to varying factors out of the programs control.',
bg='gray', wraplength=250)
update_label.grid(row=5, column=0, sticky=E + W)
notice_label.grid(row=6, column=0, sticky=E + W)
else:
messagebox.showwarning('Error', 'Please select from the drop down menus, then hit enter!')
def next_vid(self, urls, num): # Allows for a next video to be played
new = 0
current_vid = urls[num]
webbrowser.open(current_vid, new=new)
# Need to forget the previous buttons so new ones can be applied
self.next_btn.grid_forget()
self.prev_btn.grid_forget()
self.status.grid_forget()
# Create status bar and next/prev buttons
self.status = Label(self.next_frame, text='Video ' + str(num + 1) + ' of ' + str(len(urls)),
relief=SUNKEN, width=16)
# If it is the last video do not want to keep going, so disable next
if urls[num] == urls[len(urls) - 1]:
self.next_btn = Button(self.next_frame, text="Next", state=DISABLED, bg='red', width=8)
else:
self.next_btn = Button(self.next_frame, text='Next',
command=lambda: self.next_vid(urls, num + 1), bg='cyan', width=8)
self.prev_btn = Button(self.next_frame, text='Prev',
command=lambda: self.prev_vid(urls, num - 1), bg='pink', width=8)
# Place the buttons and label onto a grid
self.next_btn.grid(row=4, column=2, sticky=E, pady=5, padx=10)
self.status.grid(row=4, column=1, sticky=E + W, padx=5, ipadx=4)
self.prev_btn.grid(row=4, column=0, sticky=W, pady=5, padx=10)
def prev_vid(self, urls, num): # Allows for a previous video to be played
new = 0
current_vid = urls[num]
webbrowser.open(current_vid, new=new)
# Need to forget the previous buttons\labels to not mess up new buttons\labels
self.next_btn.grid_forget()
self.prev_btn.grid_forget()
self.status.grid_forget()
# Create status bar and next/prev buttons
self.status = Label(self.next_frame, text='Video ' + str(num + 1) + ' of ' + str(len(urls)),
relief=SUNKEN, width=16)
self.next_btn = Button(self.next_frame, text='Next',
command=lambda: self.next_vid(urls, num + 1), bg='cyan', width=8)
self.prev_btn = Button(self.next_frame, text='Prev',
command=lambda: self.prev_vid(urls, num - 1), bg='pink', width=8)
# If its the first video do not want to go backwards
if urls[num] == urls[0]:
self.prev_btn = Button(self.next_frame, text="Prev", state=DISABLED, bg='red', width=8)
# Place the buttons and label onto a grid
self.prev_btn.grid(row=4, column=0, sticky=W, padx=10, pady=5)
self.status.grid(row=4, column=1, sticky=E + W, ipadx=4)
self.next_btn.grid(row=4, column=2, sticky=E, padx=10, pady=5)
# Program starts here
if __name__ == '__main__':
root = Tk()
root.title("Random YouTube Video?") # This is title of program
root.iconbitmap('C:/Users/white/Desktop/YouTube Python Project/Project_imgs/youtube_button.ico')
root.geometry("400x400")
root.configure(bg='gray')
root.resizable(False, False)
# Api key is stored as an environment variable, don't share your api key!
youtube_key = os.environ.get('YT_KEY')
youtube_vid = RandomVid(youtube_key)
root.mainloop()
|
83be6851ae93b99c875827bb0b197d07787ec039 | DeirdreHegarty/Augmented-Reality | /camera.py | 7,021 | 3.546875 | 4 | """ Example of using OpenCV API to detect and draw checkerboard pattern"""
import numpy as np
import cv2
# These two imports are for the signal handler
import signal
import sys
import calibcam # calibrate the camera
#### Some helper functions #####
def reallyDestroyWindow(windowName) :
''' Bug in OpenCV's destroyWindow method, so... '''
''' This fix is from http://stackoverflow.com/questions/6116564/ '''
cv2.destroyWindow(windowName)
for i in range (1,5):
cv2.waitKey(1)
def shutdown():
''' Call to shutdown camera and windows '''
global cap
cap.release()
reallyDestroyWindow('img')
def signal_handler(signal, frame):
''' Signal handler for handling ctrl-c '''
shutdown()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
##########
############## calibration of plane to plane 3x3 projection matrix
def compute_homography(fp,tp):
''' Compute homography that takes fp to tp.
fp and tp should be (N,3) '''
if fp.shape != tp.shape:
raise RuntimeError('number of points do not match')
# create matrix for linear method, 2 rows for each correspondence pair
num_corners = fp.shape[0]
# construct constraint matrix
A = np.zeros((num_corners*2,9));
A[0::2,0:3] = fp
A[1::2,3:6] = fp
A[0::2,6:9] = fp * -np.repeat(np.expand_dims(tp[:,0],axis=1),3,axis=1)
A[1::2,6:9] = fp * -np.repeat(np.expand_dims(tp[:,1],axis=1),3,axis=1)
# solve using *naive* eigenvalue approach
D,V = np.linalg.eig(A.transpose().dot(A))
H = V[:,np.argmin(D)].reshape((3,3))
# normalise and return
return H
##############
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# YOU SHOULD SET THESE VALUES TO REFLECT THE SETUP
# OF YOUR CHECKERBOARD
HEIGHT = 6
WIDTH = 9
# CAMWIDTH = 1280
# CAMHEIGHT = 720
CAMWIDTH = calibcam.w
CAMHEIGHT = calibcam.h
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((WIDTH*HEIGHT,3), np.float32)
objp[:,:2] = np.mgrid[0:HEIGHT,0:WIDTH].T.reshape(-1,2)
cap = cv2.VideoCapture(0)
## Step 0: Load the image you wish to overlay
im_src = cv2.imread('doge.jpg')
# im_src = cv2.imread('car.png')
pattern = cv2.imread('pattern.png')
ret,patterncorners = cv2.findChessboardCorners(pattern, (HEIGHT,WIDTH),None)
# linspace returns evenly spaced numbers over a specified interval
# a.k.a. splitting up my image to be projeced
wi = np.linspace(0, CAMWIDTH, WIDTH) # width of picture to project
hi = np.linspace(0, CAMHEIGHT, HEIGHT) # height of picture to project
# print(wi) # default to 50 intervals ( 0. 17.20408163 34.40816327 51.6122449 ...)
# print(hi)
# empty list
imgmat = []
# Now that I have wi and hi, create the XY coordinates for projected image
for i in wi:
for j in hi:
imgmat.append([i,j])
imgmat = np.matrix(imgmat)
# print(imgmat.shape) # X Y coordinates of linear space (54,2)
homoimg = np.concatenate((imgmat, np.ones(WIDTH*HEIGHT)[:,None]), axis=1)
# print(homoimg.shape) #(54,3)
while (True):
#capture a frame
ret, img = cap.read()
## IF YOU WISH TO UNDISTORT YOUR IMAGE YOU SHOULD DO IT HERE
# calibcam.py is imported at the top
# Our operations on the frame come here
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (HEIGHT,WIDTH),None)
# If found, add object points, image points (after refining them)
if ret == True:
# check of specified criteria above is met
# cornerSubPix refines the corner locations
# (11,11) specifies half of side length of search window
# (-1,-1) means no dead region in middle of search zone (chessboard)
cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
# reproject corners (diagonal lines)
# corners = 2d coordinates
# (Draw lines)
# cv2.drawChessboardCorners(img, (HEIGHT,WIDTH), corners,ret)
# print(corners.shape) #(54, 1, 2)
## STEP 1A : Compute fp -- an Nx3 array of the 2D homogeneous coordinates of the
## detected checkerboard corners
# SOLUTION:
# convert the 2d coordinates for the corners to matrix
cornermatrix = np.matrix(corners)
# print(cornermatrix.shape) # shape = (54,2)
# now make these coordinates homogeneous
# WIDTH & HEIGHT are defined above
homocorners = np.concatenate((cornermatrix, np.ones(WIDTH*HEIGHT)[:,None]), axis=1)
# print(homocorners) # shape = (54,3)
## STEP 1B: Compute tp -- an Nx3 array of the 2D homogeneous coordinates of the
## samples of the image coordinates
## Note: this could be done outside of the loop either!
# THIS IS DONE OUTSIDE THE LOOP
## STEP 2: Compute the homography from tp to fp
# h, status = cv2.findHomography(homocorners,homoimg)
hi, status = cv2.findHomography(patterncorners, homocorners)
# print(h)
# USE CALIBCAM TO UNDISTORT CAMERA FEED
# print calibcam.mtx, calibcam.dist
cv2.undistort(img, calibcam.mtx, calibcam.dist, 0, calibcam.newcameramtx)
## STEP 3: Compute warped mask image
im_dst = cv2.warpPerspective(im_src, hi, (CAMWIDTH,CAMHEIGHT))
# cv2.imshow('im_dst',im_dst)
## STEP 4: Compute warped overlay image
# creating the black and white "mask"
gray = cv2.cvtColor(im_dst, cv2.COLOR_BGR2GRAY) #turn image grey
ret,thresh1 = cv2.threshold(gray,1,255,cv2.THRESH_BINARY) #threshold
# cv2.imshow('thresh1',thresh1)
thresh1 = cv2.bitwise_not(thresh1) # swaps black and white
# HAD AN ERROR: IMAGE WASNT MAPPING AS THE RIGHT SIZE.
# NEEDED TO FIND HOMOGRAPHY BETWEEN IMAGE OF CHESSBOARD
# AND THE CAMERA FEED
## STEP 5: Compute final image by combining the warped frame with the captured frame
# the black and white image is going to be an array of 1 or 255
# where 0 is completely black and 1 is completely white
# ERROR (fix by changing back to RGB)
# (-209) The operation is neither 'array op array' (where arrays have the same size and type),
# nor 'array op scalar', nor 'scalar op array' in function binary_op
thresh1 = cv2.cvtColor(thresh1, cv2.COLOR_GRAY2RGB) # grey > colour
img = cv2.bitwise_and(img,thresh1)
img = cv2.add(img,im_dst) # current error
# cv2.imshow('img',img)
cv2.imshow('img',img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# release everything
shutdown() |
5fed049c370d944d2f964c19fc2da9cf8eb9f11c | adfisher4/tic_tac_toe | /tic_tac_toe.py | 3,662 | 4.25 | 4 |
print("\n TIC TAC TOE \n")
print ("Choose players X and O. Whoever's turn it is, type the number that corresponds with the spot you want your mark. First to get 3 in a row, column or diagonal wins.")
# 3x3 Grid with numbers 1-9
def grid():
print("""
1|2|3
-----
4|5|6
-----
7|8|9
""".format())
grid()
#Variables are to keep track of the series.
#will be xw within functions
x_wins = 0
#will be ow within functions
o_wins = 0
#will be dr within functions
draws = 0
#when it's x's turn to start a game
x_starts = True
def new_game(xw, ow, dr, starter):
game_on = True
pos = [" "," "," "," "," "," "," "," "," "]
# Turn count
if starter == True:
#X starts the game
turn = 1
#For O to start the next game
starter = False
else:
#O starts the game
turn = 0
#For X to start the next game
starter = True
while game_on:
if turn % 2 == 1:
player_turn = "X"
else:
player_turn = "O"
print("It is %s's turn" % (player_turn))
try:
player_select = int(raw_input("Choose a number location: "))
if player_select > 0 and player_select < 10:
if pos[player_select - 1] == " ":
# Depending on turn count: place chosen location with X or O.
pos[player_select - 1] = player_turn
else:
print ("\n \n Position already taken. Try again")
turn -= 1
else:
print ("\n \n Not a valid input. Choose a number between 1-9")
turn -= 1
except (TypeError, ValueError, NameError):
print ("\n \n Not a valid input. Choose a number between 1-9")
turn -= 1
print("""
{}|{}|{}
-----
{}|{}|{}
-----
{}|{}|{}
""".format(pos[0],pos[1],pos[2],pos[3],pos[4],pos[5],pos[6],pos[7],pos[8]))
turn += 1
# If player has 3 in a row, player wins.
if turn > 4:
if pos[0] == player_turn and pos[1] == player_turn and pos[2] == player_turn or pos[3] == player_turn and pos[4] == player_turn and pos[5] == player_turn or pos[6] == player_turn and pos[7] == player_turn and pos[8] == player_turn or pos[0] == player_turn and pos[3] == player_turn and pos[6] == player_turn or pos[1] == player_turn and pos[4] == player_turn and pos[7] == player_turn or pos[2] == player_turn and pos[5] == player_turn and pos[8] == player_turn or pos[0] == player_turn and pos[4] == player_turn and pos[8] == player_turn or pos[2] == player_turn and pos[4] == player_turn and pos[6] == player_turn:
print ("%s WINS!!!" % (player_turn))
game_on = False
if player_turn == "X":
xw += 1
else:
ow += 1
# If all numbers have been replaced but no one has 3 in a row: It's a draw.
if starter == False and turn == 10 or starter == True and turn == 9:
print ("It's a draw!")
game_on = False
dr += 1
play_again(xw, ow, dr, starter)
def play_again(xw, ow, dr, starter):
print("\n Series:")
print ("Number of X wins: %s" % (xw))
print ("Number of O wins: %s" % (ow))
print ("Number of Draws: %s \n" % (dr))
new = str(raw_input("Would you like to play again? Type y for yes: "))
if new == 'y' or new == 'Y':
grid()
new_game(xw, ow, dr, starter)
new_game(x_wins, o_wins, draws, x_starts) |
60c8150cba99f347ae0d568adbc77036a996a52f | SoniaB78/supportSG | /class/compteBanque.py | 1,499 | 3.828125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Administrateur
#
# Created: 08/01/2020
# Copyright: (c) Administrateur 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
global depot, retrait
class Compte:
def __init__(self, nom, solde):
self.nom = nom
self.solde = solde
def soldeRestant(self):
print("Mme / Mr:", self.nom, "Le solde de votre compte est de ", self.solde, "€.")
def retrait(self):
retrait = float(input("Combien souhaitez vous retirer?"))
if retrait < self.solde:
self.solde -= retrait
else:
print("Impossible de retirer plus que le solde disponible sur le compte.")
#return self.solde
self.soldeRestant()
def depot(self):
depot = float(input("Combien souhaitez vous déposer?"))
if depot > 5000:
print("OK... J'appel la police, nous gardons l'argent.")
self.solde += depot
self.soldeRestant()
"""
def __add__(self):
self.depot = float(input("Combien souhaitez vous déposer?"))
self.solde += self.depot
def __sub__(self):
self.retrait = float(input("Combien souhaitez vous retirer?"))
self.solde -= self.retrait
"""
Dupont = Compte("Dupont", 1000)
Braunstein = Compte("Braunstein", 8000)
Lavillier = Compte("Lavillier", 2000)
Dupont.soldeRestant() |
c87412be0e62789a0c4370ec61872e2170f55b80 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4171/codes/1807_2569.py | 171 | 3.84375 | 4 | from numpy import *
x = array(eval(input("valores de x: ")))
m = sum(x)/size(x)
a = 0
for g in x:
a += (g - m)**2
h = a / (size(x) - 1)
v = sqrt(h)
print(round(v,3)) |
15dd288c69a46b9ba30c36b726276d5deb48b7fd | abhijithshankar93/coding_practise | /CodeChef/coins.py | 528 | 3.65625 | 4 |
def recursive(num, max_dict):
if num==1:
max_dict['1']=1
return 1
if num ==0:
max_dict['0']=0
return 0
try:
return max_dict[str(num)]
except KeyError:
pass
max_value = max(num, (recursive(int(num/2), max_dict)+
recursive(int(num/3), max_dict)+
recursive(int(num/4), max_dict))
)
max_dict[str(num)]=max_value
return max_value
final=[]
for cnt in range (10):
num=int(raw_input())
max_dict={}
max_val = recursive(num, max_dict)
final.append(max_val)
for value in final:
print value |
754c77ba200dd7a37653d3218a48c11d7db6a52d | aleexnl/aws-python | /UF2/Practica 24/Ejercicio 1/modules/functions.py | 437 | 3.640625 | 4 | def recursive_div(divend, divsor): # creeamos la funcion y le añadimos dos valores.
if divend == 0: # si el dividendo es = 0 nos devolvera 0.
return 0
elif divend < divsor: # cuando el dividendo sea mas pequeño que el divisor nos devolvera como valor 1.
return 1
else: # En caso de que las otras condiciones no se hayan cumplido entraremos en esta.
return 1 + recursive_div(divend - divsor, divsor)
|
41db70c6c03e6c60f478ab071b2d51856cb52ee5 | andreiolegovichru/pandas1 | /from_csv_5rows.py | 785 | 3.578125 | 4 | import pandas as pd
import os
CSV_PATH = os.path.join(".", "collection-master", "artwork_data.csv")
print(CSV_PATH)
# pandas will create its own index column - Index
df = pd.read_csv(CSV_PATH, nrows=5)
# pandas will use existing column "id" as an index column
df = pd.read_csv(CSV_PATH, nrows=5, index_col="id")
# see only "artist" column
df = pd.read_csv(CSV_PATH, nrows=5, index_col="id", usecols=["id", "artist"])
# same result can be achieved
df = pd.read_csv(CSV_PATH, nrows=5, index_col="id", usecols=[0, 2])
COLS_TO_USE = ["id", "artist", "title", "medium", "year", "acquisitionYear",
"height", "width", "units"]
df = pd.read_csv(CSV_PATH, nrows=5, index_col="id", usecols=COLS_TO_USE)
# Save for later
df.to_pickle(os.path.join(".", "data_frame.pickle")) |
b589dcd9fb7ca93269d4cafdaa8472d65e9fcc12 | craigdub/SiteScrapper | /link_diff.py | 1,136 | 3.640625 | 4 | import sys
def find_dff_between_files(file_name1, file_name2):
matching_url = set()
unmatched_url = set()
with open(file_name1, "r") as file1:
for line1 in file1:
match_found = False
with open(file_name2, "r") as file2:
for line2 in file2:
if line1 == line2:
matching_url.add(line1)
match_found = True
break
if match_found:
continue
else:
unmatched_url.add(line1)
return matching_url, unmatched_url
if __name__ == "__main__":
file_name1 = sys.argv[1]
file_name2 = sys.argv[2]
matching_url, unmatched_url = find_dff_between_files(file_name1, file_name2)
print("unmatched urls between {} and {} ".format(file_name1, file_name2))
for url in unmatched_url:
print(url)
matching_url, unmatched_url = find_dff_between_files(file_name2, file_name1)
print("unmatched urls between {} and {} ".format(file_name2, file_name1))
for url in unmatched_url:
print(url)
|
17190581bf7d963a127c3ed1b105a8fce2c19d7a | daniel-reich/ubiquitous-fiesta | /v2k5hKnb4d5srYFvE_5.py | 489 | 3.53125 | 4 |
def letters_combinations(digits):
if len(digits) == 0:
return set()
d = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" }
start_list = lambda digit: [d[digit][n] for n in range(len(d[digit]))]
advance_list = lambda list, digit: [l8r + d[digit][n] for l8r in list for n in range(len(d[digit]))]
lst = start_list(digits[0])
for digit in digits[1:]:
lst = advance_list(lst, digit)
return set(lst)
|
9cda10f7e64fcafbc4590e6297a17b7f97946f00 | mishra-anubhav/Competitive-Programming | /Network-marketing.py | 341 | 3.53125 | 4 | parent = input()
ques = input()
if ques=='Y':
list = input()
list = list.split(',')
n = len(list)
print("TOTAL MEMBERS :",n)
print("COMMISSION DETAILS")
print(parent,":",(n*500))
for i in list:
print(i,": 250")
else:
print("TOTAL MEMBERS : 1")
print("COMMISSION DETAILS")
print(parent,":250")
|
a304e5575cad06863f6bd07764c3c17ade16e8d5 | jayala-29/Project-Euler | /Problem1.py | 422 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def Problem1 (n) :
total = 0
n -= 1
while (n > 0) :
if (n % 3 == 0 or n % 5 == 0) :
total += n
n -= 1
return total
print (Problem1(1000))
|
b38f577a3e9d003f926e63957745dfd8adc8cdee | J4Mary/homework | /6.1.py | 371 | 3.671875 | 4 | students=dict([('Mary',[9,9,10,9]),('Alex',[10,10,9,10]),('Max',[9,8,10,8]),('Lera',[10,9,10,9])])
print(students)
for key,val in students.items():
students[key]=sum(val)/len(val)
print(students)
for key,val in students.items():
if val==max(students.values()):
print(key, 'is the best')
if val==min(students.values()):
print(key, 'is a loser') |
90d3c82cbfff35e6e01bbaa17adf543be0bf57e5 | StarwipeNet/Adops-repo | /Simplilearn/Predict House Price.py | 1,713 | 3.53125 | 4 | # coding=utf-8
# !/usr/bin/env python
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
class PredictHousePrice(object):
def __init__(self, input_file):
self.input_file = input_file
self.house_price = None
self.X_one = None
self.y_one = None
def read_file(self):
house_price = pd.read_csv(self.input_file)
self.house_price = house_price[house_price.columns[::-1]]
# Bonus Exercise: Predict housing prices based on median_income and plot the regression chart.
def median_income_predict_house_price(self):
# Seprate the data with features and label
X_one = self.house_price.iloc[:, 1:8]
y_one = self.house_price.iloc[:, :1]
self.X_one = X_one
self.y_one = y_one
# Deal with missing values
def handling_missing_values(self):
self.X_one['total_bedrooms'].fillna(self.X_one['total_bedrooms'].mean(), inplace=True)
# missing_value_imputer = SimpleImputer(missing_values='nan', strategy='mean', verbose=0)
# missing_value_imputer.fit(self.X_one['total_bedrooms'].values.reshape(-1, 1))
# self.X_one['total_bedrooms'] = missing_value_imputer.transform(self.X_one['total_bedrooms'].values.reshape
# (-1, 1))
# self.X_one['total_bedrooms'] = missing_value_imputer.fit_transform(self.X_one['total_bedrooms'])
def main(self):
self.read_file()
self.median_income_predict_house_price()
self.handling_missing_values()
if __name__ == "__main__":
obj = PredictHousePrice('housing.csv')
obj.main() |
448cbf51bd0214ec5f19d66871aa340b3d67ba1c | littlelilyjiang/two_leetcode_daybyday | /easy/num263.py | 511 | 3.921875 | 4 | '''
编写一个程序判断给定的数是否为丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
'''
def isUgly(num):
if num == 0:
return False
while(num != 1):
if num%2 == 0:
num = num/2
continue
if num%3 == 0:
num = num/3
continue
if num%5 == 0:
num = num/5
continue
if num%2 != 0 and num%3 != 0 and num%5 != 0:
return False
return True
print(isUgly(14)) |
b8f9defc0f30fb6538ac094956725492639394ac | AkshayMokalwar/python_programs.github.io | /my_python_programs/basic/nonlocal.py | 3,966 | 4.65625 | 5 | #global and local variable with different name
# x="global"
# #global variable can be accessed from anywhere
# def funct1():
# global x
# y="local"
# x=x*2
# print(x)
# print(y)
#
# print("Global x= ",x)
# funct1()
# print("Global x= ",x)
# -----------------------------------------------------------------------------------Global and Local variable with same name----------------------------------------------------------------------------------
a=5
def funct2():
a=10 #local variables are accessed from the block where it is defined only
print("local a:",a)
print("global a:",a)
funct2()
print("global a:",a)
#creating and using a non local variable
# def outer():
# x="local" #x will be updated after define x is non local
# def inner():
# nonlocal x #Nonlocal vriable are used in nested function
# x="nonlocal"
# print("inner",x)
#
# inner()
# print("outer:",x)
# outer()
#
# # o/p:inner: nonlocal
# # outer: nonlocal
#
# def outer():
# x="local"
# def inner():
# # nonlocal x #Nonlocal vriable are used in nested function
# x="nonlocal"
# print("inner",x)
#
# inner()
# print("outer:",x)
# outer()
# o/p: inner nonlocal
# outer: local
# Global Variables
# In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.
# x = "global"
#
# def foo():
# print("x inside :", x)
#
# foo()
# print("x outside:", x)
# Local Variables
# A variable declared inside the function's body or in the local scope is known as local variable
# def foo():
# y = "local"
#
# foo()
# print(y)
# NameError: name 'y' is not defined
#The output shows an error, because we are trying to access a local variable y in a global scope whereas the local variable only works inside foo() or local scope
# def foo():
# y = "local"
# print(y)
#
# foo()
#Using Global and Local variables in same code
# x = "global"
#
#
# def foo():
# global x
# y = "local"
# x = x * 2
# print(x)
# print(y)
#
#
# foo()
#Global variable and Local variable with same name
# x = 5
#
# def foo():
# x = 10
# print("local x:", x)
#
# foo()
# print("global x:", x)
#In above code, we used same name x for both global variable and local variable. We get different result when we print same variable because the variable is declared in both scopes, i.e. the local scope inside foo() and global scope outside foo().
#When we print the variable inside the foo() it outputs local x: 10, this is called local scope of variable.
#Similarly, when we print the variable outside the foo(), it outputs global x: 5, this is called global scope of variable.
# Nonlocal Variables
# Nonlocal variable are used in nested function whose local scope is not defined. This means, the variable can be neither in the local nor the global scope.
#
# Let's see an example on how a global variable is created in Python.
#
# We use nonlocal keyword to create nonlocal variable.
# def outer():
# x = "local"
#
# def inner():
# nonlocal x
# x = "nonlocal"
# print("inner:", x)
#
# inner()
# print("outer:", x)
# outer()
#In the above code there is a nested function inner(). We use nonlocal keyword to create nonlocal variable. The inner() function is defined in the scope of another function outer().
#Note : If we change value of nonlocal variable, the changes appears in the local variable
# def myfunc1():
# x = "John"
# def myfunc2():
# nonlocal x
# x = "hello"
# myfunc2()
# return x
#
# print(myfunc1())
# def myfunc1():
# x = "John"
# def myfunc2():
# x = "hello"
# myfunc2()
# return x
#
# print(myfunc1())
|
880a8d56cf3b938cc52409084403e2cdf18fda13 | LiuY-ang/leetCode | /climbStairs4.py | 904 | 3.625 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
base=[[1,1],[1,0]]
s=self.power(base,n)
return s[0][0]
def power(self,matrix,n):
li=[[1,0],[0,1]] #2价单位矩阵,应该是叫这个名,相当于整数的1,任何整数和此举证相乘,都为原矩阵
while n >0 :
if n%2 ==1 : #这个判断最为重要了,主要是为了若n为奇数,再乘base一遍,实现奇数价
li=self.multiply(li,matrix)
n=n/2
matrix=self.multiply(matrix,matrix)
return li
def multiply(self,m1,m2): #2价矩阵乘法
temp=[[-1,-1],[-1,-1]]
for i in range(0,2):
for j in range(0,2):
temp[i][j]=m1[i][0]*m2[0][j]+m1[i][1]*m2[1][j]
return temp
so= Solution()
print so.climbStairs(5)
|
d6cf531d983c974414e7e2bd016dd7a875dac13e | DoosanJung/neural-networks-for-time-series | /miscellaneous/keras/convnets_image_generator.py | 6,738 | 3.921875 | 4 | '''
* Francois Chollet, 2017, "Deep Learning with Python"
* Francois Chollet's example code([GitHub](https://github.com/fchollet/deep-learning-with-python-notebooks))
* I bought this book. I modified the example code a bit to confirm my understanding.
'''
import keras
import os
from keras import backend as K
from keras import models
from keras import layers
from keras import optimizers
import matplotlib.pyplot as plt
# keras.preprocessing.image.ImageDataGenerator
# Python generators that can automatically turn image files on disk
# into batches of pre-processed tensors
from keras.preprocessing.image import ImageDataGenerator
from util import DataPrepDogCat
class ConvnetsFromImageGen(object):
def __init_(self):
pass
def augment(self):
"""
https://keras.io/preprocessing/image/
- rotation_range is a value in degrees (0-180), a range within which to randomly rotate pictures.
- width_shift and height_shift are ranges (as a fraction of total width or height) within which to randomly translate pictures vertically or horizontally.
- shear_range is for randomly applying shearing transformations.
- zoom_range is for randomly zooming inside pictures.
- horizontal_flip is for randomly flipping half of the images horizontally. relevant when there are no assumptions of horizontal asymmetry (e.g. real-world pictures).
- fill_mode is the strategy used for filling in newly created pixels, which can appear after a rotation or a width/height shift.
=> The inputs that it sees are still heavily intercorrelated, since they come from a small number of original images
"""
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
return train_datagen
def preprocessing(self, train_dir, validation_dir, batch_size=20, augment=False):
"""
- Read the picture files.
- Decode the JPEG content to RBG grids of pixels.
- Convert these into floating point tensors.
- Rescale the pixel values (between 0 and 255) to the [0, 1] interval.
"""
# All images will be rescaled by 1./255
if augment:
train_datagen = self.augment()
else:
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
self.train_generator = train_datagen.flow_from_directory(
# This is the target directory
train_dir,
# All images will be resized to 150x150
target_size=(150, 150),
batch_size=batch_size,
# Since we use binary_crossentropy loss, we need binary labels
class_mode='binary')
self.validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=batch_size,
class_mode='binary')
def build_model(self):
"""
a stack of Conv2D and MaxPooling2D layers
then into a densely-connected classifier network
"""
self.model = models.Sequential()
self.model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
self.model.add(layers.MaxPooling2D((2, 2)))
self.model.add(layers.Conv2D(64, (3, 3), activation='relu'))
self.model.add(layers.MaxPooling2D((2, 2)))
self.model.add(layers.Conv2D(128, (3, 3), activation='relu'))
self.model.add(layers.MaxPooling2D((2, 2)))
self.model.add(layers.Conv2D(128, (3, 3), activation='relu'))
self.model.add(layers.MaxPooling2D((2, 2)))
self.model.add(layers.Flatten())
self.model.add(layers.Dropout(0.5))
self.model.add(layers.Dense(512, activation='relu'))
self.model.add(layers.Dense(1, activation='sigmoid'))
self.model.compile(optimizer=optimizers.RMSprop(lr=1e-4),
loss='binary_crossentropy',
metrics=['acc'])
def train_model(self, epochs, save=False):
# installed pillow: pip install pillow-5.4.1
# https://keras.io/models/sequential/#fit_generator
self.history = self.model.fit_generator(
self.train_generator,
steps_per_epoch=100,
epochs=epochs,
validation_data=self.validation_generator,
validation_steps=50)
if save:
self.model.save('cats_and_dogs_small_2.h5')
def partially_validate_model(self, show=True):
"""
"""
def show_val_result(history):
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.clf() # clear figure
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
if show == True:
show_val_result(self.history)
def data_prep_func(needed=False):
if needed:
# The path to the directory where the original
orig_data_dir = os.path.join(os.path.curdir, "kaggle_original_data")
# The directory where we will store our smaller dataset
base_dir = os.path.join(os.path.curdir, "data")
DataPrepDogCat.data_prep(orig_data_dir=orig_data_dir, base_dir=base_dir)
if __name__=="__main__":
print("keras.__version__: ", keras.__version__)
print("Backend TensorFlow __version__: ", K.tensorflow_backend.tf.__version__)
data_prep_func(needed=False)
convnets = ConvnetsFromImageGen()
train_dir = os.path.join(os.path.curdir, "data", "train")
validation_dir = os.path.join(os.path.curdir, "data", "validation")
convnets.preprocessing(train_dir, validation_dir, batch_size=32, augment=True)
convnets.build_model()
convnets.train_model(epochs=100, save=True)
convnets.partially_validate_model(show=True) |
9321b5d3d480ee12c396f0c03b93f43df60bf5f0 | Harishsowmy/python_learning | /introduction/test9.py | 251 | 4.09375 | 4 | age=input("how old are you?")
print("my age is :{age}".format(age=age))
height=input("how tall are you?")
print("myheight is :{height}".format(height=height))
weight=input("how much do you weigh?")
print("my weight is :{weight}".format(weight=weight)) |
0ac88aa07cd79fd9663ae48f43d4d2ba0fbf46e5 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4469/codes/1590_1016.py | 227 | 3.859375 | 4 | import math
a = float(input("lado 1 do triangulo: "))
b = float(input("lado 2 do triangulo: "))
c = float(input("lado 3 do triangulo: "))
s = (a + b + c) / 2
A = math.sqrt(s * (s - a) * (s - b) * (s - c))
print(round(A, 5)) |
375fd1fa69ef4c09c13ccf587ee88812b8a5d98d | fenglihanxiao/Python | /Module01_CZ/day4_oop/04-代码/day4/77_手机.py | 1,220 | 4 | 4 | """
演示手机案例
要求:
手机电量默认是100
打游戏每次消耗电量10
听歌每次消耗电量5
打电话每次消耗电量4
接电话每次消耗电量3
充电可以为手机补充电量
"""
# 分析
# 1. 定义类Phone
# 2. 定义变量用于描述电量值
# 3. 定义4个方法用于描述耗电操作
# 4. 定义1个方法用于描述充电操作
# 5. 运行程序,执行上述操作,观察结果
class Phone:
def __init__(self):
self.power = 100
def game(self):
"""打游戏操作,耗电10"""
print("正在打游戏,耗电10")
self.power = self.power - 10
def music(self):
print("正在听歌,耗电5")
self.power -= 5
def call(self):
print("正在打电话,耗电4")
self.power -= 4
def answer(self):
print("正在接电话,耗电3")
self.power -= 3
def charge(self,num):
print("正在充电,冲电量是%d" % num)
self.power += num
def __str__(self):
return "当前手机电量为:%d" % self.power
# 创建一部电话,当前电量是100
p = Phone()
# 执行耗电操作
p.game()
print(p)
p.music()
print(p)
p.charge(8)
print(p) |
1bc670de4018c510a2b18ed7dc84dc6951a6c31f | isemona/codingchallenges | /1-FirstReverse.py | 432 | 3.59375 | 4 | # https://www.coderbyte.com/editor/First%20Reverse:Python#
# Difficulty - Easy
def FirstReverse(str):
# no built in reverse functions for strings
# using extended slice syntax (begins and ends at 0)
# src - https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/
return str[::-1]
#You can also do:
return ''.join(reversed(str))
# keep this function call here
print FirstReverse(raw_input())
|
a1760731e66a15305ebf346996fd5b72bff14c84 | aseemchopra25/Integer-Sequences | /Farey Sequence Numerators/Farey_Sequence_Numerator.py | 703 | 4.0625 | 4 | #This is one of the solution, I will come up with more optimal solution soon
def farey_sequence(n):
l=[]
for i in range(1,n+1):
(a, b, c, d) = (0, 1, 1, i) #here a/b is first term and c/d is consecutive term
l.append(0) #first farey seq. numerator will always be 0
#following is the logic of next term in farey seq
while (c <= i):
k = (i + b) // d
(a, b, c, d) = (c, d, k * c - a, k * d - b)
l.append(a) #appending only the numerator, here its a
return l[:n]
#taking input from user
n = int(input("Enter number of terms:"))
#printing numbers in comma separated manner
print(*farey_sequence(n), sep=",")
|
45d8e5896a9952db1e9e7c049fa57059ab0587ec | Kristin0/ASUE-P4E-Homeworks | /Homework4/problem1.py | 1,636 | 4.09375 | 4 | import random
iterations = int(input("Iterations quantity: "))
win_when_switching = 0
win_when_not_switching = 0
for x in range(iterations):
host_choice = random.randint(1,3)
prize_door = random.randint(1,3)
cont_num = random.randint(1,3)
switched_door = random.randint(1,3)
while (host_choice == cont_num or host_choice == prize_door):
host_choice = random.randint(1,3)
print("Prize is behind " + str(prize_door))
print("Host door: " + str(host_choice))
print("Contestant chooses door " + str(cont_num))
switching = random.randint(0,1)
if switching == 0:
print("Contestant doesn't switch the door")
if cont_num == prize_door:
print("Contestant Won!\n")
win_when_not_switching += 1
else:
win_when_switching += 1
print("Contestant Lost!\n")
elif switching == 1:
while (switched_door == cont_num or switched_door == host_choice):
switched_door = random.randint(1,3)
print("Contestant switches from door " + str(cont_num) + " to "+\
str(switched_door))
if switched_door == prize_door:
print("Contestant Won!\n")
win_when_switching += 1
else:
win_when_not_switching += 1
print("Contestant Lost!\n")
percent_if_switching = (win_when_switching/iterations)*100
percent_if_not_switching = (win_when_not_switching/iterations)*100
print("Probability of winning when swtiching: " + str(percent_if_switching)+"%")
print("Probabilty of winning when NOT switching: " + str(percent_if_not_switching) + "%")
|
a75bf416b81f4062f707b126e3b07ba51123f9bf | marianafcruz17/Learn-to-Code-in-Python | /Conditionals, Loops, Functiond and a bit more/error_handling.py | 1,760 | 4.1875 | 4 | data_valid = False
while data_valid == False:
grade1 = input("Type the grade of the first test: ")
try:
grade1 = float(grade1)
except:
print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.")
continue
if grade1<0 or grade1>10:
print("Grade should be between 0 and 10")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
grade2 = input("Type the grade of the second test: ")
try:
grade2 = float(grade2)
except:
print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.")
continue
if grade2<0 or grade2>10:
print("Grade should be between 0 and 10")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
total_classes = input("Type the total number of classes: ")
try:
total_classes = float(total_classes)
except:
print("Invalid input. Only numbers are accepted.")
continue
if total_classes<=0:
print("The number of classes can't be zero or less")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
absences = input("Type the number of absences: ")
try:
absences = float(absences)
except:
print("Invalid input. Only numbers are accepted.")
continue
if absences<0 or absences>total_classes:
print("The number of absences can't be less than zero or greater than the number of total classes")
continue
else:
data_valid = True
data_valid = False
|
2c2dcde7dcee2679d8de376b9c188eabd8794313 | Panda3D-public-projects-archive/pandacamp | /Handouts 2012/src/3-1 Coordinates and Projectiles/03-paths.py | 500 | 3.71875 | 4 | from Panda import *
# A function which takes a parameter t and returns a position defines a path.
# This path goes up and down.
def path(t):
return P3(t-2, 0, sin(t*2))
# Place a bunch of pandas on this path:
for x in range(5):
panda(position = path(time-x))
# Challenges:
# Make the pandas follows this path forward
# Launch a panda along this path every second
# Make the pandas speed up as they follow the path
# Create a socond path that controls the HPR of the panda
start() |
eddb309d1e37ad65083117071f06d7286c7081d9 | Justion1234/KOSPI_index | /KOSPI_index_colered.py | 543 | 3.609375 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import datetime
from pandas_datareader import data
start = datetime(2020, 1, 1)
end = datetime(2021, 2, 9)
plt.title('KOSPI index')
df = data.get_data_yahoo('^KS11', start, end) #pandas_datareader를 통해서 주식 데이터 가져옴 df = data frame
plt.plot(df['Adj Close'])
ymin = df['Adj Close'].min()
ymax = df['Adj Close'].max()
plt.ylim(ymin, ymax)
plt.fill_between(df.index, ymin, df['Adj Close'], alpha=0.5)
plt.xticks(rotation=30)
plt.show() |
6da7b42d45874b8c3705bcbd94851a6d37ab8a36 | zpyao1996/leetcode | /copyrandomlist.py | 1,835 | 3.65625 | 4 | # Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None
s=RandomListNode(head.label)
ans=s
p=head
visitset=set()
visitset.add(head)
wdict={}
wdict[head]=s
while p:
if p.random:
if p.random not in visitset:
visitset.add(p.random)
s.random=RandomListNode(p.random.label)
wdict[p.random]=s.random
elif p.random==p:
s.random=s
else:
s.random=wdict[p.random]
if p.next:
if p.next not in visitset:
visitset.add(p.next)
s.next=RandomListNode(p.next.label)
wdict[p.next]=s.next
else:
s.next=wdict[p.next]
p=p.next
s=s.next
return ans
'''
don't care about the internal structure until we copy all the nodes
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
p=head
dic={}
while p:
dic[p]=RandomListNode(p.label)
p=p.next
p=head
while p:
dic[p].random=dic[p.random]
p=p.next
return dic[head]
'''
sol=Solution()
a=RandomListNode(1)
a.random=a
sol.copyRandomList(a)
|
b59a04e18cf4bbb51928ea7b428a280ee0cdbd0f | kadirovgm/shifr_zameny | /shifr_zameny.py | 5,597 | 3.546875 | 4 | import random
import math
from collections import Counter
alphabet = 'абвгдежзийклмнопрстуфхцчшщъыьэюяАБВГДЕЖЗИЙКЛМНПРСТУФЧЦЧШЩЪЫЬЭЮЯ '
def keygen(alphabet):
with open('key.txt', mode='w', encoding="utf-8") as file:
key = ''.join(random.sample(alphabet, len(alphabet)))
file.write(key)
return key
key = keygen(alphabet)
for i in range(len(alphabet)):
if alphabet[i] == key[i]:
key = keygen(alphabet)
def encrypt(alphabet, key):
k = key
d = dict()
res = ""
for i in range(len(alphabet)):
d[alphabet[i]] = k[i]
with open('file.txt', encoding="utf-8") as f:
read_data = f.read().strip()
for i in range(len(read_data) - 1):
res += d[read_data[i]]
with open('output_enc.txt', 'w', encoding="utf-8") as o:
o.write(res)
def decrypt(key, alphabet):
a = alphabet
d = dict()
res = ""
for i in range(len(key)):
d[key[i]] = a[i]
with open('output_enc.txt', encoding="utf-8") as enc:
read_data = enc.read().strip()
for i in range(len(read_data) - 1):
res += d[read_data[i]]
with open('output_dec.txt', 'w', encoding="utf-8") as o:
o.write(res)
# next code is for menu
print(" -----------------------------")
print("| Type 'encrypt' or 'decrypt' |")
print("| Type 'back' for exit |")
print(" -----------------------------")
temp = 0
while temp < 10:
choise = input()
if choise == 'encrypt':
encrypt(alphabet, key)
temp += 1
print("File.txt encrypted! Check output_enc.txt")
elif choise == 'decrypt':
decrypt(key, alphabet)
temp += 1
print("output_enc.txt decrypted! Check output_dec.txt")
elif choise == 'back':
break
else:
print("Wrong, try again 'encrypt' or 'decrypt'")
########################################################## 1 METHOD
# decrypting teachers cryptographic text
# collection.Counter ()
# используя collection.Counter () для получения
# количество каждого элемента в строке
# with open('example.txt', encoding="utf-8") as ex:
# read_ex = ex.read().strip()
# result = Counter(read_ex)
######################################################### 2 METHOD
# используя dict.get () для подсчета
# каждого элемента в строке
result = {}
with open('example.txt', encoding="utf-8") as ex:
read_ex = ex.read().strip()
for keys in read_ex:
result[keys] = result.get(keys, 0) + 1
sorted_result = {}
sorted_keys = sorted(result, key=result.get, reverse=True)
for w in sorted_keys:
sorted_result[w] = result[w]
#########################################################
fr_dict = {' ': 0.175, 'о': 0.089, 'е': 0.072, 'а': 0.062, 'и': 0.062, 'т': 0.053, 'н': 0.053, 'с': 0.045,
'р': 0.040, 'в': 0.038, 'л': 0.035, 'к': 0.028, 'м': 0.026, 'д': 0.025, 'п': 0.023, 'у': 0.021,
'я': 0.018, 'ы': 0.016, 'з': 0.016, 'ь': 0.014, 'ъ': 0.014, 'б': 0.014, 'г': 0.013, 'ч': 0.012,
'й': 0.010, 'х': 0.009, 'ж': 0.007, 'ю': 0.006, 'ш': 0.006, 'ц': 0.004, 'щ': 0.003, 'э': 0.003,
'ф': 0.002}
fr_dict_podgon = {' ': 0.175, 'о': 0.089, 'е': 0.072, 'н': 0.053, 'т': 0.053, 'а': 0.062, 'и': 0.062, 'с': 0.045,
'к': 0.028, 'в': 0.038, 'р': 0.040, 'м': 0.026, 'у': 0.021, 'л': 0.035, 'п': 0.023, 'д': 0.025,
'ч': 0.012, 'ь': 0.014, 'х': 0.009, 'ж': 0.007, 'г': 0.013, 'ы': 0.016, 'я': 0.018, 'з': 0.016,
'б': 0.014, 'ш': 0.006, 'й': 0.010, 'ю': 0.006, 'э': 0.003, 'щ': 0.003, 'ц': 0.004, 'ф': 0.002,
'ъ': 0.014}
########################################################
# print("res1: " + str(sorted_result)) # Counted
# print("res2:" + str(fr_dict_podgon)) # reference
print("The result of freq analys: " + str(sorted_result)) # Counted
print("Reference freq analys of Russian alphabeth:" + str(fr_dict_podgon)) # reference
spis1 = ''.join(sorted_result.keys())
spis2 = ''.join(fr_dict.keys())
print("The freq analys like list:" + str(spis1))
print("The reference like list:" + str(spis2))
######################################################## encryption attempt
def decrypt_p(result, fr_dict):
fr = fr_dict
d = dict()
res = ""
for i in range(len(result)):
d[result[i]] = fr[i]
with open('example.txt', encoding="utf-8") as enc:
read_data = enc.read().strip()
for i in range(len(read_data) - 1):
res += d[read_data[i]]
with open('output_example_dec.txt', 'w', encoding="utf-8") as o:
o.write(res)
#######################################################
def entropy():
h = 0
pi = dict()
result = {}
with open('example.txt', encoding="utf-8") as ex:
read_ex = ex.read().strip()
for keys in read_ex:
result[keys] = result.get(keys, 0) + 1
for k in result:
pi[k] = (result.get(k, 0)) / len(read_ex)
s = 0
for value in pi.values():
s += value
print("Sum of probability: " + str(s))
print("Probability of every symbol: ")
for value in pi.values():
if value > 0:
h += float(value) * math.log((1 / float(value)), 2)
print(value)
print("entropy is: " + str(h))
entropy()
res_join = ''.join(sorted_result.keys())
fr_dict_join = ''.join(fr_dict_podgon.keys())
decrypt_p(res_join, fr_dict_join)
|
fa231835aeea287255f15dc6c26c53f2edf369fb | Sheep-coder/practice2 | /Python00/chap03list0314.py | 255 | 3.828125 | 4 | # aはbで割り切れるか
a=int(input('整数a:'))
b=int(input('整数b:'))
c=b!=0 and a%b
print(c,end='・・・')
if c:
print('aはbでは割り切れません。')
else:
print('bが0またはaがbで割り切れます。')
|
d7f660f06298f0f8e2ca305f3c4db02d773878ff | thomasbtatum/adventofcode2019 | /bolwingTest.py | 799 | 3.5 | 4 | import bowling
import unittest
class BowlingGameTest(unittest.TestCase):
g = bowling.Game()
def setUp(self):
self.g = bowling.Game()
def RollMany(self, num, pins):
for x in range(1,num+1):
self.g.Roll(pins)
def testGutterGame(self):
self.RollMany(20,0)
self.assertEqual(0,self.g.score(), "Gutter Test Fail")
def testAllOnes(self):
self.RollMany(20,1)
self.assertEqual(20,self.g.score(), "All1s Test Fail")
def testOneSpare(self):
self.g.Roll(5)
self.g.Roll(5)
self.g.Roll(3)
self.RollMany(17,0)
sc = self.g.score()
self.assertEqual(16,sc,"test one spare "+str(sc))
if __name__ == '__main__':
unittest.main()
#b = BowlingGameTest()
#b.testGutterGame("Test") |
12e9e2d2b5e810a542ef23e0bd5a7c839edf1fb6 | sunnywalden/double_color_lottery | /unit_test/lottery_test.py | 654 | 3.703125 | 4 | #!/bin/python
# -*- coding:utf-8 -*-
import unittest
from main.double_color_lottery_generator import random_shuangse
class Tests(unittest.TestCase):
def test(self):
lottery = random_shuangse(1)[0]
red_nums = lottery[:5]
#print(red_nums)
for num in red_nums:
#print(num)
self.assertLess(num, 34, msg='red number is out of range')
self.assertIsInstance(num, int, msg='red num is not int')
self.assertLess(lottery[-1], 17, msg='blue number is out of range')
self.assertIsInstance(num, int, msg='blue num is not int')
if __name__ == '__main__':
unittest.main()
|
d9cd6331415c28be62bf7bfd646571077e9082a7 | mnauman-tamu/ENGR-102 | /chemEq.py | 953 | 4.09375 | 4 | # chemEq
#
# Write a program to find the number of atoms of a specific element in a molecule
#
# Muhammad Nauman
# UIN: 927008027
# September 19, 2018
# ENGR 102-213
#
# Lab 4B - 5
# Pre-processor
A = input("Enter the chemical formula for the molecule (Type subscripts as normal numbers): ")
sym = input("Enter the symbol of the element you want to find the atoms of: ")
# Processor
index = A.find(sym)
length = len(sym)
if index + length >= len(A):
print("There is only one atom of " + sym + " in the molecule " + A)
elif A[index + length].isdigit():
print("There are ", end='')
print(A[index + length], end='')
for i in range(1, (len(A) - index - 1)):
if A[index + length + i].isdigit():
print(A[index + length + i], end='')
else:
break
print(" atoms of " + sym + " in the molecule " + A)
else:
print("There is only one atom of " + sym + " in the molecule " + A)
|
644ef988436e69c91a9929c554ef8cf38cecfeb3 | juselius/python-tutorials | /Basics/lists.py | 543 | 3.703125 | 4 | a = ['spam', 'eggs', 100, 1234]
print a
print a[0]
print a[2:4]
print a[-2]
print a[1:-1]
print 3*a[:3] + ['Boo!']
a[2] = a[2] + 23 # Lists are mutable!
a[0:2] = [1, 12] # Replace items
a[0:2] = [] # Remove items (also try del a[0:2])
a[1:1] = ['urk', 'purk'] # Insert items
a.append('tjohoo!') # Append items
a.insert(3, a) # Insert a copy of a into a
print a
print a[3][2] # Nested lists
print len(a) # Number of elements in a
del a # Get rid of a
|
b947a443c61a6015f047d5860e73f99a021ca0ef | nkuraeva/python-exercises | /week5/row_2.py | 314 | 4.1875 | 4 | # Given two integers A and B.
# Print all numbers from A to B inclusive,
# in ascending order if A <B,
# or in decreasing order otherwise.
A = int(input())
B = int(input())
if A < B:
for i in range(A, B + 1):
print(i, end=' ')
if A >= B:
for i in range(A, B - 1, -1):
print(i, end=' ')
|
388fecdd279ca42ec47661810317f3ff270c1bc4 | Urscha/SpaceX | /Problem_c/Alleen kilo's/Heaviest_First_C.py | 3,352 | 3.78125 | 4 | '''
This is the constructive algorithm 'Heaviest First' to solve problem C of the Space Freight case
By team SpaceX: Rico, Ellen, Urscha
'''
import math
import sys
from operator import itemgetter
# cargo and ships indices
NAME, KG, M3, CARGO = 0, 1, 2, 3
# _____FUNCTIONS_____
# read cargolists
def read_data(input_file):
data = []
with open(input_file, 'r') as f:
for line in f:
value = line.split()
for l in range(len(value)):
if l % 3 == 0:
t = (int(value[l]), int(value[l+KG]), float(value[l+M3]))
data.append(t)
return data
# calculates the kg left in a ship
def kg_left(s):
return s[4] - sum(item[KG] for item in s[CARGO])
# calculates the m3 left in a ship
def m3_left(s):
return s[5] - sum(item[M3] for item in s[CARGO])
# updates the ships information (free space)
def update_ship(s):
s[KG] = kg_left(s)
s[M3] = m3_left(s)
# putting the packages into the spacecrafts with the most free space
def fill_cargo_kg(ships, cargolist):
# sort cargolist: most kg on top
cargolist.sort(key=itemgetter(KG), reverse=True)
# sort ships: most left kgs on top
ships.sort(key=itemgetter(KG), reverse=True)
# Put package with most kg in ships with most kgs left
for item in cargolist:
# skip the lightest package
if item[1] == 11:
continue
print "packing ", item[NAME], " in ship ", ships[0][NAME]
ships[0][CARGO].append(item)
update_ship(ships[0])
ships.sort(key=itemgetter(KG), reverse=True)
# if a ship is overloaded, swap two packages to make it fit
def change_cargo(ships):
# ship iterator
k = 0
# check if ships on bottom (with least kg) has negative kg
while ships[-1][KG] < 0 and k < len(ships):
# sort cargo
ships[-1][CARGO].sort(key=itemgetter(KG))
ships[0][CARGO].sort(key=itemgetter(KG))
# cargo iterators
i, j = 0, 0
while i < len(ships[-1][CARGO]) and j < len(ships[k][CARGO]):
# swap counter
swaps = 0
# difference in kg & m3 for specified cargo
kg_diff = ships[-1][3][i][KG] - ships[k][3][j][KG]
m3_diff = ships[-1][3][i][M3] - ships[k][3][j][M3]
if kg_diff > 0 and kg_diff <= ships[k][KG]:
# swap
ships[-1][3][i], ships[k][3][j] = ships[k][3][j], ships[-1][3][i]
# update info
update_ship(ships[-1])
update_ship(ships[k])
k = 0
swaps += 1
break
elif kg_diff < ships[-1][1]:
i += 1
else:
j += 1
# if no more possible swaps, go to the next ship
if swaps == 0:
k += 1
ships.sort(key=itemgetter(KG), reverse=True)
# print information per ship
def print_ships(ships, cargo=False, errorcheck=False):
for i in ships:
print i[NAME], "\t kg: ", kg_left(i), "\t m3: ", m3_left(i)
if(cargo):
print "cargo: ", [item[NAME] for item in i[CARGO]], "\n"
if(errorcheck):
print i[KG], i[M3], "\n"
# _____MAIN_____
def main():
# initiale ships
ships = [["Cygnus ", 2000, 18.9, [], 2000, 18.9],
["Verne_ATV", 2300, 13.1, [], 2300, 13.1],
["Progress ", 2400, 7.6, [], 2400, 7.6],
["Kounotori", 5200, 14.0, [], 5200, 14.0]]
# read data
cargolist = read_data("CargoList2.txt")
# distibute cargo
fill_cargo_kg(ships, cargolist)
change_cargo(ships)
# print result
print_ships(ships)
empty_space = 0
for i in ships:
empty_space += i[1]
score1 = (11900 - float(empty_space)) / 11900 *100
print "Score: ", score1, "%"
if __name__ == "__main__":
main() |
b4786a3cb0de98081ab051229351c7f35cb16e86 | andydevs/tketris | /tketris/game/tileset.py | 2,336 | 3.84375 | 4 | """
Tketris
Tetris using tkinter
Author: Anshul Kharbanda
Created: 10 - 11 - 2018
"""
import numpy as np
from .bounds import TileSetBound
class BoardTileSet:
"""
Represents all tiles currently on the board.
Handles boundaries for tiles and row completion detection.
"""
def __init__(self, tile_colors=[]):
"""
Initializes instance with the given initial tile colors
:param tile_colors: initial tile_colors
"""
self.tile_colors = tile_colors
def clear_tiles(self):
"""
Clears all tiles from board
"""
self.tile_colors = []
def add_tiles(self, tiles, color):
"""
Adds the given tiles in the given color to the tileset
:param tiles: set of tiles to add
:param color: color of new tiles being added
"""
for tile in tiles.tolist():
self.tile_colors.append((tile[0], tile[1], color))
def clear_rows(self):
"""
Clears all full rows.
:return: number of rows cleared
"""
cleared_rows = 0
required_columns = {i for i in range(10)}
rows = {tile[0] for tile in self.tile_colors}
for row in rows:
# Check if all required columns are in row
columns = {tile[1] for tile in self.tile_colors if tile[0] == row}
clear_row = all(required in columns for required in required_columns)
if clear_row:
self.tile_colors = [
(i + 1 if i < row else i, j, color)
for i, j, color in self.tile_colors if i != row
]
cleared_rows += 1
return cleared_rows
@property
def tiles(self):
"""
All tiles in the tileset as a numpy tileset
"""
return np.array([[i, j] for i, j, color in self.tile_colors])
@property
def left_bound(self):
"""
Left boundary of tileset
"""
return TileSetBound(self.tiles, 1, -1)
@property
def right_bound(self):
"""
Right boundary of tileset
"""
return TileSetBound(self.tiles, 1, 1)
@property
def up_bound(self):
"""
Upper boundary of tileset
"""
return TileSetBound(self.tiles, 0, -1)
|
0262ddf0ee1d67a5cba32d5f04ed215eda63f8ae | dlefcoe/daily-questions | /URLshortener.py | 1,790 | 4.125 | 4 | '''
This problem was asked by Microsoft.
Implement a URL shortener with the following methods:
shorten(url), which shortens the url into a six-character alphanumeric string, such as zLg6wl.
restore(short), which expands the shortened string into the original url. If no such shortened string exists, return null.
Hint: What if we enter the same URL twice?
25 aug 2019
This was solved by D Ross. Tested by dlefcoe.
'''
import random
urls = {} # keys are long urls - values are short urls
chars = "abcdefghijklmnopqrstuvwxyz"
chars += chars.upper()
chars += "0123456789"
def gen_url():
"""Generate a unique 6 character short URL code."""
short = [random.choice(chars) for i in range(6)]
short = "".join(short)
# ensure short url is unique
while short in urls.values():
return gen_url()
return short
def shorten(url):
"""Shorten a url."""
if url in urls:
# this url has already been shortened
return urls[url]
else:
# this url has not been shortened so generate a new short url and add it to our dict
short = gen_url()
urls[url] = short
return short
def restore(short):
"""Restore a shortened url."""
for longurl, shorturl in urls.items():
if shorturl == short:
return longurl
# not found
return None
def test():
"""Shorten some urls, test duplicate input, re-expand urls."""
testurls = (
"http://www.aol.com",
"http://www.cnn.com",
"http://www.poo.com",
"http://www.cnn.com",
"http://www.bbc.com",
)
for testurl in testurls:
shortened = shorten(testurl)
print(testurl, shortened, restore(shortened))
test() |
4b5602e32e8d46d2a7220f3ee18fa305ee4128b7 | benjaminleon/EulerProject | /23_non-abundant_sums.py | 2,315 | 3.609375 | 4 | import numpy as np
import ast
from number_helper import is_abundant # My own module
from datetime import datetime
start_time = datetime.now()
# Find if number can be written as a sum of abundant numbers by subtracting by an abundant number and see if the difference is in the list of abundant numbers
# Used to find the abundant numbers
abundant_numbers = []
for number in range(12, 28123 + 1):
if is_abundant(number):
abundant_numbers.append(number)
print "Found all the abundant_numbers"
""" Saves and reads abundant numbers
f = open('23_saved_abundant_numbers.txt','w')
f.write(str(abundant_numbers))
f.close()
f = open('23_saved_abundant_numbers.txt','r')
abundant_string = f.read()
f.close()
abundant_numbers = ast.literal_eval(abundant_string)
"""
def go_through_all(abundant_numbers):
ans = 0
go_on = False
for number in range(1, 28123 + 1):
if number % 500 == 0:
print number
num_found = False
for abundant in abundant_numbers:
if abundant > number / 2: # Symmetry
num_found = True
break
if (number - abundant) in abundant_numbers:
break
if num_found:
ans += number
return ans
def make_combinations(abundant_numbers):
summable_numbers = []
for idx, abundant1 in enumerate(abundant_numbers):
for abundant2 in abundant_numbers[idx:]:
if abundant1 + abundant2 < 28123 + 1:
summable_numbers.append(abundant1 + abundant2)
print "Found all summable numbers"
#print "Got {} duplicates".format(len(summable_numbers) - len(list(set(summable_numbers)))) # Got 24205224 duplicates
summable_numbers = list(set(summable_numbers))
non_summable = range(1, 28123 + 1)
for summable in summable_numbers:
non_summable.remove(summable)
return sum(non_summable)
ans = make_combinations(abundant_numbers)
print "Sum of all positive integers which cannot be written as the sum of two abundant numbers is {}".format(ans)
print "This whole thing took {}".format(datetime.now() - start_time)
# 9 minutes when reading the abundant numbers from file, using go_through_all
# 21 seconds without reading saved numbers, using make_combinations
|
bae63f0072606c7c66a3e9460c28989aa09c5fdf | CallmeTorre/Analisis_De_Algoritmos | /Practica 2/CubeSum.py | 884 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
INSTITUTO POLITÉCNICO NACIONAL
ESCUELA SUPERIOR DE CÓMPUTO
Análisis de Algoritmos
GRUPO: 3CV1
ALUMNOS:
Reyes Fragoso Roberto
Torreblanca Faces Jesús Alexis
PROFESOR: Luna Benoso Benjamín
FECHA: 5/Septiembre/2017
"""
def recursiveS(n):
"""Funcion que regresa la suna de los primeros n cubos de manera recursiva"""
if n == 1:
return 1
else:
return recursiveS(n-1) + n*n*n
def iterativeS(n):
"""Funcion que regresa la suna de los primeros n cubos de manera iterativa"""
sum = 0
for x in range(n,1,-1):
sum = sum + x*x*x
return sum + 1
def main():
#Recursivo
print("Recursivo")
for x in range(1,80):
print("Para %d el resultado es: %d" %(x,recursiveS(x)))
#Iterativo
print("Iterativo")
for x in range(1,80):
print("Para %d el resultado es: %d" %(x,iterativeS(x)))
if __name__ == '__main__':
main()
|
1dc92d958960c7dabc21956b5cff0fcf99fa4fb4 | LinaShanghaitech/JobSeeking | /algorithms/leetcode/2-dim-array-search.py | 842 | 3.625 | 4 | #coding=utf-8
#=========================================================
# Copyright (C) 2019 Shanghaitech SVIP Lab. All rights reserved.
#
# ScriptName: 2-dim-array-search.py
# Author: Lina Hu
# CreatedDate: Wed 22 May 2019 11:19:43 AM CST
#
#=========================================================
import pdb
def search(arr, val):
cols, rows = len(arr), len(arr[0])
pdb.set_trace()
x = 0
y = cols-1
while(y>=0 and x<=rows-1):
cur = arr[y][x]
if val < cur:
y -= 1
elif val > cur:
x += 1
else:
return x, y
return -1, -1
def main():
target = 15
arr = [[1,2,3],[4,5,6],[7,8,9],[10,12,13]]
val = 2
print(arr, val)
x, y = search(arr, val)
print(x, y)
if __name__ == '__main__':
main()
|
9afb36f0acdfeba72d9ac2cd6268c6292b9be096 | joncucci/SSW567 | /Week 1/Code Assignment/script.py | 1,759 | 3.578125 | 4 |
'''
Author: Jon Cucci
SSW-567 HW#1 Testing Classify Triangle
9/10/21
'''
import math
import pytest
# Triangle classification
def classify_triangle(a, b, c):
result = []
a, b, c = sorted([a,b,c])
# Filter invalid cases
if (a<=0 or b<=0 or c<=0) or not ((a + b > c) and (a + c > b) and (b + c > a)):
result.append("Invalid Triangle")
# Equilateral Triangle Classification
elif (a == b == c):
result.append("Equilateral Triangle")
else:
# Right Triangle classification
if round(a**2, 6) + round(b**2, 6) == round(c**2, 6):
result.append("Right Triangle")
# Isosceles Triangle Classification
if (a in [b, c]) or (b in [a, c]):
result.append("Isosceles Triangle")
# Scalene Triangle Classification
if (a != b != c):
result.append("Scalene Triangle")
# An invalid triangle input.
if result == []:
result.append("Invalid Triangle")
result = (" and ").join(result)
print(result)
return result
# Tests
def main():
assert classify_triangle(5,4,3) == "Right Triangle and Scalene Triangle"
assert classify_triangle(1, 1, math.sqrt(2)) == "Right Triangle and Isosceles Triangle"
assert classify_triangle(1,1,1) == "Equilateral Triangle"
assert classify_triangle(10000,10000,10000) == "Equilateral Triangle"
assert classify_triangle(2, 3, 4) == "Scalene Triangle"
assert classify_triangle(4, 6, 8) == "Scalene Triangle"
assert classify_triangle(1, 1, 100000) == "Invalid Triangle"
assert classify_triangle(-3, -4, -5) == "Invalid Triangle"
assert classify_triangle(-4, 5.334324, 1000003232432) == "Invalid Triangle"
if __name__ == "__main__":
main() |
00b045d3cca18473122917b98c6f4d6b405cdbdb | kosemMG/gb-python-basics | /1/3.py | 159 | 3.96875 | 4 | n = input('Please, enter a number: ')
result = int(n) + int(n + n) + int(n + n + n)
print(f'The result of {n} + {n + n} + {n + n + n} is equal to {result}')
|
e95d5e860679def8ad47b3ad48fa1d686cf79f13 | martinegeli/TDT4110 | /øving2/øving2-3.py | 417 | 3.8125 | 4 | a=int(input('Skriv inn et tall: '))
b=int(input('Skriv inn et tall til: '))
c=int(input('Skriv inn et siste tall: '))
d=b**2-(4*a*c)
if d<0:
print('Andregradslikningen', a,'*x^2 +', b,'*x +', c, 'har to imaginære løsninger')
elif d>0:
print('Andregradslikningen', a,'*x^2 +', b,'*x +', c, 'har to reelle løsninger')
else:
print('Andregradslikningen', a,'*x^2 +', b,'*x +', c, 'har en reell løsning')
|
eac202b7b94609212e41db2377243a49449e09cf | h3xadron/Python | /Divisors/Divisors.py | 126 | 3.75 | 4 | #!/bin/python
import sys
userinput = int(input("Please give me a number! "))
for i in range(2,11):
print (userinput // i )
|
31537c21b133950386cfa09e648ed911c5430453 | brettjbush/adventofcode | /2016/day03/day03_1.py | 1,554 | 4.28125 | 4 | #!/usr/bin/python
"""
--- Day 3: Squares With Three Sides ---
Now that you can think clearly, you move deeper into the labyrinth of hallways and office furniture that makes up this part of Easter Bunny HQ. This must be a graphic design department; the walls are covered in specifications for triangles.
Or are they?
The design document gives the side lengths of each triangle it describes, but... 5 10 25? Some of these aren't triangles. You can't help but mark the impossible ones.
In a valid triangle, the sum of any two sides must be larger than the remaining side. For example, the "triangle" given above is impossible, because 5 + 10 is not larger than 25.
In your puzzle input, how many of the listed triangles are possible?
"""
import sys
def main():
filename = sys.argv[1]
valid_triangle_count = 0
file = open(filename)
contents = file.read()
print(contents)
side_sets = contents.splitlines()
for side_set in side_sets:
invalid_found = False
sides = list()
for side_string in side_set.split():
sides.append(int(side_string))
for i in range(len(sides)):
sides_temp = list(sides)
comp_val = sides_temp.pop(i)
sides_sum = sum(sides_temp)
if sides_sum <= comp_val:
invalid_found = True
break
if not invalid_found:
valid_triangle_count += 1
print("There are " + str(valid_triangle_count) + " possible triangles in the list")
if __name__ == "__main__":
main()
|
c7a8a3a40df6f8f06c1eaf002b2113e1db6cf59f | minsuhan1/programmers_algorithm_practice | /42839_find_primenum.py | 783 | 3.578125 | 4 | from itertools import permutations
# 소수판별함수
def isprime(num):
if num <= 1: return False
if num == 2: return True
for i in range(2, int(num ** (1/2))+1):
if num % i == 0:
return False
return True
def solution(numbers):
# input 문자열 분할
numbers = [numbers[i] for i in range(len(numbers))]
# 조각을 붙여 만들 수 있는 모든 수 생성
permute = []
answer = []
for i in range(1, len(numbers)+1):
permute = permute + list("".join(_) for _ in permutations(numbers, i))
# 숫자로 바꾸고 중복제거
permute = list(set(map(int, permute)))
# 소수만 answer에 저장
for i in permute:
if isprime(i) == True:
answer.append(i)
return len(answer)
|
d8f532524728822c4cd8aacf90940393608c5b9a | ahmcpsc/Python- | /Lessons/Functions.py | 6,417 | 4.5625 | 5 | # A function is a block of code which only runs when it is called.
# You can pass data, known as parameters, into a function.
# A function can return data as a result.
# Creating a Function:
# In Python a function is defined using the def keyword:
def my_function():
print("Hello, world")
# Calling a Function:
# To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello, world")
my_function()
# Arguments:#my_function(arguments)
# Information can be passed into functions as arguments.
# Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
def my_function(name): # my_function(parameter)
print("Hello " + name)
my_function("salim") # my_function(argument)
my_function("ali")
# From a function's perspective:
# A parameter is the variable listed inside the parentheses in the function definition.
# def my_function(name) , so name is parameter
# An argument is the value that is sent to the function when it is called.
# my_function("salim")# my_function(argument)
# Number of Arguments:
# By default, a function must be called with the correct number of arguments.
# Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments,
# not more, and not less.
def my_function(name1, name2):
print("Hello " + name1 + " and " + name2)
my_function("omar", "saleh")
print("\n")
# Arbitrary Arguments, *args:
# If you do not know how many arguments that will be passed into your function,
# add a * before the parameter name in the function definition.
# This way the function will receive a tuple of arguments, and can access the items accordingly:
def my_function(*name):
print("Hello " + name[2])
my_function("omar", "saleh", "saeed")
# Keyword Arguments:
# You can also send arguments with the key = value syntax.
# This way the order of the arguments does not matter.
def my_function(student1, student2, student3):
print("Hello " + student3 + ", hello " + student2 + " and hello " + student1)
my_function(student1="omar", student2="saleh", student3="saeed")
# Default Parameter Value:
# If we call the function without argument, it uses the default value def my_function(name):
def my_function(name="Ali"): # (name="ali) is the default
print("Hello " + name)
my_function("omar")
my_function("john")
my_function() # use the default
my_function("sarah")
print("\n")
# Passing a List as an Argument:
def college(students):
for each_character in students:
print(each_character)
names = ["Ali", "Hassan", "Ahmed"]
college(names)
# Return Values:
# To let a function return a value, use the return statement:
def add(x, y):
z = x * y
return z
num1 = 6
num2 = 8
result = add(num1, num2)
print("the result of adding two numbers is :", result)
# The pass Statement:
# function definitions cannot be empty, but if you for some reason have a function definition with no content,
# put in the pass statement to avoid getting an error.
# having an empty function definition like this, would raise an error without the pass statement
def my_function():
pass
# Recursion:
# Python also accepts function recursion, which means a defined function can call itself.
# In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse.
# The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
def tri_recursion(k):
if k > 0:
output = k + tri_recursion(k - 1)
print(output)
else:
output = 0
return output
print("\n\nRecursion Example Results")
tri_recursion(6)
# another example:
def my_rec(num):
if num > 0:
my_result = num + my_rec(num - 1)
print(my_result)
else:
my_result = 0
return my_result
print("\nrecursion is:")
my_rec(3)
# fact(4):
def x():
num = int(input("enter a num: "))
for i in range(num):
if i == 4:
print("i is equal to 4")
break
print(i)
x()
##
print()
##break:
def x(num):
for i in range(num):
if i == 20:
print("i is equal to 20")
break
print(i)
x(50)
##continue:
def x(num):
for i in range(num):
if i == 20:
print("i is equal to 20")
continue
print(i)
x(50)
print()
##fact of 3:
def x():
num = int(input("enter a number: "))
fact = 1
rec_num = 1
for i in range(1, num + 1):
fact = i * 1
rec_num *= fact
print(fact)
print("the recursion of", num, "is :", rec_num)
x()
print()
##
def x(num):
fact = 1
rec_num = 1
for i in range(1, num + 1):
fact = i * 1
rec_num *= fact
print(fact)
print("the recursion from the function of ", num, "is :" + str(rec_num))
x(6)
##
def point(x, y, z):
for i in range(x):
for j in range(y):
for k in range(z):
print("(", i, ",", j, ",", k, ")")
point(3, 4, 5)
# return information from a function:
# here it returns nothing:
def cube(num):
num * num * num
cube(4)
# here it returns nothing as well, it only prints none:
def cube(num):
num * num * num
print(cube(4)) # prints none , it returns no value from function
# here it returns something:
def cube(num):
return num * num * num # not python gives u back the value
print(cube(4))
# here it returns something:
def cube(num):
return num * num * num # not python gives u back the value
print("hello") # this code will not print after retun
result = cube(4)
print(result)
print()
# global and local variable in function:
d = int(input("enter num ")) # d is global variable
def add(m, t):
global d # d is global but we can change it now
d = d + 1
k = 7 # k is locl variable
print(k)
print("d inside function is ", d)
return m + t + d
result = add(8, 4)
print("d outside the function is ", d)
print(result)
|
62ddcea02b4baa0344f6ec9646bf71cfa602abc3 | FinnMoolenaar/UnicPongGame | /PongGame007.py | 20,947 | 3.71875 | 4 | import arcade
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Pong Game"
class TextButton:
#hier geef je variabelen mee voor de buttons, zoals de grootte en de tekst die er in moet komen.
def __init__(self, center_x, center_y, width, height, text, font_size=18, font_face="Arial", face_color=arcade.color.LIGHT_GRAY, highlight_color=arcade.color.WHITE, shadow_color=arcade.color.GRAY, button_height=2):
self.center_x = center_x
self.center_y = center_y
self.width = width
self.height = height
self.text = text
self.font_size = font_size
self.font_face = font_face
self.pressed = False
self.face_color = face_color
self.highlight_color = highlight_color
self.shadow_color = shadow_color
self.button_height = button_height
def draw(self):
#hier zeg je dat de buttons getekend moeten worden
arcade.draw_rectangle_filled(self.center_x, self.center_y, self.width, self.height, self.face_color)
if not self.pressed:
color = self.shadow_color
else:
color = self.highlight_color
# onderkant horizontaal
arcade.draw_line(self.center_x - self.width / 2, self.center_y - self.height / 2, self.center_x + self.width / 2, self.center_y - self.height / 2, color, self.button_height)
# rechts verticaal
arcade.draw_line(self.center_x + self.width / 2, self.center_y - self.height / 2, self.center_x + self.width / 2, self.center_y + self.height / 2, color, self.button_height)
if not self.pressed:
color = self.highlight_color
else:
color = self.shadow_color
# bovenkant horizontaal
arcade.draw_line(self.center_x - self.width / 2, self.center_y + self.height / 2, self.center_x + self.width / 2, self.center_y + self.height / 2, color, self.button_height)
# links verticaal
arcade.draw_line(self.center_x - self.width / 2, self.center_y - self.height / 2, self.center_x - self.width / 2, self.center_y + self.height / 2, color, self.button_height)
x = self.center_x
y = self.center_y
if not self.pressed:
x -= self.button_height
y += self.button_height
arcade.draw_text(self.text, x, y, arcade.color.BLACK, font_size=self.font_size, width=self.width, align="center", anchor_x="center", anchor_y="center")
def on_press(self):
self.pressed = True
def on_release(self):
self.pressed = False
#hier zeg je dat hij moet kijken of de buttons worden aan gedrukt of niet
def check_mouse_press_for_buttons(x, y, button_list):
for button in button_list:
if x > button.center_x + button.width / 2:
continue
if x < button.center_x - button.width / 2:
continue
if y > button.center_y + button.height / 2:
continue
if y < button.center_y - button.height / 2:
continue
button.on_press()
def check_mouse_release_for_buttons(_x, _y, button_list):
for button in button_list:
if button.pressed:
button.on_release()
class IncreaseButton(TextButton):
#variabelen voor de level increase button
def __init__(self, center_x, center_y, action_function):
super().__init__(center_x, center_y, 150, 50, "Increase difficulty", 12, "Arial")
self.action_function = action_function
def on_release(self):
super().on_release()
self.action_function()
class DecreaseButton(TextButton):
#variabelen voor de level decrease button
def __init__(self, center_x, center_y, action_function):
super().__init__(center_x, center_y, 150, 50, "Decrease difficulty", 12, "Arial")
self.action_function = action_function
def on_release(self):
super().on_release()
self.action_function()
class StartLevelButton(TextButton):
#variabelen voor de level start button
def __init__(self, center_x, center_y, action_function):
super().__init__(center_x, center_y, 150, 50, "Start Level", 12, "Arial")
self.action_function = action_function
def on_release(self):
super().on_release()
self.action_function()
class InstructionButton(TextButton):
#variabelen voor de level start button
def __init__(self, center_x, center_y, action_function):
super().__init__(center_x, center_y, 150, 50, "Instructions", 12, "Arial")
self.action_function = action_function
def on_release(self):
super().on_release()
self.action_function()
class GoBackButton(TextButton):
#variabelen voor de level start button
def __init__(self, center_x, center_y, action_function):
super().__init__(center_x, center_y, 150, 50, "Go Back", 12, "Arial")
self.action_function = action_function
def on_release(self):
super().on_release()
self.action_function()
class MenuView(arcade.View):
def __init__(self):
super().__init__()
#variabelen voor de buttons en de actie die de buttons moeten geven
self.button_list = []
increase_button = IncreaseButton(SCREEN_WIDTH/4, SCREEN_HEIGHT/2, self.difficulty_increase)
self.button_list.append(increase_button)
decrease_button = DecreaseButton(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, self.difficulty_decrease)
self.button_list.append(decrease_button)
startlevel_button = StartLevelButton(SCREEN_WIDTH - 200, SCREEN_HEIGHT/2, self.start_game)
self.button_list.append(startlevel_button)
instruction_button = InstructionButton(SCREEN_WIDTH - 80, SCREEN_HEIGHT - 30, self.instruction_game)
self.button_list.append(instruction_button)
self.difficulty = 0
#laat menu view zien en welke kleur de achtergrond moet zijn
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
#tekenen de buttons
def on_draw(self):
arcade.start_render()
arcade.draw_text("Menu Screen", SCREEN_WIDTH / 2, SCREEN_HEIGHT - 200, arcade.color.WHITE, font_size=50, anchor_x="center")
for button in self.button_list:
button.draw()
output = f"Level difficulty = {self.difficulty}"
arcade.draw_text(output, SCREEN_WIDTH - 520, SCREEN_HEIGHT/3, arcade.color.WHITE, 20)
def on_update(self, delta_time):
pass
def on_mouse_press(self, x, y, button, key_modifiers):
check_mouse_press_for_buttons(x, y, self.button_list)
def on_mouse_release(self, x, y, button, key_modifiers):
check_mouse_release_for_buttons(x, y, self.button_list)
#de acties van de buttons
def difficulty_decrease(self):
self.difficulty -= 1
def difficulty_increase(self):
self.difficulty += 1
def start_game(self):
my_game_view = MyGameView(self.difficulty)
self.window.show_view(my_game_view)
def instruction_game(self):
instruction_view = InstructionView()
self.window.show_view(instruction_view)
class Ball():
def __init__(self, difficulty):
# Hier leg je uit wat alle variabbelen zijn
self.position_x = SCREEN_WIDTH/8
self.position_y = SCREEN_HEIGHT/6
self.change_x = 4+difficulty
self.change_y = 4+difficulty
self.radius = 20
def setup(self):
pass
def on_draw(self):
# hier teken je objecten.
arcade.draw_circle_filled(self.position_x, self.position_y, self.radius, arcade.color.WHITE)
def on_update(self, delta_time):
# hier zeg je dat de positie van x en y steeds met 3 omhoog moet gaan
self.position_x = self.position_x + self.change_x
self.position_y = self.position_y + self.change_y
# Hier zeg je dat de bal om moet draaien als hij de bovenkant en onderkant raakt.
if self.position_y + self.radius > SCREEN_HEIGHT and self.change_y > 0:
self.change_y = self.change_y * -1
if self.position_y - self.radius < 0 and self.change_y < 0:
self.change_y = self.change_y * -1
class Paddle():
def __init__(self, x, color):
# hier leg je uit wat de variabellen zijn van de Padlles
self.x = x
self.y = SCREEN_HEIGHT / 2
self.change_y = 0
self.width = 30
self.height = 90
self.color = color
def on_draw(self):
#hier zeg je dat hij de paddle moet tekenen, self.x geef je later mee
arcade.draw_rectangle_filled(self.x, self.y, self.width, self.height, self.color)
def on_update(self, delta_time):
# hier leg je uit dat je de self.y update en dan de self.change_y er bij doet
self.y = self.y + self.change_y
class Player1():
#score van player 1, verandert in het spel
def __init__ (self):
self.score = 0
class Player2():
#score van player 2
def __init__ (self):
self.score = 0
class InstructionView(arcade.View):
def __init__(self):
super().__init__()
#2e button list aanmaken en variabelen en acties van de button
self.button_list2 = []
go_back_button = GoBackButton(SCREEN_WIDTH - 80, SCREEN_HEIGHT - 30, self.go_back)
self.button_list2.append(go_back_button)
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
def on_draw(self):
arcade.start_render()
#button tekenen en text tekenen op het scherm met instructies
arcade.draw_text("Instructions", SCREEN_WIDTH / 2, SCREEN_HEIGHT - 150, arcade.color.WHITE, font_size=50, anchor_x="center")
for button in self.button_list2:
button.draw()
output = f"If you want to pause the game press P"
arcade.draw_text(output, SCREEN_WIDTH - 620, SCREEN_HEIGHT - 200, arcade.color.WHITE, 20)
output = f"If you want to resume the game press ESCAPE"
arcade.draw_text(output, SCREEN_WIDTH - 620, SCREEN_HEIGHT - 250, arcade.color.WHITE, 20)
output = f"Team Blue uses the Arrow Up to move the paddle up "
arcade.draw_text(output, SCREEN_WIDTH - 620, SCREEN_HEIGHT/2, arcade.color.WHITE, 20)
output = f"and uses the Arrow down to move the paddle down "
arcade.draw_text(output, SCREEN_WIDTH - 620, SCREEN_HEIGHT - 320, arcade.color.WHITE, 20)
output = f"Team Red uses the W key to move the paddle up "
arcade.draw_text(output, SCREEN_WIDTH - 620, SCREEN_HEIGHT- 370, arcade.color.WHITE, 20)
output = f"and the S key to move the paddle down "
arcade.draw_text(output, SCREEN_WIDTH - 620, SCREEN_HEIGHT - 390, arcade.color.WHITE, 20)
output = f"First team that has 10 points wins "
arcade.draw_text(output, SCREEN_WIDTH - 620, SCREEN_HEIGHT - 440, arcade.color.WHITE, 20)
def go_back(self):
#als de go back button wordt aangeklikt terug gaan naar het menu
menu_view2 = MenuView()
self.window.show_view(menu_view2)
def on_mouse_press(self, x, y, button, key_modifiers):
check_mouse_press_for_buttons(x, y, self.button_list2)
def on_mouse_release(self, x, y, button, key_modifiers):
check_mouse_release_for_buttons(x, y, self.button_list2)
class MyGameView(arcade.View):
#hier zeg je dat je de vorige getypte dingen ook echt moet uitvoeren.
def __init__(self, difficulty):
# super wilt zeggen dat hij bovenliggende classes nodig heeft
super().__init__()
self.difficulty = difficulty
self.ball = Ball(difficulty)
self.paddle1 = Paddle(SCREEN_WIDTH - 750, arcade.color.RED)
self.paddle2 = Paddle(SCREEN_WIDTH - 50, arcade.color.BLUE)
self.total_time = 0.0
self.Player1 = Player1()
self.Player2 = Player2()
#geluidjes invoeren
self.paddle_sound = arcade.load_sound('paddlepop.wav')
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
def setup(self):
self.total_time = 0.0
self.Player1.score = 0
self.Player2.score = 0
def on_draw(self):
# hier leg je uit dat arcade moet gaan tekenen en renderen.
arcade.start_render()
self.ball.on_draw()
self.paddle1.on_draw()
self.paddle2.on_draw()
minutes = int(self.total_time) // 60
seconds = int(self.total_time) % 60
output = f"Time: {minutes:02d}:{seconds:02d}"
#arcade.draw_text(output, 300, 500, arcade.color.WHITE_SMOKE, 30)
output = f" {self.Player1.score} : {self.Player2.score}"
arcade.draw_text(output, SCREEN_WIDTH - 450, SCREEN_HEIGHT - 100, arcade.color.WHITE, 30)
debug = f"cx:{self.ball.change_x} | cy:{self.ball.change_y}"
arcade.draw_text(debug, 0, 100, arcade.color.WHITE, 20)
def on_update(self, delta_time):
self.ball.on_update(delta_time)
self.paddle1.on_update(delta_time)
self.paddle2.on_update(delta_time)
self.total_time += delta_time
# hier zeg je dat als de ball over de rechterkant gaat dat je dan 1 punt bij het andere team moet doen
if self.ball.position_x >= SCREEN_WIDTH:
self.ball.position_x = SCREEN_WIDTH - 100
self.ball.position_y = SCREEN_HEIGHT - 100
self.Player1.score = self.Player1.score + 1
self.ball.change_x = self.ball.change_x * -1
#als de score hoger is dan 3 moet de bal sneller gaan bewegen
if self.Player1.score == 5:
if self.ball.change_x > 0:
self.ball.change_x = self.ball.change_x + 1
else:
self.ball.change_x = self.ball.change_x - 1
if self.ball.change_y > 0:
self.ball.change_y = self.ball.change_y + 1
else:
self.ball.change_y = self.ball.change_y - 1
if self.Player1.score == 7:
if self.ball.change_x > 0:
self.ball.change_x = self.ball.change_x + 1
else:
self.ball.change_x = self.ball.change_x - 1
if self.ball.change_y > 0:
self.ball.change_y = self.ball.change_y + 1
else:
self.ball.change_y = self.ball.change_y - 1
if self.Player1.score == 9:
if self.ball.change_x > 0:
self.ball.change_x = self.ball.change_x + 1
else:
self.ball.change_x = self.ball.change_x - 1
if self.ball.change_y > 0:
self.ball.change_y = self.ball.change_y + 1
else:
self.ball.change_y = self.ball.change_y - 1
# hier zeg je dat als de ball over de linkerkant gaat dat je dan 1 punt bij het andere team moet doen
if self.ball.position_x <= 0:
self.ball.position_x = SCREEN_WIDTH - 700
self.ball.position_y = SCREEN_HEIGHT - 500
self.Player2.score = self.Player2.score + 1
self.ball.change_x = self.ball.change_x * -1
#als de score hoger is dan 3 moet de bal sneller gaan bewegen
if self.Player2.score == 5:
if self.ball.change_x > 0:
self.ball.change_x = self.ball.change_x + 1
else:
self.ball.change_x = self.ball.change_x - 1
if self.ball.change_y > 0:
self.ball.change_y = self.ball.change_y + 1
else:
self.ball.change_y = self.ball.change_y - 1
if self.Player2.score == 7:
if self.ball.change_x > 0:
self.ball.change_x = self.ball.change_x + 1
else:
self.ball.change_x = self.ball.change_x - 1
if self.ball.change_y > 0:
self.ball.change_y = self.ball.change_y + 1
else:
self.ball.change_y = self.ball.change_y - 1
if self.Player2.score == 9:
if self.ball.change_x > 0:
self.ball.change_x = self.ball.change_x + 1
else:
self.ball.change_x = self.ball.change_x - 1
if self.ball.change_y > 0:
self.ball.change_y = self.ball.change_y + 1
else:
self.ball.change_y = self.ball.change_y - 1
#Hier zeg je dat de ball moet omdraaien als je de rechter paddle raakt
if self.ball.position_x + self.ball.radius >= self.paddle2.x and self.ball.position_y <= self.paddle2.y + self.paddle2.height/2 and self.ball.position_y >= self.paddle2.y - self.paddle2.height/2:
self.ball.change_x = self.ball.change_x * -1
arcade.play_sound(self.paddle_sound)
#Hier zeg je dat de ball moet omdraaien als je linkerpaddle raakt
if self.ball.position_x - self.ball.radius < self.paddle1.x and self.ball.position_y <= self.paddle1.y + self.paddle1.height/2 and self.ball.position_y >= self.paddle1.y - self.paddle1.height/2 :
self.ball.change_x = self.ball.change_x * -1
arcade.play_sound(self.paddle_sound)
#hier zeg je dat als de score van speler 1 of speler 2 10 is dat hij dan naar het Game over scherm moet gaan
if self.Player1.score == 3:
game_over_view1 = GameOverView1()
self.window.show_view(game_over_view1)
if self.Player2.score == 3:
game_over_view2 = GameOverView2()
self.window.show_view(game_over_view2)
def on_key_press(self, symbol, key_modifiers):
# als je de key indrukt dan gaat hij 7 pixels omhoog of 7 pixels omlaag
if symbol == arcade.key.W:
self.paddle1.change_y = 7
if symbol == arcade.key.S:
self.paddle1.change_y = -7
if symbol == arcade.key.UP:
self.paddle2.change_y = 7
if symbol == arcade.key.DOWN:
self.paddle2.change_y = -7
#pause en resume keys. als je P indrukt dan gaat hij op pauze en als je op ESCAPE drukt dan gaat hij verder.
if symbol == arcade.key.P:
self.ball.change_x = 0
self.ball.change_y = 0
if symbol == arcade.key.ESCAPE:
self.ball.change_x = 4 + self.difficulty
self.ball.change_y = 4 + self.difficulty
def on_key_release(self, symbol, mod):
#als je de key lostlaat dan stop de paddle met bewegen
if symbol == arcade.key.W:
self.paddle1.change_y = 0
if symbol == arcade.key.S:
self.paddle1.change_y = 0
if symbol == arcade.key.UP:
self.paddle2.change_y = 0
if symbol == arcade.key.DOWN:
self.paddle2.change_y = 0
class GameOverView2(arcade.View):
def __init__(self):
#hier zorg je ervoor dat hij een geluid maakt als speler 2 wint
super().__init__()
self.point_sound = arcade.load_sound('ohyeah.wav')
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
arcade.play_sound(self.point_sound)
def on_draw(self):
arcade.start_render()
arcade.draw_text("Blue Team won!", SCREEN_WIDTH - 590, SCREEN_HEIGHT - 200, arcade.color.WHITE, 54)
class GameOverView1(arcade.View):
def __init__(self):
#hier zeg je dat hij een geluidje maakt als player 1 wint
super().__init__()
self.point_sound = arcade.load_sound('ohyeah.wav')
def on_show(self):
arcade.set_background_color(arcade.color.BLACK)
arcade.play_sound(self.point_sound)
def on_draw(self):
arcade.start_render()
arcade.draw_text("Red team won!", SCREEN_WIDTH - 590, SCREEN_HEIGHT - 200, arcade.color.WHITE, 54)
def main():
window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
menu_view = MenuView()
window.show_view(menu_view)
arcade.run()
# hij checkt hier of het proces van python het hoofdproces is.
if __name__ == "__main__":
main() |
188e22cb39af42f37d332240cd356ebde785dbae | gabby-cervantes-projects/RPGModFileProcesser-Creator | /modmakers.py | 5,062 | 4.0625 | 4 | import pandas as pd
import numpy as np
import random
def run_complaint():
number_complaint = random.randint(0,10)
complain = ['Yo, you good fam?', 'You\'re pretty indesisive huh?', 'It\'s two letters?', 'Dude, choose a letter.', 'Okay, you got this fam. Choose a letter.', 'Low key impressed you haven\'t chosen yet.', 'Are you confused?', 'Do you need help?', 'Exit the program whenever you want dude.', 'Are you trapped?', 'Do you feel trapped']
print(complain[number_complaint])
def build_database():
"""
To be completed: Want to create a new panda database, specifying the rows the user wants and the values they would like to input
"""
col_string = input('An example input: first_col, second_col, third_col, fourth_col\nSpecify the columns you would like to see: ')
col_names = col_string.split(',')
row_string = input('Example Data input: first_col_data, second_col_data, None, fourth_col_data\nIf there is no data to be inputted, please put \'None\'\nInput data: ')
data = row_string.split(',')
data_dict = {}
for i in range(len(col_names)):
data_dict[col_names[i]] = data[i]
print(data_dict)
def add_new_row():
"""
to be completed: I want to itterate over the col_names that the user specified in the begining and assign them to the correct values in the dictionary.
"""
des = input("Description: ")
basemod = input("Base Moditication: ")
mod_opt = input("Mod Options: ")
price = input("Price: ")
hp = input("HP: ")
rarity = input("Rarity: ")
book = input("Book/Link: ")
data_dict = {'Name':name, 'Description':des, 'Base Modification':basemod, 'Mod Options':mod_opt,'Price':price, 'HP' : hp, 'Rarity': rarity, 'Book/Link': book}
# mod_values = mod_values.append(data_dict, ignore_index=True)
return data_dict
if __name__ == "__main__":
# Set it up so they can either creat a document or edit an alread existing one
num = 0
"""
while(1):
# give the user the choice to make a document or edit a document
# keep them here if they don't input a correct value
val = input("Would you like to create or edit a document?[c/e]")
option = val.lower()
if num > 1:
run_complaint()
if val.lower() == 'c':
print("You have chosen to create a CSV document")
new_mod_database = build_database()
break
if val.lower() == 'e':
print("You have chosen to edit a CSV document")
file_name = input("Please specify path to document (if in same directory, this will be the file name): ")
break
print(val + " is not a valid response. Please enter a valid response.")
num+=1
"""
# for testing
file_name = 'modification.csv'
mod_values = pd.read_csv(file_name)
print(mod_values.head())
while(True):
answer = input("Would you like to continue[y/n]?")
answer = answer.lower()
if answer == 'n' or answer == 'no':
mod_values.to_csv('modification.csv')
break
name = input("Name: ").strip()
selected_mod = mod_values.loc[mod_values['Name'] == name]
if selected_mod.empty:
data_dict = add_new_row()
mod_values = mod_values.append(data_dict, ignore_index=True)
print("_________________________________________________")
print(mod_values)
else:
print("\nMod " + name + " has already been added to the csv file \n_______________________________________________\n")
print(selected_mod)
update = input("_______________________________________________\nWould you like to upgrade the specs [y/n]?")
if update.lower() == 'y' or update.lower() == 'yes':
# //update the thing
index_num = selected_mod.keys().tolist()[0]
print(selected_mod[index_num])
mod_values.drop(selected_mod[index_num],axis=0, inplace=True)
data_dict = add_new_row()
mod_values = mod_values.append(data_dict, ignore_index=True)
# name = 'Droid Brain Defense System'
# des = 'Using a droid brain chip and installing a set of sensors on the armour, the wearer is alerted to incoming fire in some fashion. More advanced versions include mini repulsor generators that push the wearer out of harm\'s way.'
# basemod = 'Defense +1.'
# mod_opt = '1x \"Defense +1 when taking Guarded Stance maneuver.\"'
# price = '5000'
# hp = '3'
# rarity = '6'
# book = 'Engineer career; [SWA47] Fully Operational'
# col_names = ['Name', 'Description', 'Base Modification', 'Mod Options' ,'Price', 'HP', 'Rarity', 'Book/Link']
# data_list = [(name, des, basemod, mod_opt, price, hp, rarity, book)]
# mods = pd.DataFrame(data_list, columns=col_names)
# new_values = mods
|
d61b211c8f01b256c6f3c328c7b6bb36b67e56c1 | picardcharlie/python101 | /projects/file_search.py | 1,441 | 4.25 | 4 | # Write a script that searches a folder you specify (as well as its subfolders, up to two levels deep)
# and compiles a list of all .jpg files contained in there.
# The list should include the complete path of each .jpg file.
# If you are feeling bold, create a list containing each type of file extension you find in the folder.
# Start with a small folder to make it easy to check whether your program is working correctly. Then search a bigger folder.
# This program should work for any specified folder on your computer.
import pathlib
# copy and pasted the lab, why reinvent all of the wheel?
# path to the current directory
current_directory = pathlib.Path().cwd()
print(current_directory)
for files in current_directory.iterdir():
#if it's a .jpg file, print the name.
if files.suffix == ".jpg":
print(files.name)
# if it's a directory, change to it
if files.is_dir() == True:
sub_directory = current_directory.joinpath(files.name)
# go through directory and print all .jpg
for sub_files in sub_directory.iterdir():
if sub_files.suffix == ".jpg":
print(sub_files.name)
# Check the sub-sub directory for them.
if sub_files.is_dir() == True:
basement_files = sub_directory.joinpath(sub_files.name)
for base in basement_files.iterdir():
if base.suffix == ".jpg":
print(base.name) |
6b426850c09b492d98660de659b599d73a10ec3c | subha9/Assignment-3 | /Assignment_3.py | 1,727 | 3.875 | 4 |
# coding: utf-8
# In[72]:
#1.1 Write a Python Program to implement your own myreduce() function which works exactly
#like Python's built-in function reduce()
def app(lst1):
app=lst1[0]
for i in range(1,len(lst1)):
app*=lst1[i]
return app
print(app([4,3,2,1]))
#from functools import reduce
#n=[4,3,2,1]
#print(reduce(lambda x,y:x*y,n))
# In[75]:
#Write a Python program to implement your own myfilter() function which works exactly like
#Python's built-in function filter()
def my_fun(lst1):
lst2=[x for x in lst1 if x>2]
return lst2
print (my_fun([4,3,2,1]))
#n=[4,3,2,1]
#print(list(filter(lambda x :x>2,n)))
# In[ ]:
#Write List comprehensions to produce the following Lists
['A', 'C', 'A', 'D', 'G', 'I', 'L’, ]
# In[84]:
word ='ACADGILD'
a_lst =[x for x in word]
print( 'word' + str(a_lst))
# In[101]:
#Write List comprehensions to produce the following Lists
#['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
input_list =['x','y','z']
res = [ item*num for item in input_list for num in range(1,5) ]
print('input_list ='+str(res))
# In[99]:
lst = ['x','y','z']
i = [ item*num for num in range(1,5) for item in lst ]
print( str(i))
# In[98]:
a = [2,3,4]
b = [ [item+num] for item in a for num in range(0,3)]
print(str(b))
# In[107]:
a=[2,3,4,5]
b= [[item+num for item in a] for num in range(0,4)]
print(str(b))
# In[116]:
a=[1,2,3]
t=tuple(a)
r =[(x,y) for x in a for y in a]
print(str(r))
# In[117]:
def long_word(word_lists):
word_length=[]
for n in word_lists:
word_length.append((len(n),n))
word_length.sort()
return word_length[-1][1]
print(long_word(["python","java","Science"]))
|
9be222e4f82bf785084d7a3630e46c07ac14b4dd | jlardy/Python-Scripts | /pdf_writer.py | 1,465 | 3.90625 | 4 | """
This program writes pictures to a pdf.
Running the program will launch tkinter file dialogs to get a path to images you want converted to a pdf.
- Images must be vertically oriented
- Images must be stored in the order you want written
- Only works with png, jpg, and jpeg currently
This was just a quick and dirty solution becuase my computers pdf printer driver was corrupted and I couldn't
be bothered to figure that one out.
"""
from PIL import Image
from os import listdir, getcwd
from os.path import join
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw() #hide the tkinter window
# Select folder with all the pictures in order you want stored
files_path = filedialog.askdirectory(initialdir = getcwd(), title = "Select Files")
# save as a pdf
outfile = filedialog.asksaveasfilename(initialdir = getcwd(),initialfile='output.pdf' ,title = "Save As", filetypes = (("pdf", "*.pdf*"), ("all files", "*.*")))
if not outfile.endswith('.pdf'):
outfile += '.pdf'
# get the path for all the images
images = [join(files_path, f) for f in listdir(files_path) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
# have to create a starting image to append the rest of the images to
start = Image.open(images.pop(0)).rotate(-90, expand=True).convert('RGB')
others = [Image.open(img).rotate(-90, expand=True).convert('RGB') for img in images]
start.save(fp=outfile, save_all=True, append_images=others)
|
c2850b6e3666fdf9f95977683c67934eae3cfd8b | andreasdjokic/piratize | /piratize_translate.py | 3,482 | 3.609375 | 4 | #Contains methods that are to be used in the piratize file, and the various classes
from fractions import Fraction
"""General method that takes a string, s1, and returns the string after being
translated to pirish. Couldn't find a great equivalent to Ruby's
talk_like_a_pirate gem, so I just covered some of the basics here"""
def translate_to_pirish(s1):
s1 = s1.replace('gold', '')
s1 = s1.replace('treasure', '')
s1 = s1.replace('coin', '')
s1 = s1.replace('coins', '')
s1 = s1.replace('Hello', 'Ahoy')
s1 = s1.replace('hello', 'ahoy')
s1 = s1.replace('Hi', 'Yo-ho-ho')
s1 = s1.replace('hi', 'yo-ho-ho')
s1 = s1.replace('My', 'Me')
s1 = s1.replace('my', 'me')
s1 = s1.replace('Friend', 'Bucko')
s1 = s1.replace('friend', 'bucko')
s1 = s1.replace('Sir', 'Matey')
s1 = s1.replace('sir', 'matey')
s1 = s1.replace('Miss', 'Proud beauty')
s1 = s1.replace('miss', 'proud beauty')
s1 = s1.replace('Stranger', 'Scurvy Dog')
s1 = s1.replace('stranger', 'scurvy dog')
s1 = s1.replace('Officer', 'Foul blaggart')
s1 = s1.replace('officer', 'foul blaggart')
s1 = s1.replace('Where', 'Whar')
s1 = s1.replace('where', 'whar')
s1 = s1.replace('Is', 'Be')
s1 = s1.replace('is', 'be')
s1 = s1.replace('The', "Th'")
s1 = s1.replace('the', "th'")
s1 = s1.replace('You', 'Ye')
s1 = s1.replace('you', 'ye')
s1 = s1.replace('Old', 'Barnacle covered')
s1 = s1.replace('old', 'barnacle covered')
s1 = s1.replace('Happy', 'Grog-filled')
s1 = s1.replace('happy', 'grog-filled')
s1 = s1.replace('Nearby', 'Broadside')
s1 = s1.replace('nearby', 'broadside')
s1 = s1.replace('Restroom', 'Head')
s1 = s1.replace('restroom', 'head')
s1 = s1.replace('Restaurant', 'Galley')
s1 = s1.replace('restaurant', 'galley')
s1 = s1.replace('Hotel', 'Fleabag inn')
s1 = s1.replace('hotel', 'fleabagg inn')
return s1
"""A method that takes a float and returns the nearest rational
where 8 is the denominator. Fraction reduces the passed-in numbers
though, so I left numerator and denominator commented out in case
those would be better to use"""
def float_to_rational(f1):
#numerator = int(round(f1 * 8))
#denominator = 8
return Fraction(int((round(f1*8))), 8)
"""A method that iterates through a list(array) and checks the type
of each index. If it's a string, piratize the string. If it's a float,
convert it to the Rational near 8"""
def process_array(list_1):
temp_list = []
for i in range(len(list_1)):
if isinstance(list_1[i], basestring):
#list_1[i] = translate_to_pirish(list_1[i])
temp = translate_to_pirish(list_1[i])
temp_list.append(temp)
elif isinstance(list_1[i], float):
#list_1[i] = float_to_rational(list_1[i])
temp = float_to_rational(list_1[i])
temp_list.append(temp)
#return list_1
return temp_list
test_list_1 = ["Hello my coin", "Where is the treasure"]
t1 = process_array(test_list_1)
print t1
"""Should be a method that iterates through a dictionary(hash table) and does
the same as process_array. In this case, I'm not sure what key we would be
looking for, so not sure how to iterate through it without just repeating
process_array """
def process_hash(dict_1):
return '' |
07d106d4d2141bf05aa4d98458c3525e5e352108 | rainishadass/127 | /code/misc_hw/ch7_9.py | 1,660 | 4.0625 | 4 |
def isEven(number):
if number % 2 == 0:
return True
else:
return False
def isEvenTerse(number):
return number % 2 == 0
def isOdd(number):
return not isEven(number)
longString ="""
Street bands have been picking up the slack for the last year in NYC, performing for outside diners and more throughout the city. This festival celebrates them and puts them front and center.
Email readers can see the video
"""
def countLetters(s,letter):
"""
count the number of times letter occurs in string s
"""
count = 0
for l in s:
print(l)
longString ="""
Street bands have been picking up the slack for the last year in NYC, performing for outside diners and more throughout the city. This festival celebrates them and puts them front and center.
Email readers can see the video
"""
def countLetters(s,letter):
"""
count the number of times letter occurs in string s
"""
count = 0
print(s)
for l in s:
if l==letter.lower() or l==letter.upper():
count = count + 1
return count
def tests():
print("IsEven tests")
print("isEven(23)",isEven(23))
print("isEven(24)",isEven(24))
print()
print("IsEvenTerse tests")
print("isEvenTerse(23)",isEvenTerse(23))
print("isEvenTerse(24)",isEvenTerse(24))
print()
print("IsOdd tests")
print("isOdd(23)",isOdd(23))
print("isOdd(24)",isOdd(24))
print()
print("Count letters a in longString")
print(countLetters(longString,'A'))
if __name__=="__main__":
# put the stuff here to be run automatically if you
# run this file as a program
tests()
|
4ead8fa459f65bd69ff7378f0569accbdae55f6f | KevinF42/Python | /print_sfi_functions.py | 233 | 3.53125 | 4 | def intcalc():
A = int(5)
B = int(9)
print (A+B)
def floatcalc():
C = float(12)
D = float(25)
print (C+D)
def stringcat():
E = str("Abra")
F = str("Kadabra")
print (E+F)
def main():
intcalc(),floatcalc(),stringcat()
main()
|
a52650ba8ea7978a4a82a17910ca38629c2337b4 | elenatheresa/CSCI-160 | /lab9b.py | 1,316 | 3.890625 | 4 | '''
elena corpus
csci 160
tuesday 5 -7 pm
program to ask for data file, and then finding data from it
'''
fileName = open('testscores.txt','r')
def largestScore():
fileName.readlines()
num = int(fileName)
for num in range(0,101):
if num <= 99:
num = largestScore
elif num <= 80:
num = largestScore
elif num <= 60:
num = largestScore
elif num <= 40:
num = largestScore
else:
num = largestScore
def smallestScore():
fileName.readlines()
num = int(fileName)
for num in range(0,101):
if num < 10:
num = smallestScore
elif num <= 40:
num = smallestScore
elif num <= 60:
num = smallestScore
elif num <= 80:
num = smallestScore
else:
num = smallestScore
totalNum = 0
fileName.readlines()
for lines in fileName:
totalNum = totalNum + 1
num = num + num
print('Searching for values')
upperLimit = input('Enter the upper limit: ')
lowerLimit = input('Enter the lower limit: ')
if num > lowerLimit and num < upperLimit:
print(num)
print('Largest Score:', largestScore)
print('Smallest Score:', smallestScore)
print('Average scores:', averageScore)
fileName.close()
|
3a4914d12865a893b0738d43c40a953a75d89827 | jonathandieu/pythonjumpstart | /learning_classes.py | 802 | 4.21875 | 4 | # Welcome to Python in Visual Studio Code!
# Click the green Run button in the top right corner
# of this editor to run your first Python program.
print("Hello world!")
class Test(object):
"""
This must be for documentation: it's a docstring
it works in multiple lines too
"""
weight = 0
difficulty = 0
def show(self):
"""
This method prints out what values are in the object.
"""
print(self.weight)
pass
pass
final = Test()
final.show()
class myClass():
"""
This is a class that does nothing
"""
x = 4
def myMethod(self):
print("this")
class myOtherClass(myClass):
"""
This is a class that does nothing
"""
def myMethod(self):
print("that")
x = myOtherClass()
x.myMethod() |
f7db06b6806abbe9de98d82ceb3c376cdc865fdf | phuonghtruong/python | /Checkio/find_message.py | 381 | 4 | 4 | #!/usr/bin/env python3
def find_message(text: str) -> str:
result= []
s = ""
for letter in text:
if letter.isupper() == True:
result.append(letter)
return s.join(result)
def find_message_2(text):
return ''.join(i for i in text if i.isupper())
if __name__=='__main__':
print(find_message("How are you? Eh, ok. Low or Lower? Ohhh."))
|
41e6890ed52a1e627685ad97d4ba589f6d1dab22 | kjqmiller/recursive-binary-search | /binary_search.py | 1,507 | 4.25 | 4 | # Binary search function using recursion
def binary_search(arr, low, high, x):
# Base case when we are left with only the high and low indices. When we calculate mid and try to run the function
# again, the low and high indices will cross with the addition of 1 to low, or subtraction of 1 from high.
if low > high:
print('Not found')
return -1
# Calculate the middle index using integer division
mid = (high + low) // 2
# See if x is in the middle, if not, determine if x is in the left or right half of the array
if arr[mid] == x:
print('Found!')
return 0
elif arr[mid] > x: # In left half
binary_search(arr, low, mid-1, x)
elif arr[mid] < x: # In right half
binary_search(arr, mid+1, high, x)
else:
print('Something went wrong')
return -2
# Hardcoded array for quick testing, must be sorted for binary search to work
arr = [-7, 0, 1, 2, 5, 8, 10, 13, 40, 55]
arr_max_index = len(arr) - 1
low_num = arr[0]
high_num = arr[arr_max_index]
# Get user input for integer to search for, making sure they enter an integer in range of the array
while True:
x = input(f'Enter an integer to search for in the range ({low_num} - {high_num}): ')
if x.lstrip('-').isdigit() and low_num <= int(x) <= high_num:
x = int(x)
break
else:
print(f'Please enter an integer in the range {low_num} - {high_num}.\n')
# Run the search function
binary_search(arr, 0, arr_max_index, x)
|
23375c51450ea15417be6d5282c0b6265b8ffd29 | CodeAltus/Python-tutorials-for-beginners | /Lesson 13 - List Comprehension and Slice Operator/slice operator.py | 130 | 3.515625 | 4 | my_list = [x for x in range(0, 10, 2)]
fruits = ["apple", "pears", "strawberries", "blueberries", "bananas"]
print(fruits[0:5:2]) |
adada8b999f483092c5fbe3fa2d6987c4812593e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2730/60580/316630.py | 338 | 3.75 | 4 | def summary(number):
string = str(number)
total = 0
for i in range(len(string)):
total = total + int(string[i])
return total
T = int(input())
for i in range(T):
number = input()
temp = input().split()
num = str(''.join(temp))
if summary(num) % 3 == 0:
print(1)
else:
print(0)
|
1a3ed228016a64a1e027be6ba5829eaf7f7f38c2 | jtbarker/codinginterviews | /linkedlistcycle.py | 1,738 | 3.90625 | 4 |
class LinkedList:
def __init__(self, head):
self.head = head
self.next = None
#O(n) time O(n) space
def detectcycle(self,head):
if not self.head or not self.head.next:
return False
else:
visited = set()
curr = self.head
while curr:
if curr in visited:
return True
visited.add(curr)
curr = curr.next
return False
def detectmerge(head1,head2):
visited = set()
dummy1.next = head1
dummy2.next = head2
curr1 = head1
curr2 = head2
# There actually might be an edge case here where the intersection happens at the last node -> use a dummy like previous example to catch this maybe
while dummy1.next is not None and dummy2.next is not None:
if curr1 and curr2 in visited:
return curr1
visited.add(curr1)
visited.add(curr2)
curr1 = curr1.next
curr2 = curr2.next
dummy1 = dummy1.next
dummy2 = dummy2.next
def detectmerge(head1,head2):
len1 = 0
len2 = 0
visited = set()
dummy1.next = head1
dummy2.next = head2
curr1 = head1
curr2 = head2
# There actually might be an edge case here where the intersection happens at the last node -> use a dummy like previous example to catch this maybe
while dummy1.next is not None and dummy2.next is not None:
if curr1 and curr2 in visited:
return curr1
visited.add(curr1)
visited.add(curr2)
curr1 = curr1.next
len1 += 1
curr2 = curr2.next
len2 += 1
dummy1 = dummy1.next
dummy2 = dummy2.next
|
0a9156d0bdef2e5452129d46013897c1eaf9362f | Hayden-Bailey/Practicals | /prac_06/guitar_test.py | 724 | 3.5 | 4 | """
Testing Guitar Class
"""
from prac_06.guitar import Guitar
def main():
gibson_guitar = Guitar("Gibson L-5 CES", 1922, 16035.40)
test_guitar = Guitar("Test Guitar", 2009, 1500)
gibson_age = gibson_guitar.get_age()
test_age = test_guitar.get_age()
print("{} get_age(): Expected 97 Got {}".format(gibson_guitar.name, gibson_age))
print("{} get_age(): Expected 10 Got {}".format(test_guitar.name, test_age))
gibson_vintage = gibson_guitar.is_vintage()
test_vintage = test_guitar.is_vintage()
print("{} is_vintage(): Expected True Got {}".format(gibson_guitar.name, gibson_vintage))
print("{} is_vintage(): Expected False Got {}".format(test_guitar.name, test_vintage))
main() |
5f49dee3a176d3045f23bbe5dc33113633545b84 | Amarildop1/Python | /ExibeDiagonalDeUmaMatrizQuadrada.py | 737 | 4.03125 | 4 | matriz = []
N = int(input("\nDigite a ordem 'N' da matriz: "))
#Preenchendo com zeros
for i in range(N):
matriz.append(N*[0])
#Preenchendo com a entrada
for i in range(N):
for j in range(N):
matriz[i][j] = int(input(f'Matriz ({i},{j}): '))
#Exibindo a matriz completa
print("\nMatriz Quadrada: ")
for i in range(N):
print(matriz[i])
#Exibindo elementos da diagonal
print("\nElementos da Diagonal: ")
for i in range(len(matriz)):
for j in range(len(matriz)):
if(matriz[i] == matriz[j]):
print(matriz[i][j])
"""
Dada uma matriz quadrada de elementos inteiros e ordem N,
exiba os elementos da diagonal principal.
Isto é, os elementos onde I = J. Obs: N será lido (N <= 10).
""" |
a4f87162ceddc7d1f4d9c31767543abed7a6935f | jfvergara/python-course-nana | /time-till-deadline.py | 400 | 4.125 | 4 | from datetime import datetime
user_input = input("Enter your goal with a deadline separated by colon\n")
input_list = user_input.split(":")
goal = input_list[0]
deadline = input_list[1]
deadline_date = datetime.strptime(deadline, "%d.%m.%Y")
today_date = datetime.today()
time_till = deadline_date - today_date
print(f"Dear user, Time remaining for your goal: {goal} is {time_till.days} days") |
5848fa1b94b232311ce3586891345e3da2a1e300 | Hwesta/advent-of-code | /aoc2015/day10.py | 2,100 | 4.4375 | 4 | #!/usr/bin/env python3
# -*- coding: <encoding name> -*-
"""
--- Day 10: Elves Look, Elves Say ---
Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones", which becomes 1221 (1 2, 2 1s).
Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by the digit itself (1).
For example:
1 becomes 11 (1 copy of digit 1).
11 becomes 21 (2 copies of digit 1).
21 becomes 1211 (one 2 followed by one 1).
1211 becomes 111221 (one 1, one 2, and two 1s).
111221 becomes 312211 (three 1s, two 2s, and one 1).
Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?
--- Part Two ---
Neat, right? You might also enjoy hearing John Conway talking about this sequence (that's Conway of Conway's Game of Life fame).
Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the new result?
"""
import itertools
def version1(data):
new_data = ''
for key, matches in itertools.groupby(data):
# This is like 100x slower especially as input increases because it keeps allocating a new string not modifying the one in place and generating page faults
# new_data = new_data + str(len(list(matches))) + key
new_data += str(len(list(matches))) + key
return new_data
def version2(data):
return ''.join(str(len(list(matches))) + key for key, matches in itertools.groupby(data))
def look_and_say(data, iterations=1, version=version2):
for _ in range(iterations):
data = version(data)
return data
if __name__ == '__main__':
data = '1113122113'
print("Look and say after 40 iterations", len(look_and_say(data, 40)))
print("Look and say after 50 iterations", len(look_and_say(data, 50)))
|
db79046c71626f4157f9928870b7721351b78541 | muskanmahajan37/Python-Code-Bits | /gui2.py | 417 | 3.65625 | 4 | from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()
|
768cd16776bbcfcf7bc176dd2ee1836e76e207c0 | enesaygur/python | /asal_sayi.py | 264 | 3.78125 | 4 | sayi=int(input("Sayı giriniz:"))
asalmi=True
if sayi==1:
asalmi=False
for i in range(2,sayi):
if sayi%i==0:
asalmi=False
break
if asalmi:
print(f"{sayi} Sayısı asaldır.")
else:
print(f'{sayi} asal DEĞİLDİR!') |
cbd0448d389851f68dc8b4925e3ae67502c4f036 | thoftheocean/exploration | /homework/case6.1.py | 2,024 | 3.828125 | 4 | #coding:utf-8
#python2.7环境
#描述
'''
题目1:打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个“水仙花数”,因为153=1的三次方+5的三次方+3的三次方。
题目2:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
题目3:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?(流程图课堂上已画)
'''
#题目1
def function1():
for num in range(100, 999):
bai = num // 100
shi = (num // 10) % 10
ge = num % 10
if num == bai ** 3 + shi ** 3 + ge ** 3:
print num,
else:
continue
def function11():
for a in range(1, 10):
for b in range(0, 10):
for c in range(0, 10):
x = a ** 3 + b ** 3 + c ** 3
y = a * 100 + b * 10 + c
if x == y:
print y,
#题目2
def function2():
a = [1, 2, 3, 4]
for i in range(4):
for j in range(4):
for k in range(4):
if a[i] != a[j] and a[j] != a[k] and a[i] != a[k]:
num = a[i] * 100 + a[j] * 10 + a[k]
print num,
else:
continue
#题目3
def function3():
import math
for num1 in range(1, 10000):
num2 = math.sqrt(num1 + 100)
num3 = math.sqrt(num1 + 268)
if num3 == math.floor(num3) and num2 == math.floor(num2):
print num1,
def function31():
for a in range(10000):
x = a ** 2 + 168
y = x ** 0.5
if y.is_integer():
print (a ** 2 - 100),
if __name__=='__main__':
function1()
print '\n'+'----------'
function11()
print '\n' + '----------'
function2()
print '\n'+'----------'
function3()
print '\n' + '----------'
function31() |
023627f094e987438401428f6547aa2314bebfae | Astralknight532/RevatureStagingProjects | /AirPol/Data Processing Code/customfunctions.py | 1,234 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 10:39:32 2020
@author: hanan
"""
import pandas as pd
from math import sin, cos, sqrt, atan2, radians, pi
# Defining functions to organize repetitive tasks
# Converts date column to datetime
def dt_convert(data:pd.Series) -> pd.Series:
data = pd.to_datetime(data.str.strip(), format = '%Y-%m-%d', errors = 'ignore')
return data
# Converts the passed string values into type float64 - extracts strings using regex
def float_convert(data:pd.Series) -> pd.Series:
data = data.str.extract('(\d*\.\d*)').astype('float64')
return data
# Converting between degrees and radians (used in the function lat_long_dist)
def d_to_r(deg): # degrees to radians
return (deg * pi) / 180
def r_to_d(rad): # radians to degrees
return (rad * 180) / pi
# Distance between 2 latitude-longitude points in kilometers
def lat_long_dist(lat1, long1, lat2, long2):
earth_r = 6378 # radius of the Earth in kilometers
lat_dif = radians(lat2) - radians(lat1)
long_dif = radians(long2) - radians(long1)
s1 = (sin(lat_dif / 2) ** 2) + (cos(radians(lat1)) * cos(radians(lat2))) * (sin(long_dif / 2) ** 2)
s2 = 2 * atan2(sqrt(s1), sqrt(1 - s1))
return earth_r * s2 |
1dc9505f3bce41c2b9490769970424917145175c | nafasamuth/SG-Basic-Gen.03 | /Tree/tree.py | 1,917 | 3.90625 | 4 | class Node:
def __init__(self,val):
self.info = val
self.left = None
self.right = None
def insert(self, val):
if val < self.info:
if self.left is None:
self.left = Node(val)
else:
self.left.insert(val)
elif val > self.info:
if self.right is None:
self.right = Node(val)
else:
self.right.insert(val)
def inOrder(self):
if self.left:
self.left.inOrder()
print (self.info, end=" "),
if self.right:
self.right.inOrder()
def preOrder(self):
print(self.info, end=" "),
if self.left:
self.left.preOrder()
if self.right:
self.right.preOrder()
def postOrder(self):
if self.left:
self.left.postOrder()
if self.right:
self.right.postOrder()
print(self.info, end=" "),
def search(self,val):
if val < self.info:
if self.left is None:
return None
else:
return self.left.search(val)
elif val > self.info:
if self.right is None:
return None
else:
return self.right.search(val)
else:
return True
def height(self):
a = 0
b = 0
if self.left:
a = 1+self.left.height()
if self.right:
b = 1+self.right.height()
if a > b:
return a
else:
return b
# def levelOrder(self):
BT = Node(23) #Root
BT.insert(10)
BT.insert(16)
BT.insert(19)
BT.insert(65)
BT.insert(45)
BT.insert(24)
BT.insert(50)
BT.insert(67)
BT.inOrder()
print(" ")
BT.postOrder()
print(" ")
BT.preOrder()
print(" ")
print(BT.search(24))
print(BT.search(1))
print(BT.search(242131))
print(BT.height())
|
cd14d701bfcfabe4d6ba2743deeb06c85917e055 | chords-app/chords-app.github.io | /Python/שבוע 7/מעבדה/LAB6Q2.py | 189 | 3.6875 | 4 | import math
def func1(a):
if(a>0):
b = math.floor(a)
if (a<0):
b = math.ceil(a)
return b
a = float(input("Enter some number "))
print(a)
d = func1(a)
print(d) |
f5d8188e6bfd53a19e2e2f61a8468051773ca8c7 | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_33.py | 524 | 4.09375 | 4 | """
Pattern
Enter number: 5
A
A B
A B C
A B C D
A B C D E
B C D E
C D E
D E
E
"""
print('Alphabet pattern:')
number_rows = int(input("Enter number of rows: "))
for row in range(1,number_rows+1):
print(" "*(number_rows-row),end="")
for column in range(1,row+1):
print(chr(64+column),end=" ")
print()
for row in range(1,number_rows+1):
print(" "*row,end="")
for column in range(1,number_rows+1-row):
print(chr(64+row+column),end=" ")
print() |
386afa5782fe884c7eb04b5c809ea4fcfeaeb6dc | BoKlassen/ColorFillSolver | /Block.py | 733 | 3.65625 | 4 | class Block:
def __init__(self, x, y, color, board_size):
self.board_size = board_size
self.x = x
self.y = y
self.color = color
self.captured = False
def to_string(self):
print("(" + str(self.x) + ", " + str(self.y) + ") - " + str(self.color))
def set_captured(self, captured):
self.captured = captured
def set_color(self, color):
self.color = color
def is_captured(self):
return self.captured
def has_left(self):
return self.x > 0
def has_top(self):
return self.y > 0
def has_right(self):
return self.x < self.board_size - 1
def has_bottom(self):
return self.y < self.board_size - 1
|
b39649027b767b25a32616973fdaa2abb0c036d2 | darkvictor13/Coisas-Python | /Desafios-Guanabara/006.py | 200 | 3.828125 | 4 | num = int(input('Informe um numero '))
print('O dobro dele eh = {}' .format(num * 2))
print('O triplo dele eh = {}' .format(num * 3))
print('O raiz quadrada dele eh = {:.5f}' .format(num ** (1 / 2)))
|
80880a9f96572d8a3db7fb66e2baa1ae19b91350 | mathphysmx/teaching-ml | /evaluation/Exercises/francisco_clustering_silhouette.py | 207 | 3.6875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = pd.DataFrame({'x': [1,1,2,3,4,5], 'y':[4,6,6,8,3,2]})
i = 0
x.iloc[i, ]
np.sqrt(3)
def dist(x1,x2):
return((x1.x - x2.x)^2)
|
6585beb4335170778cd5856e7cace0d5c45bc921 | tomemming2/Bulkbuddy | /BMI_BMR_Calculator.py | 3,486 | 3.875 | 4 | from tkinter import Tk, Label, Radiobutton, Entry, IntVar, StringVar, Button
def get_sum(event):
# Reset values so we can restart our calculations
BMI_sumEntry.delete(0, "end")
BMR_sumEntry.delete(0, "end")
TDEE_sumEntry.delete(0, "end")
# Get information from table
Height = float(Height_Entry.get().replace(",", "."))
Weight = float(Weight_Entry.get().replace(",", "."))
Age = int(Age_Entry.get())
sex_var = int(m_f.get())
Exercise_fact = Exercise_factor.get()
# Calculate the BMI
BMI_sum = round((100 * 100 * Weight) / (Height*Height))
BMI_sumEntry.insert(0, BMI_sum)
# Calculate BMR, basex on the sex selecation
if sex_var == 1:
BMR_sum = (66.5 + (13.75 * Weight) + (5.003 * Height) - (6.755 * Age))
elif sex_var == 2:
BMR_sum = (655.1 + (9.563 * Weight) + (1.850 * Height) - (4.676 * Age))
BMR_sumEntry.insert(0, BMR_sum)
# Calculate the TDEE value
TDEE_sum = round((float(BMR_sum) * float(Exercise_fact)))
TDEE_sumEntry.insert(0, TDEE_sum)
# Start the tkinter screen
root = Tk()
# Set the title
root.title("BMI / BMR / TDEE Calculator v0.1")
# Create an input field for the persons height
Label(root, text="Enter Height (in CM): ").grid(row=0, column=0, sticky='W')
Height_Entry = Entry(root)
Height_Entry.grid(row=0, column=1)
# Create an input field for the persons weight
Label(root, text="Enter Weight (in KG): ").grid(row=1, column=0, sticky='W')
Weight_Entry = Entry(root)
Weight_Entry.grid(row=1, column=1)
# Create an input field for the persons age
Label(root, text="Enter age: ").grid(row=2, column=0, sticky='W')
Age_Entry = Entry(root)
Age_Entry.grid(row=2, column=1)
'''
Create an empty variable called m_f
We use this variable to make a selection based on male/female
value 1 = male
value 2 = female
'''
m_f = IntVar()
# Create an radiobutton field to determine the persons sex
Label(root, text="What is your sex: ").grid(row=3, column=0, sticky='W')
Radiobutton(root, text="Male", variable=m_f, value=1).grid(row=3, column=1, sticky='W')
Radiobutton(root, text="Female", variable=m_f, value=2).grid(row=3, column=2, sticky='NW')
Exercise_factor = StringVar(value="1")
# Create some radiobuttons so that the person can tell us how active he is.
Label(root, text="How active are you?").grid(row=4, column=0, sticky='W')
Radiobutton(root, text="Sedentary", variable=Exercise_factor, value=1.2).grid(row=5, column=0, sticky='W')
Radiobutton(root, text="Lightly active", variable=Exercise_factor, value=1.375).grid(row=5, column=1, sticky='W')
Radiobutton(root, text="Moderately active", variable=Exercise_factor, value=1.55).grid(row=5, column=2, sticky='W')
Radiobutton(root, text="Very active", variable=Exercise_factor, value=1.725).grid(row=6, column=0, sticky='W')
Radiobutton(root, text="Extra active", variable=Exercise_factor, value=1.9).grid(row=6, column=1, sticky='W')
# Create a 'submit' button that runs the 'get_sum' class.
submit_Button = Button(root, text="Calculate BMI and BMR")
submit_Button.bind("<Button-1>", get_sum)
submit_Button.grid(row=7, column=1)
# Display all the calculated information
Label(root, text="Your BMI is: ").grid(row=8, column=0, sticky='W')
BMI_sumEntry = Entry(root)
BMI_sumEntry.grid(row=8, column=1)
Label(root, text="Your BMR is: ").grid(row=9, column=0, sticky='W')
BMR_sumEntry = Entry(root)
BMR_sumEntry.grid(row=9, column=1)
Label(root, text="Your TDEE is: ").grid(row=10, column=0, sticky='W')
TDEE_sumEntry = Entry(root)
TDEE_sumEntry.grid(row=10, column=1)
root.mainloop() |
0658ada126cc1b37a35d79ca7d70c7293a665506 | fanxc1234/fanxc | /2020-05-26_14-04-50/algorithm_interface.py | 2,409 | 3.546875 | 4 | import json
from json import JSONEncoder
import make_json_serializable # 用于自定义对象的JSON
import algorithm_test
# 关于楼层编号:从地下3到地上18编号 0-20 一楼编号:3
max_person = 12 # 电梯载客量
elevator_speed = 0.5 # 电梯速度,每秒0.5层
NUMBER_OF_FLOOR_LEVELS = 21 #总楼层数
class person: # 人
come_time = 0 # 出现的时间
from_floor = 0 # 出发楼层
to_floor = 0 # 到达楼层
current_floor = 0 # 现在的楼层
in_which_elevator = 0 # 在哪个电梯中,可取 0 1 2 3 分别指不在电梯中 在第一个电梯中 在第二个电梯中 在第三个电梯中
is_out = False # 是否已经完成电梯乘坐
def to_json(self):
dict_name_value = {}
for name, value in vars(self).items():
dict_name_value[name] = value
return dict_name_value
# 电梯
# e1:只停单层,e2:只停双数层(包括1层),e3:全停
# 单:index=0 2 3 5 7 9 ..
# 双:index=1 4 6 8 ..
# index=3为F1,3个电梯都可以停
class elevator:
current_floor = 3.0 # 现在的楼层,允许小数,每一秒都要进行精确更新.初始位置1楼
move_direction = 0 # 移动方向,可取到0 1 2,分别是 停止 向上 向下
def __init__(self, current_floor, move_direction):
self.current_floor = current_floor
self.move_direction = move_direction
def to_json(self):
dict_name_value = {}
for name, value in vars(self).items():
dict_name_value[name] = value
return dict_name_value
# 核心算法:顺向截停
# 对输入人群数组,不应假设每个人的出现时间都是1 6 11 ... 而可能是任意整数时间点(不方便的话再进行沟通),不应假设come_time<=t
def core_algorithm(time, array_people):
#初始化楼层对象(不太熟悉python语法,写的有点奇怪?
pass
class algorithm_result:
elevators = []
people = []
def to_json(self):
dict_name_value = {}
for name, value in vars(self).items():
dict_name_value[name] = value
return dict_name_value
# 通过标准输入输出,供外部程序调用,还没有写
if __name__ == "__main__":
result = algorithm_test.test2()
a = algorithm_result()
a.elevators = result[0]
a.people = result[1]
print(json.dumps(a, indent=4))
# print(json.dumps(result, indent=4))
|
6f6f34c0704c7bd34eae14687f487bbef8bffb47 | KhrystynaPetrushchak/devOps | /Lab2a/modules/common.py | 365 | 3.59375 | 4 | import datetime
import sys
def get_current_date():
"""
:return: DateTime object
"""
return datetime.datetime
def get_current_platform():
"""
:return: current platform
"""
return sys.platform
def funct(x):
if x:
a=[i for i in range (0,101) if i%2==0 ]
print(a)
else:
a=[i for i in range(1,100) if i%2==1]
print(a)
|
2fe9470f04f8ec3d1f93a68cc6eafb04b4c5963c | ss910034/Python | /practice1.py | 603 | 3.890625 | 4 | #!python3
'''spam = 1
if spam == 1:
print("Hello")
elif spam == 2:
print("Howdy")
else:
print("Greeting")
for i in range(1,11):
print(i)
i=1
while(i<11):
print(i)
i = i + 1'''
import random
secretnumber = random.randint(1,20)
print("I am thinking of a number between 1 and 20")
for i in range(1,7):
print("Take a guess")
answer = int(input())
if answer == secretnumber:
print("Good job! You guessed my number in "+str(i)+" guesses!")
break
elif answer < secretnumber:
print("Your guess is too slow")
continue
else:
print("Your guess is too high")
|
3dbef52096048078e29007a524fa3c288a6ce7fc | bayoishola20/Python-All | /Data Structure Algorithms (DSA)/binarysearch.py | 509 | 3.984375 | 4 | # array refers to all items and val is the value being searched for
def binary_search(arr, val):
if len(arr) == 0 or (len(arr) == 1 and arr[0] != val):
return False
mid = arr[len(arr)/2]
if val == mid: return True
if val < mid: return binary_search(arr[:len(arr)/2], val)
if val > mid: return binary_search(arr[len(arr)/2 + 1:], val)
''' from binarysearch import binary_search
a = [xrange(0,12)] #this will not work
a = list(xrange(0,12))
print binary_search(a, 11) ''' |
c411e7f2f47335702a0a62a56e4515cb975a2839 | Mario-szk/Tensorflow-1 | /test/test.py | 658 | 3.5625 | 4 | import numpy as np;
import tensorflow as tf;
"""
基础tensorflow的使用
"""
x_data=np.random.rand(100).astype(np.float32)
y_data=x_data*0.1+0.3
Weights=tf.Variable(tf.random_uniform([1],-1.0,1.0))
biase=tf.Variable(tf.zeros([1]))
y=Weights*x_data+biase
loss=tf.reduce_mean(tf.square(y-y_data))#定义损失函数
optimizer=tf.train.GradientDescentOptimizer(0.5)#定义优化器
train=optimizer.minimize(loss)#定义训练过程为减少loss
init=tf.global_variables_initializer()#初始化变量
sess=tf.Session()
sess.run(init)
for step in range(201):
sess.run(train)
if step%20==0:
print(step,sess.run(Weights),sess.run(biase))
|
d0356a30bfa68d747aa11020e46b1f2d0edf4e3d | soneykaa/infa_2021_bogakovskaya | /lab67/main.py | 5,356 | 3.546875 | 4 | import pygame
from pygame.draw import *
from random import randint
import math
pygame.init()
FPS = 20
dt1 = 2
dt2 = 4
scr_x = 1200
scr_y = 600
r_max = 100
screen = pygame.display.set_mode((scr_x, scr_y))
k = 0
#Цвет фона
BLACK = (0, 0, 0)
def new_ball():
'''
Создает новый шарик:
color - цвет, задается рандомно;
x, y - координаты;
r - радиус;
vx, vy - скорость шарика вдоль каждой из осей.
Все данные помещаются в словарик.
'''
red = randint(0,255)
green = randint(0,255)
blue = randint(50,255)
color = (red, green, blue)
x = randint(r_max, scr_x - r_max)
y = randint(r_max, scr_y - r_max)
r = randint(10, r_max)
vx = randint(-10, 10)
vy = randint(-10, 10)
ball = {'type': 'ball', 'clr': color, 'r': r, 'p': {'x': x, 'y': y}, 'v': {'vx': vx, 'vy': vy}}
return ball
def new_word():
'''
Создает новое слово:
color - цвет, задается рандомно;
x, y - координаты;
r - длина слова в пикселях;
vx, vy - скорость шарика вдоль каждой из осей;
f_size - размер шрифта
Все данные помещаются в словарик.
'''
# Цензура
#words = ["самое", "важное", "слово"]
# Без цезнуры
words = ["пиздато", "ебануться", "блять", "охуенно"]
l = len(words)
t = randint(0,l-1)
wrd = words[t]
f_size = randint(10, 80)
r = int(f_size * len(wrd)/2)
red = randint(0,255)
green = randint(0,255)
blue = randint(50,255)
color = (red, green, blue)
x = randint(r, scr_x - r)
y = randint(2 * f_size, scr_y - 2* f_size)
vx = randint(-10, 10)
vy = randint(-10, 10)
word = {'type':'word', 'word': wrd, 'clr': color, 'r': r, 'p': {'x': x, 'y': y},
'v': {'vx': vx, 'vy': vy}, 'f': f_size}
return word
def Pythagoras(a0, b0, a, b):
'''
Считает расстояние между двумя точками
'''
r0 = math.sqrt((a-a0)**2+(b-b0)**2)
return r0
def counter():
# Создает счетчик на экране
font = pygame.font.SysFont(None, int(40))
txt = "Колличество очков: " + str(k)
img = font.render(txt, True, (255, 255, 0))
screen.blit(img, (30, 50))
def painter(object):
'''
Отрисовка объектов в зависимости от типа.
'''
if object['type'] == 'ball':
circle(screen, object['clr'], (object['p']['x'], object['p']['y']), object['r'])
elif object['type'] == 'word':
font = pygame.font.SysFont(None, int(object['f']))
txt = object['word']
img = font.render(txt, True, object['clr'])
screen.blit(img, (object['p']['x'], object['p']['y']))
def processing(object):
'''
Изменение координат объекта.
'''
if object['type'] == 'word':
cube = randint(0, 5)
switch = randint(-50, 50)
if cube == 2:
object['p']['x'] += switch
elif cube == 3:
object['p']['y'] += switch
object['p']['x'] += object['v']['vx'] * dt1
object['p']['y'] += object['v']['vy'] * dt1
painter(object)
def wall_hit(object):
'''
Обработка удара о стенку.
'''
# Правая и левая стенки
if object['p']['x'] > scr_x - object['r'] or object['p']['x'] < object['r'] :
object['v']['vx'] *= - 1
# Нижняя и верхняя стенка
if object['p']['y'] >= scr_y - object['r'] or object['p']['y'] <= object['r']:
object['v']['vy'] *= - 1
def click(event):
'''
Обработка клика.
Клик попал в один из объектов -> объект удаляется из массива, счетчик повышается, создается новый объект.
'''
global k, floating_objects
for objects in floating_objects:
for obj in objects:
r0 = Pythagoras(event.pos[0], event.pos[1], obj['p']['x'], obj['p']['y'])
if r0 <= obj['r']:
objects.remove(obj)
if obj['type'] == 'ball':
new_obj = new_ball()
k += 1
elif obj['type'] == 'word':
new_obj = new_word()
k += 100
objects.append(new_obj)
pygame.display.update()
clock = pygame.time.Clock()
finished = False
floating_words = []
floating_balls = []
floating_objects = [floating_balls, floating_words]
for i in range(5):
ball = new_ball()
floating_balls.append(ball)
for i in range(6):
word = new_word()
floating_words.append(word)
while not finished:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
elif event.type == pygame.MOUSEBUTTONDOWN:
click(event)
for objects in floating_objects:
for obj in objects:
wall_hit(obj)
processing(obj)
counter()
pygame.display.update()
screen.fill(BLACK)
pygame.quit()
|
fe1a8bf02dd907fda249448c4a6975beafbf8a3a | leetcode-notebook/wonz | /solutions/0053-Maximum-Subarray/0053.py | 510 | 3.609375 | 4 | class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = 0
sum = -0xFFFFFFFF
for i in range(len(nums)):
dp = nums[i] + (dp if dp > 0 else 0) # if dp > 0: dp = nums[i] + dp, else: dp = nums[i]
sum = max(sum, dp)
return sum
if __name__ == "__main__":
nums = [-2,1,-3,4,-1,2,1,-5,4]
print(Solution().maxSubArray(nums)) |
46166e2eec6338d57506ac2ae920186b2378cf9a | houhailun/leetcode | /demo/demo_20120220.py | 60,167 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Time: 2021/2/20 17:02
# Author: Hou hailun
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 标题1: 股票买入卖出
# 先找到迄今为止最小价格,然后在以后找最大利润 = 卖出价格 - 最小价格
def getMaxProfit(prices):
if not prices:
return None
max_profit = float('-inf')
min_price = float('inf')
for price in prices:
if price < min_price:
min_price = price
if price - min_price > max_profit:
max_profit = price - min_price
return max_profit
# 减小if判断次数
# 找到当前最小价格时,不做利润计算
def getMaxProfit(prices):
if not prices:
return None
max_profit = float('-inf')
min_price = float('inf')
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit
# 动态规划
# dp[i]: 第i天卖出的最大收益
# dp[i] = max(dp[i-1], prices[i] - min(prices[:i]))
def getMaxProfit(prices):
dp = [0]
for i in range(1, len(prices)):
dp[i] = max(dp[i - 1], prices[i] - min(prices[0:i]))
return max(dp)
# 进阶:给出买入卖出的天
def getMaxProfit(prices):
if not prices:
return None
buy_ix = sell_ix = 0
max_profit = float('-inf')
min_price = float('inf')
for ix, price in enumerate(prices):
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
sell_ix = ix # 卖出日是最大利润日
# 买入日是卖出日前最小价格日
buy_ix = prices.index(min(prices[0:sell_ix]))
return max_profit
getMaxProfit([2, 4, 1, 2])
# 标题2: 有序数组,2数之和
# nums = [2, 7, 11, 15], target = 9
def get_two_num_sum(nums, target):
if not nums:
return None, None
nums_len = len(nums)
if nums_len == 1:
return None, None
num1, num2 = 0, nums_len - 1
while num1 != num2:
print(num1, num2)
if nums[num1] + nums[num2] > target:
num2 -= 1
elif nums[num1] + nums[num2] < target:
num1 += 1
else:
return num1, num2
return None, None
# res = get_two_num_sum([2, 7, 11, 15], 9)
# print(res)
# 标题3:非有序数组,如何查找2数之和?
# 哈希表
def get_two_num_sum_hash(nums, target):
if not nums:
return None, None
nums_len = len(nums)
if nums_len == 1:
return None, None
hash_table = {}
for ix, num in enumerate(nums):
rest = target - num
if rest in hash_table.values():
rest_ix = nums[rest]
if rest_ix != ix:
return ix, rest_ix
hash_table[ix] = num
# res = get_two_num_sum_hash([2,11,7,6], 9)
# print(res)
# 标题4:两数相加
# 两个链表,元素相加,得到一个新的链表
# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
# 输出:7 -> 0 -> 8
# 原因:342 + 465 = 807
def two_sum_list(l1, l2):
if not l1 or not l2:
return l1 or l2
new_head = Node(None) # 头节点
cur_head = new_head
carry = 0 # 标记是否进位
while l1 or l2: # 循环终止条件: 两个都遍历结束
num1 = l1.data if l1 else 0
num2 = l2.data if l2 else 0
res = num1 + num2 + carry
node = Node(res % 10)
cur_head.next = node
cur_head = node
carry = res // 10
# 链表后移
if l1: l1 = l1.next
if l2: l2 = l2.next
# 最高位有进位
if carry == 1:
node = Node(1)
cur_head.next = node
return new_head.next
# 题目5:无重复最长子串的长度
def get_max_len_substr_no_deplicated(s):
# 思路:从前往后遍历,若当前不重复,则取该字符串;否则去除前面的重复字符
res = ''
max_len = 0
for ch in s:
if ch not in res: # 不重复
res += ch
max_len = max(max_len, len(res))
else:
res += ch
ix = res.index(ch)
res = res[ix+1:]
return max_len
# 进阶:同时要求获取最长的无重复子串
def get_max_len_substr_no_deplicated_v2(s):
# step1:最大无重复子串的长度
max_len = get_max_len_substr_no_deplicated(s)
# step2:得到最大长度后,设法找到字串
# 方法1:暴力法,逐个取长度为max_len的非重复字串
# 方法2:在主串s中找res的位置ix,在ix附近找长度为max_len的非重复子串
substr = ''
for i in range(len(s)):
substr = s[i:i+max_len]
if len(substr) == len(set(substr)):
return substr
return substr
# print(get_max_len_substr_no_deplicated('abcabcbb'))
# print(get_max_len_substr_no_deplicated_v2('abcabcbb'))
# 题目6: 寻找两个有序数组的中位数
def get_median_in_two_sort_array(nums1, nums2):
# 方法1: 拼接为1个大的有序数组,然后返回中位数
def solution1(nums1, nums2):
# 时间复杂度O(m+n), 空间复杂度O(m+n)
nums = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
nums.append(nums1[i])
i += 1
else:
nums.append(nums2[j])
j += 1
nums.extend(nums1[i:])
nums.extend(nums2[j:])
mid = len(nums) // 2
if len(nums) % 2 == 1:
return nums[mid]
return (nums[mid - 1] + nums[mid]) / 2
# return solution1(nums1, nums2)
# 方法2: 有序数组 -> 二分法
nums1 = [1,3,5,7]
nums2 = [2,4,6,8]
# print(get_median_in_two_sort_array(nums1, nums2))
# 标题7:最长回文子串
# 回文串: 正读反读相同
def valid(s, left, right):
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
def getLongestPalindrome_bp(s):
# 暴力法,双指针
s_len = len(s)
if s_len < 2:
return False
res = s[0]
max_len = 1
# 枚举所有长度大于等于 2 的子串
for i in range(s_len - 1):
for j in range(i + 1, s_len):
if j - i + 1 > max_len and valid(s, i, j): # 当前长度大于max_len && 回文串 -> 更新
max_len = j - i + 1
res = s[i:j + 1]
return res
# print(getLongestPalindrome_bp('abcddcba'))
def getLongestPalindrome_dp(s):
# 动态规划
# 变量dp[i][j] 表示 s[i,j]是否是回文串
# 动态转移方程: dp[i][j] = (s[i+1][j-1] and s[i]==s[j]), 表示若s[i+1,j-1]为回文串 且 s[i]==s[j],则s[i,j]也是回文串
size = len(s)
if size < 2:
return False
dp = [[False for _ in range(size)] for _ in range(size)]
# 单个字符是回文串,即主对角线上是True
for i in range(size):
dp[i][i] = True
max_len = 1
start_ix = 0
# i在左,j在右
# j 范围 1 ~ size-1
# i 范围 0 ~ j-1
for j in range(1, size):
for i in range(0, j):
if s[i] == s[j]:
if j - i < 3: # i与j不构成边界,至少需要4个
dp[i][j] = True
else:
dp[i][j] = dp[i+1][j-1]
else:
dp[i][j] = False
if dp[i][j]:
cur_len = j - i + 1
if cur_len > max_len:
max_len = cur_len
start_ix = i
return s[start_ix: start_ix+max_len]
# print(getLongestPalindrome_dp('abcddcba'))
# 标题8: 生最多水的容器
# 思路:水最多,即面积最大;双指针,left=0,right=size-1,计算面积,然后短的移动,直到left==right为止
def maxArea(heights):
if not heights:
return None
max_area = 0
left, right = 0, len(heights)-1
while left < right:
area = (right - left) * min(heights[left], heights[right]) # 面积 = 长 * 宽
if area > max_area:
max_area = area
# 短的移动
if heights[left] < heights[right]:
left += 1
else:
right -= 1
return max_area
# print(maxArea([1,8,6,2,5,4,8,3,7]))
# 标题9: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?
# 找出所有满足条件且不重复的三元组。
def threeSum(nums):
# 思路:排序+双指针 (实际上可以认为是三指针)
size = len(nums)
if size < 3:
return None
res = []
nums.sort()
for i in range(size):
if nums[i] > 0: # nums[i]>0,则后面的必然也大于0,不存在三数之和等于0的情况
return res
# 排序后相邻两数如果相等,则跳出当前循环继续下一次循环,相同的数只需要计算一次
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = size-1
while left < right: # 终止条件: left < right
tmp = nums[i] + nums[left] + nums[right]
if tmp == 0:
res.append([nums[i], nums[left], nums[right]])
# 重复元素跳过
while left < right and nums[left+1] == nums[left]:
left += 1x
while left < right and nums[right-1] == nums[right]:
right -= 1
left += 1
right -= 1
elif tmp < 0:
left += 1
else:
right -= 1
return res
nums = [-1, 0, 1, 2, -1, -4]
# print(threeSum(nums))
# 标题10: 合并两个有序链表
# 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
def mergeList(l1, l2):
if not l1 or not l2:
return l1 or l2
new_head = tmp = Node(None)
while l1 and l2: # 终止条件: 两个链表都没有到末尾
if l1.data < l2.data:
tmp.next = l1
l1 = l1.next
else:
tmp.next = l2
l2 = l2.next
tmp = tmp.next
if l1:
tmp.next = l1
if l2:
tmp.next = l2
return new_head.next
# 标题11: 搜索旋转排序数组
# 数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] ,查找给定值
def search(nums, target):
# 思路: 旋转排序数组,基本有序,采用二分法
# 本题重点在于区分ix属于前半数组还是后半数组
# 中间值属于前半数组: mid值大于start值
# 中间值属于后半数组: mid值小于end值
if not nums:
return None
start, end = 0, len(nums)-1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] == target:
return mid
elif nums[mid] < nums[end]: # mid属于后半子数组,在右边查找
if nums[mid] < target <= nums[end]: # 右半子数组
start = mid + 1
else:
end = mid - 1
else: # mid属于前半子数组,在左边查找
if nums[start] <= target < nums[end]: # 左边查找
end = mid - 1
else:
start = mid + 1
return -1
# print(search([4,5,6,7,0,1,2], 0))
# 标题12: 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置
# 本题属于二分法的变体
def searchRange(nums, target):
if not nums:
return None
low, high = 0, len(nums)-1
while low < high:
mid = low + (high - low) // 2
if nums[mid] == target:
left = mid
right = mid
while left >= 0 and nums[left] == nums[left-1]:
left -= 1
while right <= high and nums[right] == nums[right+1]:
right += 1
return [left, right]
elif nums[mid] > target:
high = mid - 1
else:
low = mid + 1
return None
# print(searchRange([1,2,3,3,3,3,3,4,5], 3))
# 标题13: 组合总数
# 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合
def combineSum(nums, target):
if not nums:
return None
# 标题14: 最大子序列和
def maxSubArraySum(nums):
if not nums:
return None
# 思路: 当前和为负数,则跳过当前和,把下一个数字作为新的起始数;当前和为正数,相加;更新最大和
max_sum = cur_sum = 0
for num in nums:
if cur_sum > 0: # 当前和大于0,则累计
cur_sum += num
else: # 当前和小于等于0,则把下一个数字作为当前和
cur_sum = num
if cur_sum > max_sum: # 更新最大和
max_sum = cur_sum
return max_sum
# print(maxSubArraySum([-2,1,-3,4,-1,2,1,-5,4]))
# 标题15: 子集
# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
def subsets(nums):
if not nums:
return None
res = list()
res.append([])
for num in nums:
new = [s + [num] for s in res]
res += new
return res
# print(subsets([1,2,3]))
# 标题16: 对称二叉树
# 先序遍历,从跟节点出发,左子树等于右子树
def isSymmetric_helper(l_root, r_root):
if l_root is None and r_root is None: # 左右子树都遍历完成
return True
if l_root is None or r_root is None:
return False
if l_root.data != r_root.data:
return False
return isSymmetric_helper(l_root.left, r_root.right) and isSymmetric_helper(l_root.right, r_root.left)
def isSymmetric(root):
if not root:
return True
return isSymmetric_helper(root.left, root.right)
def isSymmetric_loop(root):
if not root:
return True
stack = [(root.left, root.right)]
while stack:
l, r = stack.pop() # 同时获取左右子节点
if l is None or r is None:
if l != r: # 一个为空,一个不为空
return False
else:
if l.data != r.data: # 值不相同
return False
# 成对append
stack.append((l.left, r.right))
stack.append((l.right, r.left))
return True
# 标题17: 二叉树的最大深度
def maxDepth(root):
if not root:
return 0
left_depth = maxDepth(root.left)
right_depth = maxDepth(root.right)
return max(left_depth, right_depth) + 1
def maxDepth_loop(root):
# 循环版本: 层次遍历
stack = [root]
depth = 1
while stack:
# 和层次遍历区别,每次都弹出一层的节点
n = len(stack)
for _ in range(n):
node = stack.pop(0)
stack.append(node.left if node.left else [])
stack.append(node.right if node.right else [])
depth += 1
return depth
# 标题18: 路径总和
# 判断是否存在路径和等于给定值
def hasPathSum(root, sum):
if not root:
return False
# 叶子节点 && 叶子节点值等于剩余值
if root.left is None and root.right is None:
return root.val == sum
# 递归遍历
return hasPathSum(root.left, sum-root.val) or \
hasPathSum(root.right, sum-root.val)
# 标题19: 路径总和II
# 找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
def findPathSum(root, sum):
res = []
if not root:
return res
def helper(root, tmp, sum):
if root.left is None and root.right is None and root.val == sum:
tmp.append(root)
res.append(tmp)
helper(root.left, tmp+[root.val], sum-root.val)
helper(root.right, tmp+[root.val], sum-root.val)
helper(root, [], sum)
return res
# 标题20: 卖卖股票最佳时机
def maxProfit(nums):
if not nums:
return None
min_price = float('inf')
max_profit = 0
for price in nums:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit
# 进阶:给出买入卖出的天
def maxProfit_v2(nums):
if not nums:
return None
min_price = float('inf')
max_profit = 0
buy_ix = sell_ix = 0
for ix, price in enumerate(nums):
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
sell_ix = ix
# 买入日是卖出日前最小价格的日期
buy_ix = nums.index(min(nums[:sell_ix]))
return max_profit, buy_ix, sell_ix
# print(maxProfit([3, 1, 4, 5]))
# print(maxProfit_v2([3, 1, 4, 5, 3, 0, 2]))
# 标题21: 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素
def findNumApperenceOnce(nums):
# 异或: 相同为0,不同为1; 0 ^ x = x
if not nums:
return None
res = 0
for num in nums:
res ^= num
return res
def findNumApperenceOnce_v2(nums):
# 数学公式
threshold = 2
return threshold * sum(set(nums)) - sum(nums)
# print(findNumApperenceOnce([1,2,3,1,3]))
# print(findNumApperenceOnce_v2([1,2,3,1,3]))
# 标题22: 进阶: 给定一个非空整数数组,除了两个元素只出现一次以外,其余每个元素均出现两次
def findTwoNumApperenceOnce(nums):
# 异或: 相同为0,不同为1; 0 ^ x = x
if not nums or len(nums) < 2:
return None, None
# step1: 全部元素异或
res = 0
for num in nums:
res ^= num
# step2: 找res中不为0的最低为
ix = 0
while not res & (0x01 << ix):
ix += 1
# step3: 根据ix位是否等于1,分为两个数组
nums1, nums2 = [], []
for num in nums:
if num & (0x01 << ix):
nums1.append(num)
else:
nums2.append(num)
# step4: 分别在每个数组中异或计算出现一次的数
res1 = res2 = 0
for num in nums1:
res1 ^= num
for num in nums2:
res2 ^= num
return res1, res2
# print(findTwoNumApperenceOnce([1,2,3,4,2,3]))
# 标题24: 环形链表: 给定一个链表,判断链表中是否有环。
# 前后指针,快指针每次走2步,慢指针每次走1步,若有环,则必然相遇
def hasCircle(head):
if not head or not head.next: # 空节点 or 1个节点
return False
slow = head
fast = head.next
while fast and fast.next: # 终止条件: fast为空: 已经遍历完所有节点; fast.next为空: 最后一个节点
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False
# 标题25: 最小栈: o(1)时间内得到当前栈的最小值
class MinStack:
def __init__(self):
self.stack = [] # 数据栈
self.stack_helper = [] # 辅助栈,保存当前数据栈中的最小元素
self.size = 0
def push(self, item):
# 入栈
self.stack.append(item)
# 空栈 or 辅助栈中最小元素 大于 item
if not self.stack_helper or self.stack_helper[-1] > item:
self.stack_helper.append(item)
else:
self.stack_helper.append(self.stack_helper[-1])
self.size += 1
def pop(self):
if self.size == 0:
return
self.stack.pop()
self.stack_helper.pop()
self.size -= 1
def top(self):
if self.size == 0:
return
return self.stack[self.size-1]
def getMin(self):
if self.size == 0:
return
return self.stack_helper[self.size-1]
# 标题26: 多数元素: 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
def majorityElement(nums):
# 方法1: 排序后,找中位数即可
# 方法2: 哈希
# 方法3: 当前元素与下一个元素相同,则累计次数,不同则次数减1,当次数为0时,重置次数和当前元素
res = nums[0]
cnt = 1
for num in nums[1:]:
if res == num:
cnt += 1
else:
cnt -= 1
if cnt <= 0:
res = num
cnt = 1
return num
# print(majorityElement([1,2,3,2,2,3,2]))
# 标题27: 相交链表: 本题目要求找两个链表的公共节点
# 方法1: 你走过我的路,我走过你的路,最后我们便相遇了
def findCommonNodeLink(head1, head2):
if not head1 or not head2:
return None
h1, h2 = head1, head2
while h1 != h2: # 终止条件: 两指针相遇
h1 = h1.next if h1 else head2 # h1不为空,继续往后走;走到最后,则沿着head2走
h2 = h2.next if h2 else head1
return h1
# 方法2:快慢指针
# 快的指针先走 abs(len(head1)-len(head2)), 然后一起走
def findCommonNodeLink_v2(head1, head2):
if not head1 or not head2:
return None
len_head1 = len_head2 = 0
node1, node2 = head1, head2
while node1:
len_head1 += 1
node1 = node1.next
while node2:
len_head2 += 1
node2 = node2.next
fast = head1 if len_head1 > len_head2 else head2
slow = head2 if len_head1 > len_head2 else head1
for i in range(abs(len_head1 - len_head2)):
fast = fast.next
while fast != slow and fast and slow: # 终止条件: 相遇 or 有一个遍历完也没有相遇
fast = fast.next
slow = slow.next
if fast == slow:
return fast
return None
# 标题28: 打家劫舍
# 相邻房间不能都被偷窃,那么如何获取最大金额
# 动态规划: dp[i]表示从前i间房子所能抢到的最大金额, Ai表示第i间房子的金额
# 只有1个房间,dp[1] = A[1]
# 有2个房间,dp[2] = max(A[1], A[2])
# 有3个房间,dp[3] = max(dp[1]+A[3], dp[2]),即抢第3家,金额累加;步枪第三家
# ...
# 有n个房间,dp[n] = max(dp[n-2]+A[n], dp[n-1])
def rob(nums):
if not nums:
return None
_len = len(nums)
dp = [None] * _len
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, _len):
dp[i] = max(nums[i]+dp[i-2], dp[i-1])
return dp[-1]
# print(rob([1,2,3,3]))
# 标题29:反转链表
def reverseLink(head):
# 三指针
if not head or not head.next:
return None
pre = Node(None)
cur = head
while cur:
last = head.next
cur.next = pre
pre = cur
cur = last
return cur.next
# 标题30: 回文链表
# 方法1: 遍历链表,记录链表各个节点元素,判断是否回文
def palindromeList(head):
if not head or not head.next:
return True
res = []
while head:
res.append(head.val)
head = head.next
return res == res[::-1]
# 方法2: 头尾指针, 若不等,则不为回文串; 相等则移动指针直到相遇
# note: 尾指针需要反转链表
# 标题31: 移动零: 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
# 方法1: 辅助list, 先把nums中非零元素插入到辅助list,然后再写0
def moveZero(nums):
res = []
for num in nums:
if num != 0:
res.append(num)
res += [0] * (len(nums) - len(res))
return res
# 方法2:
# 题目要求:必须在原数组上操作,不能拷贝额外的数组,因此上述方法不适用
# 思路2:双指针
def moveZero_v2(nums):
j = 0 # j表示非0元素下标
for i in range(len(nums)):
if nums[i] != 0: # i位置元素不等0,则写到j为止
nums[j] = nums[i]
j += 1
# j位置后填充0
while j < len(nums):
nums[j] = 0
j += 1
return nums
nums = [0,1,0,3,12]
# print(moveZero(nums))
# moveZero_v2(nums)
# print(nums)
# 标题32: 路径总和III
# 给定一个二叉树,它的每个结点都存放着一个整数值。
# 找出路径和等于给定数值的路径总数。
# 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
# 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
# 示例:
# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
# 10
# / \
# 5 -3
# / \ \
# 3 2 11
# / \ \
# 3 -2 1
# 返回 3。和等于 8 的路径有:
# 1. 5 -> 3
# 2. 5 -> 2 -> 1
# 3. -3 -> 11
# 首先解读题干,题干的要求是找和为sum的路径总数,这次路径的起点和终点不要求是根结点和叶结点,
# 可以是任意起终点,而且结点的数值有正有负,但是要求不能回溯,只能是从父结点到子结点的。
# 在已经做了路径总和一和二的基础上,我们用一个全局变量来保存路径总数量,在主调函数中定义变量self.result=0。
# 因为数值有正有负,所以在当我们找到一条路径和已经等于sum的时候,不能停止对这条路径的递归,
# 因为下面的结点可能加加减减,再次出现路径和为sum的情况,因此当遇到和为sum的情况时,
# 只需要用self.result+=1把这条路径记住,然后继续向下进行即可。
# 由于路径的起点不一定是根结点,所以需要对这棵树的所有结点都执行一次搜索,
# 就是树的遍历问题,每到一个结点就执行一次dfs去搜索以该结点为起点的路径:
class Solution:
def pathSum(self, root, sum):
self.account = 0
def throughRoot():
if root is None:
return
sum -= root.val
if sum == 0: # 找到路径后,记录个数,继续往下递归查找
self.account += 1
threeSum(root.left, sum)
threeSum(root.right, sum)
def loop(root, sum):
if root is None:
return self.account
throughRoot(root, sum)
loop(root.left, sum) # 每个节点都要作为起始节点
loop(root.right, sum)
loop(root, sum)
return self.account
# 标题33: 找到所有数组中消失的数字
# 给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
# 找到所有在 [1, n] 范围之间没有出现在数组中的数字。
# 方法1: 利用辅助队列 a = [i for i in range(1, n+1)], 然后查找不在a中的元素
# 方法2: 利用辅助队列 a = [i for i in range(1, n+1)], set(a) - set(nums)
# 方法3: 假设无重复,则i元素必然再位置i上,即i == num[i]
# 如果i != nums[i], 则交换 nums[nums[i]],nums[i]
# 方法4: 假设五重读, 则元素i必然等于nums.index(i)
# 二进制中1的个数
def oneBitNum(n):
if not n:
return None
cnt = 0
while n:
n = n & (n-1)
cnt += 1
return cnt
# print(oneBitNum(15))
# 标题34: 汉明距离
# 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目
# 方法:先异或 在判断二进制中1的个数
def hanmingDist(num1, num2):
num = num1 ^ num2
return oneBitNum(num)
# print(hanmingDist(12, 15))
# 标题35: 把二叉搜索树转换为累加树
# 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
# 例如:
# 输入: 二叉搜索树:
# 5
# / \
# 2 13
#
# 输出: 转换为累加树:
# 18
# / \
# 20 13
# 思路: 二叉搜索树的根节点值大于左孩子节点值,小于右孩子节点值
# 可以从 右-跟-左 顺序遍历, 把当前节点值和上一个节点值相加
num = 0 # 记录上一个节点值
def addTree(root):
if not root:
return
addTree(root.right)
global num
root.val = root.val + num
num = root.val
addTree(root.left)
return root
# 标题36: 二叉树的直径
# 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点
# 思路: 直径和左右子树高度有关,最大直径 = 最大左右子树高度相加
class Solution:
def __init__(self):
self.max = 0
def diameterOfBinaryTree(self, root):
self.depth(root)
return self.max
def depth(self, root):
if not root:
return 0
l = self.depth(root.left)
r = self.depth(root.right)
self.max = max(self.max, l+r) # 最大直径 = max(当前最大直径, 左子树高度+右子树高度)
return 1 + max(l, r) # 返回当前树高度
# 标题37: 最短无序连续子数组
# 给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
# 你找到的子数组应是最短的,请输出它的长度
def findUnsortedSubarray(nums):
# 思路: 拷贝一份nums后排序;将2排序后的数组和未排序的数组对比,记录下相同值的索引
if not nums or len(nums) == 1:
return nums
nums_copy = nums[:]
nums_copy.sort()
start_flag = end_flag = True
start, end = -1, len(nums)-1
for i in range(len(nums)): # 遍历一次,同时记录相同值的索引
if nums_copy[i] == nums[i] and start_flag: # start_flag用来记录第一个遇到不同值时的索引
start = i
else:
start_flag = False
if nums_copy[-i-1] == nums[-i-1] and end_flag:
end = len(nums)-i-1
else:
end_flag = False
if end <= start:
return 0
return end - start - 1
# print(findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15]))
# 标题38: 合并二叉树
# 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
# 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
def mergeTree(root1, root2):
# 思路: 两棵树同时进行前序遍历
# case1: 都存在节点,则累加
# case2: 有1个不存在,则返回另一颗树
# case3: 都不存在,则任意返回一棵树
if not root1 or not root2: # case2, case3
return root1 or root2
root1.val += root2.val
mergeTree(root1.left, root2.left) # 递归遍历
mergeTree(root1.right, root2.right)
return root1
# 合并两个有序数组
# 题目描述:给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
# 说明:
# 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
# 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
def mergeSortArray(nums1, nums2, m, n):
# 方法1: 把nums2写到nums1后面, 在排序
# 方法2: 从后往前遍历, p1指向num1,p2指向num2. 若p1小于p2,则在len(nums1)+nums[nums2]-1位置写p2;否则写p1;
while m > 0 and n > 0: # 终止条件:有1个遍历完成
if nums1[m-1] < nums2[n-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else:
nums1[m+n-1] = nums1[m-1]
m -= 1
# 处理nums2还有元素的可能, 把nums2剩余元素写入nums1
if n > 0:
nums1[0:n] = nums2[0:n]
return nums1
a = [2,5,7,0,0,0]
b = [1,3,8]
# print(mergeSortArray(a, b, 3, 3))
# 找不同
def findTheDifference(s, t):
# 方法1: set(t)-set(s)
# 方法2: 异或,由于s,t只有1个字符不同,其余都 相同,因此,两个异或后结果即为所求字符
res = ord(t[-1])
for i in range(len(s)):
res ^= ord(s[i])
res ^= ord(t[i])
return chr(res)
# print(findTheDifference('ab', 'bax'))
# 两个数组的交集I:
# 要求: 输出结果中的每个元素一定是唯一的。
def intersection(nums1, nums2):
return list(set(nums1) & set(nums2))
# 进阶: 要求输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致
def intersection_ii(nums1, nums2):
# 方法1: 列表生成式
res = [i for i in nums1 if i in nums2]
# 方法2: 哈希标
return res
# print(intersection([1,2,3, 2,4], [2,2,4]))
# print(intersection_ii([1,2,3, 2,4], [2,2,4]))
# 两整数之和
# 不使用加减乘除,计算两个整数和
# 方法:
# 不考虑进位:两数相加,类似异或,相同为0,不同为1
# 考虑进位: 0 & x = 0, 1 & 1 = 0,产生进位
# 循环执行以上2步,直到没有进位为止
def twoNumSum(num1, num2):
if num1 == 0 or num2 == 0:
return num1 or num2
while num2:
_sum = num1 ^ num2
carry = (num1 & num2) << 1 # 进位左移
num1 = _sum
num2 = carry
return num1
# print(twoNumSum(7, 2))
# 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
# 案例:
# s = "leetcode" 返回 0.
# s = "loveleetcode", 返回 2.
def findFirstApperenceOnceCh(s):
# 思路:涉及到次数问题,优先考虑哈希表
hash_table = {}
for ch in s:
if ch in hash_table:
hash_table[ch] += 1
else:
hash_table[ch] = 1
for ix, ch in enumerate(s):
if hash_table[ch] == 1:
return ix, ch
return None
# 方法2: count(ch) == 1
# print(findFirstApperenceOnceCh('abcdab'))
# 计算给定二叉树的所有左叶子之和
# 问题: 如何判断是左叶子?
# 回答: if node.left and node.left.left is None and node.left.right is None, 则说明node.left是node的左叶子节点
def leftNodeSum(root):
if not root:
return 0
sum = 0
if root.left and root.left.left is Node and root.left.right is None:
sum += root.left.val
sum += leftNodeSum(root.left)
sum += leftNodeSum(root.right)
return sum
# 买卖股票的最佳实际II
# 要求多次买入卖出
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
i = 0
while i < len(prices) - 1: # 循环:后一天价格大于前一天价格,则卖出,累计利润
if prices[i+1] > prices[i]:
profit += prices[i+1] - prices[i]
i = i+1
return profit
# print(maxProfit([1,2,3]))
# 删除排序数据中的重复项
# 题目描述:给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
# 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
# 示例 1: 给定数组 nums = [1,1,2],
# 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
def dropDuplicateArray(nums):
# 方法1: 遇到重复的删除
def dropDuplicateArray_v1(nums):
if not nums:
return 0
for i in range(len(nums)):
while i < len(nums) - 1 and nums[i] == nums[i + 1]: # 删除重复元素
nums.pop(i + 1)
return len(nums)
# return dropDuplicateArray_v1(nums)
def dropDuplicateArray_v2(nums):
# 方法2:不删除,把不重复的写到前面
slow = 0
length = len(nums) - 1
for fast in range(length):
if nums[fast] != nums[fast+1]: # 不重复,把fast+1指向的指向的元素写到slow+1指向的为止
nums[slow+1] = nums[fast+1] # 注意:写入的fast+1,因为要写入不重复元素
slow += 1
return slow + 1
return dropDuplicateArray_v2(nums)
# print(dropDuplicateArray([1,2,2,3, 4]))
# 加一
# 定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
# 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
# 你可以假设除了整数 0 之外,这个整数不会以零开头。
def addOne(nums):
# 方法1: 把nums数组转换为整数,加1,在转换为列表
def addOne_v1(nums):
tmp = 0
for num in nums:
tmp = tmp * 10 + num
tmp += 1
res = []
while tmp:
res.append(tmp % 10)
tmp = tmp // 10
return res[::-1]
# return addOne_v1(nums)
# 方法2: 从后往前遍历数组,+1后有进位,则加1
def addOne_v2(nums):
res = []
plus = 1
for num in nums[::-1]:
v = num + plus
if v > 9: # 有进位
plus = 1
v = v % 10
else:
plus = 0
res.insert(0, v)
if plus == 1: # 最高位进位
res.insert(0, plus)
return res
return addOne_v2(nums)
# print(addOne([1,2,3]))
# 反转整数
# 给定一个 32 位有符号整数,将整数中的数字进行反转。
def reverse(x):
reverse_num = int(str(abs(x))[::-1])
if reverse_num.bit_length() > 31: # 反转后溢出
return 0
return reverse_num if x > 0 else -reverse_num
# 回文数
# return x > 0 and str(x) == str(x)[::-1]
# 搜索插入位置
# 题目描述:给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。你可以假设数组中无重复元素。
def searchInsert(nums, target):
# 方法1: O(NlogN)
def searchInsert_v1(nums, target):
if target in nums:
return nums.index(target)
nums.append(target)
return nums.index(target)
# return searchInsert_v1(nums, target)
# 方法2: 有序数组, 二分法, 找不到则遍历数组
def searchInsert_v2(nums, target):
start, end = 0, len(nums)-1
mid = start + (end - start) // 2
while start < end: # 一般二分法是start<=end, 为毛这里是<呢?
if nums[mid] == target:
return mid
elif nums[mid] > target:
end = mid - 1
else:
start = mid - 1
mid = start + (end - start) // 2
print(start, end)
# 没有找到
if nums[mid] >= target:
return mid
return mid+1
return searchInsert_v2(nums, target)
# print(searchInsert([1,3,4,5], 2))
# 移除元素: 在数组中删除指定元素
def removeNum(nums, val):
# 思路: 前后指针, 若fast != val, 则fast写到slow位置
slow = 0
length = len(nums) - 1
for fast in range(length):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
# print(removeNum([1,2,3,4,2,2], 2))
# 题目名称:最长公共前缀
# 题目描述:编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
def maxLenCommPreStr(strs):
# 思路: 最短长度的字符串中找最长公共前缀
min_str = min(strs, key=len) # 找出最短字符串
for ix, ch in enumerate(min_str):
for other in strs:
if other[ix] != ch: # 字符ch不是other的前缀,则返回当前最长前缀
return min_str[:ix]
return min_str
# print(maxLenCommPreStr(['abc', 'abcde', 'ae']))
# 标题:实现strStr
def strStr(haystack, needle):
# return haystack.fing(needle)
# 朴素法
def strStr_bp(haystack, needle):
i = j = 0
while i < len(haystack) and j < len(needle):
if haystack[i] == needle[j]: # 匹配成功
i += 1
j += 1
else: # 匹配失败
i = i - j + 1 # i回退到上次匹配开始位置的下一位置
j = 0
if j == len(needle): # 匹配成功
return i - j # 返回起始位置
return -1
# return strStr_bp(haystack, needle)
# 每次在haystack中找长度为len(needle)的字符,比较是否相同
def strStr_cut(haystack, needle):
_len = len(needle)
for i in range(len(haystack) - _len + 1):
if haystack[i: i + _len] == needle:
return i
return -1
return strStr_cut(haystack, needle)
# print(strStr('abcde', 'cde'))
# 题目名称:最后一个单词的长度
# 思路: 首先把句子拆分为单词列表 然后,求最后1个单词的长度
def lengthOfLastWord(s):
if not s:
return 0
words = s.split()
if words:
return len(words[-1])
return 0
# print(lengthOfLastWord('hello word! python '))
# 二进制加1
# 思路: 先转换为10进制,求和后,在转为2进制
# 类似题目: 异或 求累加, 位于求进位
def binaryAdd(a, b):
a_int = int(a, 2)
b_int = int(b, 2)
res = a_int + b_int
return bin(res)[2:]
# print(binaryAdd('11', '1'))
# 反转字符串
def reverseStr(s):
# 方法1: return s[::-1]
# 方法2: 双指针法
start, end = 0, len(s)-1
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
return s
# print(reverseStr(['a', 'b', 'c', 'd']))
# 字符串相加
# 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和
def strAdd(s1, s2):
# 思路: 先转换为十进制,然后相加后再转换为字符串
# return str(int(s1) + int(s2))
# 问题:字符串很大时,对于C++等语言int后会造成溢出(python不存在溢出问题)
# 方法2:
s1_list = list(s1)
s2_list = list(s2)
sum1 = sum2 = 0
for ch in s1_list:
sum1 = sum1 * 10 + int(ch)
for ch in s2_list:
sum2 = sum2 * 10 + int(ch)
return str(sum1 + sum2)
# print(strAdd('12', '12'))
# 压缩字符串
# input: ["a","a","b","b","c","c","c"]
# 输出:返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"]
def compress(chars):
if not chars:
return None
# 方法1: set(chars)得到有序无重复元素,然后逐个找元素的次数
def compress_v1(chars):
ch_set = set(chars)
res = []
for ch in ch_set:
count = chars.count(ch)
if count == 1:
res.append(ch)
else:
res.append(ch)
res = res + list(str(count))
return res
# return compress_v1(chars)
# 方法2: 不使用辅助set,count内置函数,从后往前,统计字符个数
def compress_v2(chars):
count = 1
res = []
for i in range(len(chars)-1, -1, -1):
if chars[i] == chars[i-1]:
count += 1
else:
res += [chars[i]] if count == 1 else [chars[i]]+list(str(count))
count = 1
return res[::-1]
return compress_v2(chars)
# print(compress(["a","a","b","b","c","c","c"]))
# 541: 翻转字符串II
def reverseStr_ii(s, k):
# 因为list切片超出索引后为空列表,不影响后续结果
start, mid, end = 0, k, 2 * k
res = ''
while len(res) < len(s):
res += s[start:mid][::-1] + s[mid:end]
start, mid, end = start + 2 * k, mid + 2 * k, end + 2 * k
return res
# print(reverseStr_ii('abcdefgfxy', 2))
# 重复的子字符串
# 给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成
def duplicatedStr(s):
# 方法1: 问题:set(s)不是按照先后顺序
def duplicatedStr_v1(s):
sub_s = ''.join(list(set(s)))
s_len, sub_s_len = len(s), len(sub_s)
tmp = sub_s * (s_len // sub_s_len)
if tmp == s:
return True
return False
# return duplicatedStr_v1(s)
def duplicatedStr_v2(s):
# 逐个比较长度从1到len(s)-1的字符串
s_len = len(s)
for i in range(1, s_len):
times = s_len // i
if s[:i] * times == s:
return True
return False
# return duplicatedStr_v2(s)
def duplicatedStr_v3(s):
return s in (s+s)[1:-1]
return duplicatedStr_v3(s)
# print(duplicatedStr('ababc'))
# 翻转字符串中的单词III
def reverseWords(s):
if not s:
return s
# words = s.split()
# res = ''
# for word in words:
# res += word[::-1]
# res += ' '
# return res[:-1]
# 一句话优化
return ' '.join([word[::-1] for word in s.split()])
# print(reverseWords("Let's take LeetCode contest"))
# 重复叠加字符串匹配
# A重复多少次后,B是A的字串
def repeatStrMatch(A, B):
r = A
cnt = 1
# 不断累加A,直到r的长度大于等于B的长度,记录累加次数
while len(r) < len(B):
r += A
cnt += 1
if B in r: # 若B是r的字串,直接返回cnt
return cnt
r += A # 由于头尾没接上,导致B不是r的字串,再加A,解决头尾未接上问题
cnt += 1
if B in r:
return cnt
return -1
A = "abcd"
B = "cdabcdab"
# print(repeatStrMatch(A, B))
# 最常见的单词
import re
from collections import Counter
def mostCommonWord(paragraph, banned):
paragraph = paragraph.lower()
words = re.findall(pattern='[a-zA-Z]+', string=paragraph)
word_count = Counter(words)
res = word_count.most_common(len(banned) + 1)
for word_cnt in res:
if word_cnt[0] not in banned:
return word_cnt
# print(mostCommonWord("b12,b,b,c", ['a']))
# 亲密字符串
# 给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。
def bubbfyString(A, B):
# 必须长度相同
if len(A) != len(B):
return False
# 两字符串相等, 且A有重复元素 A = aab, B = aab
if A == B and len(set(A)) < len(B):
return True
# A,B字符串中按顺序不相等对数只能为2对,且要求对称
# [(a, b), (b, a)]
diff = [(a, b) for a, b in zip(A, B) if a != b]
return len(diff) == 2 and diff[0] == diff[1][::-1]
# 数组中重复的数字
# 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
def findRepeatNumber(nums):
# 方法1: python count()
# 方法2: 哈希表
# 方法3: 利用不重复,则i == nums.index(i)
if not nums or len(nums) == 1:
return None
for i in range(len(nums)):
while i != nums[i]: # i位置 不等于 i位置的元素, 需要把nums[i]元素放到nums[i]位置上
if nums[i] == nums[nums[i]]: # 如果nums[i]位置上有元素,则说明nums[i]是重复元素
return nums[i]
temp = nums[i]
nums[i], nums[temp] = nums[temp], nums[i]
return None
# print(findRepeatNumber([2,3,1,0,2,5,3]))
# 二维数组的查找
# 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
def findNum(nums, target):
if not nums:
return False
m, n = len(nums), len(nums[0])
i, j = 0, n-1
while i < m and j >= 0:
if nums[i][j] == target:
return True, i, j
elif nums[i][j] > target:
j -= 1
elif nums[i][j] < target:
i += 1
else:
pass
return False
# print(findNum([[1, 2, 3, 5], [2, 3, 5, 7], [4, 5, 7, 9]], 7))
# 替换空格
def replaceBlank(s):
# 方法1: return s.replace(' ', '%20')
# 方法2: 遍历,遇到空格替换为%20
s_list = list(s)
for i in range(len(s_list)):
if s_list[i] == ' ':
s_list[i] = '%20'
return ''.join(s_list)
# print(replaceBlank('hello python '))
# 从尾到头打印链表
# 思路: 一般都是从前到后打印,本题要求从后往前打印,利用栈的先进后出性质,可以实现
def printListFromTailToHead(head):
if not head:
return None
res = []
while head:
res.append(head.val)
head = head.next
return res[::-1]
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 重建二叉树
# 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
# # 例如,给出
# 前序遍历 preorder = [3,9,20,15,7]
# 中序遍历 inorder = [9,3,15,20,7]
def rebuildTree(preorder, inorder):
if not preorder or not inorder:
return
# 思路: 先找根节点,左子树和右子树;然后递归左右子树
root = TreeNode(preorder[0]) # 根节点为当前前序遍历的第一个值
loc = inorder.index(preorder[0]) # 在中序遍历中找根节点index
root.left = rebuildTree(preorder[1:loc+1], inorder[:loc])
root.right = rebuildTree(preorder[loc+1:], inorder[loc+1:])
return root
# 两个栈实现队列
class StackMakeQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, item):
# 入栈: 入栈1
self.stack1.append(item)
def push(self):
# 出栈: 若栈2不为空,则出栈2,否则吧栈1元素同步到栈2后出栈2
if self.stack2:
return self.stack2.pop()
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop() if self.stack2 else -1
# 斐波那契数列
# a[i] = a[i-1] + a[i-2]
# 方法1: 动态规划
# 方法2: a,b = b, a+b
def fibnacca(n):
# 求第n个斐波那契数
def fibnacca_dp(n):
dp = [0] * (n+1)
dp[1] = 1
for i in range(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
# return fibnacca_dp(n)
def fibnacca_v2(n):
a, b = 0, 1
for i in range(n):
a, b = b, a+b
return a
return fibnacca_v2(n)
# print(fibnacca(8))
# 旋转数组的最小数字
# 2个自增子数组, 找最小值,二分法
def minVal(nums):
if not nums:
return
s, e = 0, len(nums)-1
while e - s > 1: # 终止条件: 两个下标相差为1
mid = (s + e) // 2
if nums[s] == nums[mid] == nums[e]: # 如果出现大量重复(例如:[1,0,1,1,1]),只能顺序查找
# 顺序查找
min_val = float('inf')
for num in nums[s: e+1]:
if min_val > num:
min_val = num
return min_val
elif nums[mid] > nums[s]: # mid是第一个子数组,则最小值必然在后面
s = mid
else:
e = mid
return nums[e]
# print(minVal([3,4,5,1,2]))
# 矩阵中的路径
# 思路: 首先在矩阵中查找第一个字符,然后沿着上下左右四个方向,逐个找其他字符,失败的后退,沿着其他方向找
def exist_helper(board, rows, columns, i, j, word, visited):
if not word: # 查找完成
return True
# 异常情况
if i < 0 or i >= rows or j < 0 or j >= columns or visited[i][j] == 1 or board[i][j] != word[0]:
return False
visited[i][j] = 1
# 递归 上下左右 方向,如果有一个方向可存在word路径,则返回
# 不存在,则标记visited[i][j]未访问,便于下次访问
if (exist_helper(board, rows, columns, i + 1, j, word[1:], visited) or
exist_helper(board, rows, columns, i - 1, j, word[1:], visited) or
exist_helper(board, rows, columns, i, j - 1, word[1:], visited) or
exist_helper(board, rows, columns, i, j + 1, word[1:], visited)):
return True
# 回溯,将当前位置的布尔值标记为未访问
visited[i][j] = 0
return False
def exist(board, word):
if not board or not word:
return False
rows, cols = len(board), len(board[0])
visited = [[0 for _ in range(cols)] for _ in range(rows)]
# 查找首字符位置
for i in range(rows):
for j in range(cols):
if board[i][j] == word[0]:
return exist_helper(board, rows, cols, i, j, word[1:], visited)
return False
# 机器人的运功范围
# 剪绳子
# 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m] 。
# 请问 k[0]*k[1]*...*k[m] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18
# 分析:
# f(n): 表示长度为n的绳子 剪开后的最大长度
# 二进制中1的个数 n = n & (n-1)
# 删除链表的节点
# 思路: 查找待删除节点的前一个节点,然后删除即可,注意删除头节点的情况
def deleteNode(head, val):
if not head:
return head
if head.val == val: # 删除头节点
return head.next
node = head.next
pre_node = head
while node:
if node.val != val:
pre_node, node = node, node.next
else:
pre_node.next = node.next # 删除node节点
break
return head
# 调整数组位置,使得奇数在偶数前
# 方法1: 利用辅助列表,分别保存奇数和偶数,然后拼接
# 方法2: 前后指针p1, p2, p1当遇到奇数时p1++, 直到遇到偶数时;同时p2直到遇到奇数,交换
# 缺点:会改变奇数,偶数的相对顺序
def exchange(nums):
if not nums:
return nums
def exchange_v1(nums):
l1, l2 = [], []
for num in nums:
if num % 2 == 1:
l1.append(num)
else:
l2.append(num)
return l1+l2
# return exchange_v1(nums)
def exchange_v2(nums):
s, e = 0, len(nums)-1
while e - s > 1:
while s < e and nums[s] % 2 == 1:
s += 1
while s < e and nums[e] % 2 == 0:
e -= 1
nums[s], nums[e] = nums[e], nums[s]
return nums
return exchange_v2(nums)
nums = [1,2,3,4,5]
# print(exchange(nums))
# 链表中倒数第K个节点
# 方法: 首先,计算链表的总长度head_len 然后,从头往后走head_len - k步,该节点即为所求节点
def kNode(head, k):
if not head:
return None
node_cnt = 0
node = head
while node:
node_cnt += 1
node = node.next
if node_cnt < k: # 链表长度小于k,则输入错误
return None
node = head
for i in range(node_cnt - k):
node = node.next
return node
# 方法: 双指针 - 前后指针
# p1先走k步,然后p1,p2一起走,p1走到最后为None时,p2即为所求
def kNode_v2(head, k):
p1 = p2 = head
for i in range(k):
if p1:
p1 = p1.next
while p1:
p1 = p1.next
p2 = p2.next
return p2
# 树的子结构
# 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
def isSubTree_helper(treeA, treeB):
if not treeB: # 树B遍历完成
return True
if not treeA: # 树A完成,树B未完成,则B不是A的子结构
return False
if treeA.val != treeB.val: # 值不同,则B不是A的子结构
return False
# 同时递归遍历左右子树, 并且左右子树都是子结构
return isSubTree_helper(treeA.left, treeB.left) and \
isSubTree_helper(treeA.right, treeB.right)
def isSubTree(treeA, treeB):
if not treeA or not treeB:
return False
result = False
# 首先在树A中查找树B的根节点,先序遍历查找
if treeA.val == treeB.val: # A,B树根节点相同
result = isSubTree_helper(treeA, treeB)
if not result: # A树左子树查找
result = isSubTree_helper(treeA.left, treeB)
if not result: # A树右子树查找
result = isSubTree_helper(treeA.right, treeB)
return result
# 二叉树的镜像
# 请完成一个函数,输入一个二叉树,该函数输出它的镜像
def mirrorTree(root):
if not root:
return None
# 交换左右节点
root.left, root.right = root.right, root.left
mirrorTree(root.left)
mirrorTree(root.right)
return root
# 最小的K个数
# 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
def GetLeastNumbers(nums, k):
# 方法1: 排序后取前k个, O(NlogN)
# 方法2: partition()
def partition(nums, start, end):
print('partition(): start:%s, end:%s' % (start, end))
key = nums[start]
while start < end:
while start < end and nums[end] >= key:
end -= 1
nums[start], nums[end] = nums[end], nums[start]
while start < end and nums[start] <= key:
start += 1
nums[start], nums[end] = nums[end], nums[start]
return start
index = partition(nums, 0, len(nums) - 1)
while index != k - 1:
if index < k - 1: # 在后面找
index = partition(nums, index + 1, len(nums) - 1)
if index > k - 1: # 在前面找
index = partition(nums, 0, index - 1)
print(index, nums)
return nums[:k]
# print(GetLeastNumbers([4,5,1,6,2,7,3,8], 6))
# 数据流中的中位数
# 思路:数据流不断输入,需要持续记录
class GetMedian:
def __init__(self):
self.stack = []
self.size = 0
def addNum(self, val):
self.stack.append(val)
self.size += 1
def get_median(self):
if self.size == 0:
return None
if self.size % 2 == 1: # 奇数
return self.stack[self.size // 2]
return (self.stack[(self.size -1 ) // 2] + self.stack[(self.size + 1) //2]) / 2
# 连续子数组的最大和
# 和上面题的重复
# 把数字排成最小的数
from functools import cmp_to_key
def minNumber(nums):
if not nums:
return None
def sort_rule(x, y):
if x+y < y+x:
return -1
elif x+y > y+x:
return 1
else:
return 0
strs = [str(num) for num in nums]
nums.sort(key=cmp_to_key(sort_rule))
return ''.join(strs)
# print(minNumber([10, 2]))
# 把数字翻译成字符串
# 给定一个字符串数组,所有字符都连续成对出现除了一个字母,找出该字母。
# 例子:[AABBCCDEEFFGG], 输出为D
def find_once_str(s):
# 方法1:从前往后,逐个比较i和i+1位置的元素是否相等
def find_once_str_v1(s):
for i in range(0, len(s) - 2, 2):
if s[i] != s[i+1]:
break
return s[i]
# return find_once_str_v1(s)
def find_one_str_v2(s):
# 优化算法:二分法
# 思路:
if s[0] != s[1]:
return s[0]
n = len(s)
if s[n-1] != s[n-2]:
return s[n-1]
start, end = 0, n-1
while start <= end:
mid = (start + end) // 2
if s[mid] == s[mid-1]:
end = mid - 1
else:
if (a[mid] != a[mid - 1] and a[mid] != a[mid + 1]):
return a[mid]
else:
start = mid + 2
return s[start]
print(find_once_str('AABBCCDEEFFGG'))
|
e2892101bda7d3ad5f73612d819b689ae14423c8 | Dowfree/Data-Structures | /2014200222_DoubleLinkedList.py | 5,888 | 3.921875 | 4 | # -*- coding utf-8 -*-
import sys
"""双向链表及链表的反转"""
class LiuDataStructure:
def print(self,prefix='',postfix=''):
print(prefix+self.__repr__()+postfix)
class Node(LiuDataStructure):
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
def __repr__(self):
return str(self.data)
class LinkedList(LiuDataStructure):
def __init__(self, iterable=[]):
self.head = Node(None)
self.length = 0
for item in iterable: self.insert(self.length,item)
def __repr__(self):
(current, nodes) = self.head.next, []
while current :
nodes.append(str(current))
current = current.next
return '['+"->".join(nodes)+']'
def insert(self, index, val):
if index < 0 or index > self.length:
raise IndexError
node = Node(val)
p = self.head
for i in range(index):
p = p.next
pn = p.next
p.next = node
node.next = pn
self.length += 1
return self
def remove(self, index):
if index < 0 or index > self.length:
raise IndexError
q = p = self.head
for i in range(index):
q = p
p = p.next
q.next = p.next
del p
self.length -= 1
return self
def get(self, index):
if index < 0 or index >= self.length:
raise IndexError
p = self.head.next
for i in range(index):
p = p.next
return p.data
def find(self, val):
p = self.head
i = 0
while p.data != val and p.next != None:
p = p.next
i += 1
if p:
return i
else:
return -1
def reverse(self):
p = None
while self.head.next:
q = self.head.next
self.head.next = q.next
q.next = p
p = q
self.head.next= p
def merge_linked_lists(la,lb):
la.print('la:')
lb.print('lb:')
if la.head.next == None: return lb
if lb.head.next == None: return la
if la.head.next.data > lb.head.next.data:
dest, pb, pa = lb, la.head.next, lb.head.next
else:
dest, pa, pb = la, la.head.next, lb.head.next
q = dest.head
while pb :
while pa and pa.data <= pb.data:
q = pa
pa = pa.next
if pa == None:
q.next = pb
break
else:
tmp = pb.next
q.next = pb
pb.next = pa
pb = tmp
q = q.next
dest.print('dest:')
return dest
class DoubleLinkedList(LiuDataStructure):
def __init__(self,iterable=[]):
self.head = Node(None)
self.tail = Node(None)
self.length = 0
self.head.next = self.tail
self.tail.prev = self.head
for item in iterable:
self.insert(self.length, item)
def __repr__(self):
(current, nodes) = self.head.next, []
while current.next:
nodes.append(str(current))
current = current.next
return '['+"<->".join(nodes)+']'
def insert(self, index, val):
if index < 0 or index > self.length:
raise IndexError
node = Node(val)
p = self.head
for i in range(index):
p = p.next
if p.next is None:
p.next = self.tail
pn = p.next
p.next = node
pn.prev = node
node.prev = p
node.next = pn
self.length += 1
return self
def remove(self, index):
if index < 0 or index > self.length:
raise IndexError
p = self.head
for i in range(index):
p = p.next
p.prev.next = p.next
p.next.prev = p.prev
del p
self.length -= 1
return self
def get(self, index):
if index < 0 or index >= self.length:
raise IndexError
p = self.head.next
for i in range(index):
p = p.next
return p.data
def find(self, val):
p = self.head
i = 0
while p.data != val and p.next != None:
p = p.next
i += 1
if p:
return i
else:
return -1
def reverse(self):
p = self.head.next
for i in range(self.length):
pn = p.next
p.next = p.prev
p.prev = pn
p = pn
p = self.head.next
q = self.tail.prev
self.head.next = q
self.tail.prev = p
p.next = self.tail
q.prev = self.head
def merge_linked_lists(la,lb):
la.print('la:')
lb.print('lb:')
if la.head.next.data == None: return lb
if lb.head.next.data == None: return la
if la.head.next.data > lb.head.next.data:
dest, pb, pa = lb, la.head.next, lb.head.next
else:
dest, pa, pb = la, la.head.next, lb.head.next
q = dest.head
while pb and pb.data:
while pa and pa.data and pa.data <= pb.data:
q = pa
pa = pa.next
if pa == None:
q.next = pb
break
else:
tmp = pb.next
q.next = pb
pb.next = pa
pb = tmp
q = q.next
dest.print('dest:')
return dest |
990402348006fb79ebbbf2ea6cd0ac178f0b9a2e | ricklixo/cursoemvideo | /ex044.py | 1,577 | 3.953125 | 4 | # DESAFIO 044 - Crie um programa que calcule o valor a ser pago por um produto, considerando seu preço normal e a condição de pagamento:
# - à vista dinheiro/cheque: 10% de desconto
# - à vista no cartão: 5% de desconto
# - em até 2x no cartão: preço normal
# - 3x ou mais no cartão: 20% de juros
preco = int(input('Digite o valor do produto (R$): '))
print('[1]: À vista em dinheiro ou cheque. ')
print('[2]: À vista no cartão. ')
print('[3]: em até duas vezes no cartão. ')
print('[4]: 3x ou mais no cartão. ')
pagamento = int(input('Escolha a forma de pagamento: '))
if pagamento == 1:
preco_final = preco - (preco * 10/100)
print('10% de desconto. de R$ {:.2f} por R$ {:.2f}'.format(preco, preco_final))
elif pagamento == 2:
preco_final = preco - (preco * 5 / 100)
print('5% de desconto. de R$ {:.2f} por R$ {:.2f}'.format(preco, preco_final))
elif pagamento == 3:
parcela = int(input('Em quantas vezes deseja pagar? '))
if parcela <= 2:
preco_parcela = preco / parcela
print('{} vezes de R${:.2f}'.format(parcela, preco_parcela))
print('Sem desconto. Valor: R$ {:.2f}'.format(preco))
else:
print('Só são permitidos pagamentos em até 2x.')
elif pagamento == 4:
parcela = int(input('Em quantas vezes deseja pagar? '))
preco_final = preco + (preco * 20 / 100)
preco_parcela = preco_final / parcela
print('20% de juros. de R$ {:.2f} por R$ {:.2f}'.format(preco, preco_final))
print('{} vezes de R${:.2f}'.format(parcela, preco_parcela))
else:
print('Opção inválida.') |
448afeb01b08d3d280347aec176a32ab5844e108 | lucasnnobrega/APA-Repo | /Atvd 5/Dijkstra Path.py | 3,312 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on "Mon Feb 26 11:29:23 2018"
@author: Lucas NN
"""
# Programa em Python para o algorítimo de Dijkstra
# para o caminho mais curto. O programa recebe a
# matriz de adjacência como representação do grafo
# e retorna o caminho
import open_file as op
#Class to represent a graph
class Graph:
# Uma função para procurar o vértice com a minima distanca do conjunto de vertices
# ainda na fila
def minDistance(self,dist,fila):
# Inicialize o valor minimo e o index minimo como -1
minimum = float("Inf")
min_index = -1
# para a distancia array, escolhendo qual tem o mínimo valor ainda esta
# na fila
for i in range(len(dist)):
if dist[i] < minimum and i in fila:
minimum = dist[i]
min_index = i
return min_index
# Função para mostrar o caminho da origem para j usando o array pai
def printPath(self, parent, j):
# Caso base, se j é a origem
if parent[j] == -1 :
print (j, end = " ")
return
self.printPath(parent , parent[j])
print (j, end = " ")
# Uma função para mostrar o array de distancia construida
def printSolution(self, dist, parent):
src = 0
print("Vertex \t\tDistance from Source\tPath")
for i in range(1, len(dist)):
print("\n%d --> %d \t\t %d \t " % (src, i, dist[i]), end = " ")
self.printPath(parent,i)
def dijkstra(self, graph, src):
linha = len(graph)
col = len(graph[0])
# O array de saída. dist[i] irá armazenar a menor distância do começo até
# i, inicializando tudo com INFINITO
dist = [float("Inf")] * linha
# Array pai que armazena a árvore de menor caminho
parent = [-1] * linha
# Distância do vértice fonte para ele mesmo é sempre 0
dist[src] = 0
# Adicione todos os vértices na fila
fila = []
for i in range(linha):
fila.append(i)
# Procure o menor caminho para todos os vértices
while fila:
# Pegue o vértice que possui a distancia mínima do conjunto de vertices
# que ainda estão na fila
u = self.minDistance(dist,fila)
# Remova o mínimo elemento
fila.remove(u)
# Atualize o valor da distancia e o index do pai dos vértices adjacentes
# dos vértitices escolhidos. Considere somente os vértices nos quais
# ainda estão na vila
for i in range(col):
'''Atualize dist[i] somente se estiver na fila, existe um vértice
de u para i, e o peso total para o caminho para a origem para i
passando por u é menor que o valor corrente do dist[i]'''
if graph[u][i] and i in fila:
if dist[u] + graph[u][i] < dist[i]:
dist[i] = dist[u] + graph[u][i]
parent[i] = u
# Imprima o array de distância construida
self.printSolution(dist,parent)
g= Graph()
graph = op.grafos_matriz['dij40']
g.dijkstra(graph,0)
|
4c09e602827e8e2bb80225bc313d03e4e1de45e1 | liambolling/Python-Scraping-Coursework | /Homework/i211-HW-3.py | 1,685 | 4.34375 | 4 | # Liam Bolling
# Feb 3, 2016
# 1. (40 points)
# Use a list comprehension to load the data from a file named “race.txt”.
# There’s a sample file on Oncourse with the data shown above.
fileContents = [line.strip().split(" ") for line in open("i211-assets/race.txt", "r")]
vowelList = ["a", "e", "i", "o", "u"]
# 2. (20 points)
# Print out the information read in from the file formatted as shown in the example.
for element in fileContents:
print(element[0]+" traveled "+element[1]+" miles")
# 3. (20 points)
# Use a list comprehension to create a list of the names of the racers that begin with a vowel and print the list.
print("Names beginning with a vowel:",[i[0] for i in fileContents if i[0][0].lower() in vowelList])
# 4. (20 points)
# Use a list comprehension to create a list of the names of those who have traveled more than 500 miles
# and print the list.
print("People who have traveled over 500 miles:",[i[0] for i in fileContents if int(i[1]) >= 500])
# ------Desired Output------
# Eruc traveled 231 miles
# Gagarin traveled 2083 miles
# Kalakaua traveled 419 miles
# Earheart traveled 970 miles
# Fosset traveled 745 miles
# Ignacio traveled 1104 miles
# Names beginning with a vowel: ['Eruc', 'Earheart', 'Ignacio']
# People who have traveled over 500 miles: ['Gagarin', 'Earheart', 'Fosset', 'Ignacio']
# ------Actual Output------
# Eruc traveled 231 miles
# Gagarin traveled 2083 miles
# Kalakaua traveled 419 miles
# Earheart traveled 970 miles
# Fosset traveled 745 miles
# Ignacio traveled 1104 miles
# Names beginning with a vowel: ['Eruc', 'Earheart', 'Ignacio']
# People who have traveled over 500 miles: ['Gagarin', 'Earheart', 'Fosset', 'Ignacio'] |
a242041cc80b354c9d73e3018c8236fb9ecc8e95 | tanvi1706/practiceLeetCode | /306.py | 694 | 3.59375 | 4 | class Solution:
def AdditiveNumber(self,num: str) -> bool:
def backtrack(self, num1: str, num2: str, rem: str) -> bool:
if not rem:
return True
target = str(int(num1) + int(num2))
if rem.startswith(target) and all(str(int(x)) == x for x in (num1, num2)):
return backtrack(num2, target, rem[len(target):])
return False
for i in range(2, len(num)):
for j in range(1,i):
if len(num) - i >= j and len(num) - i >= i - j:
if backtrack(num[:j], num[j:i], num[i:]):
return True
break
return False |
71990cca17051663ed35f00b26f0688afa05b98a | Sergey-Mirzoyan/6-semester | /Моделирование/4+/lab4.py | 4,309 | 3.515625 | 4 | from numpy import arange
import matplotlib.pyplot as plt
class Data:
x0 = -5
l = 10 # Длина стержня (cm)
R = 0.5 # Радиус стержня (cm)
Tenv = 0 # Температура окружающей среды (K)
F0 = 50 # Плотность теплового потока (W / (cm^2 * K))
k0 = 0.1 # Коэффициент теплопроводности в начале стержня (W / (cm * K))
kN = 0.2 # Коэффициент теплопроводности в конце стержня (W / (cm * K))
alpha0 = 1e-2 # Коэффициент теплоотдачи в начале стержня (W / (cm^2 * K))
alphaN = 9e-2 # Коэффициент теплоотдачи в конце стержня (W / (cm^2 * K))
h = 0.0001
bk = (kN * l) / (kN - k0)
ak = - k0 * bk
b_alpha = (alphaN * l) / (alphaN - alpha0)
a_alpha = - alpha0 * b_alpha
@staticmethod
def k(x):
return Data.ak / (x - Data.bk)
@staticmethod
def alpha(x):
return Data.a_alpha / (x - Data.b_alpha)
@staticmethod
def Xn_plus_half(x):
return (2 * Data.k(x) * Data.k(x + Data.h)) / \
(Data.k(x) + Data.k(x + Data.h))
@staticmethod
def Xn_minus_half(x):
return (2 * Data.k(x) * Data.k(x - Data.h)) / \
(Data.k(x) + Data.k(x - Data.h))
@staticmethod
def p(x):
return 2 * Data.alpha(x) / Data.R
@staticmethod
def f(x):
return 2 * Data.alpha(x) / Data.R * Data.Tenv
def thomas_algorithm(A, B, C, D, K0, M0, P0, KN, MN, PN): # Tridiagonal matrix algorithm
# Initial values
xi = [None, - M0 / K0]
eta = [None, P0 / K0]
# Straight running
for i in range(1, len(A)):
x = C[i] / (B[i] - A[i] * xi[i])
e = (D[i] + A[i] * eta[i]) / (B[i] - A[i] * xi[i])
xi.append(x)
eta.append(e)
# print(xi)
# print(eta)
# Reverse running
y = [(PN - MN * eta[-1]) / (KN + MN * xi[-1])]
for i in range(len(A) - 2, -1, -1):
y_i = xi[i + 1] * y[0] + eta[i + 1]
y.insert(0, y_i)
return y
def left_boundary_conditions():
X_half = Data.Xn_plus_half(Data.x0)
p1 = Data.p(Data.x0 + Data.h)
f1 = Data.f(Data.x0 + Data.h)
p0 = Data.p(Data.x0)
f0 = Data.f(Data.x0)
p_half = (p0 + p1) / 2
K0 = X_half + Data.h * Data.h * p_half / 8 + Data.h * Data.h * p0 / 4
M0 = Data.h * Data.h * p_half / 8 - X_half
P0 = Data.h * Data.F0 + Data.h * Data.h * (3 * f0 + f1) / 4
return K0, M0, P0
def right__boundary_conditions():
X_half = Data.Xn_minus_half(Data.l)
pN = Data.p(Data.l)
pN1 = Data.p(Data.l - Data.h)
fN = Data.f(Data.l)
fN1 = (2 * Data.alpha(Data.l - Data.h)) / Data.R * Data.Tenv
KN = - (X_half + Data.alphaN * Data.h) / Data.h - Data.h * (5 * pN + pN1) / 16
MN = X_half / Data.h - Data.h * (pN + pN1) / 16
PN = - Data.alphaN * Data.Tenv - Data.h * (3 * fN + fN1) / 8
return KN, MN, PN
def calc_coefficients():
A = []
B = []
C = []
D = []
for i in arange(Data.x0, Data.l, Data.h):
An = Data.Xn_minus_half(i) / Data.h
Cn = Data.Xn_plus_half(i) / Data.h
Bn = An + Cn + Data.p(i) * Data.h
Dn = Data.f(i) * Data.h
A.append(An)
B.append(Bn)
C.append(Cn)
D.append(Dn)
return A, B, C, D
if __name__ == "__main__":
a, b, c, d = calc_coefficients()
# print(a)
# print(b)
# print(c)
# print(d)
k0, m0, p0 = left_boundary_conditions()
# print(k0)
# print(m0)
# print(p0)
kN, mN, pN = right__boundary_conditions()
# print(kN)
# print(mN)
# print(pN)
T = thomas_algorithm(a, b, c, d, k0, m0, p0, kN, mN, pN)
## print(T)
x = arange(Data.x0, Data.l, Data.h)
## print(x)
plt.title('Нагревание стержня')
plt.grid(True)
plt.plot(x, T, 'r', linewidth=0.5)
plt.xlabel("Длина (cм)")
plt.ylabel("Температура (K)")
plt.savefig("plot.png")
plt.show()
|
34ad8d42b21f82165571b7a0c3b9a37ecb722ee5 | JuanMacias07x/30abril | /ejercicio 45.py | 463 | 3.921875 | 4 | #Progama que imprima los números naturales contenidos entre dos números n y m (verificar que m>n).
number1 = int(input("Ingrese el primer número = "))
number2 = int(input("Ingrese el segundo número = "))
if number2 > number1:
for i in range(number1,number2):
print("Los números naturales que hay entre los números ingresados son =" + " " + str(i))
else:
print("El segundo número debe ser mayor que el primero porque es el límite.") |
15da8670836b5f92e88e34df9e8f80985518c1ee | prajwalmore5/python-mini-challenges | /code.py | 1,866 | 3.90625 | 4 | # --------------
#Code starts here
def palindrome(num):
while True:
num+=1
if str(num) == str(num)[::-1]:
return num
break
print(palindrome(123))
# --------------
#Code starts here
#Function to find anagram of one word in another
def a_scramble(str_1,str_2):
result=True
for i in (str_2.lower()):
if i not in (str_1.lower()):
result=False
break
str_1=str_1.replace(i,'',1) #Removing the letters from str_1 that are already checked
return (result)
#Code ends here
# --------------
#Code starts here
def check_fib(num):
if num == 0: return False
elif num == 1: return True
else:
A = 1
B = 1
FLIP = True
while(True):
new = A + B
if new > num: return False
elif new == num: return True
else:
if(FLIP):
A = new
FLIP = not FLIP
else:
B = new
FLIP = not FLIP
# --------------
def compress(word):
word = word.lower()
if len(word) == 0:
return None
final_arr = []
index = 0
letter = word[0]
for el in word:
if el == letter and ord(el) == ord(letter):
index += 1
else:
final_arr.append(letter + repr(index))
letter = el
index = 1
final_arr.append(letter + repr(index))
return "".join(final_arr)
print(compress("xxcccdex"))
# --------------
#Code starts here
def k_distinct(string,k):
string = string.lower()
if len(list(set(string))) == k:
return True
else:
return False
print(k_distinct('SUBBOOKKEEPER',8))
#Code ends here
|
af4c3af947c07768259483e97c0ec173c278c1af | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/codewar/_Codewars-Solu-Python-master/src/kyu3_Make_a_Spiral.py | 9,455 | 3.546875 | 4 | class Solution():
"""
https://www.codewars.com/kata/make-a-spiral
Your task, is to create a NxN spiral with a given size.
For example, spiral with size 5 should look like this:
00000
....0
000.0
0...0
00000
and with the size 10:
0000000000
.........0
00000000.0
0......0.0
0.0000.0.0
0.0..0.0.0
0.0....0.0
0.000000.0
0........0
0000000000
Return value should contain array of arrays, of 0 and 1,
for example for given size * result should be:
size 3:
[[1,1,1],
[0,0,1],
[1,1,1]]
size 4:
[[1,1,1,1],
[0,0,0,1],
[1,0,0,1],
[1,1,1,1]]
size 5:
[[1,1,1,1,1],
[0,0,0,0,1],
[1,1,1,0,1],
[1,0,0,0,1],
[1,1,1,1,1]]
size 6:
[[1,1,1,1,1,1],
[0,0,0,0,0,1],
[1,1,1,1,0,1],
[1,0,0,1,0,1],
[1,0,0,0,0,1],
[1,1,1,1,1,1]]
size 7:
[[1,1,1,1,1,1,1],
[0,0,0,0,0,0,1],
[1,1,1,1,1,0,1],
[1,0,0,0,1,0,1]
[1,0,1,1,1,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1]]
size 8:
[[1,1,1,1,1,1,1,1],
[0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,0,1],
[1,0,0,0,0,1,0,1],
[1,0,1,0,0,1,0,1],
[1,0,1,1,1,1,0,1],
[1,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1]]
size 9:
[[1,1,1,1,1,1,1,1,1],
[0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,0,1],
[1,0,0,0,0,0,1,0,1],
[1,0,1,1,1,0,1,0,1],
[1,0,1,0,0,0,1,0,1],
[1,0,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1]]
Because of the edge-cases for tiny spirals, the size will be at least 5.
General rule-of-a-thumb is, that the snake made with '1' cannot touch to itself.
"""
def __init__(self):
pass
def spiralize_01(self, size):
"""
top -> center <- bot
"""
if size == 0:
return []
if size == 1:
return [[1, ]]
if size == 2:
return [[1, 1], [0, 1]]
flag = size % 4
size_h = size // 2
if flag == 0:
a, b = size_h, size_h - 2
elif flag == 1:
a, b = size_h, size_h - 1
elif flag == 2:
a, b = size_h - 1, size_h - 1
else:
a, b = size_h, size_h - 1
ret_l = [[1, ] * size, ]
ret_u = [[1, ] * size,
[0, ] * (size - 1) + [1, ]]
val = 1
for i in range(1, a):
val = 0 if val == 1 else 1
r = ret_l[-1]
ret_l.append(r[:i] + [val, ] * (size - i - i) + r[-i:])
ret_l.reverse()
if b > 0:
val = 1
ret_u.append([1, ] * (size - 2) + [0, 1])
for i in range(1, b):
val = 0 if val == 1 else 1
r = ret_u[-1]
ret_u.append(r[:i] + [val, ] * (size - i - i - 2) + r[-i - 2:])
return ret_u + ret_l
def spiralize_02(self, size):
"""
rings -> half diagonal invert
"""
spiral = []
for i in range(size):
spiral.append([])
for j in range(size):
spiral[-1].append(1 - min(i, j, size - max(i, j) - 1) % 2)
for i in range(size // 2 - (size % 4 == 0)):
spiral[i + 1][i] = 1 - spiral[i + 1][i]
return spiral
def spiralize_03(self, size):
"""
rings -> half diagonal invert
"""
spiral = [[0, ] * size for _ in range(size)]
for i in range(0, (size + 1) // 2, 2):
size_i = size - i
for j in range(i, size_i):
spiral[i][j] = spiral[j][i] = spiral[size_i - 1][j] = spiral[j][size_i - 1] = 1
for i in range(size // 2 - (size % 4 == 0)):
spiral[i + 1][i] = 1 - spiral[i + 1][i]
return spiral
def spiralize_04(self, size):
"""
binary bitwise
"""
if size == 0:
return []
if size % 2 != 0:
j = [1, ]
elif size % 4 != 0:
j = [3, 1]
else:
j = [3, 3]
for s in reversed(range(size, 2, -2)):
# print('s:', s)
j = [2 ** s - 1] + \
list(
map(
(lambda a, b, c: c or (a ^ (b << 1))),
[2 ** s - 1] * (s - 2),
j,
[1, ] + [0, ] * (s - 3),
)
) + \
[2 ** s - 1]
# print(j)
return [list(map(int, '{{:0>{:d}b}}'.format(size).format(row))) for row in j]
def spiralize_05(self, size):
"""
outer -> inner
"""
_spirals_ = {
0: [],
1: [[1]],
2: [[1, 1],
[0, 1]],
3: [[1, 1, 1],
[0, 0, 1],
[1, 1, 1]],
4: [[1, 1, 1, 1],
[0, 0, 0, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]]
}
def recur(size):
if size in _spirals_:
return _spirals_[size]
spiral_inner = recur(size - 4)
spiral = [
[1, ] * size,
[0, ] + [0, ] * (size - 2) + [1, ],
[1, 1] + spiral_inner[0] + [0, 1],
] + [
[1, 0] + spiral_inner[i] + [0, 1] for i in range(1, size - 4)
] + [
[1, ] + [0, ] * (size - 2) + [1, ],
[1, ] * size,
]
# the line below caches the result which is useless in current context
# _spirals_[size] = spiral
return spiral
return recur(size)
def spiralize_06(self, size):
"""
game play, snake::1, pre-calc
"""
if size == 0:
return []
if size == 1:
return [[1, ]]
# Fill top row with '1's and rest with '0's
spiral = [
[1, ] * size,
] + [
[0, ] * size for _ in range(size - 1)
]
# Locations and directions
row, col = 0, size - 1
hor, ver = 0, 1
# Loop for the length of the spiral's arm
for n in range(size - 1, 0, -2):
# Loop for the number of arms of this length
m = 2 if n > 2 else n
for _ in range(m):
# Loop for each '1' in this arm
for _ in range(n):
row += ver
col += hor
spiral[row][col] = 1
# Change direction
hor, ver = -ver, hor
return spiral
def spiralize_07(self, size):
"""
game play, snake::0, no turning control
"""
def is_one(y, x):
return 0 <= y < size and 0 <= x < size and spiral[y][x] == 1
spiral = [[1, ] * size for _ in range(size)]
y, x = 1, -1
dy, dx = 0, 1
y_dy, x_dx = y + dy, x + dx
while is_one(y_dy, x_dx):
if is_one(y_dy + dy, x_dx + dx):
y += dy
x += dx
else:
dx, dy = -dy, dx
spiral[y][x] = 0
y_dy, x_dx = y + dy, x + dx
return spiral
def spiralize_08(self, size):
"""
game play, snake::1, turning control
"""
def is_one(x, y):
return 0 <= x < size and 0 <= y < size and spiral[y][x] == 1
def can_move(x, y, dx, dy):
x, y = x + dx, y + dy
return 0 <= x < size and 0 <= y < size and not is_one(x + dx, y + dy)
def can_turn(x, y, dx, dy):
x, y = x - dy, y + dx
return 0 <= x < size and 0 <= y < size and not (is_one(x - dy, y + dx) or is_one(x - dx, y - dy))
spiral = [[0, ] * size for _ in range(size)]
x, y = -1, 0
dx, dy = 1, 0
while True:
if can_move(x, y, dx, dy):
x += dx
y += dy
spiral[y][x] = 1
continue
if can_turn(x, y, dx, dy):
dx, dy = -dy, dx
continue
break
return spiral
def spiralize_09(self, size):
"""
coordinate peel rot
"""
range_size = list(range(size))
def _rot(arr, i=0):
if not arr or (len(arr) < 2 and i == min(size, 3)):
return ()
if i == min(size, 3):
return arr[0][:-1] + _rot(list(zip(*arr[1:]))[::-1][1:], i)
return arr[0] + _rot(list(zip(*arr[1:]))[::-1], i + 1)
a = [tuple([(i, j) for j in range_size]) for i in range_size]
pos = set(_rot(a)) # hashtab
return [[1 if (i, j) in pos else 0 for j in range_size] for i in range_size]
def spr_prt(spiral):
print('-' * len(spiral))
for r in spiral:
print(r)
print('-' * len(spiral))
def sets_gen(spiralize):
test_sets = []
for size in range(0, 51):
match = spiralize(size)
test_sets.append((
(size,),
match
))
return test_sets
if __name__ == '__main__':
sol = Solution()
from test_fixture import Test_Fixture
tf = Test_Fixture(sol, sets_gen)
tf.prep()
tf.test(prt_docstr=False)
tf.test_spd(100, prt_docstr=True)
|
94b097c44d52bdc80a32e151c2b5fe92f5c32a69 | yuu1127/projects | /UniDocuments/Algorithm_Python/maze.py | 26,158 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 12:34:23 2018
@author: yuta
"""
import sys
from copy import deepcopy
from collections import defaultdict
import os
class MazeError(Exception):
def __init__(self,message):
self.message = message
class Maze:
def __init__(self,file_name):
try:
with open(file_name,'r') as f:
data = [v.split() for v in f.readlines() if v != '\n']
#print(file_name)
#print(data)
if len(data[0]) == 1:
j = 0
for i in data:
data[j] = [int(j) for j in i[0]]
j += 1
else:
data = [list(map(int,v)) for v in data if v != []]
#print(data)
#print(len(data))
if len(data) < 2 or len(data) > 41:
raise MazeError('Incorrect input.')
keep_row = len(data[0])
for row in data:
if len(row) < 2 or len(row) > 31:
raise MazeError('Incorrect input.')
if len(row) != keep_row:
raise MazeError('Incorrect input.')
for i in data:
for j in i:
if j != 0 and j != 1 and j != 2 and j != 3:
raise MazeError('Incorrect input.')
for i in data:
if i[-1] != 0 and i[-1] != 2:
raise MazeError('Input does not represent a maze.')
if 2 in data[-1] or 3 in data[-1]:
raise MazeError('Input does not represent a maze.')
except FileNotFoundError:
print('Sorry, there is no such file.')
sys.exit()
#print(file_name)
self.maze_list = data
self.m_list = deepcopy(data)
self.p_list = deepcopy(data)
#self.a_p_list = deepcopy(data)
self.height = len(data)
self.width = len(data[0])
self.sacs = defaultdict(int)
self.sac_list = []
self.unique_paths = []
self.file_name = file_name[:-3] + 'tex'
self.path_lists = []
def number_gates(self):
h_line_top = self.maze_list[0][:-1]
h_line_below = self.maze_list[-1][:-1]
gate_lists = []
for x in range(self.width - 1):
if h_line_top[x] == 0 or h_line_top[x] == 2:
gate_lists.append((x,0))
if h_line_below[x] == 0:
gate_lists.append((x,self.height - 2))
v_line_left = [i[0] for i in self.maze_list][:-1]
v_line_right = [i[-1] for i in self.maze_list][:-1]
for y in range(self.height - 1):
if v_line_left[y] == 0 or v_line_left[y] == 1:
gate_lists.append((0,y))
if v_line_right[y] == 0:
gate_lists.append((self.width - 2,y))
return gate_lists
def _connect_right(self,x,y,m_list):
value = m_list[y][x]
if value is 1 or value is 3:
return True
else:
return False
def _connect_left(self,x,y,m_list):
if not (0 <= x - 1 < self.width and 0 <= y < self.height):
return False
value = m_list[y][x - 1]
if value is 1 or value is 3:
return True
else:
return False
def _connect_above(self,x,y,m_list):
if not (0 <= x < self.width and 0 <= y - 1 < self.height):
return False
value = m_list[y - 1][x]
if value is 2 or value is 3:
return True
else:
return False
def _connect_below(self,x,y,m_list):
value = m_list[y][x]
if value is 2 or value is 3:
return True
else:
return False
def explore_wall(self):
wall_lists = []
for y in range(self.height):
for x in range(self.width):
value = self.m_list[y][x]
if value is not 0 and value is not -1:
pt_1 = (x,y)
wall_list = []
wall = self._explore_wall(pt_1,wall_list)
wall_lists.append(wall)
else:
pass
return wall_lists
def _explore_wall(self,pt_1,wall_list):
x,y = pt_1
#print(x,y)
if not (0 <= x < self.width and 0 <= y < self.height):
return
#もっと上手くかける
if pt_1 in wall_list:
return
wall_list.append(pt_1)
#print(wall_list)
pt_right,pt_left,pt_above,pt_below = None,None,None,None
#self.m_list[y][x] = -1
if self._connect_right(x,y,self.m_list):
pt_right = (x + 1,y)
if self._connect_left(x,y,self.m_list):
pt_left = (x - 1,y)
if self._connect_above(x,y,self.m_list):
pt_above = (x,y - 1)
if self._connect_below(x,y,self.m_list):
pt_below = (x,y + 1)
self.m_list[y][x] = -1
if pt_right is not None:
self._explore_wall(pt_right,wall_list)
if pt_left is not None:
self._explore_wall(pt_left,wall_list)
if pt_above is not None:
self._explore_wall(pt_above,wall_list)
if pt_below is not None:
self._explore_wall(pt_below,wall_list)
return wall_list
def path_right(self,x,y,p_list):
#if not (0 <= x + 1 < self.width and 0 <= y < self.height):
#return False
value = p_list[y][x + 1]
if value is 1 or value is 0:
return True
else:
return False
def path_left(self,x,y,p_list):
#if not (0 <= x - 1 < self.width and 0 <= y < self.height):
#return False
value = p_list[y][x]
if value is 1 or value is 0:
return True
else:
return False
def path_above(self,x,y,p_list):
#if not (0 <= x < self.width and 0 <= y - 1 < self.height):
#return False
value = p_list[y][x]
if value is 0 or value is 2:
return True
else:
return False
def path_below(self,x,y,p_list):
#if not (0 <= x < self.width and 0 <= y + 1 < self.height):
#return False
value = p_list[y + 1][x]
if value is 0 or value is 2:
return True
else:
return False
def explore_path(self,gate_lists):
path_lists = []
for pt_1 in gate_lists:
x,y = pt_1
value = self.p_list[y][x]
if value is not -1:
path_list = []
path = self._explore_path(pt_1,path_list)
path_lists.append(path)
else:
pass
return path_lists
def _explore_path(self,pt_1,path_list):
x,y = pt_1
if not (0 <= x < self.width -1 and 0 <= y < self.height - 1):
return
if pt_1 in path_list:
return
path_list.append(pt_1)
pt_right,pt_left,pt_above,pt_below = None,None,None,None
if self.path_right(x,y,self.p_list):
#self.sacs[(x,y)] = self.sacs[(x,y)] + 1
pt_right = (x + 1,y)
if self.path_left(x,y,self.p_list):
#self.sacs[(x,y)] = self.sacs[(x,y)] + 1
pt_left = (x - 1,y)
if self.path_above(x,y,self.p_list):
#self.sacs[(x,y)] = self.sacs[(x,y)] + 1
pt_above = (x,y - 1)
if self.path_below(x,y,self.p_list):
#self.sacs[(x,y)] = self.sacs[(x,y)] + 1
pt_below = (x,y + 1)
self.p_list[y][x] = -1
if pt_right is not None:
self._explore_path(pt_right,path_list)
if pt_left is not None:
self._explore_path(pt_left,path_list)
if pt_above is not None:
self._explore_path(pt_above,path_list)
if pt_below is not None:
self._explore_path(pt_below,path_list)
return path_list
def cul_de_sacs(self,path_lists):
for i in path_lists:
for pt_1 in i:
x,y = pt_1
if self.path_right(x,y,self.maze_list):
self.sacs[(x,y)] = self.sacs[(x,y)] + 1
if self.path_left(x,y,self.maze_list):
self.sacs[(x,y)] = self.sacs[(x,y)] + 1
if self.path_above(x,y,self.maze_list):
self.sacs[(x,y)] = self.sacs[(x,y)] + 1
if self.path_below(x,y,self.maze_list):
self.sacs[(x,y)] = self.sacs[(x,y)] + 1
return self.sacs
def connect_check(self,pt_1,sac_list):
x,y = pt_1
left_0 = (x-1,y)
right_0 = (x+1,y)
above_0 = (x,y-1)
below_0 = (x,y+1)
if left_0 in sac_list:
return True
if right_0 in sac_list:
return True
if above_0 in sac_list:
return True
if below_0 in sac_list:
return True
return False
def count_sacs(self,path_lists):
# cnt = 0
for path_list in path_lists:
# cnt += 1
if 1 in [self.sacs[pt_1] for pt_1 in path_list]:
self._count_sacs(path_list)
# return cnt
sac_lists = []
for path_list in path_lists:
sac_list = []
for pt_1 in path_list:
if self.sacs[pt_1] == 0:
#print(pt_1)
if sac_list == []:
sac_list.append(pt_1)
else:
if self.connect_check(pt_1,sac_list):
sac_list.append(pt_1)
else:
sac_lists.append(sac_list)
sac_list = []
sac_list.append(pt_1)
else:
if sac_list != []:
sac_lists.append(sac_list)
sac_list = []
if sac_list != []:
sac_lists.append(sac_list)
#print(sac_lists)
for i in sac_lists:
for j in i:
self.sac_list.append(j)
return sac_lists
def _count_sacs(self,path_list):
#count_sac = 0
for pt_1 in path_list:
if self.sacs[pt_1] == 1:
#self.count_sac += 1
self.sacs[pt_1] -= 1
x,y = pt_1
left_1 = (x-1,y)
#make_list_for_sacs
if left_1 in path_list and self.sacs[left_1] != 0:
if self.path_left(x,y,self.maze_list):
#if left_1 in path_list and self.path_left(x-1,y,self.maze_list) and self.sacs[left_1] != 0 :
self.sacs[left_1] = self.sacs[left_1] - 1
return self._count_sacs(path_list)
right_1 = (x+1,y)
if right_1 in path_list and self.sacs[right_1] != 0:
#if right_1 in path_list and self.path_right(x+1,y,self.maze_list) and self.sacs[right_1] != 0:
if self.path_right(x,y,self.maze_list):
self.sacs[right_1] = self.sacs[right_1] - 1
return self._count_sacs(path_list)
above_1 = (x,y-1)
if above_1 in path_list and self.sacs[above_1] != 0:
#if above_1 in path_list and self.path_above(x,y-1,self.maze_list) and self.sacs[above_1] != 0:
if self.path_above(x,y,self.maze_list):
self.sacs[above_1] = self.sacs[above_1] - 1
return self._count_sacs(path_list)
below_1 = (x,y+1)
if below_1 in path_list and self.sacs[below_1] != 0:
#if below_1 in path_list and self.path_below(x,y+1,self.maze_list) and self.sacs[below_1] != 0:
if self.path_below(x,y,self.maze_list):
self.sacs[below_1] = self.sacs[below_1] - 1
return self._count_sacs(path_list)
def final_path(self,path_lists):
unique_paths = []
for path_list in path_lists:
check_path = [self.sacs[pt_1] for pt_1 in path_list]
if 3 in check_path or 4 in check_path:
pass
elif any(check_path):
unique_path = [pt_1 for pt_1 in path_list if self.sacs[pt_1] == 1 or self.sacs[pt_1] == 2]
unique_paths.append(unique_path)
else:
pass
self.unique_paths = unique_paths
#print(unique_paths)
return unique_paths
def p_right(self,x,y,p_list):
#if not (0 <= x + 1 < self.width and 0 <= y < self.height):
#return False
value = p_list[y][x]
if value is 0 or value is 2:
return True
else:
return False
def p_left(self,x,y,p_list):
if not (0 <= x - 1 < self.width and 0 <= y < self.height):
return True
value = p_list[y][x - 1]
if value is 0 or value is 2:
return True
else:
return False
def p_above(self,x,y,p_list):
if not (0 <= x < self.width and 0 <= y - 1 < self.height):
return True
value = p_list[y - 1][x]
if value is 0 or value is 1:
return True
else:
return False
def p_below(self,x,y,p_list):
#if not (0 <= x < self.width and 0 <= y + 1 < self.height):
#return False
value = p_list[y][x]
if value is 0 or value is 1:
return True
else:
return False
def f_right(self,x,y,p_list):
if not (0 <= x + 1 < self.width and 0 <= y < self.height):
return True
value = p_list[y][x + 1]
if value is 0 or value is 1:
return True
else:
return False
def f_left(self,x,y,p_list):
#if not (0 <= x - 1 < self.width and 0 <= y < self.height):
#return True
value = p_list[y][x]
if value is 0 or value is 1:
return True
else:
return False
def f_above(self,x,y,p_list):
#if not (0 <= x < self.width and 0 <= y - 1 < self.height):
#return True
value = p_list[y][x]
if value is 0 or value is 2:
return True
else:
return False
def f_below(self,x,y,p_list):
if not (0 <= x < self.width and 0 <= y + 1 < self.height):
return True
value = p_list[y + 1][x]
if value is 0 or value is 2:
return True
else:
return False
# def connect_unique_path(self,x,y,ee_path):
# from_x = x + 0.5
# from_y = y + 0.5
# if self.f_above(x,y,self.maze_list) and (x,y - 1) not in ee_path:
# #save
# from_y = from_y - 1
# #print(f' \\draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
# if self.f_below(x,y,self.maze_list):
# #to_x = from_x
# #to_y = from_y + 1
# return self.connect_unique_path(x,y + 1,ee_path)
# #print(f' \\draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
# else:
# to_x = x
# to_y = from_y + 1
def analyse(self):
gate_lists = self.number_gates()
gate = len(gate_lists)
if gate == 0:
print(f'The maze has no gate.')
elif gate == 1:
print(f'The maze has a single gate.')
else:
print(f'The maze has {gate} gates.')
#print(self.explore_wall())
wall_lists = self.explore_wall()
#print(wall_lists)
wall = len(wall_lists)
if wall == 0:
print(f'The maze has no wall.')
elif wall == 1:
print(f'The maze has walls that are all connected.')
else:
print(f'The maze has {wall} sets of walls that are all connected.')
path_lists = self.explore_path(gate_lists)
self.path_lists = path_lists
#print(path_lists)
total_block = (self.height - 1) * (self.width - 1)
accessible_block = 0
for i in path_lists:
accessible_block = accessible_block + len(i)
inaccessible_block = total_block - accessible_block
if inaccessible_block == 0:
print(f'The maze has no inaccessible inner point.')
elif inaccessible_block == 1:
print(f'The maze has a unique inaccessible inner point.')
else:
print(f'The maze has {inaccessible_block} inaccessible inner points.')
#print(inaccessible_block)
path = len(path_lists)
if path == 0:
print(f'The maze has no accessible area.')
elif path == 1:
print(f'The maze has a unique accessible area.')
else:
print(f'The maze has {path} accessible areas.')
#print(self.cul_de_sacs(path_lists))
self.cul_de_sacs(path_lists)
sacs = len(self.count_sacs(path_lists))
if sacs == 0:
print(f'The maze has no cul-de-sac.')
elif sacs == 1:
print(f'The maze has accessible cul-de-sacs that are all connected.')
else:
print(f'The maze has {sacs} sets of accessible cul-de-sacs that are all connected.')
unique_path = len(self.final_path(path_lists))
if unique_path == 0:
print(f'The maze has no entry-exit path with no intersection not to cul-de-sacs.')
elif unique_path == 1:
print(f'The maze has a unique entry-exit path with no intersection not to cul-de-sacs.')
else:
print(f'The maze has {unique_path} entry-exit paths with no intersections not to cul-de-sacs.')
def display(self):
tex_filename = self.file_name
gate_lists = self.number_gates()
wall_lists = self.explore_wall()
#print(wall_lists)
path_lists = self.explore_path(gate_lists)
#print(path_lists)
self.cul_de_sacs(path_lists)
sacs = len(self.count_sacs(path_lists))
#unique_path = len(self.final_path(path_lists))
unique_path = self.final_path(path_lists)
#print(unique_path)
e_e_path = [j for i in unique_path for j in i]
print(e_e_path)
#gate_lists = self.number_gates()
with open(tex_filename, 'w') as tex_file:
print('\\documentclass[10pt]{article}\n'
'\\usepackage{tikz}\n'
'\\usetikzlibrary{shapes.misc}\n'
'\\usepackage[margin=0cm]{geometry}\n'
'\\pagestyle{empty}\n'
'\\tikzstyle{every node}=[cross out, draw, red]\n'
'\n'
'\\begin{document}\n'
'\n'
'\\vspace*{\\fill}\n'
'\\begin{center}\n'
'\\begin{tikzpicture}[x=0.5cm, y=-0.5cm, ultra thick, blue]', file = tex_file
)
print(f'% Walls', file = tex_file)
for y in range(self.height):
connect_x = False
for x in range(self.width):
if self._connect_right(x,y,self.maze_list):
if connect_x == False:
from_x = x
connect_x = True
else:
pass
else:
if connect_x == True:
to_x = x
print(f' \\draw ({from_x},{y}) -- ({to_x},{y});', file = tex_file)
connect_x = False
else:
pass
for x in range(self.width):
connect_y = False
for y in range(self.height):
if self._connect_below(x,y,self.maze_list):
if connect_y == False:
from_y = y
connect_y = True
else:
pass
else:
if connect_y == True:
to_y = y
print(f' \\draw ({x},{from_y}) -- ({x},{to_y});', file = tex_file)
connect_y = False
else:
pass
print(f'% Pillars', file = tex_file)
for y in range(self.height):
for x in range(self.width):
if self.p_left(x,y,self.maze_list) and self.p_right(x,y,self.maze_list) \
and self.p_above(x,y,self.maze_list) and self.p_below(x,y,self.maze_list):
print(f' \\fill[green] ({x},{y}) circle(0.2);', file = tex_file)
print(f'% Inner points in accessible cul-de-sacs', file = tex_file)
#self.cul_de_sacs(self.path_lists)
sac_list = sorted(self.sac_list,key = lambda k:(k[1],k[0]))
for pt_1 in sac_list:
x,y = pt_1
x = x + 0.5
y = y + 0.5
print(f' \\node at ({x},{y}) ''{};', file = tex_file)
print(f'% Entry-exit paths without intersections', file = tex_file)
ee_paths = self.unique_paths
#print(ee_paths)
for ee_path in ee_paths:
connecting = False
ee_path = sorted(ee_path,key = lambda k:(k[1],k[0]))
for pt in ee_path:
x,y = pt
x_point = x + 0.5
y_point = y + 0.5
if self.f_left(x,y,self.maze_list) and not (0 <= x - 1 < self.width and 0 <= y < self.height):
#to_x = from_x
from_x = x_point - 1
from_y = y_point
connecting = True
#to_y = from_y
#print(f' \\draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
if self.f_right(x,y,self.maze_list):
if connecting == False:
from_x = x_point
from_y = y_point
connecting = True
if not 0 <= x_point + 1 < self.width:
to_x = x_point + 1
to_y = y_point
print(f' \\draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
elif connecting == True:
if not (0 <= x + 1 < self.width and 0 <= y < self.height):
to_x = x_point + 1
to_y = y_point
else:
to_x = x_point
to_y = y_point
#print(from_x,connecting)
print(f' \\draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
#print(f'({from_x},{from_y})--({to_x},{to_y})')
connecting = False
#print(ee_paths)
#print(f' \draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
for ee_path in ee_paths:
connecting = False
ee_path = sorted(ee_path,key = lambda k:(k[0],k[1]))
for pt in ee_path:
x,y = pt
x_point = x + 0.5
y_point = y + 0.5
if self.f_above(x,y,self.maze_list) and not (0 <= x < self.width and 0 <= y - 1 < self.height):
#to_x = from_x
from_x = x_point
from_y = y_point - 1
connecting = True
#to_y = from_y
#print(f' \\draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
if self.f_below(x,y,self.maze_list):
if connecting == False:
from_x = x_point
from_y = y_point
connecting = True
elif connecting == True:
if not (0 <= x < self.width and 0 <= y + 1 < self.height):
to_x = x_point
to_y = y_point + 1
else:
to_x = x_point
to_y = y_point
#print(from_x,connecting)
print(f' \\draw[dashed, yellow] ({from_x},{from_y}) -- ({to_x},{to_y});', file = tex_file)
#print(f'({from_x},{from_y})--({to_x},{to_y})')
connecting = False
print('\\end{tikzpicture}\n'
'\\end{center}\n'
'\\vspace*{\\fill}\n\n'
'\\end{document}', file = tex_file
)
#os.system('pdflatex ' + tex_filename)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.