blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
f90f200aa717a2977f5d6d7a51dc76f4035395bb | webturing/PythonProgramming_20DS123 | /lec03-loop0/while1c.py | 50 | 3.5625 | 4 | x=10
while x>0:
print("hello world")
x-=1
|
c2eab50f47b843baf1b9fcf5a6120f36c9cf7e58 | kanoria/Honeyword-decoder | /detectors/tokenslib/classifier.py | 9,417 | 3.90625 | 4 | import pprint
from password_leaner import password_leaner
pp = pprint.PrettyPrinter(indent=1)
def isInAlphabeticalSequence(word):
"""
Checks if the string passed to it is in an alphabetical sequence
"""
if len(word) == 1:
return False
else:
for i in range(len(word) - 1):
if ord(word[i]) != ord(word[i + 1]) + 1:
return False
return True
def isInReverseAlphabeticalSequence(word):
"""
Checks if the string passed to it is in a reverse alphabetical sequence
"""
if len(word) == 1:
return False
else:
for i in range(len(word) - 1):
if ord(word[i]) != ord(word[i + 1]) - 1:
return False
return True
def isSameCharacterSequence(word):
"""
Checks if the string passed to it is in a sequence of identical characters
"""
if len(word) == 1:
return False
else:
for i in range(len(word) - 1):
if word[i] != word[i + 1]:
return False
return True
def isOnlySpecialCharacters(word):
"""
Checks if the string passed is comprised entirely of special characters typically allowed in passwords
"""
for i in range(len(word)):
if word[i].isalpha() or word[i].isdigit():
return False
return True
def isInSequence(word):
"""
Checks if the string passed is a sequence of digits logically connected ("e.g. 369")
"""
if len(word)<3:
return False
else:
increment = int(word[0]) - int(word[1])
for i in range(len(word) - 2):
if int(word[i+1]) - int(word[i+2]) != increment:
return False
return True
def classifyCharacter(word):
"""
Classifies the passed single character string into an alphabet, number, or special character
"""
if word[0].isalpha():
return "isalpha"
elif word[0].isalpha():
return "isdigit"
else:
return "isspecialchar"
def classifier(token):
""" Classifies the given token into one of several categories.
categories currently defined are:
same_sequence_letters: same letter being repeated (e.g. "aaa")
sequence_letters: letters in alphabetical sequence or reverse alphabetical sequence (e.g. "abc", "zyx")
random_letters: string of random letters (e.g. dyumd)
same_sequence_numbers: same digit being repeated (e.g. "22222")
sequence_numbers: logical sequence of digits (e.g. "369")
even_numbers: all digits are even digits (e.g. "4824")
odd_numbers: all digits are odd digits (e.g. "35573")
same_sequence_specialchars: sequence of special characters (e.g. "^^^^^^")
Classifies by priority:
words: constant sequence > sequence > random
numbers: constant sequence > sequence > odd or even > random numbers
special chars: constant sequence > random
"""
#check if token is a string of alphabets
if token.isalpha():
#check if token is a sequence of the same alphabet:
if isSameCharacterSequence(token):
return "same_sequence_letters"
elif isInAlphabeticalSequence(token) or isInReverseAlphabeticalSequence(token):
return "sequence_letters"
else:
return "random_letters"
#check if token is a number
elif token.isdigit():
if isSameCharacterSequence(token):
return "same_sequence_numbers"
elif isInSequence(token):
return "sequence_numbers"
else:
evenCount = 0
oddCount = 0
for x in range(len(token)):
if int(token[x])%2 ==0:
evenCount+=1
else:
oddCount+=1
if evenCount == len(token):
return "even_numbers"
elif oddCount == len(token):
return "odd_numbers"
else:
return "random_numbers"
else:
if isSameCharacterSequence(token):
return "same_sequence_specialchars"
else:
return "random_specialchars"
def tokeniser(tokenInfo):
"""
Accepts a dictionary and maps the remaining parts of the source password.
Goes through the reamining tokens and classifies them.
Adds key - value pairs to the original dictionary under new classifications as defined in classifier.
"""
source_pass = tokenInfo["source_pass"]
tokensToSort = []
tokensToClassify = []
wordStartIndex = []
wordEndIndex = []
#Going through the words identified in the input and saving their start and end index in an array to use later
if "words" not in tokenInfo["tokens"].keys():
tokensToSort.append({
"content": source_pass,
"start_index": 0,
"end_index": len(source_pass) - 1
})
else:
for word in tokenInfo["tokens"]["words"]:
wordStartIndex.append(word["start_index"])
wordEndIndex.append(word["end_index"])
tempTokenStartIndex = 0
tempToken = ''
for i in range(len(wordStartIndex)):
tempToken = source_pass[tempTokenStartIndex:wordStartIndex[i]]
if tempToken != '':
tokensToSort.append({
"content": tempToken,
"start_index": tempTokenStartIndex,
"end_index": wordStartIndex[i] - 1
})
tempTokenStartIndex = wordEndIndex[i] + 1
if len(source_pass) > (wordEndIndex[len(wordEndIndex) - 1] + 1):
tempToken = source_pass[wordEndIndex[len(wordEndIndex)-1]+1:len(source_pass)]
tokensToSort.append({
"content": tempToken,
"start_index": wordEndIndex[len(wordEndIndex) - 1],
"end_index": len(source_pass) - 1
})
for tokenBeingSorted in tokensToSort:
if tokenBeingSorted["content"].isalpha() or tokenBeingSorted["content"].isdigit() or isOnlySpecialCharacters(tokenBeingSorted["content"]) or len(tokenBeingSorted["content"])==1:
tokensToClassify.append({
"content": tokenBeingSorted["content"],
"start_index": tokenBeingSorted["start_index"],
"end_index": tokenBeingSorted["end_index"]
})
else:
tempTokenBeingSorted = tokenBeingSorted["content"][0]
tempStartIndex = tokenBeingSorted["start_index"]
for chars in range(len(tokenBeingSorted["content"]) -1):
if classifyCharacter(tokenBeingSorted["content"][chars]) == classifyCharacter(tokenBeingSorted["content"][chars+1]):
tempTokenBeingSorted+=(tokenBeingSorted["content"][chars+1])
else:
tokensToClassify.append({
"content": tempTokenBeingSorted,
"start_index": tempStartIndex,
"end_index": tempStartIndex + len(tempTokenBeingSorted) - 1
})
tempStartIndex += len(tempTokenBeingSorted)
tempTokenBeingSorted = tokenBeingSorted["content"][chars+1]
tokensToClassify.append({
"content": tempTokenBeingSorted,
"start_index": tempStartIndex,
"end_index": tempStartIndex + len(tempTokenBeingSorted) - 1
})
for token in tokensToClassify:
unclassifiedToken = token["content"]
classification = classifier(unclassifiedToken)
if classification not in tokenInfo["tokens"]:
tokenInfo["tokens"][classification] = []
tokenInfo["tokens"][classification].append({
"content": unclassifiedToken,
"start_index": token["start_index"],
"end_index": token["end_index"]
})
return tokenInfo
def classifyHoneywords(honeywords):
"""
Accepts an array of honeywords. Sorts through the array through the password_leaner to remove LEET speak,
divides remaining word in tokens,
classifies relevant tokens,
counts the number of patterns in each honeyword,
returns the index of the honeyword with the highest number of patters or -1 if there is no maximum.
"""
classifiedHoneywords = []
valueOfPatternsInHoneywords = []
for honeyword in honeywords:
modifiedHoneyword = password_leaner(honeyword)
classifiedHoneywords.append(tokeniser(modifiedHoneyword))
typesOfPatterns = ["words", "same_sequence_letters", "sequence_letters",
"same_sequence_numbers", "sequence_numbers",
"even_numbers", "odd_numbers",
"same_sequence_specialchars"]
for tokenized_honeyword in classifiedHoneywords:
valueOfPatterns = 0
for token_type in tokenized_honeyword["tokens"].keys():
if token_type in typesOfPatterns:
for token in tokenized_honeyword["tokens"][token_type]:
valueOfPatterns += 1
valueOfPatternsInHoneywords.append(valueOfPatterns)
max_value = max(valueOfPatternsInHoneywords)
result = [i for i, j in enumerate(valueOfPatternsInHoneywords) if j ==
max_value]
if len(result) > 1:
return -1
else:
return result[0]
|
49396cb15582f4ad0ce3df93fa78360e167849cd | uniqstha/PYTHON | /Area of circle.py | 125 | 4.03125 | 4 | r=float(input("Enter radius"))
a= 3.14*r**2
p= 2*3.14*r
print (f"Area of circle is {a}")
print(f"Perimeter of circle is {p}") |
58cf95567369f215e445c1196a4076de3b2d3055 | 13323106900/1python-diyigeyue | /14day/手机号.py | 337 | 3.8125 | 4 | def check_phone(phone):
if phone.starteswith("1") and len(phone)==11:
return True
else:
return False
phone = input("请输入手机号")
result=check_phone(phone)
if result == False:
print("手机号是错的")
phone2=input("请输入手机号")
result =check_phone(phone2)
if result ==False:
print("手机号是错的")
|
df15540b753316563d8912ffac1f1fff3e67de06 | oghusky/DV_Study_Hall_Monday | /lamdas_and_oop/nestedFuncs.py | 2,458 | 4.5 | 4 | # define a function in simple words
# what are functions used for
# what is the difference between a parameter and an argument
# how many times can you use a function in a program
# what is the difference between print() and return
# ==================CHALLENGE
# Write a function that on "run" asks you for input on a language
# That language can either be Javascript or Python
# if the user enters one answer it runs another function
# else if they answer another way it run a different function
# if they dont answer correctly if gives them an error and runs the first function again
# ======================
# inside these two nested functions prompt the user to answer which job title do they want to take with that language
# give them two choices for each possibility
# if they enter one answer print them out a sentence saying something similar to
# ---- "You should learn <this> and <this> to be a <job title> using <original input from original function>"
# else if they don't enter one of the chosen options print out their error and run the program from the beginning
# without having to stop it and press the "run" button again
def langKnown():
chosen_lang = input("What language are you learning? ")
if (chosen_lang == "Python"):
data_sci(chosen_lang)
elif (chosen_lang == "JS"):
web_dev(chosen_lang)
else:
print("Choose Python or JS")
langKnown()
def data_sci(lang):
choose_path = input("Which path? Data Scientist or Data Analyst? ")
if (choose_path == "Data Scientist"):
print(
f"You should learn SciKit Learn with {lang} to be a {choose_path}")
elif (choose_path == "Data Analyst"):
print(
f"You should learn Pandas and MatPlotLib with {lang} to be a {choose_path}")
else:
print(
f"Choose either Data Scientist or Data Analyst I'm not sure what {choose_path} is.")
langKnown()
def web_dev(lang):
choose_path = input("Which path? Front End or Back End? ")
if (choose_path == "Front End"):
print(
f"You should learn HTML CSS and React with {lang} to be a {choose_path} developer.")
elif (choose_path == "Back End"):
print(
f"You should learn C#, Java, or NodeJS with {lang} to be a {choose_path} developer")
else:
print(
f"Choose either Front End or Back End I'm not sure what {choose_path} is.")
langKnown()
langKnown()
|
54ce3fc26077c7b3d1aa4890532b1358d252271a | hehuanshu96/PythonWork | /dailycoding/python_UI/ComplicatedHello.py | 3,124 | 3.53125 | 4 | """
Hello World, but with more meat.
更复杂一点的helloworld
"""
import wx
class HelloFrame(wx.Frame):
"""
A Frame that says Hello World
一个框架,显示hello world,还有其他的一些功能
"""
def __init__(self, *args, **kw):
# 调用父类(wx.Frame)的__init__函数
super(HelloFrame, self).__init__(*args, **kw)
# create a panel in the frame
pnl = wx.Panel(self)
# and put some text with a larger bold font on it
st = wx.StaticText(pnl, label="Hello World!", pos=(25, 25))
font = st.GetFont()
font.PointSize += 10
font = font.Bold()
st.SetFont(font)
# create a menu bar
self.make_menu_bar()
# and a status bar
self.CreateStatusBar()
self.SetStatusText("Welcome to wxPython!")
def make_menu_bar(self):
"""
A menu bar is composed of menus, which are composed of menu items.
This method builds a set of menus and binds handlers to be called
when the menu item is selected.
定义菜单栏:菜单名和与之绑定的事件
"""
'''File menu包括hello item和exit item'''
# Make a file menu with Hello and Exit items
file_menu = wx.Menu()
# The "\t..." syntax defines an accelerator key that also triggers
# the same event
hello_item = file_menu.Append(-1, "&Hello...\tCtrl-H",
"Help string shown in status bar for this menu item")
file_menu.AppendSeparator()
# When using a stock ID we don't need to specify the menu item's label
exit_item = file_menu.Append(wx.ID_EXIT)
'''help menu包括about item'''
# Now a help menu for the about item
help_menu = wx.Menu()
about_item = help_menu.Append(wx.ID_ABOUT)
# Make the menu bar and add the two menus to it. The '&' defines
# that the next letter is the "mnemonic" for the menu item. On the
# platforms that support it those letters are underlined and can be
# triggered from the keyboard.
menu_bar = wx.MenuBar()
menu_bar.Append(file_menu, "&File")
menu_bar.Append(help_menu, "&Help")
# Give the menu bar to the frame
self.SetMenuBar(menu_bar)
# Finally, associate a handler function with the EVT_MENU event for
# each of the menu items. That means that when that menu item is
# activated then the associated handler function will be called.
self.Bind(wx.EVT_MENU, self.on_hello, hello_item) # args:事件类型,事件,绑定对象
self.Bind(wx.EVT_MENU, self.on_exit, exit_item)
self.Bind(wx.EVT_MENU, self.on_about, about_item)
def on_exit(self, event):
"""Close the frame, terminating the application."""
self.Close(True)
def on_hello(self, event):
"""Say hello to the user."""
wx.MessageBox("Hello again from wxPython")
def on_about(self, event):
"""Display an About Dialog"""
wx.MessageBox("This is a wxPython Hello World sample",
"About Hello World 2",
wx.OK | wx.ICON_INFORMATION)
if __name__ == '__main__':
'''1. 创建一个app对象'''
app = wx.App()
'''2. 创建一个frame框架,
看来重点在这里'''
frm = HelloFrame(None, title='Hello World 2')
'''3. 显示frame框架'''
frm.Show()
'''4. 启动app对象'''
app.MainLoop()
|
c98ad559369734cb6c85e5de9b38a8a134240c6c | thxa/test_python | /python_beyond_basics/Exceptions_and_Errors/median.py | 807 | 4.125 | 4 | def median(iterable):
"""Obtain the central value of a series
Sorts the iterable and returns the middle value if there is an even
number of elements, or the arithmetic mean of the middle two elements
if there is an even number of elements.
Args:
iterable: A series of orderable items.
Returns:
The median value.
"""
items = sorted(iterable)
median_index = ((len(items) - 1 ) // 2)
if len(items) == 0:
raise ValueError("median() arg is empty sequence")
if len(items) % 2 != 0:
return items[median_index]
return (items[median_index] + items[median_index + 1]) / 2.0
def main():
try:
print(median([5, 2, 1, 4, 3]))
print(median([5, 2, 1, 4, 3, 6]))
print(median([]))
except ValueError as e:
print("Payload:", e.args)
print(str(e))
if __name__ == '__main__':
main() |
78591e455550a1bf25df27e7d74d533fb39b43c2 | cfan-guo/ECE422-Homework | /PS12/PS12Q7.py | 353 | 3.828125 | 4 | # Question 7
from math import *
R_earth = 6378e3
R_orb = 250e3
R_total = R_earth + R_orb
mu = 3.986e14 # Nm^2/kg
T = (2*pi*(R_total)**(3/2.0))/sqrt(mu)/60 # period in minutes, decimal
T_sec = int((T-int(T))*60)
T_min = int(T)
print("Orbital period: "+str(T_min)+" min "+str(T_sec)+" sec")
v = sqrt(mu/R_total)
print("Velocity: "+str(v*10**-3)+"km/s")
|
0967ab047577706f4295a338ad59e727261f2b97 | ewartj/cs50_2020 | /week6/mario.py | 990 | 3.90625 | 4 | from cs50 import get_int
def main():
while True:
# this do/wile loop from https://cs50.stackexchange.com/questions/32589/cs50-pset6-cash-py-not-returning-number-of-coins-used-for-change
# https://www.reddit.com/r/cs50/comments/7tcnok/pset_6_need_help_with_mariopy_more_comfortable/
user_input = input("Please give a height?\n")
height = int(user_input) if user_input and user_input.isdigit() else -1
if not height:
print("Invalid number range.")
if str(height).isalpha():
print("Invalid number range.")
elif not int(height) in range (1,9):
print("Invalid number range.")
elif int(height) >= 1 and int(height) <= 8:
break
mario(int(height))
def mario(n):
for i in range(n + 1):
hashes = n - (n - i)
spaces = n - i
print(" " * spaces, end= "")
print("#" * hashes, end= "")
print(" ", end= "")
print("#" * hashes)
main() |
d29a5e9173eab6aa1205a6b48be468efdd4f0b51 | bulue94/Game | /game_what_is_your_quest.py | 6,599 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 17:52:46 2018
@author: chase.kusterer
"""
"""
DocString:
A) Introduction:
This game is based on the movie Monty Python and the Holy Grail
(1975). It consists of three stages, and also has defined functions
for start, win, and lose. This game requires honesty, and having a
small amount of knowledge from the movie will be helpful.
Round 1: Decide whether or not to approach the bridge.
Round 2: Cross the Bridge of Death
Round 3: Defeat the Black Knight
B) Known Bugs and/or Errors:
None.
"""
from sys import exit
import random
def start():
print("""
As you start on your journey, you see a bridge in the
distance. It stretches over a furious volcano. You need to
cross it in order to continue your quest for the Holy Grail.
""")
input("<Press enter to continue>\n")
starting_path()
def starting_path():
print("""
As the leader of the quest, what would you like to do?
1) approach the bridge.
2) rest here an decide later.
3) run away!
""")
choice = input("> \n")
if "1" in choice or "approach" in choice or "bridge" in choice:
print("\nYou're off to the bridge!\n")
input("<Press enter to continue>\n")
bridge_area()
elif "2" in choice or "rest" in choice or "later" in choice:
print("""\nNow that you're rested, what would you like to do?.""")
input("<Press enter to continue>\n")
starting_path()
elif "3" in choice or "run" in choice:
print("\nWell I guess the quest is over. Good-bye!")
exit(0)
else:
print("Invalid command. Please try again.")
input("<Press enter to continue>\n")
starting_path()
def bridge_area():
print("""
As you're about to start crossing the bridge, a wizard cuts
in front of you and shouts:
"STOP. Who would cross the Bridge of Death must answer me
these questions three, ere the other side he see."
In this, you must truthfully answer three questions.
""")
question_list = ['What... is your name?',
'What... is your quest?',
'What... is your favorite color?',
'What... is the capital of Assyria?',
'What... is the air-speed velocity of an unladen swallow?']
questions = 3
while questions > 0:
question = random.choice(question_list)
input("<Press enter for your question>\n")
print(question)
print(" ")
if question == question_list[0]:
print("You can input anything and you're ok.")
name = input("Your name: \n")
print(f"WIZARD: Nice to meet you {name}!")
questions -=1
elif question == question_list[1]:
print("1) I am on a quest for the Holy Grail")
print("2) I am NOT on a quest for the Holy Grail.")
print("3) I forgot.")
quest = input("> \n")
if quest == '1':
print("Thanks for letting me know. It's kind of lonely guarding this bridge all the time.\n")
questions -=1
else:
print("You fly high into the air and land in the volcano.")
fail()
elif question == question_list[2]:
print("You can choose any primary color.\n")
color = input("> \n")
color = color.lower()
if 'red' in color or 'blue' in color or 'yellow' in color:
print("WIZARD: I like that color too!\n")
questions -=1
else:
print("WIZARD: What? That's not a primary color!")
print("You fly high into the air and land in the volcano.\n")
fail()
elif question == question_list[3]:
print("1) Keep silent until the wizard gets bored.")
print("2) Try to guess.\n")
guess = input("> \n")
if '1' in guess or 'silent' in guess or 'bored' in guess:
print("WIZARD: Ok, ok, I will give you a freebie.\n")
questions -= 1
elif '2' in guess or 'try' in guess or 'guess' in guess:
input("Your guess: \n")
print("WIZARD: Ha! I made that place up!")
print("You fly high into the air and land in the volcano.")
fail()
elif question == question_list[4]:
print("1) 62.3 meters per second")
print("2) 63.2 meters per second")
print("3) What do you mean? An African or European swallow?\n")
swallow = input("> \n")
if '1' in swallow or '62.3' in swallow or '2' in swallow or '63.2' in swallow:
print("You fly high into the air and land in the volcano.")
fail()
elif '3' in swallow or 'African' in swallow or 'European' in swallow:
print("WIZARD: Huh? I... I don't know that.")
print("WIZARD: Ahhhhhh.\n")
print("The wizard flies into the volcano and you are free to pass.")
break
print("You made it across the Bridge of Death!\n")
input("<Press enter to continue>\n")
black_knight()
def black_knight():
print("""
You are across the bridge and on your way to the Holy Grail when the
Black Knight pops out to challenge you.
""")
print("What do you do?")
print("1) Attack with your sword")
print("2) Run away!")
knight = input("> \n")
if '1' in knight or 'attack' in knight or 'sword' in knight:
print("You attack with your sword and cut the Black Knight's arm off.")
print("The black night yells: 'Tis but a scratch' and runs away.\n")
input("<Press enter to continue>\n")
grail()
elif '2' in knight or 'run' in knight:
print('You end up back at the bridge.')
bridge_area()
def grail():
print("""
You have completed your quest for the Holy Grail! Great job!
""")
input("<Press enter to exit, you champion!>\n")
exit(0)
def fail():
print('\nYou have failed in your quest for the Holy Grail.')
input('<Game Over>')
exit(0)
start()
|
1944e0318d7908f1f364e31e7de933d0c224a954 | codename1995/LeetCodeHub | /python/34. Find First and Last Position of Element in Sorted Array.py | 2,037 | 3.828125 | 4 | import math
class Solution:
def searchRange(self, nums, target):
# INPUT: nums: List[int], target: int
# OUTPUT: the position of first target number.
def leftBound(nums, target):
# return the number of elements that less than target
l = 0
r = len(nums) # right open interval
while (l < r):
m = l + (r - l) // 2
if (nums[m] == target):
r = m # tighten the right border
elif (nums[m] < target):
l = m + 1
elif (nums[m] > target):
r = m
# return l
# Use following code to return -1 when target does NOT exist
if (l==len(nums)): return -1
return l if nums[l]==target else -1
# INPUT: nums: List[int], target: int
# OUTPUT: the position of last target number.
def rightBound(nums, target):
# return the number of elements that <= target
l = 0
r = len(nums) # right open interval
while (l < r):
m = l + (r - l) // 2
if (nums[m] == target):
l = m + 1 # tighten the left border
elif (nums[m] < target):
l = m + 1
elif (nums[m] > target):
r = m
# return l - 1 # left -1
# Use following code to return -1 when target does NOT exist
if (l==0): return -1
return l-1 if nums[l-1]==target else -1
le = leftBound(nums, target)
ri = rightBound(nums, target)
return [le, ri]
import time
start = time.clock()
nums = [5,7,7,8,8,10]
target = 8
ExpectOutput = [3, 4]
solu = Solution() # 先对类初始化,才能进行调用
temp = solu.searchRange(nums, target)
if (temp == ExpectOutput):
print('right')
else:
print('wrong')
print(temp)
elapsed = (time.clock() - start)
print("Time used:", elapsed)
|
b36503282926d73cabe8f8d0a9fa312484b25f4f | nhforman/MicromouseSimulator | /algorithm/search.py | 3,338 | 3.859375 | 4 | from stack import Stack
from robot_wrapper import Robot, Direction
from maze import Maze, Neighbors, Square
class Move:
def __init__(self, current_x, current_y, direction):
self.x = current_x + (direction % 2) * (direction - 2)
self.y = current_y + ((direction % 2)-1) * (direction - 1)
self.parent_x = current_x
self.parent_y = current_y
self.direction = direction
def get_relative_move(relative_direction, current_direction):
retval = current_direction + relative_direction
retval %= 4
return retval
def create_current_square(robot):
current_direction = robot.get_direction()
front, left, right = not robot.get_front(), not robot.get_left(), not robot.get_right()
if current_direction == Direction.up:
neighbors = Neighbors(front, left, True, right)
elif current_direction == Direction.left:
neighbors = Neighbors(right, front, left, True)
elif current_direction == Direction.down:
neighbors = Neighbors(True, right, front, left)
elif current_direction == Direction.right:
neighbors = Neighbors(left, True, right, front)
return Square(robot.x, robot.y, neighbors)
def add_move(move, stack, maze):
if (move.x, move.y) in maze.squares:
return False
else:
#print('Adding move from ({}, {}) to ({}, {})'.format(move.parent_x, move.parent_y, move.x, move.y))
stack.add(move)
return True
def add_moves(robot, stack, maze):
current_direction = robot.get_direction()
x = robot.get_x()
y = robot.get_y()
valid_moves = False
if not robot.get_front():
direction = get_relative_move(Direction.up, current_direction)
#print('Front open at ({}, {}) in direction {}'.format(x, y, direction))
move = Move(x, y, direction)
add_move(move, stack, maze)
valid_moves = True
if not robot.get_left():
direction = get_relative_move(Direction.left, current_direction)
#print('Left open at ({}, {}) in direction {}'.format(x, y, direction))
move = Move(x, y, direction)
add_move(move, stack, maze)
valid_moves = True
if not robot.get_right():
direction = get_relative_move(Direction.right, current_direction)
#print('Right open at ({}, {}) in direction {}'.format(x, y, direction))
move = Move(x, y, direction)
add_move(move, stack, maze)
valid_moves = True
return valid_moves
def move_valid_from_square(move, square):
return square.x == move.parent_x and square.y == move.parent_y
def search(robot):
maze = Maze()
to_be_explored = Stack()
backtrace_directions = Stack()
current_square = create_current_square(robot)
current_square.neighbors.bottom = False
add_moves(robot, to_be_explored, maze)
maze.add_square(current_square, robot.x, robot.y)
while to_be_explored.size() > 0:
current_move = to_be_explored.pop()
if (current_move.x, current_move.y) in maze.squares:
continue
while not move_valid_from_square(current_move, current_square):
back_move = backtrace_directions.pop()
robot.rotate_to_direction(get_relative_move(Direction.down, back_move.direction))
robot.move_forward()
current_square = create_current_square(robot)
robot.rotate_to_direction(current_move.direction)
robot.move_forward()
backtrace_directions.add(current_move)
current_square = create_current_square(robot)
add_moves(robot, to_be_explored, maze)
maze.add_square(current_square, robot.x, robot.y)
maze.link_squares()
return maze
|
9f19fbb7cdcde22519a7512f3d1da0bb812471c7 | abilalakin/Project-Euler | /q4-Largest palindrome product/palindrome.py | 326 | 3.796875 | 4 | def isPalindrome (pal):
return str(pal) == str(pal)[::-1]
def largest ():
maxPal = 999999
minPal = 100000
print ("abc")
for i in range(maxPal,minPal,-1):
if isPalindrome(i):
#print (i)
for j in range(100,1000):
if i % j == 0:
div = int(i / j)
if len(str(div)) == 3:
#print (i)
return i |
965898dab26ae99a0ea65a052b28302d427e260c | nag-sa/testpython | /exam/q6.py | 271 | 4.53125 | 5 | #Write a program to find whether a string is pallindrome or not. The output should be true/false.
#kanak
#str = input("Enter string: ")
str = "hello"
print(str)
str1 = str[::-1]
print(str1)
if str == str1:
print("pallindrom")
else:
print("not pallindrom")
|
ff61d8820400382c2afb5abb168c38ef6956fa34 | shuchenWu/git_ | /src/matrix_mul.py | 816 | 4.0625 | 4 |
# 没有必要,但是可以,just for practicing iterators
from operator import mul
from itertools import tee, islice
class Matrix(object):
def __init__(self, values):
self.values = values
def __repr__(self):
return f'<Matrix values="{self.values}">'
def __matmul__(self, other):
x = zip(*(row for row in other.values))
y = (sum(mul(*item) for item in zip(row, col)) for col in x for row in self.values)
z = (islice(y_out, idx, None, len(self.values)) for idx, y_out in enumerate(tee(y, len(self.values))))
return Matrix([list(i) for i in z])
if __name__ == '__main__':
m1 = Matrix([[11, 12], [13, 14], [15, 16]])
m2 = Matrix([[1, 2, 3], [4, 5, 6]])
m3 = m1 @ m2
assert m3.values == [[59, 82, 105], [69, 96, 123], [79, 110, 141]] |
74214e35c8b9d0d63cafcd1463d02aabb800e1ed | Roy-Gal-Git/TicTacToe | /algo.py | 1,670 | 3.625 | 4 | def checkWinner(positionsDict):
keysList = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
diagX = [0, 0]
diagO = [0, 0]
rowX = [0, 0, 0]
rowO = [0, 0, 0]
colX = [0, 0, 0]
colO = [0, 0, 0]
for i in range(len(keysList)):
# Check if there are 3 of the same char in the first diagonal
if positionsDict[keysList[i][i]] == 'X':
diagX[0] += 1
elif positionsDict[keysList[i][i]] == 'O':
diagO[0] += 1
# Check if there are 3 of the same char in the second diagonal
if positionsDict[keysList[len(keysList[i]) - 1 - i][i]] == 'X':
diagX[1] += 1
elif positionsDict[keysList[len(keysList[i]) - 1 - i][i]] == 'O':
diagO[1] += 1
for j in range(len(keysList)):
# Check if there are 3 of the same char in the same row
if positionsDict[keysList[i][j]] == 'X':
rowX[i] += 1
elif positionsDict[keysList[i][j]] == 'O':
rowO[i] += 1
# Check if there are 3 of the same char in the same column
if positionsDict[keysList[j][i]] == 'X':
colX[i] += 1
elif positionsDict[keysList[j][i]] == 'O':
colO[i] += 1
for val in diagX:
if val == 3:
return 'X'
for val in diagO:
if val == 3:
return 'O'
for val in rowX:
if val == 3:
return 'X'
for val in rowO:
if val == 3:
return 'O'
for val in colX:
if val == 3:
return 'X'
for val in colO:
if val == 3:
return 'O'
|
5f1f0e17e67ad738caca77d6fbc2599d4939abb9 | barassah/File-Handling-in-Python | /F_handling.py | 1,232 | 4.53125 | 5 | #File Handling in python
#creating and deleting
import os
#checking if file exists before creating
if os.path.exists('text.txt'):
#print('File Exist!')
#inquire overwrite or append content
#prompt for over witing of file contents
i=input('Overwrite file? y/n: ')
if i!='n':
myfile = open('text.txt', 'w')
#appending text to be done
myfile.write('Hello there, added Content!')
myfile.close()
else:
myfile = open('text.txt', 'a')
#appending text to be done
myfile.write('\nHello there, New Content!')
myfile.close()
else:
#print('File Doesn\'t Exist')
#create a new and opening the file to append new content
myfile = open('text.txt', 'a')
#appending text to be done
myfile.write('Hello there, New Content!')
#close file
myfile.close()
#open and read file created
myfile=open('text.txt','r+')
#read one line using the readdline function
#print(f.readline())
#Read and display the entire content in the text file
for x in myfile:
print(x)
#close the file
myfile.close()
#prompt for deletion of file
d=input('Delete File? y/n: ')
if d!='n':
# use system defined remove function
os.remove('text.txt')
print('File Deleted')
else:
print('File Not Deleted')
|
56d5b4e0478444fe850eade7826d9245b9225548 | azafrob/fin-model-course | /fin_model_course/lectures/start_python_excel/notes.py | 6,289 | 3.84375 | 4 | from lectures.model import LectureNotes, Lecture, LectureResource
from resources.models import RESOURCES
def get_intro_and_problem_lecture() -> Lecture:
title = 'Introduction and an Example Model'
youtube_id = 'KL48T_XGbzI'
week_covered = 1
notes = LectureNotes([
'In the beginning of the course, we will do everything with both Excel and Python to understand '
'the differences. Later we will focus on choosing the best tool for the task at hand and '
'the ability to combine the two tools.',
'Everyone should know how to solve this simple time-value of money investment problem',
'Many would think to reach for a financial calculator and use the five keys',
'Or to directly type some values into the =NPER function in Excel',
'With either of these approaches, you are doing a calculation rather than building a model',
'If you realize you need to adjust the inputs, you need to do the calculation again',
'With a model, the calculations are linked from the inputs to the outputs, so changing the '
'inputs changes the outputs. This increases reproducibility and efficiency.'
], title=title)
return Lecture(title, week_covered, notes, youtube_id=youtube_id)
def get_excel_solution_lecture() -> Lecture:
title = 'Building a Simple Excel Model'
youtube_id = 'hySE7wOAlfc'
week_covered = 1
notes = LectureNotes([
'It is crucial that all your Excel calculations are linked together by '
'cell references. If you hard-code values in your calculations you are '
'just using Excel as a calculator.',
'It is important to visually separate the inputs from the outputs. This makes '
'it much more clear for the consumer of your model, especially in more complex models',
'More complex models should be broken into multiple sheets with each sheet dedicated to a concept or '
'calculation',
'Cell formatting can be used in combination with the layout to separate them',
'For small models, intermediate outputs/calculations may be kept in the outputs section, while '
'for larger models it makes sense to have separate calculation sections'
], title=title)
resources = [
RESOURCES.examples.intro.excel.simple_retirement_model,
]
return Lecture(title, week_covered, notes, youtube_id=youtube_id, resources=resources)
def get_python_solution_lecture() -> Lecture:
title = 'Building a Simple Python Model'
youtube_id = 'syrwXU1wqps'
week_covered = 1
notes = LectureNotes([
'In Python, we keep things linked together by using variables. If you hard-code values in '
'your calculations, you are just using Python as a calculator',
'Basic math in Python is mostly what you might expect, it is the same as Excel only exponents '
'are specified by ** and not ^',
'Jupyter allows us to create an interactive model complete with nicely formatted text, '
'equations, tables, graphs, etc. with relative ease',
'Inputs should be kept at the top in a separate section, the main outputs should be kept '
'at the bottom in a separate section. ',
'More complex models should be broken into sections and subsections with sections dedicated to a concept or '
'calculation',
], title=title)
resources = [
RESOURCES.examples.intro.python.simple_retirement_model,
]
return Lecture(title, week_covered, notes, youtube_id=youtube_id, resources=resources)
def get_basic_iteration_lecture() -> Lecture:
title = 'Basic Iteration'
youtube_id = 'vAOrxaKnXaQ'
week_covered = 1
notes = LectureNotes([
'Iteration is a key concept in financial modeling (as well as programming)',
'Using iteration, we can complete the same process for multiple inputs to '
'yield multiple outputs',
'As the same process is applied to each input, the process only needs to be '
'created once and any updates to the process can flow through all the inputs'
'Iteration can be internal or external to the main model. You can use iteration '
'within your model, or you can iterate the model itself',
'To iterate in Excel, drag formulas. To iterate in Python and other '
'programming languages, use loops.',
], title=title)
return Lecture(title, week_covered, notes, youtube_id=youtube_id)
def get_excel_extending_lecture() -> Lecture:
title = 'Extending a Simple Excel Model'
youtube_id = 'GD34LyjvMaE'
week_covered = 1
notes = LectureNotes([
'Essentially the model with iteration is the same, we just drag the formula to '
'cover multiple inputs',
'It is crucial to set up fixed and relative cell references appropriately before you drag formulas'
], title=title)
return Lecture(title, week_covered, notes, youtube_id=youtube_id)
def get_python_extending_lecture() -> Lecture:
title = 'Extending a Simple Python Model'
youtube_id = 'Ejk6ektd21I'
week_covered = 1
notes = LectureNotes([
'To add iteration to the Python model, just wrap the existing code in a loop',
'We must also collect or show the output in some way, as we can no longer take advantage '
'of the Jupyter shortcut to show the output without printing.',
], title=title)
return Lecture(title, week_covered, notes, youtube_id=youtube_id)
def get_lab_exercise_lecture() -> Lecture:
title = 'Getting Started with Python and Excel Labs'
youtube_id = '2J-GCwSNGBw'
week_covered = 1
notes = LectureNotes([
'This is our first real lab exercise (must be submitted). Be sure to complete the same exercise in '
'both Python and Excel',
'We often want to iterate over more than one input. Here we want to look at the pairwise combinations '
'of the savings rate and interest rate possibilities.',
'Excel hint: there is a nice way to lay this out so you only need to type the formula a single time',
'Python hint: It is possible to nest loops to loop over the combination of two different inputs',
], title=title)
return Lecture(title, week_covered, notes, youtube_id=youtube_id)
|
2fe53ed2538c82ac5cb5c9d95c1f74114aa20435 | srinidhik/pycharm_projects | /srinidhi/PycharmProjects/OOP/vehicle2.py | 1,887 | 4.03125 | 4 | class Vehicle(object):
vehicleType = ""
vehicleColor = ""
def __init__(self,type,color):
self.vehicleType = type
self.vehicleColor = color
def get_no_of_wheels(self):
pass
class Car(Vehicle):
vehicleWheels = 4
def __init__(self,type,color):
Vehicle.__init__(self,type,color)
def get_no_of_wheels(self):
return self.vehicleWheels
class Bus(Vehicle):
vehicleWheels = 6
def __init__(self,type,color):
Vehicle.__init__(self,type,color)
def get_no_of_wheels(self):
return self.vehicleWheels
class Aeroplane(Vehicle):
vehicleWheels = 7
def __init__(self,type,color):
Vehicle.__init__(self,type,color)
def get_no_of_wheels(self):
return self.vehicleWheels
class Ship(Vehicle):
vehicleWheels = 0
def __init__(self,type,color):
Vehicle.__init__(self,type,color)
def get_no_of_wheels(self):
return self.vehicleWheels
class CustomVehicle(Car,Bus,Aeroplane,Ship):
def __init__(self,type,color):
Car.__init__(self,type,color)
Bus.__init__(self, type, color)
Aeroplane.__init__(self, type, color)
Ship.__init__(self, type, color)
def get_no_of_wheels(self):
if super(CustomVehicle,self).get_no_of_wheels() == 4:
print("Car")
elif super(CustomVehicle, self).get_no_of_wheels() == 6:
print("Bus")
elif super(CustomVehicle, self).get_no_of_wheels() == 7:
print("Aeroplane")
elif super(CustomVehicle, self).get_no_of_wheels() == 0:
print("Ship")
else:
print "..........."
c1 = CustomVehicle("land","red")
c1.get_no_of_wheels()
c2 = CustomVehicle("land","red")
c2.get_no_of_wheels()
c3 = CustomVehicle("air","red")
c3.get_no_of_wheels()
c4 = CustomVehicle("sea","red")
c4.get_no_of_wheels() |
5e49edfa627e7d8ce6841a2cc8c2ee34b8793a39 | qiujiandeng/- | /python1基础/day03/Code/get-max-number2.py | 1,044 | 3.953125 | 4 | # 2.写程序,任意给出三个数,打印出三个数中最大的一个数
#laoshi
a = int(input("请输入第一个数:"))
b = int(input("请输入第一个数:"))
c = int(input("请输入第一个数:"))
#改进算法:
#先假设第一个最大,用变量绑定
#进了西瓜地,看到第一个西瓜拿起来,看到第二个西瓜比第一个大,把第一个扔掉拿第二个,...第三个
zuida = a #zuida等于手,a等于第一个西瓜
if b >zuida: #第二个比手里的大,扔掉手里的,把第二个拿到手里,手上等于第二个西瓜
zuida = b
if c >zuida:
zuida = c
print("最大数式:",zuida)
# if a > b:
# #a 和 c 在比
# if a > c:
# print("最大数是",a)
# # if a > d:
# # ........
# # else:
# # ..... 下面也是
# else:
# print("最大数是",c)
# else:
# # b 和 c 再比
# if b > c:
# print("最大数是",b)
# else:
# print("最大数是",c) |
06d4824980ba599577cf110951d659521fef489e | Skluchnik/homework | /HW-03&04/Lesson-03-2-print.py | 216 | 3.84375 | 4 | #Каждый пишет сумму списка при помощи for и while
L = [3, 5, 1]
sum = 0
index = 0
list_last_index = len(L)
while (index < list_last_index):
sum += L[index]
index += 1
print(sum) |
e46d24f37a441740d591d5212a24addd93e27e5b | dbconfession78/interview_prep | /leetcode/102_binary_tree_level_order_traversal.py | 1,408 | 4.0625 | 4 | # Instructions
"""
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
retlst = []
if root is None:
return retlst
stk = [root]
while stk:
_len = len(stk)
lvl = []
for i in range(_len):
_this = stk.pop(0)
lvl.append(_this.val)
for x in (_this.left, _this.right):
if x:
stk.append(x)
retlst.append(lvl)
return retlst
def print_solution(lst):
for row in lst:
print(row)
def main():
root = None
print_solution(Solution().levelOrder(root))
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.right = TreeNode(7)
root.right.left = TreeNode(15)
print_solution(Solution().levelOrder(root))
# LC input
# []
#
if __name__ == '__main__':
main() |
d721aa5dacf72ae27bfee1bf10db80e774982ba4 | zhou-jia-ming/leetcode-py | /problem_105.py | 947 | 3.59375 | 4 | # coding:utf-8
# Created by: Jiaming
# Created at: 2020-03-20
# 根据一棵树的前序遍历与中序遍历构造二叉树。
from typing import List
from utils import TreeNode, levelOrder
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder:
return None
if len(preorder) == 1:
return TreeNode(preorder[0])
root = TreeNode(preorder[0])
index = inorder.index(root.val)
left_inorder = inorder[0:index]
right_inorder = inorder[index + 1:]
left_preorder = preorder[1:index + 1]
right_preorder = preorder[index + 1:]
root.left = self.buildTree(left_preorder, left_inorder)
root.right = self.buildTree(right_preorder, right_inorder)
return root
if __name__ == "__main__":
s = Solution()
res = s.buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])
print(levelOrder(res)) |
c9139a930c31b7168d2c178b76820e9c680d5af6 | mottola/dataquest_curriculum | /python_basics/conditional_logic.py | 1,580 | 4.21875 | 4 | # USING CONDITIONAL LOGIC IN PYTHON
# BOOLEANS IN PYTHON - True False
cat = True
dog = False
print(type(cat))
print(type(dog))
print(cat)
print(dog)
# BOOLEAN OPERATORS IN PYTHON
# ___________________________
# ==
# !=
# >
# <
# >=
# <=
print(8 == 8)
print(8 != 8)
print(8 == 10)
print(8 != 10)
list = [
"The Hitchhiker's Guide to the Galaxy",
"The Restaurant at the End of the Universe",
"Life, the Universe and Everything",
"So Long, and Thanks for All the Fish",
"Mostly Harmless"
]
# PRINTS THE INDEX(i) AND THE ELEMENT(el) IN LIST
# ENUMERATE ADDS A COUNTER TO THE VARIABLE i
# i WILL START AT 0 UNLESS AN OTHERWISE STARTING INDEX IS PASSED IN WITH list
for i, el in enumerate(list):
print(i, el)
for i, el in enumerate(list, 10):
print(i, el)
for item in list:
print(item)
# BOOLEAN LOGIC AND CONDITIONAL STATEMENTS
sample_rate = 749
greater = (sample_rate > 5) # greater is assigned the True boolean
if greater:
print(sample_rate)
t = True
f = False
if t:
print('Now you see me')
if f:
print('Now you don\'t')
# NESTING if STATEMENTS
value = 5000
if value > 500:
if value > 2500:
print('This number is quite large!')
# IF STATEMENTS AND FOR LOOPS
cities = ['Seattle', 'Boulder', 'Austin', 'San Francisco', 'Washington']
counter = 0 # TRACKS HOW MANY ITEMS ARE IN THE LIST
index = 0 # TRACKS THE INDEX THAT AUSTIN WILL BE FOUND AT
found = False
for city in cities:
if city == 'Austin':
index = counter
counter += 1
print(index)
print(counter)
|
690e148f0458973434dd39a1a7ef16a9a4aac544 | he44/Practice | /leetcode/20_0808_contest/1.py | 703 | 3.515625 | 4 | from typing import *
class Solution:
def makeGood(self, s: str) -> str:
list_s = [char for char in s]
good_string = False
while not good_string:
good_string = True
n = len(list_s)
for i in range(n-1):
if list_s[i] != list_s[i+1] and list_s[i].lower() == list_s[i+1].lower():
good_string = False
list_s.pop(i)
list_s.pop(i) # after popping i, i + 1 became the new i
break
return ''.join(list_s)
cases = [
"leEeetcode",
"abBAcC",
"s"
]
sol = Solution()
for case in cases:
print(sol.makeGood(case))
|
9544f45c08c21341077c17ebd8c337854e2544cb | Iamnetis/Nitesh | /hello world.py | 99 | 3.71875 | 4 | str='Hello world !!'
print (str)
print (str[2])
print (str[2:5])
print (str*2)
print (str+ "TEST")
|
ea2b79d97f8261f344b6e6c10721af10016d939f | ytyc2k/MYCPP | /CCC/2017CCC_J1-J5.py | 2,159 | 3.515625 | 4 | # #######################################
# @ Canadian Computing Competition #
# @ Junior 2017 #
# @ Author : Jun Yang #
# @ Time : 2020-08-28 #
# #######################################
# '''
# Problem J1: Quadrant Selection
# '''
# a=int(input())
# b=int(input())
# if a > 0 and b > 0:
# print('1')
# elif a < 0 and b > 0:
# print('2')
# elif a < 0 and b < 0:
# print('3')
# else:
# print('4')
# '''
# Problem J2: Shifty Sum
# '''
# a=input()
# b=int(input())
# c=0
# for i in range(b+1):
# c=c+int(a+i*'0')
# print(c)
# '''
# Problem J3: Exactly Electrical
# '''
# a,b=input().split()
# c,d=input().split()
# e=int(input())
# a=int(a)
# b=int(b)
# c=int(c)
# d=int(d)
# distance=abs(a-c)+abs(b-d)
# if e >= distance and (e-distance)%2==0:
# print("Y")
# else:
# print("N")
# '''
# Problem J4: Favourite Times
# '''
# a=int(input())
# b1,b2,b3,b4 = 1,2,0,0
# count=0
# for i in range(a+1):
# b4=b4+1
# if b4 >= 10:
# b3 = b3 + 1
# b4=0
# if b3 >= 6:
# b2 = b2 + 1
# b3=0
# if b2 >= 3 and b1 == 1:
# b1 = 0
# b2 = 1
# if b2 >= 10:
# b1 = b1 + 1
# if b4 - b3 == b3 - b2 and b1 == 0:
# count = count + 1
# elif b4 - b3 == b3 - b2 and b3 - b2 == b2 - b1 and b1 != 0:
# count = count + 1
# print(count)
# '''
# Problem J5: Nailed It!
# '''
# import itertools
# n = int(input())
# boards = [int(x) for x in input().split()]
# boards.sort()
# maxlength, tmp, hlist, output = 0, boards.copy(), [], 0
# for i in range(n):
# tmp.pop(0)
# for j in tmp:
# if boards[i] == j and boards.count(boards[i]) // 2 > hlist.count(boards[i] + j) or tmp.count(boards[i]) == 0:
# hlist.append(boards[i] + j)
# print(hlist)
# print(tmp)
# if hlist.count(hlist[-1]) > maxlength:
# maxlength, output = hlist.count(hlist[-1]), 1
# elif hlist.count(hlist[-1]) == maxlength:
# output = output + 1
# print(maxlength)
# print(output)
# print(maxlength, output) |
18b4e8fdf1bf347edd4951f2583320d45b8635fc | Betrezen/SimpleCV2 | /SimpleCV/Display/Base/DrawingLayer.py | 12,881 | 3.703125 | 4 | from Shapes import *
from ...Color import Color
class DrawingLayer:
"""
**SUMMARY**
DrawingLayer gives you a way to mark up Image classes without changing
the image data itself.
**NOTE**
This class should be kept picklable so that the it can be sent over a Pipe
"""
#TODO
#include buffers for alpha related stuff
#look into anti aliasing in gtk
def __repr__(self):
return "<SimpleCV %s Image Resolution: (%d, %d) at memory location: (%s)>" % (self.name(), self.imgSize[0], self.imgSize[1], hex(id(self)))
def __init__(self, (width,height)) :
"""
**SUMMARY**
Initializes a drawing layer
**PARAMETERS**
* *width,height* - The dimensions of the layer
"""
self.imgSize = (width,height)
self.bold = False
self.italic = False
self.underlined = False
self.font = "Georgia"
self.fontSize = 20
self._shapes = []
def name(self):
return "DrawingLayer"
def getDefaultAlpha(self):
"""
Returns the default alpha value.
"""
#TODO I dont think this is really needed
pass
def setLayerAlpha(self, alpha):
"""
This method sets the alpha value of the entire layer in a single
pass. This is helpful for merging layers with transparency.
"""
self.alpha = alpha
def setDefaultColor(self, color):
"""
This method sets the default rendering color.
Parameters:
color - Color object or Color Tuple
"""
pass
#TODO may not be required
def line(self, start, stop, color = Color.DEFAULT, width = 1, antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw a single line from the (x,y) tuple start to the (x,y) tuple stop.
Optional parameters:
**PARAMETERS**
* *start* - The starting point of the line.
* *stop* - The ending point of the line.
* *color* - Color object or Color Tuple
* *width* - The line width in pixels.
* *antialias* - Whether of not the edges are antialiased.
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
self._shapes.append(Line(start,stop,color,width,antialias,alpha))
def lines(self, points, color = Color.DEFAULT, width = 1, antialias = True, alpha = 255):
"""
**SUMMARY**
Draw a set of lines from the list of (x,y) tuples points. Lines are draw
between each successive pair of points.
**PARAMETERS**
* *points* - a sequence of points to draw lines in between.
* *color* - Color object or Color Tuple
* *width* - The line width in pixels.
* *antialias* - Whether of not the edges are antialiased.
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
for i in range(len(points)-1):
self.line(points[i],points[i+1],color,width,antialias,alpha)
def rectangle(self, topLeft, dimensions, color = Color.DEFAULT,width = 1, filled = False,antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw a rectangle given the topLeft the (x,y) coordinate of the top left
corner and dimensions (w,h) tge width and height
**PARAMETERS**
* *topLeft* - The (x,y) coordinates of the top left corner of the rectangle
* *dimensions* - The (width,height) pf the rectangle
* *color* - Color object or Color Tuple.
* *width* - The width of the edges of the rectangle.
* *filled* - Whether or not the rectangle is filled
* *antialias* - Whether of not the edges are antialiased
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
_p1 = topLeft
_p2 = (topLeft[0]+dimensions[0],topLeft[1]+dimensions[1])
self.rectangle2pts(_p1, _p2, color, width, filled, antialias, alpha)
def rectangle2pts(self, pt1, pt2, color = Color.DEFAULT,width = 1, filled = False,antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw a rectangle given two (x,y) points
**PARAMETERS**
* *pt1* - The top left corner of the rectangle.
* *pt2* - The bottom right corner of the rectangle.
* *color* - Color object or Color Tuple.
* *width* - The width of the edges of the rectangle.
* *filled* - Whether or not the rectangle is filled
* *antialias* - Whether of not the edges are antialiased
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
self._shapes.append(Rectangle(pt1,pt2,color,width,filled,antialias,alpha))
def centeredRectangle(self, center, dimensions, color = Color.DEFAULT,width = 1, filled = False,antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw a rectangle given the center (x,y) of the rectangle and dimensions (width, height)
**PARAMETERS**
* *center* - The (x,y) coordinate of the center of the rectangle
* *dimensions* - The (width,height) of the rectangle
* *color* - Color object or Color Tuple.
* *width* - The width of the edges of the rectangle.
* *filled* - Whether or not the rectangle is filled
* *antialias* - Whether of not the edges are antialiased
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
p0 = (center[0]-dimensions[0]/2.0,center[1]-dimensions[1]/2.0)
p1 = (center[0]+dimensions[0]/2.0,center[1]+dimensions[1]/2.0)
self.rectangle2pts(p0,p1,color,antialias,width,filled,alpha)
def polygon(self, points, color = Color.DEFAULT,width = 1, filled = False,antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw a polygon from a list of (x,y)
**PARAMETERS**
* *points* - The list of (x,y) coordinates of the vertices of the polygon
* *color* - Color object or Color Tuple.
* *width* - The width of the edges of the rectangle.
* *filled* - Whether or not the rectangle is filled
* *antialias* - Whether of not the edges are antialiased
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent..
"""
self._shapes.append(Polygon(points,color,width,filled,antialias,alpha))
def circle(self, center, radius, color = Color.DEFAULT,width = 1, filled = False,antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw a circle given a location and a radius.
**PARAMETERS**
* *center* - The (x,y) coordinates of the center.
* *radius* - The radius of the circle.
* *color* - Color object or Color Tuple.
* *width* - The width of the edges of the rectangle.
* *filled* - Whether or not the rectangle is filled
* *antialias* - Whether of not the edges are antialiased
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
self._shapes.append(Circle(center,radius,color,width,filled,antialias,alpha))
def ellipse(self, center, dimensions, color = Color.DEFAULT,width = 1, filled = False,antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw an ellipse given a location and a dimensions.
**PARAMETERS**
* *center* - The coordinates of the center.
* *dimensions* - The length of axes along horizontal and vertical
* *color* - Color object or Color Tuple.
* *width* - The width of the edges of the rectangle.
* *filled* - Whether or not the rectangle is filled
* *antialias* - Whether of not the edges are antialiased
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
self._shapes.append(Ellipse(center,dimensions,color,width,filled,antialias,alpha))
def bezier(self, points, color = Color.DEFAULT,width = 1,antialias = True, alpha = 255 ):
"""
**SUMMARY**
Draw a bezier curve based on the control points
**PARAMETERS**
* *points* - Control points . You must specify 3.
* *color* - Color object or Color Tuple.
* *width* - The width of the edges of the rectangle.
* *antialias* - Whether of not the edges are antialiased
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
self._shapes.append(Bezier(points,color,width,antialias,alpha))
def text(self, text, location, color = Color.DEFAULT,size = 20,font = "",bold = False ,italic = False,underline = False, alpha = 255):
"""
**SUMMARY**
Write the a text string at a given location
**PARAMETERS**
* *text* - A text string to print.
* *location* - The location to place the top right corner of the text
* *color* - Color object or Color Tuple
* *font* - The font to be used.
* *size* - The size of letters.
* *bold* - Whether or not text is bold.
* *italic* - Whether or not text is italic.
* *underline* - Whether or not text is underlined
* *alpha* - The alpha blending for the object. A value of 255 means opaque,
while 0 means transparent.
"""
self._shapes.append(Text(text,location, color, size, font, bold, italic, underline, alpha,None))
def sprite(self,img,pos=(0,0),scale=1.0,rot=0.0,alpha=255):
"""
sprite draws a sprite (a second small image) onto the current layer.
The sprite can be loaded directly from a supported image file like a
gif, jpg, bmp, or png, or loaded as a surface or SCV image.
pos - the (x,y) position of the upper left hand corner of the sprite
scale - a scale multiplier as a float value. E.g. 1.1 makes the sprite 10% bigger
rot = a rotation angle in degrees
alpha = an alpha value 255=opaque 0=transparent.
"""
pass
def blit(self, img, coordinates = (0,0)):
"""
Blit one image onto the drawing layer at upper left coordinates
Parameters:
img - Image
coordinates - Tuple
"""
pass
def shapes(self):
"""
**SUMMARY**
Returns a list of shapes drawn on this layer
**RETURNS**
A list of shapes
"""
return self._shapes
def clear(self):
"""
**SUMMARY**
This method removes all of the drawing on this layer (i.e. the layer is
erased completely)
"""
self._shapes = []
def ezViewText(self,text,location,color = (255,255,255),size = 20,bgColor = (0,0,0)):
"""
**SUMMARY**
ezViewText works just like text but it sets both the foreground and background
color and overwrites the image pixels. Use this method to make easily
viewable text on a dynamic video stream.
**PARAMETERS**
* *text* - A text string to print.
* *location* - The location to place the top right corner of the text
* *color* - Color of the text.
* *size* - The size of letters.
* *bgColor* - The colour of the background.
"""
#TODO Maybe include all paramaters for text over here, if required
self._shapes.append(Text(text,location, color, size, "", False, False, False, 255,bgColor))
def renderToOtherLayer(self,other):
"""
Add this layer to another layer.
Parameters:
* *layer* - layer
"""
if not isinstance(other, DrawingLayer):
return "Please pass a DrawingLayer object"
shapes = self._shapes
for s in shapes:
other._shapes.append(s)
#TODO rotatedrectangle
|
beac9db2b9bd482dc933865229a84db6b5cdb5c0 | LarryStanley/mathCampClass | /wave.py | 105 | 3.796875 | 4 | while True:
n= int(input("> "))
for i in range(n,-n-1,-1):
print(" "*(i**2),"*",sep="")
|
91ac10d81b17a59776f6e1000ac8dac7f16b5f90 | FuneyYan/Python- | /hello.py | 33,858 | 3.984375 | 4 | import math
'''
name=input('please enter you username:')
print(name)
a=100
if a>=1:
print(0)
else:
print(1)
print(10.0/3.0)
print('i\' am \"ok\"!')
#字符串原样输出 \\r\\
print(r'\\r\\')
#占位符
s1=72
s2=85
r=(s2-s1)/100
print('hello,{0}成绩提升了{1:.1f}%'.format('james',r))
#占位符
print('hello,%s的成绩是%.1f' % ('james',11.22));
# 打印 Apple python lisa
list=[
["Apple","Google","Microsoft"],
["java","python","ruby","php"],
['Adam', 'Bart', 'Lisa']
]
print(list[0][0])
print(list[1][1])
print(list[2][2])
#判断语句,注意缩进
age=20
if age>=18:
print('age is ',age)
print("is adult")
else:
print("is not adult")
# elif 是else if的缩写
age=5
if age>=18:
print("is adult")
elif age<=6:
print("is kid")
else:
print("is teenager")
#在python中1是true,0是false
x=1
if x:
print("true")
#input函数接受的是字符串,需要将输入的内容强制转换成int,注意强转是int()
birth=input("birth:")
birth=int(birth)
if birth <2000:
print("夕阳红")
else:
print("00后")
#计算BMI
weight=82
height=1.7
bmi=weight/(height*height)
#print(int(math.floor(bmi)))#需要在第一行import math
bmi=int(bmi)
print(bmi)
if bmi<18:
print("过轻")
elif bmi>18 and bmi<25:
print("正常")
elif bmi>25 and bmi<32:
print("肥胖")
else:
print("超重")
#for in循环注意缩进
names = ["james","tom","jack"]
for name in names:
print(name)
#计算1-10的整数之和,注意,没有大括号,会将缩进的都看做循环体,另外也要注意冒号不能少
sum=0
for i in [1,2,3,4,5,6,7]:
sum+=i
print(sum)
#使用for+range函数计算1+100
sum=0
for i in range(101):
sum+=i
print(sum)
#while循环计算1+100
sum=0
n=1
while n<=100:
sum+=n
n+=1
print(sum)
#利用循环打印人名
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print(name)
i=0
while i<len(L) :
print(L[i])
i+=1
#continue结束本次循环
n=0
while n<10:
n+=1
if n%2==0:
continue
print(n)
#break退出循环
n=0
while n<100:
print(n)
if(n==10):
break
n+=1
print("end...")
#dict字典,键值对,类似map,字典是无序的
score={"james":89,"tom":88,"bosh":90,"bosh":99}#如果两个键一样,后面覆盖前面的
#print(score["james"])
score["james"]=99
print(score["james"])
print(score)
#判断键是否在dic中,有则返回True;或者使用get(),找不到的话为None
#print("james" in score)#True
#print(score.get("jame"))#结果是None
#删除指定键的值
#score.pop("james")
#print(score)#dic的键只能是不可变的值,比如字符串,整数;但不能是list
#直接往字典中添加数据
score={}
print(score)
score["james"]=90
print(score)
#用字典做电话本
dic={"james":"111"}
name=input("请输入联系人姓名")
if name in dic:
print("联系人已存在")
else:
phone=input("请输入联系人电话")
dic[name]=phone
print(dic)
#除了用name in dic找外还可以get()...
dic={"james":11}
if dic.get("jame"):
print("find james")
#set,存储一组键,不存值
s=set([1,2,3,4,5])
print(s)
s.add(6)#添加元素
s.add(7)
s.remove(7)#删除元素
print(s)
#set的创建方法有很多:s=({1,2,3}) s={1,2,3} s={(1,2,3)}
s1=set([1,2,3])
s2=set([2,3,4])
#两个set做交集
print(s1 & s2)
#两个set做并集
print(s1|s2)
#关于set类型的坑
s={}
print(type (s)) #dict
s={1}
print(type (s)) #set
s={1:2}
print(type (s)) #dict
s={1,2}
print(type (s)) #set
#函数
#求绝对值
print(abs(-10))
print(abs(11.23))
#求最大值(可以接收多个参数)
print(max(1,5,34,99,4))
print(max(1,54,4,9))
#数据类型转换
print(int("123"))
print(float("12.22"))
print(str(True))
print(bool(1))#True
print(bool(''))#False
#函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量(相当于js中的函数表达式)
a=abs
print(a(-1))
n1=255
print("十六进制转换%s"%(hex(n1)))
#定义函数
def myAbs(x):
if x>=0:
return x
else:
return -x
print(myAbs(-10))
a=myAbs;
print(a(-109))
#如果函数没有写return,默认会return None
def myfun():
print("myFun")
result=myfun()
print(result)#None
#利用函数,dic做电话本
phoneDic={"james":120}
phoneDic["tom"]=110
#获取所有key
#print(phoneDic.keys())
#for dict_key in phoneDic.keys():
# print(dict_key)
def startup():
print("1.save")
print("2.find")
index=int(input("chose:"))
if index==1:
save()
elif index==2:
find()
else:
startup()
def save():
name=input("please enter name : ")
if name in phoneDic:
print("person exists!")
else:
phone=input("please enter phone : ")
phoneDic[name]=phone
print("save success!")
startup()
def find():
name=input("please enter name : ")
result=phoneDic.get(name)
if result:
print(result)
else:
print("not exists")
startup()
startup()
#from cellPhone import startup #导入文件的方法(来自XX文件导入XX方法)
#startup()#调用方法
#空函数
def nop():
pass #pass表示占位符,在if中也可以使用pass,空函数如果不谢pass会报错
#参数类型判断
def myAbs(x):
if not isinstance(x,(int,float)):#如果X不是int,也不是float的话
#print("参数类型不正确")
#return
raise TypeError("参数类型不正确")
if x>=0:
print(x)
else:
print(-x)
myAbs("A")
#python函数可以返回多个值,最终多个值组成元组
def fun():
return "A","B"
result=fun()
print(result)
A,B=fun()#拿两个变量分别接受
print(A,B)
#函数默认参数
def mypower(x,n=2):#n=2是函数的默认参数,必选参数在前,默认参数在后
result=1
for i in range(1,n+1):
result*=x
return result
print(mypower(2))
def mypower(x,n=2):#n=2是函数的默认参数,必选参数在前,默认参数在后;默认参数必须指向不变对象!
result=1
for i in range(1,n+1):
result*=x
return result
print(mypower(2,n=5))
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(5,3))
def add_end(L=[]):
L.append('END')
return L
print(add_end())
print(add_end())
print(add_end())
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
print(add_end())
print(add_end())
print(add_end())
#可变参数(不定项参数)
def calc(*numbers):#如果是可变参数,参数前加*,自动组装成tuple
sum=0
for i in numbers:
sum+=i*i
print(sum)
#calc((1,2,3))#可以传list和tuple,如果是可变参数则不可用
#calc(1,2,3)
#如果非要将一个list或者tuple传递到可变参数中可以:
list=[1,2,3]
calc(*list)
#关键字参数(自动组装成dict)
def person(name,age,**kw):
print(name,age,kw)
person("james",22,city="jz")#可以不填kw
person("tom",22,gender="man")
#和list一样,先组装一个dict,然后传到函数中
myDic={"city":"beijing","job":"manager"}
person("james",22,**myDic)
#命名关键字参数(限制关键字参数的名字)
def person(name,age,*,city,job):#*后面的都会被视为关键字参数,传递时候必须 参数名="XXX"
print(name,age,city,job)
person("james",22,city="beijing",job="manager")
#如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了:
def person(name,age,*arg,city,job):#*后面的都会被视为关键字参数,关键字参数也是可以有默认值的
print(name,age,arg,city,job)
person("james",22,city="beijing",job="manager")
#▲参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
def f1(a,b,c=0,*arg,**kw):
print(a,b,c,arg,kw)
def f2(a,b,c=0,*,d,**kw):
print(a,b,c,d,kw)
f1(1,2)#1,2,0,(),{}
f1(1,2,3)#1,2,3,(),{}
f1(1, 2, 3, 'a', 'b')#1,2,3,(a,b),{}
f1(1, 2, 3, 'a', 'b', x=99)#1 2 3 ('a', 'b') {'x': 99}
f2(1, 2, d=99, ext=None)#1 2 0 99 {'ext': None}
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args,**kw)#1 2 3 (4,) {'d': 99, 'x': '#'}
args = (1, 2, 3)
kw = {'d': 88, 'x': '#'}
f2(*args, **kw)#1 2 3 88 {'x': '#'}
#递归函数
#▲在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
#递归计算阶乘
def fact(n):
if n==1:
return 1
return n*fact(n-1)
print(fact(1000))
#尾递归
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)
print(fact(1000))
#切片(比如取出列表中的前N个元素)
list=["james","tom","jack","paul"]
print(list[0:3])#取出前三个(从0开始,到3为止)
print(list[:3])
print(list[-2:])#jack,paul
list=list(range(100))#0-99
print(list[90:])#从90取到最后
print(list[:11])
print(list[10:21])
print(list[-10:])#后10个数字
print(list[:10:2])#前10个数,每两个取一个
print(list[::5])#每5个取一个
print(list[:])#原样输出
#利用切片去除字符串首尾空格(字符串也可以切片)
def trim(s):
while(s[:1]==' '):
s=s[1:]
while(s[-1:]==' '):
s=s[:-1]
return s
print(len(trim("abcd ")))
#迭代
#同时迭代K,V
dic={"a":"a1","b":"b1"}
for k,v in dic.items():
print(k,v)
#当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行
#判断对象是否是可迭代的对象
from collections import Iterable#导入
print(isinstance("abc",Iterable))#True
print(isinstance([1,2,3],Iterable))#True
print(isinstance(123,Iterable))#False
#索引迭代
for i,value in enumerate(["A","B","C"]):
print(i,value)
list=["A","B","C"]
for i,value in enumerate(list):
print(list[i])
for x,y in[(1,2),(3,4),(5,6)]:
print(x,y)
#请使用迭代查找一个list中最小和最大值,并返回一个tuple:
list=[10,9,8,56,4,0,99,1];
def findMaxAndMin(list):
if list==[]:
return(None,None)
max=list[0]
min=list[0]
print(max,min)
for i in list:
if max<i:
max=i
if min>i:
min=i
return (max,min)
print(findMaxAndMin(list))
#列表生成式
list=[1,2,3,4,5]#等价于list(range(1, 11))
print(list)
#生成[1*1,2*2,3*3...10*10]
list=[]
for i in range(1,11):
list.append(i*i)
print(list)
#简化
print([x*x for x in range(1,11)])
#偶数平方
print([x*x for x in range(1,11) if x%2==0])
#列表生成式两个变量生成list
dic={"X":"A","Y":"B","Z":"C"}
print([k+"="+v for k,v in dic.items()])
#列表生成式将list中的字母变小写
list=["James","Tom","JACK"]
print([s.lower() for s in list])
#列表生成式将list中的字母变小写(注意如果包含数字该如何处理)
list=["James","Tom",12,"JACK"]
print([s.lower() if isinstance(s,str) else s for s in list] )
print(type([x*x for x in range(1,11)]))#list
#生成器(generator)
#把一个列表生成式的[]改成(),就创建了一个generator
g=(x*x for x in range(1,11))#创建生成器
print(g)
#通过next()函数获得generator的下一个返回值
print(next(g))
#generator是可迭代对象
for n in g:
print(n)
#斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
fib(6)#1,1,2,3,5,8
#赋值语句
n,a,b=0,0,1
print(n,a,b)#0,0,1
a, b = b, a + b#相当于
t = (b, a + b) # t是一个tuple
a = t[0]
b = t[1]
#迭代器
#用isinstance()判断一个对象是否是Iterable(可迭代)对象
from collections import Iterable
print(isinstance([],Iterable))#True
print(isinstance({},Iterable))#True
print(isinstance("abc",Iterable))#True
print(isinstance((x for x in range(10)),Iterable))#生成器也是可迭代对象,True
print(isinstance(100,Iterable))#False
#可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
from collections import Iterator
print(isinstance([],Iterator))#False
print(isinstance({},Iterator))#False
print(isinstance("abc",Iterator))#False
print(isinstance((x for x in range(10)),Iterator))#生成器可以用next(),True
print(isinstance(100,Iterator))#False
#▲生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator
#把list、dict、str等Iterable变成Iterator可以使用iter()函数
from collections import Iterator
print(isinstance(iter([]),Iterator))#True
print(isinstance(iter({}),Iterator))#True
#凡是可作用于for循环的对象都是Iterable类型;
#凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
#▲函数式编程
#高阶函数
#print(abs)#直接输出内置函数:abs(10)是调用函数,而abs是函数本身
#函数赋值
f=abs
result=f(-10)
print(result)
#▲函数名其实就是指向函数的变量,比如
abs=10
abs(10)#报错TypeError: 'int' object is not callable
#将绝对值函数作为参数传递过去
def add(a,b,f):
return f(a)+f(b)
result=add(-1,-2,abs)
print(result)
#map/reduce
#map()函数接收两个参数,一个是函数,一个是Iterable(可迭代对象)
#map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator(迭代器对象)返回
#计算1-10的每个数的平方
def f(x):
return x*x
result=map(f,range(1,11))#结果是一个map对象
print(list(result))#强制转换为list对象
#将list中的每个值转换为字符串
print(list(map(str,[1,2,3,4,5,6,7,8,9,10])))
#reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,
#这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,
#其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
#将[1,2,3,4,5]转换为12345
from functools import reduce
def f(x,y):
return x*10+y
print(reduce(f,range(1,6)))
#将str转换为int
from functools import reduce
def charToint(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
def fn(x,y):
return x*10+y
result=reduce(fn,map(charToint,"12345"))
print(type(result))#int
#利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
#输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']
def normalize(name):
name=name[0].upper()+name[1:].lower()
return name
r=list(map(normalize,['adam', 'LISA', 'barT']))
print(r)
#prod()函数,可以接受一个list并利用reduce()求积:
from functools import reduce
def fn(x,y):
return x*y
result=reduce(fn,[3, 5, 7, 9])
print(result)
#将字符串转换为整数,并求出最大值
dic={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def fn(x):
return dic[x]
result=map(fn,"123645")
from functools import reduce
def jisuan(x,y):
return x if x>y else y#三元表达式
print(reduce(jisuan,result))
#▲filter(过滤序列)把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
#filter()函数返回的是一个Iterator(惰性序列)
#删除序列中的偶数(只要奇数)
def is_odd(x):
return x%2==1
print(list(filter(is_odd,[1,2,3,4,5,6])))#[1,3,5]
#把一个序列中的空字符串删掉
def mytrim(s):
return s!=" "
print("".join((filter(mytrim," a s d "))))#asd; "".join(list)将list转为字符串
#排序算法
#print(sorted([3,12,6,4]))
#print(sorted([-1,2,-22,4,-6],key=abs))#key指定的函数将作用于list的每一个元素上
#字符串排序
#print(sorted(["C","D","a","Cat"]))#['C', 'Cat', 'D', 'a']
#print(sorted(["C","D","a","Cat"],key=str.lower))#['a', 'C', 'Cat', 'D']
#降序排序
#print(sorted([1,2,99,6],reverse=True))#[99, 6, 2, 1]
#分别按名字排序,再按成绩降序排列
l = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def byName(t):
return t[0].lower()
def byScore(t):
return t[1]
print(sorted(l,key=byName))
print(sorted(l,key=byScore,reverse=True))
#返回函数(函数作为返回值)
def f(*x):
def sum():
s=0
for i in x:
s+=i
return s
return sum;#将函数返回出去
result=f(1,2,3,4,5)()#调用函数
print(result)
def count():
fs=[]
for i in range(1,4):
def f():
return i*i
fs.append(f)
return fs
f1,f2,f3=count()
print(f1())#9
print(f2())#9
print(f3())#9
def count():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
f1,f2,f3=count()
print(f1())#1
print(f2())#4
print(f3())#9
#用过滤器筛选list中的偶数(lambda表达式)
def is_odd(n):
return n%2==0
print(list(filter(lambda n:n%2==0,[1,2,3,4,5,6])))
#装饰器
#由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。
def now():
print("2018-1-30")
f=now
f()
#函数对象有一个__name__属性,可以拿到函数的原始名字:
#print(abs.__name__)#abs
#在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
def log2(func):
def wrapper(*args,**kw):
print("call %s():"%func.__name__)
return func(*args,**kw)
return wrapper
@log2#相当于now = log2(now)
def now():
print("2018-1-30")
now()#call now: 2018-1-30
#自定义log文本的装饰器
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args,**kw):
print("%s %s():"%(text,func.__name__))
return func(*args,**kw)
return wrapper
return decorator
@log("自定义的文本")#now = log('execute')(now)
def now():
print("2018-1-30")
now()#自定义的文本 now(): 2018-1-30
print(now.__name__)#@functools.wraps(func),为了避免那些依赖函数签名的代码出现错误,可以使用functools.wraps,就变成now了
#设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
import time
def log(func):
def wrapper(*args,**kw):
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
return func(*args,**kw)
return wrapper
@log
def fn():
print("...")
fn()
#偏函数
print(int("12345"))
print(int("1234",base=16))#4660 十六进制
print(int("1234",8))#668 八进制
def int2(x, base=2):
return int(x, base)
print(int2("1000000"))#64
#functools.partial就是帮助我们创建一个偏函数的,不需要我们自己定义int2()
import functools
int2=functools.partial(int,base=2)
print(int2("1000000"))#64
#模块(在Python中,一个.py文件就称之为一个模块(Module))
#▲使用模块还可以避免函数名和变量名冲突。相同名字的函数和变量完全可以分别存在不同的模块中
#https://docs.python.org/3/library/functions.html Python的所有内置函数。
#为了避免模块名冲突,Python又引入了按目录来组织模块的方法,称为包(Package)。
#每一个包目录下面都会有一个__init__.py的文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包
#__init__.py可以是空文件,也可以有Python代码,因为__init__.py本身就是一个模块,而它的模块名就是mycompany。
#▲自己创建模块时要注意命名,不能和Python自带的模块名称冲突。例如,系统自带了sys模块,自己的模块就不可命名为sys.py,否则将无法导入系统自带的sys模块。
#使用模块
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"a test module"#表示模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释;
__author__="james"#作者名
import sys#导入模块
def test():
args=sys.argv#用list存储了命令行的所有参数,argv至少有一个元素,因为第一个参数永远是该.py文件的名称
if len(args)==1:
print("Hello world "+args[0])#Hello world hello.py
elif len(args)==2:
print("Hello %s" % args[1])#运行python hello.py james 结果是:Hello james
else:
print("no argument")
if __name__=="__main__":#在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败
test()
#第1行和第2行是标准注释,第1行注释可以让这个hello.py文件直接在Unix/Linux/Mac上运行,
#第2行注释表示.py文件本身使用标准UTF-8编码;
#作用域
#函数和变量我们希望仅仅在模块内部使用。在Python中,是通过_前缀来实现的
#类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用
def _private_1(name):
return "hello %s"%name
def _private_2(name):
return "hi %s"%name
def getting(name):
if len(name)>3:
return _private_1(name)
else:
return _private_2(name)
print(getting("james"))#hello james
#外部不需要引用的函数全部定义成private,只有外部需要引用的函数才定义为public。
#第三方库
#https://pypi.python.org/pypi
#要安装一个第三方库,必须先知道该库的名称,可以在官网或者pypi上搜索,
#比如Pillow的名称叫Pillow,因此,安装Pillow的命令就是:pip install Pillow
#用pip一个一个安装费时费力,还需要考虑兼容性。我们推荐直接使用Anaconda,内置了许多非常有用的第三方库
#下载GUI安装包 https://www.anaconda.com/download/#download
#国内镜像:https://pan.baidu.com/s/1kU5OCOB#list/path=%2Fpub%2Fpython
#安装好Anaconda后,重新打开命令行窗口,输入python 尝试直接import numpy等已安装的第三方模块。
#如果我们要添加自己的搜索目录,有两种方法:
#一是直接修改sys.path,添加要搜索的目录:import sys sys.path.append('src') 运行时有效
#第二种方法是设置环境变量PYTHONPATH
import sys
print(sys.path)
#面向对象编程
class Student(object):#(object)表示继承自object
def __init__(self,name,score):#通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去:
self.name=name
self.score=score
def printScore(self):
print("%s %s"%(self.name,self.score))
james=Student("james",66)#创建对象
bart=Student("bart",96)
james.printScore()
bart.printScore()
#类和实例
class Student():
pass
james=Student()
james.name="james" #可以自由地给一个实例变量绑定属性
print(james.name)
#▲__init__方法的第一个参数永远是self,表示创建的实例本身(self就指向创建的实例本身。)
#有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数
#要定义一个方法,除了第一个参数是self外,其他和普通函数一样
#访问限制
#▲如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__
class Student(object):
def __init__(self,name,age):
self.__name=name#外部访问不到
self.__age=age
james=Student("james",22)
print(james.name)#'Student' object has no attribute 'name'
#setXXX和getXXX方法
class Student(object):
def __init__(self,name,age):
self.__name=name
self.__age=age
def setName(self,name):
self.__name=name
def getName(self):
return self.__name
def setAge(self,age):
self.__age=age
def getAge(self):
return self.__age
james=Student("james",22)
print(james.getName())
print(james.getAge())
print(james._Student__name)#james
#在Python中,以双下划线开头,并且以双下划线结尾的
#是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。
#以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的
#但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。
#Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量:
#继承和多态
class Animal(object):
def run(self):
print("animal run...")
class Dog(Animal):
pass
class Cat(Animal):
pass
dog=Dog()
dog.run()
cat=Cat()
cat.run()
class Animal():#不写,默认继承自object
def run(self):
print("animal run ...")
class Dog(Animal):
def run(self):
print("dog run ...")
dog=Dog()
dog.run()#dog run ...
#多态
class Animal():
pass
class Cat(Animal):
pass
cat=Cat()
print(isinstance(cat,Cat))#True
print(isinstance(cat,Animal))#True
#在继承关系中,如果一个实例的数据类型是某个子类,那它的数据类型也可以被看做是父类。但是,反过来就不行:
animal=Animal()
print(isinstance(animal,Cat))#False
class Animal():
def __init__(self,name):
self.name=name
class Dog(Animal):
pass
dog=Dog("d")
print(dog.name)#d
#获取对象信息
#判断对象类型,使用type()函数,基本类型都可以用type()判断:
print(type(123))#<class 'int'>
print(type("str"))#<class 'str'>
print(type(None))#<class 'NoneType'>
#如果一个变量指向函数或者类,也可以用type()判断
print(type(abs))#<class 'builtin_function_or_method'>
#type()返回的是Class类型
print(type(123)==type(345))#True
print(type(123)==int)#True
print(type('abc')==type('123'))#True
print(type('abc')==str)#True
print(type('abc')==type(123))#False
#如果要判断一个对象是否是函数可以使用types模块中定义的常量:
import types
def fn():
pass
print(type(fn)==types.FunctionType)#True
print(type(abs)==types.BuiltinFunctionType)#True,判断是否是内置函数
print(type(lambda x: x)==types.LambdaType)#True,判断是否是lambda表达式
print(type((x for x in range(10)))==types.GeneratorType)#True,判断是否是生成器
#判断class的类型,可以使用isinstance()函数。
class Animal():
pass
class Dog(Animal):
pass
class Hasky(Dog):
pass
a=Animal()
d=Dog()
h=Hasky()
print(isinstance(a,Animal))#True
print(isinstance(d,Dog))#True
print(isinstance(h,Hasky))#True
print(isinstance(h,Dog))#True
print(isinstance(h,Animal))#True
#能用type()判断的基本类型也可以用isinstance()判断:
print(isinstance('a', str))#True
print(isinstance(123, int))#True
print(isinstance(b'a', bytes))#True
#判断一个变量是否是某些类型中的一种
print(isinstance([1, 2, 3], (list, tuple)))#True
print(isinstance((1, 2, 3), (list, tuple)))#True
#dir获得一个对象的所有属性和方法,它返回一个包含字符串的list
print(dir("abc"))#['__add__', '__class__', '__contains__'......]
#类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。
#在Python中,如果你调用len()函数试图获取一个对象的长度,
#实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:
print(len("abc"))#3
print("abc".__len__())#3
#我们自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法:
class MyClass():
def __len__(self):
return 100
print(MyClass().__len__())#100
#实例属性和类属性
#给实例绑定属性的方法是通过实例变量,或者通过self变量:
class Student():
def __init__(self,name):
self.name=name
s=Student("james")
print(s.name)
#如果Student类本身需要绑定一个属性,这种属性是类属性,归Student类所有(相当于java中的静态变量):
class Student():
name="Student"
s=Student()
print(Student.name)#Student
print(s.name)#Student
s.name="jack"
print(s.name)#jack
del s.name#删除实例的属性
print(s.name)#Student
#面向对象高级编程
#使用__slots__
def talk():#必须在上面,不能像js一样可以在下面
print("talk")
class Student():
pass
s=Student()
s.name="james"#动态绑定属性和方法
s.talk=talk
#给对象绑定方法的另一种方式
def set_name(self,name):
self.name=name
from types import MethodType
s.set_name=MethodType(set_name,s)
s.set_name("jack")
s.talk()#talk
print(s.name)#jack
#但是绑定的方法都是针对一个实例有效,为了给所有实例都绑定方法,可以给class绑定方法:
def set_score(self,score):
self.score=score
Student.set_score=set_score
s1=Student()
s2=Student()
s1.set_score(22)
s2.set_score(55)
print(s1.score)#22
print(s2.score)#55
#如果要限制实例的属性,可以使用__slots__特殊变量来限制
class Student():
__slots__=("name","age")#只允许对Student实例添加name和age属性
s=Student()
s.name="jack"
s.age=22
s.score=99# 'Student' object has no attribute 'score'
#▲__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
#除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。
#@property 类似OC中的@prooerty
class Student():
@property#装饰器
def score(self):
return self._score
@score.setter#是被@property创建的另一个装饰器
def score(self,score):
if not isinstance(score,int):
raise ValueError("score must be an integer")
if score <0 and score > 100:
raise ValueError("score must between 0-100")
self._score=score
@property
def name(self):
return "james"#name属性设置为只读的
s=Student()
s.score=10
s.name="jack"#can't set attribute
print(s.score)
print(s.name)
#多重继承
class Animal():
pass
#但是Bat具备鸟类的飞,而鸵鸟具备哺乳动物的跑
#我们要给动物再加上Runnable和Flyable的功能
#这两个类一定要写在子类上面
class Runnable():
def run(slef):
print("run...")
class Flyable():
def fly(self):
print("fly...")
#大类
class Mammal(Animal):#哺乳动物
pass
class Bird(Animal):#鸟类
pass
#各种子类
class Dog(Mammal):#狗继承自哺乳动物类
pass
class Bat(Mammal,Flyable):#蝙蝠继承自哺乳动物类,同时也继承飞翔类
pass
class Osrich(Bird,Runnable):#鸵鸟继承自鸟类,同时也继承奔跑类
pass
class Parrot(Bird):#鹦鹉继承自鸟类
pass
b=Bat()
b.fly()#fly
o=Osrich()
o.run()#run
#▲让Ostrich除了继承自Bird外,再同时继承Runnable。这种设计通常称之为MixIn。
#▲在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系
#定制类
#__str__
class Student():
def __init__(self,name):
self.name=name
#print(Student)#<class '__main__.Student'>
#print(Student("james"))#<__main__.Student object at 0x0000000002639710>
#实现类似java中的toString
def __str__(self):
return "Student object (name:%s)"%(self.name)
print(Student("james"))#Student object (name:james)
#__repr__和__str__的区别
#__str__()返回用户看到的字符串,而__repr__()返回程序开发者看到的字符串,也就是说,__repr__()是为调试服务的。
#通常__str__()和__repr__()代码都是一样的,所以,有个偷懒的写法:
class Student():
def __init__(self,name):
self.name=name
def __str__(self):
return "Student object (name:%s)"%(self.name)
__repr__=__str__#将__str__赋值给__repr__
#__iter__(如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法)
#该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值
class Fib():
def __init__(self):
self.a=1
def __iter__(self):
return self;# 实例本身就是迭代对象,故返回自己
def __next__(self):
self.a+=1
if self.a>100:
raise StopIteration()
return self.a
for i in Fib():
print(i)
#__getitem__(像list那样按照下标取出元素)
class Fib():
def __getitem__(self,n):
a=0
for i in range(n):
a=i
return a
print(Fib()[1])
#__getattr__(动态返回一个属性)
class Student():
def __init__(self,name):
self.name=name
def __getattr__(self,attr):
if attr=="score":
return 99
print(Student("james").name)#james
print(Student("").score)#如果没有__getattr__方法,'Student' object has no attribute 'score',有的话是99
#当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性
class Student():
def __init__(self,name):
self.name=name
def __getattr__(self,attr):
if attr=="score":
return lambda: 25#也可以是函数
raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)#没找到时候
#在调用时是:
s=Student("james")
print(s.score())#25
print(s.sex)#None,__getattr__默认返回就是None,可以抛出AttributeError
#利用完全动态的__getattr__,写出一个链式调用:
class Chain():
def __init__(self,path=""):
self._path=path
def __getattr__(self,path):
return Chain("%s/%s"%(self._path,path))
def __str__(self):
return self._path
__repr__=__str__
print(Chain().status.user.timeline.list)#/status/user/timeline/list
#还有些REST API会把参数放到URL中,比如GitHub的API:GET /users/:user/repos
#调用时,需要把:user替换为实际用户名,以下实现
class Chain(object):
def __init__(self,path =''):
self._path = path
def __getattr__(self,path):
return Chain('%s/%s' % (self._path,path))
def __str__(self):
return self._path
__call__ = __getattr__
__repr__ = __str__
print(Chain().users('Michael').repos)
#__call__
#任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用
class Student():
def __init__(self,name):
self.name=name
def __call__(self):
print("My name is %s"%self.name)
s=Student("james")
s()#My name is james
#能被调用的对象就是一个Callable对象
print(callable(Student("james")))#True
print(callable(max))#True
print(callable([1, 2, 3]))#False
print(callable(None))#False
print(callable('str'))#False
'''
#使用枚举类
from enum import Enum
Month=Enum("Month",('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name,member in Month.__members__.items():
print(name,member,member.value)#Jan Month.Jan 1 ...
|
359684540bbf8117b3895bb47320036022c52817 | RaymondHealy/Karahl_Codespace | /CS 1/Homeworks/hw8/sort_compare.py | 2,539 | 4.28125 | 4 | """Raymond Healy"""
import random as r
import time as t
from insertionSort import *
from quickSort import *
from mergeSort import *
def GenerateRandomList(size, minimum, maximum):
toReturn = []
for i in range(0, size-1):
toReturn += [r.randint(minimum, maximum)]
return toReturn
def test_insertion_sort():
unsortedList = GenerateRandomList(10, 0, 30)
sortedList = InsertionSort(unsortedList)
if max(sortedList) == sortedList[-1]:
print("InsertionSort was Correct")
else:
print("InsertionSort was Incorrect")
def test_quick_sort():
unsortedList = GenerateRandomList(10, 0, 30)
sortedList = quickSort(unsortedList)
if max(sortedList) == sortedList[-1]:
print("quickSort was Correct")
else:
print("quickSort was Incorrect")
def test_merge_sort():
unsortedList = GenerateRandomList(10, 0, 30)
sortedList = mergeSort(unsortedList)
if max(sortedList) == sortedList[-1]:
print("mergeSort was Correct")
else:
print("mergeSort was Incorrect")
def main():
quickSortMaxedOut = False
mergeSortMaxedOut = False
insertionSortMaxedOut = False
listSize = int(input("Initial List Size: "))
minValue = int(input("Min Item Size : "))
maxValue = int(input("Max Item Size : "))
while not quickSortMaxedOut or not mergeSortMaxedOut or not insertionSortMaxedOut:
unsortedList = GenerateRandomList(listSize, minValue, maxValue)
print("\n============================================================")
print("List Size: ", listSize)
print("------------------------------")
if not insertionSortMaxedOut:
start = t.time()
InsertionSort(unsortedList)
end = t.time()
print("Insertion Sort Time: ", end - start)
insertionSortMaxedOut = end - start >= 1
if not quickSortMaxedOut:
start = t.time()
quickSort(unsortedList)
end = t.time()
print("Quick Sort Time : ", end - start)
quickSortMaxedOut = end - start >= 1
if not mergeSortMaxedOut:
start = t.time()
mergeSort(unsortedList)
end = t.time()
print("Merge Sort Time : ", end - start)
mergeSortMaxedOut = end - start >= 1
print("============================================================")
listSize = listSize * 10
main() |
15fa64079ab80947c8e5e0136963ad160fa0df00 | zack-ashen/noted | /noted/NoteGrid.py | 7,486 | 3.640625 | 4 | """Helper functions for printing out grid of notes.json or one note. These functions
assist with the printing of a grid of notes.json. Primarily manipulate a nested list
object which can be ragged or note.
Author: Zachary Ashen
Date: June 4th 2020
"""
import os
import re
from textwrap import fill
from . import NotedItem
# get terminal dimensions
columns, rows = os.get_terminal_size()
width = columns
def _listify_noted_item(noted_item_list):
# Returns: a ragged list of notes with the format [[['list title'],['list body']], [['list title'],['item 1']]]
# Precondition: noted_item_list is a list of NotedItem objects.
note_list_formatted = []
for index in range(len(noted_item_list)):
note = noted_item_list[index]
note_title = note.title
# execute if note is a list
if type(note) == NotedItem.ListItem:
# Only retrieve unchecked list items
note_list = note.get_unchecked_items()
note_list.insert(0, note_title)
note_list_formatted.append(note_list)
# execute if note is a note not list
elif type(note) == NotedItem.NoteItem:
note_list = note.body_text.rstrip('\n').split('\n')
note_list.insert(0, note_title)
note_list_formatted.append(note_list)
return note_list_formatted
def _wrap_text(nested_list):
# Returns: a nested list with return keys if the string within the nested list goes beyond the width of the
# terminal.
# Precondition: nested_list is a ragged list of NotedItem objects that has already been listified using
# _listify_noted_item.
for index in range(len(nested_list)):
for i in range(len(nested_list[index])):
if len(nested_list[index][i]) > (width - 25):
nested_list[index][i] = fill(nested_list[index][i], width=(width - 22))
unwrapped_text = nested_list[index][i]
wrapped_text_list = nested_list[index][i].split('\n')
for a in range(len(wrapped_text_list)):
nested_list[index].insert(i + (a), wrapped_text_list[a])
nested_list[index].remove(str(unwrapped_text))
return nested_list
def _add_list_border(nested_list):
# Returns: a ragged list with ASCII borders. The nested lists will have borders.
# Precondition: list is a nested list and all items in the nested list are strings
for index in range(len(nested_list)):
list_item = nested_list[index]
border_width = max(len(s) for s in list_item)
# add top border
top_border = ['┌' + '─' * border_width + '┐']
top_border = re.sub("['',]", '', str(top_border)).strip('[]')
nested_list[index].insert(0, top_border)
# iterate over middle lines and add border there
for i in range(len(list_item)):
if i == 1:
list_item[i] = '│' + (' ' * ((border_width - len(list_item[i])) // 2)) + (list_item[i] + ' ' * (
(1 + border_width - len(list_item[i])) // 2))[:border_width] + '│'
elif i >= 2:
list_item[i] = '│' + (list_item[i] + ' ' * border_width)[:border_width] + '│'
# add bottom border
bottom_border = ['└' + '─' * border_width + '┘']
bottom_border = re.sub("['',]", '', str(bottom_border)).strip('[]')
nested_list[index].append(bottom_border)
return nested_list
def _remove_list_border(nested_list):
# Returns: a ragged list without ASCII borders the returned list will not have any borders.
# Precondition: nested_list contains borders applied to it by the function _add_list_borders and nested_list is a
# ragged list.
for index in range(len(nested_list)):
nested_list[index].pop(0)
nested_list[index].pop(len(nested_list[index]) - 1)
for index in range(len(nested_list)):
for i in range(len(nested_list[index])):
nested_list[index][i] = re.sub("[│□]", '', str(nested_list[index][i])).rstrip(' ').lstrip(' ')
return nested_list
def _build_note_list(noted_item_list):
# Returns: a formatted note list with borders and in list format for an easier way to display in grid view.
# Precondition: noted_item_list is a list of NotedItem objects.
noteList = _add_list_border(_wrap_text(_listify_noted_item(noted_item_list)))
return noteList
def print_grid(noted_item_list, start_pos=0):
""" Prints out a grid of NotedItem objects with borders and responsively to the size of the terminal.
@param noted_item_list: is a list of NotedItem objects.
@param start_pos: the position in the array of NotedItem objects to begin printing. This should be left alone and
the default value of 0 should be used. As the function is recursively called this is increased to print more rows.
"""
note_list = _build_note_list(noted_item_list)
max_note_list_length = max(len(i) for i in note_list)
note_list_item_width_accumulator = 0
found_column_count = False
global columnEndPos
global continuePrintingRow
row_position = range(len(note_list))
# ------ Find columnEndPos ------
for index in row_position[start_pos:]:
note_list_item = note_list[index]
note_width = max(len(s) for s in note_list_item)
note_list_item_width_accumulator += note_width
if note_list_item_width_accumulator > (width - 20) and not found_column_count:
columnEndPos = (note_list.index(note_list[index - 1]))
found_column_count = True
elif index == max(row_position[start_pos:]) and not found_column_count and note_list_item_width_accumulator < width:
columnEndPos = len(note_list)
continuePrintingRow = False
found_column_count = True
# ------ End Find columnEndPos ------
# ------ Add spaces below note to make rectangular row of characters ------
if columnEndPos == start_pos:
max_note_list_length = len(note_list[columnEndPos])
elif columnEndPos == len(note_list):
max_note_list_length = max(len(i) for i in note_list[start_pos:columnEndPos])
else:
max_note_list_length = max(len(i) for i in note_list[start_pos:columnEndPos + 1])
for index in row_position[start_pos:columnEndPos + 1]:
note_list_item = note_list[index]
note_width = max(len(s) for s in note_list_item)
for i in range(len(note_list_item)):
if len(note_list_item) < max_note_list_length:
for x in range(max_note_list_length - len(note_list_item)):
note_list_item.append(' ' * note_width)
# ------ End add spaces below note to make rectangular row of characters ------
if (columnEndPos + 1) == start_pos:
note_list_formatted = note_list[columnEndPos + 1]
else:
note_list_row = note_list[start_pos:columnEndPos + 1]
note_list_formatted = zip(*note_list_row)
note_list_formatted = list(note_list_formatted)
# ------ Center Notes ------
center_space_count = round(abs((width - len(''.join(note_list_formatted[0]))) / 2))
for i in range(len(note_list_formatted)):
print('\u001b[0;34m', end='')
if i == 1:
print('\u001b[1;34m', end='')
string_line = ''.join(note_list_formatted[i])
print((center_space_count * ' '), string_line)
while continuePrintingRow:
print_grid(note_list, columnEndPos + 1)
|
d19693e07f7436eb1cfc7164e74677dfca172216 | Anshikaverma24/meraki-list-questions | /meraki list ques/q2.py | 218 | 3.78125 | 4 | # Write a code, that counts the numbers between 20 and 40 and then print its count.
numbers=[50, 40, 23, 70, 56, 12, 5, 10, 7]
i=0
while i<len(numbers):
if numbers[i]>20 and numbers[i]<40:
print(numbers[i])
i+=1 |
0ffdea8b5f188623511a3da2c029720320c9e45e | notwhale/FizzBuzz | /fizzbuzz.py | 1,607 | 4.09375 | 4 | #!/usr/env python3
"""
Write a program to print numbers from 1 to 100.
But for multiples of 3 print 'Fizz' instead and
for the multiple of 5 print 'Buzz' and
for the numbers multiple of both 3 and 5 print 'FizzBuzz'.
"""
import sys
import time
def fizz_buzz1(r_min, r_max):
"""
Straight solution
"""
result = []
for num in range(r_min, r_max + 1):
if num % 15 == 0:
result.append('FuzzFuzz')
elif num % 3 == 0:
result.append('Fizz')
elif num % 5 == 0:
result.append('Buzz')
else:
result.append(num)
return result
def fizz_buzz2(r_min, r_max):
"""
With ternary condition
"""
return list(
('' if num % 3 else 'Fizz') +
('' if num % 5 else 'Buzz') or
num for num in range(r_min, r_max + 1)
)
def fizz_buzz3(r_min, r_max):
"""
With ternary condition, map and lambda
"""
return list(
map(
lambda num:
('Fizz' if num % 3 == 0 else '') +
('Buzz' if num % 5 == 0 else '') or
num, range(r_min, r_max + 1)
)
)
def main(r_min=1, r_max=101):
"""
Execute all fizz_buzz functions, print and measure results
"""
fizz_buzz_all = (
fizz_buzz1(r_min, r_max),
fizz_buzz2(r_min, r_max),
fizz_buzz3(r_min, r_max)
)
for f in fizz_buzz_all:
start = time.time()
print(*f, sep='\n')
end = time.time()
print("Execution time: ", end - start)
if __name__ == "__main__":
sys.exit(main())
|
3fc47789635941d4b5215568a5e8d5612200d539 | LolaSun/Tasks | /Camel to Snake.py | 763 | 4.46875 | 4 | """
The company you are working for is refactoring its entire codebase. It's changing all naming conventions from
camel to snake case (camelCasing to snake_casing).
Every capital letter is replaced with its lowercase prefixed by an underscore _, except for the first letter,
which is lowercased without the underscore, so that SomeName becomes some_name.
Task:
Write a program that takes in a string that has camel casing, and outputs the same string but with snake casing.
Input Format:
A string with camelCasing.
Output Format:
The same string but with snake_casing.
Sample Input:
camelCasing
Sample Output:
camel_casing
"""
import re
camel=input()
pattern=r".[a-z]*"
snake="_".join(re.findall(pattern, camel)).lower()
print(snake)
|
a9209700cf92a020ebf0b3825c28027d040f368d | MluskGit/Note | /py/increase.py | 677 | 3.734375 | 4 | #!/usr/bin/python3
from readURL import ReadURL
# 增加某用户的CSDN阅读量, 发现是每天都能去增加一次
def read_blog(list_url):
readUrl = ReadURL(list_url)
soup = readUrl.readhtml()
li_list = soup.find_all('li')
for li_element in li_list:
li_class = readUrl.getelement(str(li_element), 'class')
if li_class == "blog-unit":
# print(li_element)
a_href = readUrl.getelement(str(li_element), 'href')
readUrl.url = a_href
readUrl.readhtml()
# print("*"*40)
for i in range(1, 3, 1):
list_url = 'http://blog.csdn.net/kcp606/article/list/'+str(i)
read_blog(list_url) |
27ae0dc2f9eff4ac89d583dc50b33789095c9dec | nchdms1999/Python | /Python/4-6成员运算符.py | 440 | 4.125 | 4 |
# in ; not in
str01 = "my name is KK, I come from China"
if "come" in str01:
print("include")
else: print("not include")
name_array = ["Alice","Bob","Peter","Tomas"]
name = input("Please input name: ")
if name in name_array:
print("The name %s is in the List!" % name)
else: print("The name %s is NOT in the List" % name)
num_array = [10,20,30,40,50,60]
if 23 in num_array:
print("Exist!")
else: print("NOT Exist!")
|
2ee9e967a8ba89af405ee0129b67b106297110f7 | mulongxinag/xuexi | /L2基础类型控制语句/练习题:学习成绩.py | 855 | 4.15625 | 4 | # 接收用户输入的学生成绩
score=input('成绩:')
score=int (score)
if score< 60:
passed='不及格'
print(passed)
else:
passed='及格'
print(passed)
if 60<=score<70:
rank='D'
elif 70<=score<80:
rank='C'
elif 80<=score<90:
rank='B'
elif 90<=score<=100:
rank='A'
print(rank)
# score=input('成绩:')
# score=int(score)
#print(score,type(score))
#判断成绩
# if score<0 or score>100:
# print('用户输入不合法')
# if 0<=score<60:
# print('不及格')
# else:
# # print('及格')
# if 60<=score<70:
# print('D')
#
# elif 70<=score<80:
# print('C')
# elif 80<=score<90:
# print('B')
# elif 90<=score<=100:
# print('A')
#
|
0c57d38ab22ad465e0322eba46028567039fa495 | anujaverma11/-100DaysOfCode | /0035_ElectronicsShop.py | 2,320 | 4.03125 | 4 | #!/bin/python3
import sys
def getMoneySpent(keyboards, drives, s):
# keyboards = [3, 1]
# drives = [5, 2, 8]
# s = 622830
maxAmount = -1
for x in keyboards:
for y in drives:
if (x + y <= s and x+y > maxAmount):
maxAmount = x+y
if (maxAmount>s):
maxAmount = -1
return (maxAmount)
s,n,m = input().strip().split(' ')
s,n,m = [int(s),int(n),int(m)]
keyboards = list(map(int, input().strip().split(' ')))
drives = list(map(int, input().strip().split(' ')))
# The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
moneySpent = getMoneySpent(keyboards, drives, s)
print(moneySpent)
# Monica wants to buy exactly one keyboard and one USB drive from her favorite electronics store. The store sells different brands of keyboards and different brands of USB drives. Monica has exactly dollars to spend, and she wants to spend as much of it as possible (i.e., the total cost of her purchase must be maximal).
# Given the price lists for the store's keyboards and USB drives, find and print the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.
# Note: She will never buy more than one keyboard and one USB drive even if she has the leftover money to do so.
# Input Format
# The first line contains three space-separated integers describing the respective values of (the amount of money Monica has), (the number of keyboard brands) and (the number of USB drive brands).
# The second line contains space-separated integers denoting the prices of each keyboard brand.
# The third line contains space-separated integers denoting the prices of each USB drive brand.
# Constraints
# The price of each item is in the inclusive range .
# Output Format
# Print a single integer denoting the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.
# Sample Input 0
# 10 2 3
# 3 1
# 5 2 8
# Sample Output 0
# 9
# Explanation 0
# She can buy the keyboard and the USB drive for a total cost of .
# Sample Input 1
# 5 1 1
# 4
# 5
# Sample Output 1
# -1
# Explanation 1
# There is no way to buy one keyboard and one USB drive because , so we print . |
4faeae492ce66e5cc0f2b92ea015b442c505e56c | jimishere/SI506-practice | /problem_sets/ps_09-2020Fall/problem_set_09.py | 5,240 | 4.28125 | 4 | # START PROBLEM SET 09
print('Problem set 09 \n')
# SETUP
import csv
class Country():
"""
Representation of a country
Attributes:
code (str): the code of the country
name (str): the name of the country
population (int): the population of the country
meat_consumption_per_capita (dict): the meat consumption per capita of the country
meat_co2_emission_per_capita (float): the co2 emission caused by consumption of meat per capita of the country
meat_co2_emission_total (float): the total co2 emission caused by consumption of meat of the country
"""
# Problem 1
def __init__(self,): # TODO complete the parameter list
"""
The constructor of the < Country > class. Here you will need to create
the attributes ("instance variables") that were described in the < Country >
docstring. Note that some of the attributes are defined by parameters passed
to this constructor method, but others are not.
Parameters:
code (str): The code of the country
name (str): The name of the country
population (int): The population of the country
Returns:
None
"""
pass # TODO
# Problem 2
def __str__(self):
"""
This is the string method for the < Country > class. Whenever an instance of
< Country > is passed to the str() or print() functions, the return string
from this method will be returned.
Parameters:
None
Returns:
str: A string that describes this instance of < Country >
"""
pass # TODO
# Problem 3
def add_meat_consumption(self, meat_type, consumption):
"""
This method will modify <meat_consumption_per_capita> by adding a new key:value pair
where <meat_type> is the key and <consumption> is the value.
Parameters:
meat_type (str): Type of the meat.
consumption (float): Consumption(kg) of the meat
Returns:
None
"""
pass # TODO
# Problem 4
def calculate_emission_per_capita(self, meat_emission):
"""
This method will modify <meat_co2_emission_per_capita> by increasing
its value with co2 emission of different types of meat.
Parameters:
meat_emission (dict): Key is type of the meat and value is co2 emission (kg) of corresponding meat.
Returns:
None
"""
pass # TODO
# Problem 5
def calculate_total_emission(self):
"""
This method will modify <meat_co2_emission_total> by multiply <population>
with <meat_co2_emission_per_capita>.
Parameters:
None
Returns:
None
"""
pass # TODO
# Problem 6
def write_to_file(filepath, data):
"""
This function takes any < data >, converts it into a string via the str()
function (if possible), and then writes it to a file located at < filepath >. Note
that this function is a general writing function. It should not use the .csv
module, but rather the python write() function. This is because we want this
function to write ANYTHING we give it as the < data > parameter (in the
case of this assignement, you will actually use it to write string representations
of the class instances you create).
NOTE: It is important that you convert < data > to a str BEFORE you write it!
The object being passed into this function as < data > could already be a
string, and if so, passing it through the str() function won't do anything. But
any other object will need to be changed into a string object.
Parameters:
filepath (str): the filepath that points to the file that will be written.
data (obj): any object capable of being converted into a string.
Returns:
None, but a file is produced.
"""
pass # TODO
# We provide the read_csv function for you
def read_csv(filepath):
"""Returns a list of dictionaries where each dictionary is formed from the data.
Parameters:
filepath (str): a filepath that includes a filename with its extension
Returns:
list: a list of dictionaries where each dictionary is formed from the data
"""
with open(filepath, mode='r', newline='', encoding='utf-8-sig') as file_obj:
data = list(csv.DictReader(file_obj))
return data
def main():
"""Program entry point. Handles program workflow.
Parameters:
None
Returns:
usa (str)
usa_meat_consumption_per_capita (dict)
usa2 (str)
max_country (obj)
min_country (obj)
"""
meat_emission = {
'BEEF': 27.0,
'PIG': 12.1,
'SHEEP': 39.2,
'POULTRY': 6.9,
}
### Problem 7.1
### Problem 7.2
### Problem 7.3
### Problem 7.4
### Problem 7.5
# Don't forget to return variables
# If you want to test your code before you finish all the PS,
# you can assign None to those return variables
#Do not delete the lines below.
if __name__ == '__main__':
main()
|
76437de03673fa10258883b76a0297afa06e6260 | Karpo22/Project-Euler | /Problem 8.py | 771 | 3.546875 | 4 | ## Variables
highestValue = 0
intContainer = 1
lowerBound = 0
spotHolder = 0
f = open("/Users/karp/Desktop/Numbers.rtf", "r")
lines = f.read().splitlines()
## Strip only to digits then store in control string
cleaned = [x for x in lines if x[:1].isdigit()]
controlString = ''
for x in cleaned:
for i in x:
if i.isdigit() == True:
controlString += i
## Find highest consecutive 13 digits products
while lowerBound <= (len(controlString) - 13):
spotHolder = lowerBound
for i in range (0, 13):
intContainer *= int(controlString[lowerBound])
lowerBound += 1
if intContainer > highestValue:
highestValue = intContainer
intContainer = 1
lowerBound = (spotHolder + 1)
print(highestValue)
|
3c566b16d82cc04538d23f43c8c3b9af7b5a9845 | animeshsahu80/Data-Structures-and-Algorithms | /Algorithm_Solutions/hash_map.py | 2,377 | 3.953125 | 4 | from collections import namedtuple
HashMapNode = namedtuple('HashMapNode', ['key', 'value'])
class HashMap:
def __init__(self, bucket_count=16):
self.size = 0
self.bucket_count = bucket_count
self.buckets = [[] for i in range(bucket_count)]
def put(self, key, value):
"""Insert an item into the HashMap"""
bucket_index = self._get_bucket_index(key)
bucket = self.buckets[bucket_index]
for index, node in enumerate(bucket):
if node.key == key:
bucket[index] = HashMapNode(key, value)
return
bucket.append(HashMapNode(key, value))
self.size += 1
def get(self, key):
"""Retrieve an item from the HashMap"""
bucket_index = self._get_bucket_index(key)
bucket = self.buckets[bucket_index]
for node in bucket:
if node.key == key:
return node.value
return None
def remove(self, key):
"""Remove an item from the HashMap"""
bucket_index = self._get_bucket_index(key)
bucket = self.buckets[bucket_index]
for index, node in enumerate(bucket):
if node.key == key:
bucket.pop(index)
self.size -= 1
return
def count(self):
return self.size
def _get_bucket_index(self, key):
"""Hash a key and limit the resulting value to the number of buckets"""
return hash(key) % self.bucket_count
def display(self):
"""Print out the HashMap to view how values are being stored"""
print('[')
for bucket in self.buckets:
nodes = [str(node) for node in bucket]
print('\t[{}]'.format(', '.join(nodes)))
print(']')
if __name__ == '__main__':
hash_map = HashMap()
print('Putting {hello: world}')
hash_map.put('hello', 'world')
print('Putting {foo: bar}')
hash_map.put('foo', 'bar')
print('Putting {foo: baz}')
hash_map.put('foo', 'baz')
print('Count: {}'.format(hash_map.count()))
print('Value for "hello": {}'.format(hash_map.get('hello')))
print('Value for "foo": {}'.format(hash_map.get('foo')))
print('Removing "hello"')
hash_map.remove('hello')
print('Count: {}'.format(hash_map.count()))
print('Value for "hello": {}'.format(hash_map.get('hello')))
|
46095d4b2c385effec4993cb58f997ac138424ab | DJSull93/python-oop | /webscrap/wikipedia.py | 542 | 3.890625 | 4 | class Wikipedia(object):
def __init__(self, url):
self.url = url
def __str__(self):
return self.url
@staticmethod
def main():
while 1:
menu = int(input(f'0.Exit\n1.Input\n2.Print URL\n'))
if menu == 0:
break
elif menu == 1:
wiki = Wikipedia(input(f'Input URL\n'))
elif menu == 2:
print(f'URL = {wiki}\n')
else:
print('wrong number')
continue
Wikipedia.main()
|
d51df74f709e8a3e4c2594a0697e2c492460bc30 | linmartinescu/Code | /bb_temperature.py | 1,849 | 3.53125 | 4 | """
Aurthor: Lindsay Martinescu
"""
from Blackbody import Blackbody
def bb_temperature(wavelength, radiance, epsilon = 1e-8):
tLow = 0.0 # initial low temperature
tHigh = 6000.0 # initial high temperature
tResult = (tHigh + tLow)/2.0 # current calculated temperature
while ((tHigh - tLow) > epsilon): # while our temperature difference is > epsilon, loop
tBb = Blackbody(wavelength, tResult) #create a new blackbody for the given wavelength and current temperature
cRadiance = tBb.radiance() #calculate current radiance
if (cRadiance > radiance): # if calculated radiance is > target radiance, set new 'high'
tHigh = tResult
else: # else , set new 'low'
tLow = tResult
tResult = (tHigh + tLow)/2.0 # compute new target temperature, continue loop
return tResult
def spectral_radiance(self, wavelengths):
"""
Computes a list
Args:
wavelength in microns
Returns:
the radiances
Author:
Lindsay Martinescu
"""
radiances = []
for wavelength in wavelengths:
self.wavelength = wavelength
radiances.append(self.radiance())
return radiances
if __name__ == '__main__':
bb = Blackbody(10, 300)
print bb
print 'L =', bb.radiance(), '[W / m^2 / micron / sr]'
print 'Peak wavelength =', bb.peak_wavelength(), '[microns]'
import pylab
pylab.figure()
pylab.title('f(x) = sqrt(x)')
pylab.xlabel('Wavelength [microns]')
pylab.ylabel('Radiance [W / m^2 / micron / sr]')
pylab.xlim([0,20])
pylab.ylim([0,5])
pylab.plot(x, y)
pylab.show()
n = 100
x = []
y = []
xMin = 8
xMax = 14
increment = (xMax - xMin)/float(n)
for i in range(n):
x.append(xMin + i*increment)
y = spectral_radiance(x)
|
07a94f2e0462d566138041a779a2df40191570a6 | todorovventsi/Software-Engineering | /Python-Advanced-2021/Exam-preparation/Python_Advanced_Retake_Exam-16-Dec-2020/02.Problem_2-Letter-game.py | 1,246 | 3.6875 | 4 | def move_is_valid(coordinates):
return True if 0 <= coordinates[0] < size and 0 <= coordinates[1] < size else False
moves_mapper = {
"up": lambda x, y: (x - 1, y),
"down": lambda x, y: (x + 1, y),
"right": lambda x, y: (x, y + 1),
"left": lambda x, y: (x, y - 1),
}
initial_string = input()
size = int(input())
field = [list(input()) for _ in range(size)]
number_of_moves = int(input())
player_position = ()
for row in range(size):
for col in range(size):
if field[row][col] == "P":
player_position = (row, col)
for _ in range(number_of_moves):
command = input()
next_position = moves_mapper[command](*player_position)
if not move_is_valid(next_position):
initial_string = initial_string[0:-1]
continue
field[player_position[0]][player_position[1]] = "-"
location_symbol = field[next_position[0]][next_position[1]]
if not location_symbol == "-":
initial_string += location_symbol
field[next_position[0]][next_position[1]] = "P"
player_position = next_position
else:
field[next_position[0]][next_position[1]] = "P"
player_position = next_position
print(initial_string)
[print(f"{''.join(row)}") for row in field]
|
755c056515dc6a1d65818a14023d643757d0f879 | oojo12/algorithms | /sort/count_sort.py | 972 | 4.03125 | 4 | def count_sort(arr, k):
'''
This is a non-negative implementation of count sort it runs with the following
complexities:
time - O(K+N)
space - O(K+N)
Input:
arr - array to be sorted
k - integer space to allot to the temp storage array.
It is recommeneded to make this an integer for which
len(arr) < k.
Output:
sorted_arr - sorted array
'''
# initialize
sorted_arr = [None]*len(arr) # O(N)
temp_storage = [0]*(k+1) # O(K)
# build array of counts O(N)
for index in range(len(arr)):
temp_storage[arr[index]] += 1
# update to number of elements below O(K)
for index in range(1, k+1):
temp_storage[index] += temp_storage[index-1]
# build sorted array O(N)
for index in range(len(arr)-1, -1, -1):
sorted_arr[temp_storage[arr[index]]-1] = arr[index]
temp_storage[arr[index]] -= 1
return sorted_arr
|
17a10d0551e47d62b70e0bccb6981cc8c973ee2c | kharrigian/emnlp-2020-mental-health-generalization | /mhlib/util/helpers.py | 534 | 4.0625 | 4 |
def flatten(l):
"""
Flatten a list of lists by one level.
Args:
l (list of lists): List of lists
Returns:
flattened_list (list): Flattened list
"""
flattened_list = [item for sublist in l for item in sublist]
return flattened_list
def chunks(l,
n):
"""
Yield successive n-sized chunks from l.
Args:
l (list): List of objects
n (int): Chunksize
Yields:
Chunks
"""
for i in range(0, len(l), n):
yield l[i:i + n] |
e8035ecc665c887d6641216f67ac9b2f1d027f81 | Ukasz11233/Algorithms | /Algorytmy/Ćwiczenia1/zad5_reverse_list.py | 638 | 3.84375 | 4 | class Node:
def __init__(self, value = None):
self.value = value
self.next = None
def MakeFromArray(A):
first = None
for el in A:
p = Node(el)
p.next = first
first = p
return first
def Write(first):
tmp = first
while tmp is not None:
print(tmp.value, end=" ")
tmp = tmp.next
print()
L = MakeFromArray([2, 5, 3, 7, 11])
Write(L)
def ReverseList(first):
prev = None
curr = first
while curr is not None:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
RL = ReverseList(L)
Write(RL)
|
3b2f49704f8857af05d2962b6b6bc298ba572fc6 | DahrielG/EvenOdd | /app/models/model.py | 477 | 3.828125 | 4 | sentence = "Hello"
def count(sentence):
sentence = sentence.replace(" ", "")
sentence = sentence.replace(".", "")
sentence = sentence.replace(",", "")
sentence = sentence.replace("!", "")
sentence = sentence.replace("?", "")
sentence = sentence.replace("'", "")
sentence = sentence.replace('"', "")
length = len(sentence)
return length
def nums(sentence):
if sentence%2==0:
return "even"
else:
return "odd"
|
1ede3d16dbe9459a7efac3f4028dbffa8ddc4a0d | lindsaymarkward/CP1200InClassDemos2015 | /files.py | 1,042 | 3.796875 | 4 | __author__ = 'sci-lmw1'
# writeFile = open("data.txt", 'a')
# # writeFile.write("CP1200 is such\n\n a good\nSubject!!!")
# # writeFile.write("Goodbye")
# writeFile.write("\nHappy!\n")
# writeFile.close()
# file = open("data.txt", 'r')
# # text = file.read()
# countLines = 0
# for line in file:
# line = line.strip()
# print(repr(line))
# countLines += 1
# # if line == "\n":
# # break
#
#
# file.close()
# print(countLines)
#
# # print(text)
# # print(repr(text))
"""
Write pseudocode for a program that opens a file and toggles
"on" and "off" each time it's run.
So, if the file contains "on", change it to "off" and vice versa
file = open "switch.txt" file for reading
line = read line from file
close file
file = open "switch.txt" file for writing
if line == "on"
write "off" to file
else
write "on" to file
close file
"""
file = open("switch.txt")
line = file.read().strip()
file.close()
file = open("switch.txt", 'w')
if line == "on":
file.write("off")
else:
file.write("on")
file.close()
|
224bc22ac75d49eb241315a270d175d360c849ea | sudhanthiran/Python_Practice | /Competitive Coding/maxSubArray.py | 480 | 3.515625 | 4 | from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
len_nums = len(nums)
sum_nums = nums[0]
temp = nums[0]
for i in nums[1:]:
if (temp + i > i):
temp = temp + i
else:
temp = i
if (sum_nums < temp):
sum_nums = temp
return sum_nums
nums = [-2,1,-3,4,-1,2,1,-5,4]
print(Solution.maxSubArray(self=Solution,nums=nums)) |
37f06770c1c6ddf6c67119d879e95bbed27d47f6 | zack-ashen/noted | /noted/NotedItem.py | 4,553 | 3.734375 | 4 | """Noted Items class and subclasses including Notes Class and Lists Class.
Author: Zachary Ashen
Date: June 4th 2020
"""
class _NotedItem(object):
# Master class of NotedItems including NoteItem and ListItem
# Invariant: title is a string
def __init__(self, title):
# Initializes _NotedItem
# Precondition: title is a string
self.title = title
class NoteItem(_NotedItem):
"""A note item with a body that can be printed or displayed in a grid format. It is a sticky note type of idea.
@invariant title: is a string of the title of the note
@invariant body_text: a string of the text for the body
"""
def __init__(self, title, body_text):
"""NoteItem initializer
@param title: is a string of the title of the note
@param body_text: a string of the text for the body
"""
super().__init__(title)
self.body_text = body_text
def to_dict(self):
"""Converts the NoteItem into a dictionary
@return: a dictionary with the note item title and body as keys and content
"""
list_item_dict = {
'title': self.title,
'body': self.body_text
}
return list_item_dict
class ListItem(_NotedItem):
"""A list of items that can be checked of or displayed in a grid has a format similar to a todo list.
@invariant title: is a string of the title of the note
@invariant items: is an item or multiple items with the format of a tuple ('item name', True). The second boolean
dictates whether the item is checked or not: True means it is checked, False means it is not checked.
"""
def __init__(self, title, *items):
"""ListItem initializer
@param title: is a string of the title of the note
@param items: is an item or multiple items with the format of a tuple ('item name', True). The second boolean
dictates whether the item is checked or not: True means it is checked, False means it is not checked.
"""
super().__init__(title)
self.items = items
def get_unchecked_items(self):
"""Gets all of the unchecked items in the ListItem
@return: a list of unchecked items
"""
unchecked_list = []
for item in self.items[0]:
if not item[1]:
unchecked_list.append('□ ' + item[0])
return unchecked_list
def add_item(self, item):
"""Adds item to ListItem
@param item: tuple of item to add in format ('item name', True) second boolean determines whether the item is
checked or not if True the item is checked if False the item is not checked.
"""
self.items[0].append(item)
def delete_item(self, item_name):
"""Deletes item from ListItem
@param item_name: string of item name to delete, must be a name of an item
"""
for item in self.items[0]:
if item_name == item[0]:
print(self.items[0])
index_of_item = self.items[0].index(item)
self.items[0].pop(index_of_item)
def rename_item(self, old_name, new_name):
"""Renames an item
@param old_name: a string of the old name of the item must be in the list item
@param new_name: a string of the new name of the item
"""
for item in self.items[0]:
if old_name == item[0]:
item_list = list(item)
item_list[0] = new_name
index_of_item = self.items[0].index(item)
self.items[0][index_of_item] = tuple(item_list)
def check_item(self, items_to_check):
"""Checks items. In other words, converts tuple of item from ('string title', False) to ('string title', True)
@param items_to_check: is a string of the name of the item to check off
"""
for item in self.items[0]:
for item_to_check in items_to_check:
if item[0] == item_to_check:
index_of_item = self.items[0].index(item)
item_list = list(item)
item_list[1] = True
item = tuple(item_list)
self.items[0][index_of_item] = item
def to_dict(self):
"""Converts the ListItem into a dictionary
@return: a dictionary with the note item title and items as keys and content
"""
list_item_dict = {
'title': self.title,
'items': self.items
}
return list_item_dict
|
c6e71c6a1215eb2cda3b999f9e55e7ddadfedd51 | becurrie/py-sorts | /py_sorter/sorter.py | 7,533 | 3.921875 | 4 | """py_sorter.sorter: provides argument parsing and entry point main().
Any calls to the sorts methods are called from here based on the -s/--sort
argument specified by the user.
"""
__version__ = "0.3.1"
import argparse
import os
import timeit
from random import randint
from .sorts import *
def parse_args(args):
"""Create the parser and add all required arguments before parsing
user input and returning the parser.parse_args() results.
"""
parser = argparse.ArgumentParser(description='sort some integers.')
# Parser group created to take in either argument. (-i or -g).
# Integers manually specified or generated on the fly.
integers_group = parser.add_mutually_exclusive_group(required=True)
integers_group.add_argument('-i', '--integers', type=int, nargs='+',
help='integer(s) being sorted.')
integers_group.add_argument('-g', '--generate', type=int,
help='generate a random list of integers to sort.')
# Specific sort algorithm or use all sort algorithms.
sorting_group = parser.add_mutually_exclusive_group(required=True)
sorting_group.add_argument('-s', '--sort', type=str,
choices=['bubble', 'bogo', 'merge', 'selection', 'quick', 'radix', 'insertion',
'insertion_recursive', 'heap', 'shell'],
help='type of sort being performed.')
sorting_group.add_argument('-a', '--allsorts', action='store_true',
help='run all sort methods (excluding bogo sort).')
# List argument used to display unsorted/sorted list in output.
parser.add_argument('-l', '--list', action='store_true',
help='displays the original and unsorted lists if present.')
# Compare argument to display the time difference compared to the default python sorted() function.
parser.add_argument('-c', '--compare', action='store_true',
help='display the difference in time compared to pythons default \'sorted()\' function.')
return parser.parse_args(args)
def print_error(args, error):
"""Print an error to the screen when a sort fails."""
print('\tAlgorithm: [%s]' % str(args.sort))
print("\terror occurred while sorting: %s" % error)
print("\t")
def print_results(args, sorted_list, time):
"""Print an original list, sorted list and time required to sort the original list."""
print('\tAlgorithm: [%s]' % str(args.sort))
# Determine whether or not the original and sorted lists will be printed
# as part of the results output.
if args.list:
print('\tOriginal List:')
for original_chunk in print_list_chunks(args.integers, 20):
print('\t' + str(original_chunk)[1:-1])
print('\tSorted List:')
for sorted_chunk in print_list_chunks(sorted_list, 20):
print('\t' + str(sorted_chunk)[1:-1])
# Check for the --compare flag being present, and print out the difference
# between this results time and the default sorted() function time.
if args.compare:
print('\tTime(seconds) %s: %s' % (args.sort, time))
print('\tTime(seconds) sorted(): %s' % args.compare_time)
print('\t%s' % calculate_compare_time_difference(time, args.compare_time, args.sort))
else:
print('\tTime(seconds): %s' % time)
print('\t')
def calculate_compare_time_difference(algorithm_time, default_time, algorithm):
"""Calculate the difference between a custom algorithms time taken to sort, and
pythons sorted() function time taken to sort the same list, returns a readable string
detailing which was faster.
"""
difference = algorithm_time - default_time
if difference > 0:
return '%s was %s seconds slower.' % (algorithm, difference)
else:
return '%s was %s seconds faster.' % (algorithm, -difference)
def print_list_chunks(integer_list, n):
"""Simple helper method to print out a list in chunks. This allows
the console output to never surpass a specific width. Giving a cleaner
output if the original/sorted lists are being printed.
"""
for i in range(0, len(integer_list), n):
yield integer_list[i:i + n]
def generate_integer_list(size):
"""Generate a list of integers between specified size value."""
integer_list = list()
for i in range(0, size):
integer_list.append(randint(0, 1000))
return integer_list
def sort(args):
"""Sort a list of integers based on the type of sort specified. Any recursive
algorithms use a try/except to print an error if recursive depth is reached.
"""
# Create a clone of the initial args.integers property.
original_list = list(args.integers)
# Empty sorted_list that will hold list after sort method returns.
sorted_list = list()
# Initial default_timer() method call to grab current time of call.
initial = timeit.default_timer()
if args.sort == 'bubble':
sorted_list = bubble_sort(original_list)
elif args.sort == 'bogo':
sorted_list = bogo_sort(original_list)
elif args.sort == 'selection':
sorted_list = selection_sort(original_list)
elif args.sort == 'merge':
sorted_list = merge_sort(original_list)
elif args.sort == 'shell':
sorted_list = shell_sort(original_list)
elif args.sort == 'quick':
try:
sorted_list = quick_sort(original_list)
except RecursionError as e:
print_error(args, e.args[0])
return
elif args.sort == 'radix':
try:
sorted_list = radix_sort(original_list)
except RecursionError as e:
print_error(args, e.args[0])
return
elif args.sort == 'insertion':
sorted_list = insertion_sort(original_list)
elif args.sort == 'insertion_recursive':
try:
sorted_list = insertion_sort_recursive(original_list)
except RecursionError as e:
print_error(args, e.args[0])
return
elif args.sort == 'heap':
sorted_list = heap_sort(original_list)
# Final default_timer() method call to grab time after sort is completed.
final = timeit.default_timer()
# Check for compare flag and get the time taken for the default sorted() call on list.
if args.compare:
default_initial = timeit.default_timer()
sorted(original_list)
default_final = timeit.default_timer()
args.compare_time = default_final - default_initial
print_results(args, sorted_list, final - initial)
def all_sorts(args):
"""Sort a list using each sorting algorithm excluding the bogo sort."""
sorts = ['bubble', 'selection', 'merge', 'quick', 'radix', 'insertion', 'insertion_recursive', 'heap']
for i in range(0, len(sorts)):
args.sort = sorts[i]
sort(args)
def main():
"""Main method. build arguments, clear console and parse arguments"""
args = parse_args(sys.argv[1:])
# Clear system terminal based on operating system name.
if os.name == 'posix':
os.system('clear')
elif os.name == 'nt':
os.system('cls')
# Check for generate argument specified and create random list.
if args.generate:
args.integers = generate_integer_list(args.generate)
# Print each sort algorithm or just one that has been specified.
if args.allsorts:
all_sorts(args)
else:
sort(args)
|
8b210c5f155c4d4dfefc5c9769790c1203a01111 | the-blackbeard/python-code | /bfs.py | 1,019 | 4.21875 | 4 | class Node:
def __init__(self, name):
self.name = name
self.adjacency_list = []
self.visited = False
def breadth_first_search(start_node):
# FIFO: First item we insert will be taken out first
queue = [start_node]
# We keep iterating (considering the neighbour) until the queue is empty
while queue:
# Remove and return the first item we have inserted in queue
actual_node = queue.pop(0)
actual_node.visited = True
print(actual_node.name)
# Let's consider the neighbour one by one
for n in actual_node.adjacency_list:
if not n.visited:
queue.append(n)
if __name__ == '__main__':
# We create the nodes or vertices
node1 = Node('A')
node2 = Node('B')
node3 = Node('C')
node4 = Node('D')
node5 = Node('E')
# We have to handle the neighbour
node1.adjacency_list.append(node2)
node1.adjacency_list.append(node3)
node2.adjacency_list.append(node4)
node4.adjacency_list.append(node5)
# Run BFS algorithm
breadth_first_search(node1)
|
13bcb68da10012c1f64fb2c6dbc14754813ba162 | aljubaer/AES-Implementation | /engine/cipher_block_chaining.py | 1,278 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 16:01:11 2019
@author: hp
"""
from block_cipher_encryption import block_cipher_encrypt
from block_cipher_decryption import block_cipher_decrypt
from utility import array_xor
def encrypt(message, expanded_key, number_of_rounds, iv):
print('CBC Encrypt')
encrypted_text = []
for i in range(0, len(message), 16):
initial = message[i : i + 16]
initial = array_xor(iv, initial)
block_encypted_text = block_cipher_encrypt(initial, expanded_key, number_of_rounds)
encrypted_text += block_encypted_text
iv = block_encypted_text[0:16]
encrypted_text = [chr(i) for i in encrypted_text]
return ''.join(encrypted_text)
def decrypt(encrypted_message, expanded_key, number_of_rounds, iv):
decrypted_text = []
print('CBC Decrypt')
for i in range(0, len(encrypted_message), 16):
initial = encrypted_message[i : i + 16]
block_decrypted_text = block_cipher_decrypt(initial, expanded_key, number_of_rounds)
block_decrypted_text = array_xor(iv, block_decrypted_text)
decrypted_text += block_decrypted_text
iv = initial
decrypted_text = [chr(i) for i in decrypted_text]
return ''.join(decrypted_text)
|
7456e34e998eb140942f5d714cd2430d84f4181c | birajaghoshal/uncertainties-1 | /representation/mnist.py | 3,795 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""Simple feedforward neural network for Mnist."""
#%% Packages
import os
import shutil
from absl import app
import numpy as np
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Flatten
from sklearn.model_selection import train_test_split
import utils.util as util
NUM_CLASSES = 10
#%% Define and train the model
def build_model(num_classes):
model = Sequential()
model.add(Flatten(input_shape=(28, 28), name='l_1'))
model.add(Dense(512, activation='relu', name='l_2'))
model.add(Dense(20, activation='relu', name='features_layer'))
model.add(Dense(num_classes, activation='softmax', name='ll_dense'))
return model
def input_data():
(x_train, y_train),(x_test, y_test) = keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
return (x_train, y_train), (x_test, y_test)
def features_extraction(model, model_path, input_data):
"""Extract the features from the last layer.
Args:
model: full keras model.
model_path: path to the full saved model.
input_data: input data for the features.
Returns:
features: features corresponding to the input data.
"""
submodel = Model(inputs=model.input,
outputs=model.get_layer('features_layer').output)
submodel.load_weights(model_path, by_name=True)
features = submodel.predict(input_data)
return features
def main(argv):
# batch_size = 32, default
# Training of the model
n_class = argv[0]
method = argv[1]
(x_train, y_train), (x_test, y_test) = input_data()
model = build_model(n_class)
index = util.select_classes(y_train, n_class, method=method)
path_dir = 'saved_models/mnist-{}-{}'.format(method, n_class)
sec = np.dot(y_train, index).astype(bool)
if os.path.isdir(path_dir):
shutil.rmtree(path_dir, ignore_errors=True)
os.makedirs(path_dir)
np.save(os.path.join(path_dir, 'index.npy'), index)
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train[sec,:], y_train[np.ix_(sec, index)], epochs=20)
model_path = os.path.join(path_dir, 'mnist.h5')
model.save_weights(model_path)
print('Saved trained model at %s ' % model_path)
sec_test = np.dot(y_test, index).astype(bool)
losses_in = model.evaluate(x_test[sec_test,:],
y_test[np.ix_(sec_test, index)])
print('losses in')
print(losses_in)
# In and out of sample distribution
sec_train = np.dot(y_train, index).astype(bool)
sec_test = np.dot(y_test, index).astype(bool)
x_train_in, x_train_out = x_train[sec_train, :], x_train[~sec_train, :]
y_train_in = y_train[np.ix_(sec_train, index)]
x_test_in, x_test_out = x_test[sec_test, :], x_test[~sec_test, :]
y_test_in = y_test[np.ix_(sec_test, index)]
# Compute the features
submodel = Model(inputs=model.input,
outputs=model.get_layer('features_layer').output)
submodel.load_weights(model_path, by_name=True)
features_train_in = submodel.predict(x_train_in)
features_train_out = submodel.predict(x_train_out)
features_test_in = submodel.predict(x_test_in)
features_test_out = submodel.predict(x_test_out)
np.savez(os.path.join(path_dir, 'features.npz'),
features_train_in=features_train_in,
features_train_out=features_train_out,
features_val_in=features_test_in,
features_val_out=features_test_out
)
np.savez(os.path.join(path_dir, 'y.npz'),
y_train_in=y_train_in,
y_val_in=y_test_in
)
if __name__ == '__main__':
app.run(main, argv=[5, 'first'])
|
7c89ce41eb74d47444d7f8bef22ff0aee2497048 | SunshineHai/PythonTest | /DataStructure/mo.py | 346 | 3.625 | 4 |
def BBsort(array):
for i in range(1, len(array)):
for j in range(0, len(array)-i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
def writeresult(path, result):
with open(path, 'w' ,encoding='utf-8') as source:
source.writelines(result) |
778ffeb74ddaae6e0d01d15ddb73219948b30722 | Team-Tomato/Learn | /Juniors - 1st Year/Suvetha Devi/day4/string_rev.py | 164 | 4.3125 | 4 |
def reverse(word):
i= -1
while i>=-(len(word)):
print (word[i] ,end =" ")
i-=1
str = input("Enter a string to reverse")
reverse(str) |
6a178cf163df0fa5e59cd39318538b49dab0a22e | thisismsp78/PythonCodsLearn | /p1/RangeDemo/RangeDemo.py | 210 | 4 | 4 | number=int(input("Enter number : "))
if number>100 or number<0:
print("Invalid !")
elif number>75:
print("A")
elif number>50:
print("B")
elif number>25:
print("C")
else:
print("D") |
0a68c4b7482b395f09b33602f7d1797aa9699e50 | cuiqs/pythonlearn | /dnsreverse.py | 1,292 | 4.15625 | 4 | #!/usr/bin/env python
# Performs a reverse lookup on the IP address given on the command line
import sys,socket
def getipaddrs(hostname):
"""Get a list of IP address from a given hostname. this is a standard\
(forward) lookup"""
result=socket.getaddrinfo(hostname,None,0,socket.SOCK_STREAM)
return [x[4][0] for x in result]
def gethostname(ipaddr):
"""Get the hostname from a given ip address.this is a reverse look\ up."""
return socket.gethostbyaddr(ipaddr)[0]
try:
#First ,do the reverse lookup and get the hostname
hostname=gethostname(sys.argv[1])
#Now,do a forward lookup on the result from the earlier reverse lookup
ipaddrs=getipaddrs(hostname)
except socket.gaierror,e:
print "Got hostname %s,but it could not be forward-resovled:%s"\
%(hostname,str(e))
sys.exit(1)
except socket.herror,e:
print "No host names a vailable for %s ; this maybe normal." %sys.argv[1]
sys.exit(0)
# If the forward lookup did not yield the original ip address anywhere
#someone is playing tricks . Explain the situation and exit.
if not sys.argv[1] in ipaddrs:
print "Got hostname %s,but on forward lookup,"%hostname
print "original IP %s did not appear in IP address list" %sys.argv[1]
sys.exit(1)
#Otherwise show the validated hostname
print "Validated hostname:", hostname
|
8841ad7e4cf981985bbe154bbc9677cab722573b | CharlieHoffmann/NumericalMethods | /BubbleSortCH.py | 500 | 4 | 4 | def Bubble(a):
for j in range(len(a)-1):
for k in range(len(a)-1,j,-1):
print("j=",j,"k=",k);
if(a[k]<a[k-1]):
temp=a[k];
a[k]=a[k-1];
a[k-1]=temp;
print(*a);
else:
print("a*");
print("Final sorted string", *a, " n =",len(a));
print("Charlie Hoffmann BubbleSort");
a=eval(input("Enter a list of numbers(ex. '[1,5,3,7,4]') "));
Bubble(a);
|
03c7f1944bceb2bd7878abb52ff4395201ecfa03 | vcarehuman/tf-pose-estimation-master | /ytfgpu.py | 1,958 | 3.765625 | 4 | import numpy as np
#
#def sigmoid(x):
# s = 1 /(1+np.exp(-x))
# print(s)
# return s
#x = np.array([1, 2, 3])
#print("Sigmoid of x is = " +str(sigmoid(x)) + "\n")
#
#def sigmoid_derivative(x):
# s = sigmoid(x)
# ds = s*(1-s)
# print(ds)
# return ds
#x = np.array([1, 2, 3])
#
#print("\n sigmoid_derivative of x = "+ str(sigmoid_derivative(x)))
# GRADED FUNCTION: image2vector
#def image2vector(image):
# """
# Argument:
# image -- a numpy array of shape (length, height, depth)
#
# Returns:
# v -- a vector of shape (length*height*depth, 1)
# """
#
# ### START CODE HERE ### (≈ 1 line of code)
# v = image.reshape((image.shape[0]*image.shape[1]*image.shape[2], 1))
# ### END CODE HERE ###
#
# return v
#image = np.array([[[ 0.67826139, 0.29380381],
# [ 0.90714982, 0.52835647],
# [ 0.4215251 , 0.45017551]],
#
# [[ 0.92814219, 0.96677647],
# [ 0.85304703, 0.52351845],
# [ 0.19981397, 0.27417313]],
#
# [[ 0.60659855, 0.00533165],
# [ 0.10820313, 0.49978937],
# [ 0.34144279, 0.94630077]]])
#a = image.shape
#print(a)
#print (image, "\n")
#print ("image2vector(image) = " + str(image2vector(image)))
# GRADED FUNCTION: normalizeRows
def normalizeRows(x):
"""
Implement a function that normalizes each row of the matrix x (to have unit length).
Argument:
x -- A numpy matrix of shape (n, m)
Returns:
x -- The normalized (by row) numpy matrix. You are allowed to modify x.
"""
### START CODE HERE ### (≈ 2 lines of code)
# Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)
x_norm = np.linalg.norm(x, ord =2, axis = 1, keepdims = True )
# Divide x by its norm.
x = x/x_norm
### END CODE HERE ###
return x
x = np.array([
[0, 3, 4],
[1, 6, 4]])
print("normalizeRows(x) = " + str(normalizeRows(x))) |
b9bc1dd86e9796ddf1074c0ce1bb2974a7d496bc | KuroDev89/Python-Crash-Course | /dicc.py | 210 | 3.734375 | 4 | person={'name':'Aurelio','age':31, 'job':'Profesor'}
# print(person)
# print(type(person))
# print(dir(dict))#conociendo los métodos y funciones
#obtener las llaves
print(person.keys())
print(person.items()) |
884c5b9339b84174d009239ed54146266fc782aa | ayushakar1/Pycamp | /day 2/assig1.py | 280 | 4.0625 | 4 | def input(a,b,c,d):
summ = a+b+c+d
product= a*b*c*d
diff = (a+b)+(c-d)
random_operation = ((a+b-3)**c)//d
return summ,product,diff,random_operation #returns multiple values as a result
print(input(5,33,6,9)) #passes multiple arguments as input |
b5e4ef7c2c9b94a29456899b56a48547d5b5a10d | demelue/easy-medium-code-challenges | /Python/ArrayManipulation/find_maximum_square.py | 1,326 | 3.828125 | 4 | #brute force
def find_max_square(matrix):
row_dim = len(matrix)
col_dim = len(matrix[0])
max_sq_len = 0
for r in range(row_dim):
for c in range(col_dim):
if matrix[r][c] == 1:
flag = True
sq_len = 1
while sq_len + r < row_dim and sq_len + c < col_dim and flag: #find more 1's
#check next box along col
# print(r,c,sq_len)
for k in range(c,sq_len + c + 1):
# print("col index: ",r + sq_len,k)
if matrix[r + sq_len][k] == 0:
flag = False
break
#check next box along row
for k in range(r,sq_len + r + 1):
# print("row index: ",k,c+sq_len)
if matrix[k][c + sq_len] == 0:
flag = False
break
if flag:
sq_len += 1
if sq_len > max_sq_len:
max_sq_len = sq_len
print("Maximum sub matrix: ", max_sq_len * max_sq_len)
if __name__ == '__main__':
mat = [[0,0,1,0],
[1,1,1,0],
[0,1,1,1],
[1,1,1,0]]
find_max_square(mat)
|
83d682f5c753c15e3e6e556776b0806d68215d4d | RiikkaKokko/JAMK_ohjelmoinnin_perusteet | /exercise15/Tehtävä_L15T04.py | 495 | 3.6875 | 4 | while True:
luku = input("Kirjoita numero")
try:
luku = int(luku)
print('This is a int')
filename1=("Integers.txt")
file1=open(filename1, "w")
file1.write(str(luku))
file1.close()
except:
try:
luku = float(luku)
print('This is a float')
filename="Floats.txt"
file=open(filename, "w")
file.write(str(luku))
file.close()
except:
break
|
d7a4fd338e4e40bc66b7760167f59ea6a8a8b17b | vuquocm/VuQuocMinh-c4t7 | /dict_hw2/tn.py | 1,204 | 3.890625 | 4 | # print('how many engines does an a 340 have?')
# answer = {
# 'A' : 2,
# 'B' : 4,
# 'C' : 3,
# 'D' : 1
# }
# for k, v in answer.items():
# print(k,v, sep=":")
# rep = str.upper(input('enter your anwser'))
# while True:
# if rep == 'B':
# print('correct')
# break
# else:
# print('incorrect')
a = 0
print('how many engines does an a 340 have?')
answer1 = {
'A' : 2,
'B' : 4,
'C' : 3,
'D' : 1
}
for f, g in answer1.items():
print(f,g, sep=":")
rep1 = str.upper(input('enter your anwser'))
if rep1 == 'B':
print('correct')
a += 1
print('how many engines does an a 777 have?')
answer2 = {
'A' : 2,
'B' : 4,
'C' : 3,
'D' : 1
}
for h,j in answer2.items():
print(h,j, sep=":")
rep2 = str.upper(input('enter your anwser'))
if rep2 == 'B':
print('correct')
a += 1
print('how many engines does an a Flacon 700X have?')
answer3 = {
'A' : 2,
'B' : 4,
'C' : 3,
'D' : 1
}
for k, v in answer3.items():
print(k,v, sep=":")
rep3 = str.upper(input('enter your anwser'))
if rep3 == 'B':
print('correct')
a += 1
print('correct ', a)
percent = a/3*100
print('percentage:', percent)
|
bbcf7129700f0857cc607bc510c55b150a56c5b1 | YashSaxena75/GME | /gameer.py | 1,861 | 3.921875 | 4 | c=None
k=None
y=""
z=""
x=None
print("You have 30 points in the very starting of the game")
print("Rules for the game are:")
print("""
1:If you choose any attribute u will loose 7.5 points
2:You can take back ur points from that attribute
3:You will loose the game if ur points become 0 or less than 0
""")
p=30
flag=0
att={"Strength":"You will loose 7.5 points","health":"Yo will loose 7.5 points"}
print("Attribute list contains",list(att))
while c!=0:
c=int(input("Enter 0 here to exit or Enter 1 to continue the script:"))
if c==0:
print("GOOD-BYE!!!")
flag=1
if flag==0:
y=input("Please Choose ur Attribute:")
if y=='Strength':
p-=7.5
print("NOw ur points are:",p)
elif y=='health':
p-=7.5
print("ur points are:",p)
print("Choosed the wrong attribute accedentaly No worry just enter the 9 and see the magic")
x=int(input("Enter 9 here:"))
if x==9:
z=input("Enter the wrongly selected Attribute here:")
if 'Strength' in y:
if z=='Strength':
p+=7.5
print("YIPEEE!!! you got ur points back,Ur points are:",p,"but if u cheat u will loose more points according to the rules!!!")
else:
print("U are trying to cheat bro!!!","now if you continue u will loose more points")
if 'health' in y:
if z=='health':
p+=7.5
print("Yipee you got ur points back,""ur points are:",p,"but if u cheat u will loose more points according to the rules!!! ")
else:
print("U are trying to cheat bro","now if you continue u will loose more points")
else:
print("According to u,u have entered the correct attribute so proceeding further.....")
if p<=0:
print("As ur points are zero now so You loose the game!exiting the game")
c=0
|
0235317cfab4f69d6a50a316ebb0feed1e52bcbf | EyreC/PythonCiphers | /backwards.py | 483 | 4.25 | 4 | import string
def backwards(inputString):
wordList = inputString.split(" ") #list of space-separated words in inputString
backwardsList = [] #list of reversed words
#Generate list of reversed words
for word in wordList:
newWordList=[]
for index,letter in enumerate(word):
newWordList.append(word[-(index+1)])
newWord = "".join(newWordList)
backwardsList.append(newWord)
return " ".join(backwardsList).capitalize()
|
5825345d205a5cd2277684d0c9c41a55b97dea1f | Aasthaengg/IBMdataset | /Python_codes/p02261/s626200736.py | 1,271 | 3.828125 | 4 | import time
import copy
def BubbleSort(A, N):
flag = 1
while flag:
flag = 0
for j in reversed(range(1, N)):
if A[j]['value']<A[j-1]['value']:
A[j], A[j-1] = A[j-1], A[j]
flag = 1
return A
def SelectionSort(A, N):
for i in range(0, N):
minj = i
for j in range(i, N):
if A[j]['value']<A[minj]['value']:
minj = j
if i!=minj:
A[i], A[minj] = A[minj], A[i]
return A
def IsStable(answer, target):
N = len(answer)
for i in range(N):
if answer[i]['body'] != target[i]['body']:
return False
return True
# Stable Sort
def main():
N = int(input())
A = list(
map(lambda x: {'body': x, 'value': int(x[1])}, input().split())
)
A_sortby_bubble = copy.deepcopy(A)
A_sortby_select = copy.deepcopy(A)
A_sortby_bubble = BubbleSort(A_sortby_bubble, N)
A_sortby_select = SelectionSort(A_sortby_select, N)
print(' '.join(map(lambda x: x['body'],A_sortby_bubble)))
print('Stable')
print(' '.join(map(lambda x: x['body'], A_sortby_select)))
if IsStable(A_sortby_bubble, A_sortby_select):
print('Stable')
else:
print('Not stable')
main()
|
75ab452b5b19b73a743c89d58dfb892a9660f3be | tpt5cu/python-tutorial | /language/old/built_in_types/floats.py | 831 | 3.875 | 4 | def float_precision():
"""The maximum floating point value is just under 1.08e308, which is 64-bit double precision.
Any floating point value greater than that is represented by the string 'inf'."""
print(1.79e308)
print(1.8e308)
print(1.79e309)
"""The smallest positive floating point value is about 5.0e-324. Anything less is 0."""
print(5.0e-324)
print(5.0e-325)
print(3.0e-324)
"""Most decimal fractions cannot be perfectly represented by binary fractions, so a floating point value
is often an approximation of a decimal fraction."""
def scientific_notation():
"""Using 'e' or 'E' with a floating point value uses scientific notation"""
# 40,000
print(4.0e5)
# .0041
print(4.1e-3)
if __name__ == "__main__":
float_precision()
# scientific_notation()
|
6928daa9732d370a0d361ab941c8f6a56734955d | BrandonP321/Python-masterclass | /Dictionaries&Sets/sets.py | 957 | 4.15625 | 4 | # farm_animals = {"sheep", "cow", "hen", "pig"}
# print(farm_animals)
#
# for animal in farm_animals:
# print(animal)
#
# wild_animals = set(["lion", "tiger", "bear"])
# print(wild_animals)
#
# for animal in wild_animals:
# print(animal)
#
# farm_animals.add("horse")
# wild_animals.add("horse")
# print(farm_animals)
# print(wild_animals)
#
# empty_set = set()
# empty_set2 = {}
# empty_set.add("a")
# empty_set2.add("a")
# print(empty_set)
# print(empty_set2)
even = set(range(0, 40, 2))
print(even)
print(len(even))
squares_tuple = 4, 6, 9, 16, 25
squares = set(squares_tuple)
print(squares)
print(len(squares))
print(even.union(squares))
print(even & squares)
even.difference_update(squares)
print(even)
even = set(range(0, 40, 2))
squares = {4, 6, 16}
if squares.issubset(even):
print("Squares is a subset of even")
if even.issuperset(squares):
print("Even is a superset of squares")
|
20ca3b613852f9d5c7d06ff9ca145e5d54ca65a1 | qi-zhang8/Exercises | /stringPermutation.py | 198 | 3.59375 | 4 | def getPermutation(s, prefix=''):
if len(s) == 0:
print prefix
for i in range(len(s)):
print("s[0:%d]"%i, s[0:i])
getPermutation(s[0:i]+s[i+1:len(s)],prefix+s[i])
getPermutation('abc', '')
|
2db126e208d792e7a1f0edcfa0d072b611362bdc | blakeaw/PyBILT | /pybilt/common/distance_cutoff_clustering.py | 7,070 | 3.828125 | 4 | """Function to compute hiearchical distance cutoff clusters."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import range
def distance_euclidean(v_a, v_b):
"""Compute the Euclidean distance between two vectors.
Args:
v_a (numpy.array, array like): The first input vector.
v_b (numpy.array, array like): The second input vector.
Returns:
float: The Euclidean distance between the two vectors.
Notes:
The two vectors should have the same size and dimension.
"""
d_v = v_a - v_b
return np.sqrt(np.dot(d_v, d_v))
def distance_euclidean_pbc(v_a, v_b, box_lengths, center='zero'):
"""Compute the Euclidean distance between two vectors under periodic boundaries.
Args:
v_a (numpy.array, array like): The first input vector.
v_b (numpy.array, array like): The second input vector.
box_lengths (numpy.array, array like): The periodic boundary box
lengths for each dimension.
center (Optional[str, array like]): Set the coordinate center of the
periodic box dimensions. Defaults to 'zero', which sets the
center to numpy.zeros(len(box_lengths)). Also accepts the string
value 'box_half', which sets the center to 0.5*box_lengths.
Returns:
float: The Euclidean distance between the two vectors.
Notes:
The two vectors should have the same size and dimension, while
box_lengths should have the length of the vector dimension.
"""
if isinstance(center, str):
if center == 'zero':
center = np.zeros(len(v_a))
elif center == 'box_half':
center = np.array(box_lengths)/2.0
# shift center to zero for minimum image
v_a = v_a - center
v_b = v_b - center
#print(v_a)
#print(v_b)
# difference
d_v = v_a - v_b
#print(d_v)
d_v_a = np.absolute(d_v)
dim = len(v_a)
# check for minimum image
for i in range(dim):
v_i = d_v_a[i]
box_i = box_lengths[i]
box_i_h = box_i/2.0
if v_i > box_i_h:
d_v[i] = box_i - np.absolute(v_a[i]) - np.absolute(v_b[i])
#print(d_v)
r = np.sqrt(np.dot(d_v, d_v))
return r
def vector_difference_pbc(v_a, v_b, box_lengths, center='zero'):
"""Compute the Euclidean distance between two vectors under periodic boundaries.
Args:
v_a (numpy.array, array like): The first input vector.
v_b (numpy.array, array like): The second input vector.
box_lengths (numpy.array, array like): The periodic boundary box
lengths for each dimension.
center (Optional[str, array like]): Set the coordinate center of the
periodic box dimensions. Defaults to 'zero', which sets the
center to numpy.zeros(len(box_lengths)). Also accepts the string
value 'box_half', which sets the center to 0.5*box_lengths.
Returns:
float: The Euclidean distance between the two vectors.
Notes:
The two vectors should have the same size and dimension, while
box_lengths should have the length of the vector dimension.
"""
if isinstance(center, str):
if center == 'zero':
center = np.zeros(len(v_a))
elif center == 'box_half':
center = np.array(box_lengths)/2.0
# shift center to zero for minimum image
v_a = v_a - center
v_b = v_b - center
#print(v_a)
#print(v_b)
# difference
d_v = v_b - v_a
#print(d_v)
d_v_a = np.absolute(d_v)
dim = len(v_a)
# check for minimum image
for i in range(dim):
v_i = d_v_a[i]
box_i = box_lengths[i]
box_i_h = box_i/2.0
if v_i > box_i_h:
d_v_p = box_i - np.absolute(v_a[i]) - np.absolute(v_b[i])
d_v_aa = np.absolute(d_v[i])
if (d_v_p > 0.0) and (d_v_aa > 0.0):
d_v[i] = d_v_p * (-1.0*d_v[i]/d_v_aa)
#print(d_v)
#d_v_pbc = d_v * d_v_n
#r = np.sqrt(np.dot(d_v, d_v))
return d_v
def distance_cutoff_clustering(vectors, cutoff, dist_func, min_size=1,
*df_args, **df_kwargs):
"""Hiearchical distance cutoff clustering.
This function takes a set of vector points and clusters them using a
hiearchical distance based clustering algorithm. Points are clustered
together whenevever a point is within the cutoff distance of any point
within in a cluster.
Args:
vectors (np.array, list like): The array of vector points.
cutoff (float): The cutoff distance.
dist_func (function): The function to use when computing the distance
between points.
min_size (Optional[int]): The minimum size of a cluster. Defaults to 1.
*df_args: Any additional arguments to be passed to the distance
function (dist_func).
**df_kwargs: Any additional keyword arguments to be passed to the
distance function (dist_func).
Returns:
list: Returns a list of clustered points where each set of clustered i
points is a list of the indices of the points in that cluster.
"""
# compute the boolean distance-cutoff matrix
nvecs = len(vectors)
dist_bool = np.zeros((nvecs, nvecs), dtype=np.bool)
for i in range(nvecs-1):
vec_a = vectors[i]
for j in range(i+1, nvecs):
vec_b = vectors[j]
dist = dist_func(vec_a, vec_b, *df_args, **df_kwargs)
if dist <= cutoff:
dist_bool[i][j] = True
dist_bool[j][i] = True
else:
dist_bool[i][j] = False
dist_bool[j][i] = False
clusters = []
master = []
for i in range(nvecs):
master.append([i, False])
# print(master)
# clustind = 0
neighbors = []
while len(master) > 0:
start = master[0][0]
master[0][1] = True
# print(master)
# reset the neigbor list
neighbors = []
# seed neighborlist with start
neighbors.append(start)
# now loop over the neigbor list and build neigbors and
# neighbors of neighbors
i = 0
while i < len(neighbors):
# print(neighbors)
a = neighbors[i]
# vec_a = vectors[a]
for j in range(len(master)):
b = master[j][0]
if not master[j][1]:
# print "a ",a," b ",b
# vec_b = vectors[b]
if dist_bool[a][b]:
neighbors.append(b)
master[j][1] = True
# print(neighbors)
# print(master)
i += 1
master = list([v for v in master if not v[1]])
# print(master)
if len(neighbors) > min_size:
clusters.append(list(neighbors))
# clusters[clustind] = list(neighbors)
return clusters
|
8c310ec646b3164f8fc6f210c265df590fdf4aa8 | neriphy/evaluar_numeros_perfectos | /numeros_perfectos.py | 748 | 3.78125 | 4 | #Calculador de numeros perfectos
#Creado por @neriphy
import time
numero = int(input("¿Que numero desea evaluar? "))
start = time.time()
intentos = numero
suma = 0
intentos = numero - 1
while intentos>0:
if numero%intentos == 0:
suma = intentos + suma
print("intentos",intentos,"y suma=",suma)
"""elif numero&intentos != 0:
intentos = intentos - 1"""
intentos = intentos - 1
if suma == numero:
print(numero , "es un numero perfecto")
else:
print(numero, "no es un numero perfecto")
print(suma)
if suma == 1:
print(numero,"es numero primo")
if suma != 1:
print(numero,"no es numero primo")
end = time.time()
time_elapsed = end - start
time_in_miliseconds = time_elapsed * 1000
print("\nTiempo:",time_in_miliseconds)
|
b993d85079946b5d54b0138a16d172970974331b | piekey1994/spiderdemo | /initSql.py | 700 | 3.53125 | 4 | import sqlite3
conn = sqlite3.connect('test.db')
print("Opened database successfully")
conn.execute('''CREATE TABLE food
(id varchar(50) PRIMARY KEY NOT NULL,
name varchar(100) NOT NULL,
href text not null,
usetime varchar(10),
taste varchar(50),
img text not null,
technology varchar(10),
steps int,
hot int,
time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP);''')
conn.execute('''CREATE TABLE label
(id INTEGER PRIMARY KEY NOT NULL,
fid varchar(50) NOT NULL,
label varchar(50) NOT NULL,
time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP);''')
print("Table created successfully")
conn.close() |
38dc347dd5e01a4a145f117fec8e76858bd009f9 | lucasffgomes/Python-Intensivo | /seçao_06/exercicio_seçao_06/exercicio_05.py | 256 | 4.03125 | 4 | """
Faça um programa que peça ao usuário para digitar 10 valores e some-os.
"""
print("Vamos calcular a soam de 10 valores.")
resultado = 0
for vez in range(0, 10):
valor = int(input("Digite o valor: "))
resultado += valor
print(resultado)
|
7d68f461be3e8144e36a2faaf0ee3f9d65edbbe8 | chionglai/euler | /q032.py | 2,445 | 3.5625 | 4 | #!/usr/bin/env python
import time
import itertools as it
"""
q032:
We shall say that an n-digit number is pandigital if it makes use of all the digits 1
to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand,
multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written
as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it
once in your sum.
Algorithm:
1. Given a * b = c, where a, b, c must contain all digits 1-9
2. Hence, a = 9 permutate i, and b = (9-i) permutate j
3. Since i + j < 9 digits - i - j + 1 --> i + j < 5, (i, j) = (1, 4), (2, 3), ...
"""
DIGIT = range(1, 10)
MAX_DIGIT_FACTOR = 4
aRes = []
bRes = []
cRes = []
tic = time.time()
# for i = 1 to 4
for i in range(MAX_DIGIT_FACTOR, 0, -1):
# get all permutation for a
aList = list(it.permutations(DIGIT, i))
# for each permutation of a
for aSub in aList:
# remove digits already in a
bDigit = [d for d in DIGIT if d not in aSub]
# convert a to int
a = reduce(lambda r, d: r * 10 + d, aSub)
# for j = 4 to 1
for j in range(1, MAX_DIGIT_FACTOR - i + 2):
# get all permutation for b
bList = list(it.permutations(bDigit, j))
# for each permutation of b
for bSub in bList:
# remDigit will always in ascending order
remDigit = [d for d in bDigit if d not in bSub]
b = reduce(lambda r, d: r * 10 + d, bSub)
product = a * b
prodList = [int(digit) for digit in str(product)]
# product found iff
# 1. length of (a * b) == length(remDigit)
# 2. all digit in remDigit in (a * b)
if len(prodList) == len(remDigit) and all(x in prodList for x in remDigit):
aRes.append(a)
bRes.append(b)
cRes.append(product)
res = sum(set(cRes))
toc = time.time()
print "Result = %d, in %f s" % (res, toc - tic)
# (Optional) remove non-unique product
aUni = []
bUni = []
cUni = []
for i, c in enumerate(cRes):
if c not in cUni:
aUni.append(aRes[i])
bUni.append(bRes[i])
cUni.append(c)
|
24cc718e8fea644181372537feecf9039e7b3c5f | nurack/eric-pcc-solutions | /PCC2_10.py | 362 | 4.0625 | 4 | #it prints the message using the variable name
name = "Eric"
print(f"Hello {name}, would you like to learn some Python today?")
name = "\t Anurag \n Singh "
print(name)
print(name.lstrip())
print(name.rstrip())
print(name.strip())
#different strip functions are performed on the same variable but it is not permanent the value of the variable is stil the same |
ddfe0a592d2a9d801d971c7048f10f6a0e19c6ee | Moeh-Jama/Kattis-Problems | /flip.py | 119 | 3.59375 | 4 | numbers = input().split()
i = 2
a = ''
b = ''
while i>=0:
a += numbers[0][i]
b += numbers[1][i]
i-=1
print(max(a,b)) |
cd3591ccded132a91a48821d7a9b9b3cb77c16b4 | JayantGoel001/Open-Source | /Week2/20.py | 356 | 3.921875 | 4 | import collections
import pprint
file_input = input()
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
a = file_input.split(".")
if a[1] == "txt":
print("it is a text file")
elif a[1] == "cpp":
print("it is a c++ file")
else:
print("it is a c file")
|
2dcb81c7bbeba7e426829a378f9afbe12237fd5a | Elvis2597/Python_Programs | /CountChar.py | 89 | 3.921875 | 4 | list=input("enter the list:")
str=str(list)
for i in str:
str=str.count(i)
print str
|
b3547d48193d66569259bda3679dd9a9d4cecafa | MikuWRS/PythonJust4Fun | /Proyecto4_TicTacToe_IA/proyecto4.py | 3,192 | 3.578125 | 4 | import os
tablero=[' ' for x in range(10)]
c_posicion='123456789'
def insertar(marca,ins_posicion):
tablero[ins_posicion]=marca
def p_tablero(tablero):
print(" | | \n")
print(" "+tablero[1]+" | "+tablero[2]+" | "+tablero[3]+" \n")
print(" | | \n")
print("------------------\n")
print(" | | \n")
print(" "+tablero[4]+" | "+tablero[5]+" | "+tablero[6]+" \n")
print(" | | \n")
print("------------------\n")
print(" | | \n")
print(" "+tablero[7]+" | "+tablero[8]+" | "+tablero[9]+" \n")
print(" | | \n")
def espaciolibre(esp_posicion):
return (tablero[esp_posicion]==' ')
def tablerolleno(tablero):
if tablero.count(' ')>1:
return False
else:
return True
def ganador(tablero,marca):
return ((tablero[1]==marca and tablero[2]==marca and tablero[3]==marca) or
(tablero[4]==marca and tablero[5]==marca and tablero[6]==marca) or
(tablero[7]==marca and tablero[8]==marca and tablero[9]==marca) or
(tablero[1]==marca and tablero[4]==marca and tablero[7]==marca) or
(tablero[2]==marca and tablero[5]==marca and tablero[8]==marca) or
(tablero[3]==marca and tablero[6]==marca and tablero[9]==marca) or
(tablero[1]==marca and tablero[5]==marca and tablero[9]==marca) or
(tablero[3]==marca and tablero[5]==marca and tablero[7]==marca))
def turnojugador():
while True:
turno=input("Ingrese posicion para marcar (1-9)\n")
if turno in c_posicion:
turno=int(turno)
if espaciolibre(turno):
insertar('X',turno)
break
else:
print("El espacio ya esta ocupado\n")
else:
print("Seleccione una posicion correcta\n")
def turnoIA():
movposibles=[x for x, marca in enumerate(tablero) if marca==' ' and x != 0]
movimiento=0
for marca in ['O','X']:
for m in movposibles:
c_tablero=tablero[:]
c_tablero[m]=marca
if ganador(c_tablero,marca):
movimiento=m
return movimiento
esquinas=[]
for i in movposibles:
if i in [1,3,7,9]:
esquinas.append(i)
if len(esquinas) > 0:
turno=selrandom(esquinas)
return turno
if 5 in movposibles:
turno=5
return turno
lados=[]
for i in movposibles:
if i in [2,4,6,8]:
lados.append(i)
if len(lados)>0:
turno=selrandom(lados)
return turno
def selrandom(lista):
import random
l=len(lista)
r=random.randrange(0,l)
return lista[r]
def main():
print("Bienvenido al 3 en raya\n")
p_tablero(tablero)
while not(tablerolleno(tablero)):
if not(ganador(tablero,'O')):
turnojugador()
os.system('clear')
p_tablero(tablero)
else:
print("Lo siento, perdiste\n")
break
if not(ganador(tablero,'X')):
turno=turnoIA()
if turno==0:
print(" ")
else:
insertar('O',turno)
print("IA puso un O en la posicion ",turno,":\n")
os.system('clear')
p_tablero(tablero)
else:
print("Has Ganado\n")
break
if tablerolleno(tablero):
print("Empate\n")
main()
while True:
x=input("Quieres jugar otra vez? (s/n)\n")
if x.lower()=='s':
tablero=[' ' for x in range(10)]
print('-------------------------\n')
main()
elif x.lower()=='n':
break
else:
print("Ingrese una opcion correcta\n")
|
921975d39894238512519cd91d3fcca833838a4b | mrsempress/Simple-Interpreter | /Python/test.py | 813 | 3.65625 | 4 | """
read code from "Code.txt", and then put the strings to the interpreter
show the pictures of the statements
"""
import matplotlib.pyplot as plt
import Grammar
import Exceptions
# Open code document
print("The code is follows: ")
with open("Code.txt") as fp:
for line in fp.readlines():
# 删除分隔符,如\n, \r, \t, ' '
print(line.strip())
print()
# run the code
print("Begin learning the code, and draw the result.")
try:
Grammar.program()
ax = plt.gca()
plt.xlim(0)
plt.ylim(0)
ax.set_aspect("equal") # set axes per unit length are same
ax.xaxis.set_ticks_position('top') # set the number's position of axis
ax.invert_yaxis() # make the y axis invert
plt.show()
except Exceptions.NoMatchingWord as e:
print("GRAMMAR EXCEPTION:", e.args)
|
12b1ede17ae5e072c62477e430e672caf5bed798 | fdouw/AoC2019 | /Day04/day04.py | 688 | 3.921875 | 4 | #!/usr/bin/env python3
def match(num):
"""
count the recurrence of digits
-1 if any digits are in the wrong order: filter this out
2 if any digit appears exactly twice: count these for part 1 and 2
max recurrence otherwise: count for part 1 if > 2, but filter if 1
"""
s = str(num)
for i, c in enumerate(s):
if i > 0 and s[i-1] > c:
return -1
l = list(s)
counts = set(l.count(c) for c in set(s))
return 2 if 2 in counts else max(counts)
digit_counts = list(match(n) for n in range(137683,596253))
print("Day 04")
print(f"1. {sum(1 for n in digit_counts if n > 1)}")
print(f"2. {sum(1 for n in digit_counts if n == 2)}") |
2d7b2c0e8b4798a7fa336c3c6ebc35957c5e3e68 | saeidp/Data-Structure-Algorithm | /Sorting/InsertionSort.py | 1,859 | 4.125 | 4 | # Implement Insertion Sort
# On the first pass, it compares a maximum of one item.
# On the second pass, it’s a maximum of two items,
# and so on, up to a maximum of N-1 comparisons on the last
# pass. This is 1 + 2 + 3 + … + N-1 = N*(N-1)/2
# However, because on each pass an average of only half of
# the maximum number of items are actually compared before
# the insertion point is found, we can divide by 2,
#which gives N*(N-1)/4. Insertion sort is almost 2 times
# the bubble sort but slightly better than selection sort
#O(N^2)
def insertionSort(array):
n = len(array)
for i in range(n - 1):
for j in range(i + 1, 0 , -1):
if(array[j - 1] > array[j]):
array[j - 1] , array[j] = array[j], array[j-1]
else:
break
return array
array = [2,7,8,5,4,3,1]
insertionSort(array)
print(array)
# The insertion sort always maintains a sorted sublist
# in the lower positions of the list.
# Each new item is then “inserted” back into the previous
# sublist such that the sorted sublist is one item larger.
# We begin by assuming that a list with one item (position 0)
# is already sorted.
# On each pass, one for each item 1 through n−1, the current
# item is checked against those in the already sorted
# sublist.
# As we look back into the already sorted sublist, we shift
# those items that are greater to the right.
# When we reach a smaller item or the end of the sublist,
# the current item can be inserted.
def insertionSort2(arr):
for i in range(1, len(arr)):
currentValue = arr[i]
position = i
while position > 0 and arr[position - 1] > currentValue:
arr[position] = arr[position - 1]
position = position - 1
arr[position] = currentValue
array = [2,7,8,5,4,3,1]
insertionSort2(array)
print(array)
|
daf90277269b9dffcc8e2818c5626b62d1062398 | jayyei/Repositorio | /Python/Curso-Python-3-Udemy/CursoPython/Fase 4 - Temas avanzados/Tema 11 - Modulos/Apuntes/Leccion 02 (Apuntes) - Paquetes/paquete/adios/despedidas.py | 270 | 3.546875 | 4 | #Este es un modulo con funciones que despiden
def despedirse():
print("Adios, me estoy despidiendo, desde la funcion despedirse del modulo adios")
class Despido():
def __init__(self):
print("Adios, me despido desde la clase despido en el modulo adios") |
d3763659b8b824588d2640a02bc7e627e96a57b3 | clarissadesimoni/aoc15 | /day8/day8.py | 1,422 | 3.59375 | 4 | data = open('day8/day8.txt').read().split('\n')
def countChars1(string):
i, code, memory = 0, 0, 0
hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
while i < len(string):
if string[i] == '\\':
if string[i + 1] == 'x' and string[i + 2] in hexChars and string[i + 3] in hexChars:
memory += 3
i += 3
else:
memory += 1
i += 1
elif string[i] == '\"':
code -= 1
code += 1
memory += 1
i += 1
return memory - code
def part1():
return sum(map(lambda x: countChars1(x), data))
def countChars2(string):
i, memory, encoded = 0, 0, 0
hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
while i < len(string):
if string[i] == '\\':
if string[i + 1] == 'x' and string[i + 2] in hexChars and string[i + 3] in hexChars:
memory += 3
encoded += 4
i += 3
else:
memory += 1
encoded += 3
i += 1
elif string[i] == '\"':
encoded += 2
encoded += 1
memory += 1
i += 1
return encoded - memory
def part2():
return sum(map(lambda x: countChars2(x), data))
print(f'Part 1: {part1()}')
print(f'Part 2: {part2()}') |
c6414f3b48a4a3c2ee90f0e31b73e98337dc5144 | pandey-ankur-au17/Python | /coding-challenges/week07/day04/ccQ2.py | 665 | 3.96875 | 4 | # Given a sorted array with Duplicates . Write a program to find UPPER
# BOUND of a TARGET using Binary search Method .
# Return Index corresponding to the element of the upper bound element.
# Example :
# Input : - arr = [1,1,1,2,2,3,3,5,5,5,7,7] , Target = 4
# Output : - 7
def Upper_bound(arr,target):
n=len(arr)
left=0
right=n-1
res=-1
while(left<=right):
mid=(left+right)//2
if(arr[mid]==target):
res=mid
right=mid+1
elif (arr[mid]>target):
right=mid-1
else:
left=mid+1
return res
arr=[1,1,1,2,2,3,3,4,5,5,5,7,7]
target=4
print(Upper_bound(arr,target))
|
6238ac26cdbe54d32de42f1f2a1b129bc5d5d5cd | codeBeefFly/bxg_python_basic | /Day09/07.datetime.py | 147 | 3.59375 | 4 | import datetime
year = datetime.datetime.now().year
month = datetime.datetime.now().month
day = datetime.datetime.now().day
print(year,month,day) |
9d14724a55e90399dc43cc6fdf932f8044f01ad9 | samuaicc/Python | /课练三十.py | 953 | 4.3125 | 4 | #-*-coding:utf-8-*-
#输入一周内某一天的英文首字母判断这是星期几,第一个字母重复就判断第二个字母
f_letter = str(input('First letter:'))
if f_letter.upper() == 'M':
print('This day is Monday !')
elif f_letter.upper() == 'W':
print('This day is Wednesday !')
elif f_letter.upper() == 'F':
print('This day is Friday !')
elif f_letter.upper() == 'S':
sec_letter = str(input('Second letter:'))
if sec_letter.lower() == 'a':
print('This day is Saturday !')
elif sec_letter.lower() == 'u':
print('This day is Sunday !')
else:
print('Input Error!')
elif f_letter.upper() == 'T':
sec_letter = str(input('Second letter:'))
if sec_letter.lower() == 'u':
print('This day is Tuesday !')
elif sec_letter.lower() == 'h':
print('This day is Thursday !')
else:
print('Input Error!')
else:
print('Input Error!')
|
c4149bd78577535c55476234bd0bf717436cb2e3 | qqizai/python36patterns | /创建型模式-单例模式.py | 2,305 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Author : ydf
# @Time : 2019/10/8 0008 13:55
"""
单例模式
适用范围三颗星,这不是最常用的设计模式。往往只能脱出而出仅仅能说出这一种设计模式,但oop根本目的是要多例,
使用oop来实现单例模式,好处包括
1 延迟初始化(只有在生成对象时候调用__init__里面时候才进行初始化)
2 动态传参初始化
否则,一般情况下,不需要来使用类来搞单例模式,文件级模块全局变量的写法搞定即可,python模块天然单例,不信的话可以测试一下,c导入a,b也导入a,c导入b,在a里面直接print hello,
运行c.py,只会看到一次print hello。
"""
from monkey_print2 import print
class A:
"""
# 这种方式重写new实现的单例模式要注意,虽然生成的对象都是同一个,但init会每次都被自动调用。py2这种写法实现的单例模式,init不会自动被调用,py3会被自动调用。
要是init里面成本很大,不希望每次都被自动调用,可以改成另外的方式,参考其他方式的单例模式。
"""
_inst = None
def __new__(cls, identity):
if not cls._inst:
cls._inst = object.__new__(cls)
return cls._inst
def __init__(self, identity):
print('执行init')
self.identity = identity
def eat(self):
print(f'{self.identity} 吃饭')
if __name__ == '__main__':
a1 = A('001')
a2 = A('001')
print(a1 == a2)
a1.eat()
a2.eat()
a3 = A('003')
print(a1 == a3)
a3.eat()
"""
"D:/coding2/python36patterns/创建型模式-单例模式.py:27" 16:13:31 执行init
"D:/coding2/python36patterns/创建型模式-单例模式.py:27" 16:13:31 执行init
"D:/coding2/python36patterns/创建型模式-单例模式.py:37" 16:13:31 True
"D:/coding2/python36patterns/创建型模式-单例模式.py:31" 16:13:31 001 吃饭
"D:/coding2/python36patterns/创建型模式-单例模式.py:31" 16:13:31 001 吃饭
"D:/coding2/python36patterns/创建型模式-单例模式.py:27" 16:13:31 执行init
"D:/coding2/python36patterns/创建型模式-单例模式.py:41" 16:13:31 True
"D:/coding2/python36patterns/创建型模式-单例模式.py:31" 16:13:31 003 吃饭
"""
|
e16f6a60db6bf7d9682571965bbf910a78b5f7c0 | zy199529/data_structure1 | /排序/InsertSort.py | 876 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Lenovo
# @Date: 2019-05-28 08:52:20
# @Last Modified by: Lenovo
# @Last Modified time: 2019-05-28 09:53:06
# 插入排序工作原理:对于每个未排序数据,在已排序序列中总后往前扫描,找到相应位置并插入。
# 直接插入排序被分为:有序数据和无序数据
# 每次从无序数据中选择一个数据插入到有序数据中
def InsertSort(k, n):
for i in range(1, n):
if k[i-1] > k[i]:
temp = k[i]
index = i
for j in range(i-1, -1, -1):
if k[j] > temp:
k[j+1] = k[j]
index = j
else:
break
k[index] = temp
return k
if __name__ == '__main__':
k = [1, 3, 2, 5, 7, 9, 0, 6, 4, 8]
print(InsertSort(k, len(k)))
|
0a4602da934f3d2cbdcc17c10084fb8baf591d96 | ankile/ITGK-TDT4110 | /timeoppgaver/sum_table.py | 234 | 3.5 | 4 | def sum_table(table):
sum = 0
for i in range(len(table)):
for j in range(len(table[i])):
sum += table[i][j]
return sum
my_list = [[1 for i in range(10)] for i in range(5)]
print(sum_table(my_list)) |
b3d20eaaa79efacd8b10b943495c5cb8ba99e6a1 | mitzaM/python-learning-program | /plp_1_p3.py | 1,397 | 4.1875 | 4 | #! /usr//bin/env python
def _sort_list(l):
"""
Sorts a list of (key, value) pairs
"""
for i in range(len(l) - 1):
for j in range(i + 1, len(l)):
if (l[i][0] > l[j][0]):
l[i], l[j] = l[j], l[i]
return l
def _compare_dict(dict_a, dict_b):
"""
Compares two dictionaries and returns >0 if dict_a > dict_b
0 if dict_a = dict_b
<0 if dict_a < dict_b
"""
list_a = _sort_list(dict_a.items())
list_b = _sort_list(dict_b.items())
i = t = 0
while i < len(list_a) and i < len(list_b) and t == 0:
t = list_a[i][1] - list_b[i][1]
i += 1
if (i == len(list_a)): t = -1
if (i == len(list_b)): t = 1
return t;
def sort_dict(file):
"""
Reads a list of dictionaries from 'file' and sorts them
"""
f = open(file)
dict_list = []
i = 0
dict_list.append({})
for line in f:
if (line == '\n'):
i += 1
dict_list.append({})
else:
dict_list[i][line[0]] = int(line[2])
f.close()
idx_list = range(len(dict_list));
for i in range(len(dict_list) - 1):
for j in range(i + 1, len(dict_list)):
if (_compare_dict(dict_list[i], dict_list[j]) > 0):
idx_list[i], idx_list[j] = idx_list[j], idx_list[i]
f = open('result', 'r+')
for i in idx_list:
f.write(str(i))
f.write(' ')
f.write('\n')
f.close()
sort_dict('file')
|
6a30f8e41742853e1535cbdf86f296299ffc8fb0 | yanliang1/Python-test | /Python-03/dict.py | 567 | 3.71875 | 4 | #键值对(字典)->映射
d = {} #创建
print(type(d))
print(len(d))
#添加
#d[key] = value
d["red"] = 0xff0000
d["green"] = 0x00ff00
d["blue"] = 0x0000ff
print(len(d))
print(d)
#修改
d["red"] = 123456
print(len(d))
print(d)
#移除
d.pop("red")
print(d)
#获取指定的值
value = d.get("green")
print("value =",value)
print("-"*30)
#获取所有的项
print(d.items())
#获取所有的键
print(d.keys())
#获取所有的值
print(d.values())
print("---------------------------")
for k,v in d.items():
print(type(k),type(v))
print(k,v) |
85c1b5eb8d3870e882bf1d1d62e1ebdefab98d60 | nishanthakur/Modified-RSA | /rsa.py | 4,683 | 3.921875 | 4 | import time
import sys
#Checking whether the user input is prime number or composite number.
def check_prime(number):
counter = 0
for divider in range(1,number+1):
remainder = number % divider
if remainder == 0:
counter += 1
return counter
#Selecting First prime Number(p)
def first_prime():
print('********** FIRST PRIME NUMBER SELECTION *********\n')
while True:
try:
p = int(input("\nSelect first large random prime number: "))
no_of_divider = check_prime(p)
if no_of_divider == 2:
print(f"Congratulation, {p} is a prime number.\n")
return p
break
else:
print(f"Sorry, {p} is composite Number.\nTry Again...\n")
except:
print("Invalid Input. Try Again !!!")
#Selecting Second Prime Number(q)
def second_prime():
print('************* SECOND PRIME NUMBER SELECTION ****************\n')
while True:
try:
q = int(input("Select second large random prime number: "))
no_of_divider = check_prime(q)
if no_of_divider == 2:
print(f'Congratulation Again, {q} is a prime Number.\n')
time.sleep(1)
return q
break
else:
print(f'Sorry, {q} is a composite Number.\nTry Again...\n')
except:
Print("Invalid Input. Try Again !!!")
#Selecting public key(e) For Data Encryption
def select_public_key():
print("********* PUBLIC KEY SELECTION ************")
print("Conditions : ")
print(f' [1] : 1 < e < phi_n i.e. 1 < e < {phi_n}')
print(f' [2] : gcd(e , phi_n) = 1.\n') #gcd = greatest common divisor
while True:
try:
e = int(input('Select your public key in the given range:'))
if e > 1 and e < phi_n:
no_of_divider = check_prime(e)
if no_of_divider == 2:
print(f'public key : {e}\n')
return e
break
else:
print(f'gcd({e} , {phi_n}) != 1.\nTry Again...')
continue
else:
print(f'Please, Select Pubic Key in Range 1 < e < {phi_n}')
continue
except:
print('Please, Use Integer as Public key.')
continue
#Calculating Private Key For Data Encryption.
def private_key_selection():
for k in range(0,100):
d = (1 + k * phi_n) / e
if d.is_integer():
time.sleep(1)
print('Please Wait !!! Generating private key.')
time.sleep(1)
print('\n')
print(f'Private Key : {int(d)}\n')
return int(d)
break
#Encrypting / Decrypting Data According to user Choice
def encrypt_decrypt():
while True:
try:
time.sleep(1)
print('********** WELCOME TO ENCRYPTION / DECRYPTION PHASE ************\n')
time.sleep(0.6)
print('Press 1 for Encryption.\nPress 2 for Decryption.\nPress 3 to exit program\n')
time.sleep(0.6)
user_choice = input('Enter Your Choice : ')
print(f"User Choice : {user_choice}\n")
if user_choice == '1':
plain_text = int(input('Enter Plain text For Encryption: '))
time.sleep(1)
print('Please Wait !!! Generating Cipler Text...')
time.sleep(1)
cipher_text = (plain_text ** e) % n
print (f"Cipher Text : {cipher_text}\n")
if user_choice == '2':
cipher_text = int(input("Enter Cipher Text for Decryption : "))
plain_text = (cipher_text ** d) % n
print(f"Plain Text : {plain_text}\n")
if user_choice == '3':
print('Please Wait...')
time.sleep(1.4)
print('Program Ended Successfully.')
break
except:
print('Invalid Input..\n')
continue
#Main Method for executing all the created functions.
def final():
print('************ KEEP YOUR SYSTEM SECURE. ENCRYPT YOUR DATA WITH RSA *************\n')
global p, q, n, phi_n, e, d
p = first_prime()
q = second_prime()
n = p * q
print(f"The product of two prime numbers is [n : {n}]\n")
phi_n = (p-1) * (q-1)
print(f"The value of phi_n is [phi_n : {phi_n}]\n")
e = select_public_key()
d = private_key_selection()
encrypt_decrypt()
final()
|
f9dfcf505a50811077fff369a2e8e40fb1ad04f7 | Likhith-krishna/python | /beginner/set4/71.py | 87 | 3.625 | 4 | inter=input()
d=inter[::-1]
if(inter==d):
print("yes")
else:
print("no")
|
dcd0cd36c62f80c2e3e52c42c665620f2f8cb22d | JuanesFranco/Fundamentos-De-Programacion | /sesion-05/ejercicio 33.py | 205 | 3.890625 | 4 | suma=0
x=1
n=int(input("cuantas personas va a procesar"))
while x<=n:
altura=float(input("ingrese la altura"))
suma=suma+altura
x=x+1
promedio=suma/n
print("la altura promedio es de",promedio)
|
9b5d5ade3aebf589c99dc72d7b04e1e2cd730e32 | krusellp/SoftDesSp15 | /toolbox/word_frequency_analysis/frequency.py | 1,492 | 4.53125 | 5 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
fp = open(filename)
d = dict()
for line in fp:
# print line
for word in line.split():
if "xe2" not in word:
word = word.strip(string.punctuation + string.whitespace)
# print word
if len(word) >5:
if word not in d:
# print 'in'
d[word] = 1
else:
# print 'not in'
d[word] += 1
fp.close()
return d
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
freq_dict = dictionary_creation(filename)
t = []
for key, value in freq_dict.items():
t.append((value,key))
t.sort(reverse=True)
wordlist = []
freqlist = []
# print n, 'most common words:'
for freq,word in t[0:n]:
# print word,'\t', freq
wordlist.append(word)
freqlist.append(freq)
print len(freq_dict)
return wordlist,freqlist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.