text stringlengths 37 1.41M |
|---|
"""
To modify a value in a ditionary, givethe dictionary name,
followed by the key in square brackets and then the new value
you want associated with that key placed after the equal to sign( = ).
"""
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
### What Happened:
# First, we define a dictionary for alien_0 that contains only thealien's color.
# Then we change the value associated with the key 'color' to the value, 'yellow'.
# The output showswhat we changed, the alien has indeed changed from green to yellow.
|
"""
Getting the computer to make a simple decision based on temperature readings
Objectives:
To understand simple, two-way, and multi-way decision programming patterns.
To understand the concept of Boolean expressions and the bool data type.
"""
# a program to convert celsius to fahrenheit
def main():
celsius = eval(raw_input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is "+ str(fahrenheit)+ " degrees fahrenheit.")
# added str() and replaced commas with addition operators to omit unecessary output.
if fahrenheit > 90:
print("It's really hot in there. Be careful!")
if fahrenheit < 30:
print("Brrrr. Be sure to layer up!")
main()
|
# now, for the json.load() function
# this program uses json.load() to read back the list into memory
import json
filename = 'numbers.json' # we make sure to read from the same file we wrote to
with open(filename) as f_obj: # we open it in read mode
numbers = json.load(f_obj)
print(numbers)
# the json.load() function loads the info stored in numbers.json
# This is a simple way to share data between two programs
|
"""
A simple program that takes the user's input, and adds it to a list.
"""
cities = []
def main():
# def instructions():
# print("\n\tType in any city name I should visit, and I'll add it to a list.")
# print("\tTo quit, type <done>")
# instructions()
prompt = "\n\tType in any city name I should visit, and I'll add it to a list."
prompt += "\n\tTo quit, type <done>"
prompt += "\n\nCity name: "
active = True
while active:
new_city = raw_input(prompt)
cities.append(new_city)
print("\nI'd love to go " + new_city.title() + "!")
if new_city == 'done':
print("Here is the list of cities so far:")
done = 'done'
cities.remove(done)
print(cities)
active = False
again = raw_input("\nWould you like to add more cities for me to visit? y/n?")
if again == 'y':
main()
else:
raw_input("\n\nPress Enter to Exit.")
main()
|
# Python 2.7
# Example from Python Crash Course
# Here's another example of nesting a list inside of a dictionary
# looking at our previous example of a dicitonary of similar objects
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title()) # fixed attribute error ("languages" to language")
# test for remote username change
# second test, changing git config
|
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 16 17:42:04 2021
@author: mohammadtaher
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 21:40:59 2019
@author: Faradars-pc2
"""
def searchforvowels(w:str):
''' find vowels in word '''
#w = input('Yek kalame benevis: ')
v = set('aeiou')
'''found = v.intersection(set(w))
for vowel in found:
print(vowel)
return bool(found)'''
return v.intersection(set(w))
def search_for_letters(letter:str, find:str = 'aeiuo') -> set:
''' find words in your inputed letter'''
return set(find).intersection(set(letter))
|
def get_string(string):
substring = input("Get characters of string starting from n characters and m length (max is %d): " % len(string))
substring = substring.split(" ")
n = int(substring[0])
m = int(substring[1])
print('From %d to %d: %s' % (n, m + n, string[n:m + n + 1]))
print('\nFrom %d to the end: %s' % (n, string[n:]))
print('\nWhole string minus last character: %s' % string[:-1])
character = input("Input a character within the string: ")
first_index = string.index(character)
print('\n From %s to the next %d characters: %s' % (character, m, string[first_index: first_index + m + 1]))
known_substring = input('Key in a known substring: ')
is_substring_found = False
first_character_substring = known_substring[0]
while not is_substring_found:
first_index = known_substring.index(first_character_substring)
for x in range(len(known_substring)):
if known_substring[x] != string[first_index + x]:
is_substring_found = False
continue
is_substring_found = True
print('\From a known substring: %s' % string[first_index: first_index + len(known_substring)])
|
print('In Python, 0 to the power of 0 is: %d' % 0**0)
print('However, not everyone agrees that 0^0 is 1.')
|
# Goal: Record number of bikes available every minute for an hour in NYC
# This will allow us to see which station is most active during that hour
# Activity = total number taken out OR returned
import requests # requests is a URL handler to allow downloading from internet
from pandas.io.json import json_normalize
import pandas as pd
import matplotlib.pyplot as plt
r = requests.get('http://www.citibikenyc.com/stations/json')
## Check out the data
# print(r.json().keys()) # See the headers of the JSON blob
# print(r.json()['executionTime'])
# print(r.json()['stationBeanList'])
# print('Number of stations: % s' % len(r.json()['stationBeanList'])) # Get the number of stations
# ## Test that we have all fields by running through a loop
# key_list = [] #unique list of keys for each station
# for station in r.json()['stationBeanList']:
# for k in station.keys():
# if k not in key_list:
# key_list.append(k)
# print('Key list : % s' % key_list)
# ## convert into dataframe
df = json_normalize(r.json()['stationBeanList'])
print(df.head())
# print(df['statusValue'].unique())
# print(df.head())
# df['availableBikes'].hist()
# plt.show()
# Are there any test stations?
# print(any(df['testStation'] == True)) # shows that this does not contain any test stations
# print(df['testStation'][df['testStation'] == True].count()) # count how many test stations there are
# # How many are in service or not?
# print(df['statusValue'][df['statusValue'] == 'In Service'].count()) # count how many test stations there are
# # Mean & median of bikes in a station
# num_bikes_mean = df['availableBikes'].mean()
# num_bikes_med = df['availableBikes'].median()
# print('Median and mean of bikes available: {0}, {1}'.format(int(num_bikes_med), int(num_bikes_mean)))
# How does this change if we remove stations that aren't in service?
# print(df['statusValue'].unique())
df['statusNew'] = df['statusValue'][df['statusValue'] == 'In Service'] # count how many test stations there are
new_status = df['statusNew'].dropna() #need to not make new column type, weirdly
# print(new_status)
num_bikes_mean = df.groupby(['statusValue'])['availableBikes'].mean()
num_bikes_med = df.groupby(['statusValue'])['availableBikes'].median()
# print(type(num_bikes_med), type(num_bikes_mean))
print(num_bikes_mean, num_bikes_med)
|
import sys
sample_input = ['2',
'5',
'5 6 8 4 3',
'3',
'8 9 7']
def solve():
pass
def write_output(t, result):
print ('Case #%s: %s' % (t, result))
sys.stdout.flush()
def run():
#We collect the first input line consisting of a single integer = T, the total number of test cases
#T = int(input()) #SWAP
T = int(sample_input[0]) #SWAP
#We loop through each test case
for t in range(1, T+1):
N = int(sample_input[int(2*t)-1]) #SWAP
V = [int(v) for v in sample_input[int(2*t)].split(' ')] #SWAP
#N = int(input()) #SWAP
#V = [int(v) for v in input().split(' ')] #SWAP
write_output(t, solve()) |
A = int(input())
B = int(input())
maxim = A
if maxim < B:
maxim = B
print(maxim)
|
a = int(input())
b = int(input())
c = int(input())
typ = ''
if b > a:
(b, a) = (a, b)
if c > a:
(c, a) = (a, c)
if a + b > c > 0 and a + c > b > 0 and b + c > a > 0:
if a**2 < b**2 + c**2:
typ = 'acute'
elif a**2 == b**2 + c**2:
typ = 'rectangular'
elif a**2 > b**2 + c**2:
typ = 'obtuse'
else:
typ = 'impossible'
print(typ)
|
hour1 = int(input())
minut1 = int(input())
sec1 = int(input())
hour2 = int(input())
minut2 = int(input())
sec2 = int(input())
print((hour2*3600 + minut2*60 + sec2) - (hour1*3600 + minut1*60 + sec1))
|
import math # импортируется библиотека math
print(int(2.5)) # округляет в сторону нуля (отбрасывет дробную часть)
print(round(2.5)) # округляет до ближайшего целого, если дробная часть равна 0.5, то к ближайшему чётному
# перед каждым вызовом функции из библиотеки нужно писать слово ''math.'', а затем имя функции:
print(math.floor(2.5)) # округляет в меньшую сторону
print(math.ceil(2.5)) # округляет в большую сторону
print(math.trunc(2.5)) # работает аналогично int
# можно из библиотеки импортировать некоторые функции и доступ к ним можно получить без написания ''math.'':
from math import floor, ceil
print(floor(2.5)) # округляет в меньшую сторону
print(ceil(2.5)) # округляет в большую сторону
|
from datetime import datetime
def expand_tweet(status):
'''Given a tweepy Status object, expands the text of the tweet
If the status object represents a retweet, then this
function sets "full_tweet" to the full text of the
retweeted tweet (i.e. the part after the "RT @handle:")
If the status object is *not* a retweet, then this
function sets "full_tweet" to the full text of the
tweet body (by expanding any tweets > 140 characters)
'''
data = status._json
data['full_tweet'] = get_full_text(status)
def get_full_text(status):
'''Given a tweepy Status object, returns the full text of the tweet
If the status object represents a retweet, then this function
will return the full text of the retweeted tweet (i.e. the part
after the "RT @handle:")
If the status object is *not* a retweet, then this function
will return the full text of the tweet body (expanding any tweets
with > 140 characters)
'''
data = status._json
# retweet, any # of characters
if is_retweet(status):
data = data['retweeted_status']
# retweeted tweet is > 140 characters
if 'extended_tweet' in data:
return data['extended_tweet']['full_text']
# retweeted tweet is <= 140 characters
else:
return data['text']
# original tweet, > 140 characters
if 'extended_tweet' in data:
return data['extended_tweet']['full_text']
# original tweet, <= 140 characters
else:
return data['text']
def expand_hashtags(status):
data = status._json
data['full_hashtags'] = get_full_hashtags(status)
def get_full_hashtags(status):
data = status._json
# retweet, any # of characters
if is_retweet(status):
data = data['retweeted_status']
# retweeted tweet is > 140 characters
if 'extended_tweet' in data:
return data['extended_tweet']['entities']['hashtags']
# retweeted tweet is <= 140 characters
else:
return data['entities']['hashtags']
# original tweet, > 140 characters
if 'extended_tweet' in data:
return data['extended_tweet']['entities']['hashtags']
# original tweet, <= 140 characters
else:
return data['entities']['hashtags']
def expand_mentions(status):
data = status._json
data['full_mentions'] = get_full_mentions(status)
def get_full_mentions(status):
data = status._json
# retweet, any # of characters
if is_retweet(status):
data = data['retweeted_status']
# retweeted tweet is > 140 characters
if 'extended_tweet' in data:
return data['extended_tweet']['entities']['user_mentions']
# retweeted tweet is <= 140 characters
else:
return data['entities']['user_mentions']
# original tweet, > 140 characters
if 'extended_tweet' in data:
return data['extended_tweet']['entities']['user_mentions']
# original tweet, <= 140 characters
else:
return data['entities']['user_mentions']
def reformat_tweet(status):
'''Given a status object from the Twitter API, reformat its date fields
In particular, this function will convert the following raw string fields
sent by the Twitter API into actual datetime (and int) objects:
- created_at
- user.created_at
- retweeted_status.created_at
- retweeted_status.user.created_at
- timestamp_ms
By doing this, we are able to better support a wider range of database
queries on date- and time-related fields
'''
data = status._json
datetime_fmt = "%a %b %d %H:%M:%S %z %Y"
data['created_at'] = datetime.strptime(data['created_at'], datetime_fmt)
data['user']['created_at'] = datetime.strptime(data['user']['created_at'], datetime_fmt)
data['timestamp_ms'] = int(data['timestamp_ms'])
if is_retweet(status):
retweet = data['retweeted_status']
retweet['created_at'] = datetime.strptime(retweet['created_at'], datetime_fmt)
retweet['user']['created_at'] = datetime.strptime(retweet['user']['created_at'], datetime_fmt)
def get_collection_name(status):
'''Given a Status object, this function computes a collection name
In particular, the "temporal sharding" of the database requires us to
insert each Status object into the table/collection corresponding
to the time at which the tweet was created.
However, this function can be used to compute the collection name
based on *any* attribute found in the source Status object
'''
created_at = status._json['created_at']
return created_at.strftime('%Y_%m_%d')
def is_retweet(status):
'''Given a tweepy Status object, returns whether or not it's a retweet'''
data = status._json
return 'retweeted_status' in data
def get_mongo_lang_code(twitter_lang_code):
'''Converts from twitter- to mongo-supported language code
In particular, this function maps the list language codes supported
by the Twitter API (https://developer.twitter.com/en/docs/twitter-
for-websites/twitter-for-websites-supported-languages/overview.html)
into the corresponding language code supported by the *standard* (non-
enterprise) edition of MongoDB (https://docs.mongodb.com/manual/reference
/text-search-languages/#text-search-languages)
If a language is not supported by non-enterprise MongoDB or is the
special value "und" (a.k.a. "undefined") the function will default to
returning a value of "none"'''
lang_code_map = {
'da': 'da',
'en': 'en',
'ar': 'none',
'bn': 'none',
'cs': 'none',
'de': 'de',
'el': 'none',
'es': 'es',
'fa': 'none',
'fi': 'fi',
'fil': 'none',
'fr': 'fr',
'he': 'none',
'hi': 'none',
'hu': 'hu',
'id': 'none',
'it': 'it',
'ja': 'none',
'ko': 'none',
'msa': 'none',
'nl': 'nl',
'no': 'nb',
'pl': 'none',
'pt': 'pt',
'ro': 'ro',
'ru': 'ru',
'sv': 'sv',
'th': 'none',
'tr': 'tr',
'uk': 'none',
'ur': 'none',
'vi': 'none',
'zh-cn': 'none',
'zh-tw': 'none',
'und': 'none'
}
return lang_code_map.get(twitter_lang_code, 'none')
|
# exo 1
#
# def display_message():
# print("im a message")
# display_message()
# exo 2
#
# def favorite_book(title):
# if(title == "Alice in Wonderland"):
# print("One of my favorite books is Alice in Wonderland")
# favorite_book("Alice in Wonderland")
# exo 3
#
# def describe_city(name_of_city = "paris"):
# print(name_of_city)
# if name_of_city == "Reykjavik":
# print("Reykjavik is in Iceland")
# describe_city("Tel-aviv")
# exo 4
#
# import random
# random.random()
# def chek_num():
# num1 = random.randint(1,100)
# num2 = random.randint(1,100)
# if num1 == num2:
# print("good job")
# exo 5
#
# def make_shirt( size = "large" , on_shirt = "I love Python"):
# print(f"the size of the shirt is:{size} whith {on_shirt}")
# exo 6
# name = ["bob","sam","raf","toby"]
# def show_magicians(lst):
# for x in lst:
# print(x)
# show_magicians(name)
# def make_great(lst):
# count=0
# for x in lst:
# x +=" the Great"
# lst[count] = x
# count+=1
#
# return lst
# name = make_great(name)
# print(name)
# exo 8
#
# calcule = lambda x : (x+(x*10)+3+(x*10)+3+(x*100)+(x*10)+3+(x*100)+(x*1000))
# num = calcule(3)
# print(num)
|
import math
class Circle():
def __init__(self, radius ):
self.radius = radius
def area(self):
x = 2*(math.pi)*self.radius
return x
def make_circle(self):
print(" **** ")
print(" * * ")
print(" **** ")
def __add__(self, other):
if isinstance(other, int):
self.radius += other
print(self.radius)
elif isinstance(other, float):
self.radius += other
print(self.radius)
else:
self.radius += other.radius
print(self.radius)
def __gt__(self,other):
if isinstance(other, int):
if self.radius > other:
return True
elif isinstance(other, float):
if self.radius > other:
return True
else:
if self.radius > other.radius:
return True
return False
def __eq__(self, other):
if isinstance(other, int):
return self.radius == other
elif isinstance(other, float):
return self.radius == other
else:
return self.radius == other.age
c = Circle(5)
# x = c.area()
x = c == 5
print(x)
# c.make_circle()
arr = [Circle(6),Circle(4),Circle(9),Circle(4),Circle(10),Circle(3),Circle(6)]
newlist = sorted(arr, key=lambda x: x.radius)
print(newlist[0])
|
def maximum_number(*args):
max_num = args[0]
for i in args:
if i > max_num:
max_num = i
return max_num
print(maximum_number(-10,-4,-7,-10,-30)) |
# python_list_categ
l = ["haha", "poc", "Poc", "POC", "haHA", "hei","hey", "HahA", "poc", "Hei"]
d = {}
for cuv in l:
cuv.lower()
if cuv.lower() in d.keys():
d[cuv.lower()] += 1
else:
d[cuv.lower()] = 1
for cuv in d:
print ("Cuvantul {} apare de {} ori".format(cuv, d[cuv])) |
# python_substr_introductiv
s = input("Your string is ")
# a
for i in range(0, len(s)):
print (s[i:] + s[:i])
# b
print ("\n")
for i in range(0, len(s)):
print (s[-i:] + s[:-i])
# c
print ("\n")
for i in range(1, len(s)//2 + 1):
print (s[:i] + '|' + s[-i:]) |
'''
Program that calculates and list all the even, odd, and square numbers
between two given whole numbers including negatives.
'''
import math
def main():
x_value = int(input("Enter a value for x: "))
y_value = int(input("Enter a value for y: "))
print()
print("Even numbers between", x_value, "and", y_value)
for i in range (x_value, y_value + 1): # Lists even numbers in range
if i % 2 == 0:
print(i, end=' ')
print()
print()
print("Odd numbers between", x_value, "and", y_value) # Lists odd numbers in range
for i in range (x_value, y_value + 1):
if i % 2 == 1:
print(i, end=' ')
print()
print()
print("Square numbers between", x_value, "and", y_value)
for i in range (x_value, y_value + 1): # Lists square numbers in range
if i < 0:
continue
elif math.sqrt(i).is_integer():
print(i, end=' ')
main() |
# Sebastian Raschka, 2016
"""
source: http://adventofcode.com/2016/day/2
DESCRIPTION
--- Day 2: Bathroom Security ---
You arrive at Easter Bunny Headquarters under cover of darkness.
However, you left in such a rush that you forgot to use the bathroom!
Fancy office buildings like this one usually have keypad locks on their
bathrooms, so you search the front desk for the code.
"In order to improve security," the document you find says, "bathroom codes
will no longer be written down. Instead, please memorize and follow the
procedure below to access the bathrooms."
The document goes on to explain that each button to be pressed can be found by
starting on the previous button and moving to adjacent buttons on the
keypad: U moves up, D moves down, L moves left, and R moves right.
Each line of instructions corresponds to one button, starting at the
previous button (or, for the first line, the "5" button); press whatever
button you're on at the end of each line. If a move doesn't lead to a button,
ignore it.
You can't hold it much longer, so you decide to figure out the code as
you walk to the bathroom. You picture a keypad like this:
1 2 3
4 5 6
7 8 9
Suppose your instructions are:
ULL
RRDDD
LURDL
UUUUD
You start at "5" and move up (to "2"), left (to "1"), and left
(you can't, and stay on "1"), so the first button is 1.
Starting from the previous button ("1"), you move right twice (to "3")
and then down three times
(stopping at "9" after two moves and ignoring the third), ending up with 9.
Continuing from "9", you move left, up, right, down, and left, ending with 8.
Finally, you move up four times (stopping at "2"),
then down once, ending with 5.
So, in this example, the bathroom code is 1985.
Your puzzle input is the instructions from the document you found at the
front desk. What is the bathroom code?
"""
num_grid = [["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"]]
def move_input_row(curr_pos, move_str):
for char in move_str:
if char == 'U' and curr_pos[0] > 0:
curr_pos[0] -= 1
elif char == 'D' and curr_pos[0] < 2:
curr_pos[0] += 1
elif char == 'R' and curr_pos[1] < 2:
curr_pos[1] += 1
elif char == 'L' and curr_pos[1] > 0:
curr_pos[1] -= 1
return num_grid[curr_pos[0]][curr_pos[1]]
def move_input_all(move_str_all):
digits = ''
start_pos = [1, 1]
move_strs = move_str_all.split('\n')
for ms in move_strs:
digits += move_input_row(start_pos, ms.strip())
return digits
def test_1():
test_str = """ULL
RRDDD
LURDL
UUUUD"""
result = move_input_all(test_str)
assert result == '1985'
def part_1_solution():
test_str = """LURLDDLDULRURDUDLRULRDLLRURDUDRLLRLRURDRULDLRLRRDDULUDULURULLURLURRRLLDURURLLUURDLLDUUDRRDLDLLRUUDURURRULURUURLDLLLUDDUUDRULLRUDURRLRLLDRRUDULLDUUUDLDLRLLRLULDLRLUDLRRULDDDURLUULRDLRULRDURDURUUUDDRRDRRUDULDUUULLLLURRDDUULDRDRLULRRRUUDUURDULDDRLDRDLLDDLRDLDULUDDLULUDRLULRRRRUUUDULULDLUDUUUUDURLUDRDLLDDRULUURDRRRDRLDLLURLULDULRUDRDDUDDLRLRRDUDDRULRULULRDDDDRDLLLRURDDDDRDRUDUDUUDRUDLDULRUULLRRLURRRRUUDRDLDUDDLUDRRURLRDDLUUDUDUUDRLUURURRURDRRRURULUUDUUDURUUURDDDURUDLRLLULRULRDURLLDDULLDULULDDDRUDDDUUDDUDDRRRURRUURRRRURUDRRDLRDUUULLRRRUDD
DLDUDULDLRDLUDDLLRLUUULLDURRUDLLDUDDRDRLRDDUUUURDULDULLRDRURDLULRUURRDLULUDRURDULLDRURUULLDLLUDRLUDRUDRURURUULRDLLDDDLRUDUDLUDURLDDLRRUUURDDDRLUDDDUDDLDUDDUUUUUULLRDRRUDRUDDDLLLDRDUULRLDURLLDURUDDLLURDDLULLDDDRLUDRDDLDLDLRLURRDURRRUDRRDUUDDRLLUDLDRLRDUDLDLRDRUDUUULULUDRRULUDRDRRLLDDRDDDLULURUURULLRRRRRDDRDDRRRDLRDURURRRDDULLUULRULURURDRRUDURDDUURDUURUURUULURUUDULURRDLRRUUDRLLDLDRRRULDRLLRLDUDULRRLDUDDUUURDUDLDDDUDL
RURDRUDUUUUULLLUULDULLLDRUULURLDULULRDDLRLLRURULLLLLLRULLURRDLULLUULRRDURRURLUDLULDLRRULRDLDULLDDRRDLLRURRDULULDRRDDULDURRRUUURUDDURULUUDURUULUDLUURRLDLRDDUUUUURULDRDUDDULULRDRUUURRRDRLURRLUUULRUDRRLUDRDLDUDDRDRRUULLLLDUUUULDULRRRLLRLRLRULDLRURRLRLDLRRDRDRLDRUDDDUUDRLLUUURLRLULURLDRRULRULUDRUUURRUDLDDRRDDURUUULLDDLLDDRUDDDUULUDRDDLULDDDDRULDDDDUUUURRLDUURULRDDRDLLLRRDDURUDRRLDUDULRULDDLDDLDUUUULDLLULUUDDULUUDLRDRUDLURDULUDDRDRDRDDURDLURLULRUURDUDULDDLDDRUULLRDRLRRUURRDDRDUDDLRRLLDRDLUUDRRDDDUUUDLRRLDDDUDRURRDDUULUDLLLRUDDRULRLLLRDLUDUUUUURLRRUDUDDDDLRLLULLUDRDURDDULULRDRDLUDDRLURRLRRULRL
LDUURLLULRUURRDLDRUULRDRDDDRULDLURDDRURULLRUURRLRRLDRURRDRLUDRUUUULLDRLURDRLRUDDRDDDUURRDRRURULLLDRDRDLDUURLDRUULLDRDDRRDRDUUDLURUDDLLUUDDULDDULRDDUUDDDLRLLLULLDLUDRRLDUUDRUUDUDUURULDRRLRRDLRLURDRURURRDURDURRUDLRURURUUDURURUDRURULLLLLUDRUDUDULRLLLRDRLLRLRLRRDULRUUULURLRRLDRRRDRULRUDUURRRRULDDLRULDRRRDLDRLUDLLUDDRURLURURRLRUDLRLLRDLLDRDDLDUDRDLDDRULDDULUDDLLDURDULLDURRURRULLDRLUURURLLUDDRLRRUUDULRRLLRUDRDUURLDDLLURRDLRUURLLDRDLRUULUDURRDULUULDDLUUUDDLRRDRDUDLRUULDDDLDDRUDDD
DRRDRRURURUDDDRULRUDLDLDULRLDURURUUURURLURURDDDDRULUDLDDRDDUDULRUUULRDUDULURLRULRDDLDUDLDLULRULDRRLUDLLLLURUDUDLLDLDRLRUUULRDDLUURDRRDLUDUDRULRRDDRRLDUDLLDLURLRDLRUUDLDULURDDUUDDLRDLUURLDLRLRDLLRUDRDUURDDLDDLURRDDRDRURULURRLRLDURLRRUUUDDUUDRDRULRDLURLDDDRURUDRULDURUUUUDULURUDDDDUURULULDRURRDRDURUUURURLLDRDLDLRDDULDRLLDUDUDDLRLLRLRUUDLUDDULRLDLLRLUUDLLLUUDULRDULDLRRLDDDDUDDRRRDDRDDUDRLLLDLLDLLRDLDRDLUDRRRLDDRLUDLRLDRUURUDURDLRDDULRLDUUUDRLLDRLDLLDLDRRRLLULLUDDDLRUDULDDDLDRRLLRDDLDUULRDLRRLRLLRUUULLRDUDLRURRRUULLULLLRRURLRDULLLRLDUUUDDRLRLUURRLUUUDURLRDURRDUDDUDDRDDRUD"""
result = move_input_all(test_str)
return result
if __name__ == '__main__':
test_1()
print('Part 1 solution:', part_1_solution())
|
# 아무 것도 입력하지 않고 엔터만 입력하면 입력이 종료
# 여러 문장을 입력받아 대문자로 변환해 출력하는 프로그램을 작성
count = 1
while count <4 :
str_ = input()
if not str_:
break
print(">> {}".format(str_.upper()))
count =count +1 |
# #인 부분은 1 공백인 부분은 0
# # 이 하나라도 있으면 무조건 포함
# 공백은 둘다 만족
# 원래의 비밀지도를 해독하기
def bin(num):
result = ''
arr = ['0', '1']
while num > 0:
result = arr[num % 2] + result
num = num // 2
return result
def solution(n, arr1, arr2):
secret_map = []
for decimal1, decimal2 in zip(arr1, arr2):
# 1인 부분이 하나라도 있으면 포함 --> XOR
element = str(bin(decimal1 | decimal2))
print(element)
# n의 자릿수로 만들기
while len(element)< n :
element = '0'+ element
element = element.replace('1', '#')
element = element.replace('0', ' ')
secret_map.append(element)
return secret_map
n,arr1,arr2 =5,[9, 20, 28, 18, 11],[30, 1, 21, 17, 28]
print(solution(n, arr1, arr2)) |
# 1부터 20사이의 숫자 중 3의 배수가 아니거나
# 5의 배수가 아닌 숫자들의 제곱 값으로 구성된 리스트 객체를 출력하는 프로그램을 작성
list = []
for num in range(1,21):
if num % 3 !=0 or num % 5!=0 :
num = num ** 2
list.append(num)
print(list) |
from datetime import datetime
def calculate(name, age) :
year = 100- age + datetime.today().year
print(name+"(은)는"+ str(year) +"년에 100세가 될 것입니다.")
name = input()
age = int(input())
calculate(name, age) |
# 임의의 url 주소를 입력받아 protocol, host, 나머지(path, querystring, ...)로 구분하는 프로그램을 작성
url = input()
url_1 = url.split('://')[0]
url_2 = url.split('://')[1].split('/')[0]
url_3 = url.split('://')[1].split('/')[1]
print("protocol: "+url_1)
print("host: "+url_2)
print("others: "+url_3) |
# 100~300 사이의 숫자에서 각각의 자리 숫자가 짝수인 숫자를 찾아서 콤마(,)로 구분
arr =[]
for i in range (100,301) :
if (i //100)%2 ==0 and ((i%100)//10)%2 ==0 and (i%10)%2==0:
arr.append(i)
for i in range(len(arr)-1) :
print(arr[i],end=',')
print(arr[-1]) |
arr = "()[{}[]"
# arr2 = "((())))("
# check1 = []
# check2 = []
# check3 = []
# isTrue = "False"
# for i in arr2:
# if i == "(":
# check1.append(i)
# elif check1 and i == ")":
# check1.pop()
# elif i == "[":
# check2.append(i)
# elif check2 and i=="]":
# check2.pop()
# elif i == "{":
# check3.append(i)
# elif check3 and i=="}":
# check3.pop()
# else:
# break
# else:
# if not check1 and not check3 and not check2:
# isTrue = "True"
# print(isTrue)
def isValid (str):
stack = []
table = {
')' : '(',
'}' : '{',
']' : '['
}
# 스택 이용 예외 처리 및 일치 여부 판별
for s in str :
if s not in table: # (, {, [
stack.append(s)
elif not stack or table[s] != stack.pop():
return False
return len(stack) == 0
|
#7
class Restaurant():
def __init__ (self,restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
return "{} serves wonderful {}." .format(self.restaurant_name, self.cuisine_type)
def open_restaurant(self):
return "레스토랑이 오픈하였습니다."
a= Restaurant("The Mean Queen", "pizza")
b= Restaurant("Ludvig'S Bistro", "seafood")
c= Restaurant("Mango Thai", "thai food")
print(a.describe_restaurant())
print(b.describe_restaurant())
print(c.describe_restaurant())
|
# 소수인지를 판단하는 프로그램
def prime(num) :
for div in range(2,num) :
if num % div == 0:
print("소수가 아닙니다.")
break
elif div == num -1:
print("소수입니다.")
else:
continue
number = int(input())
prime(number) |
# dynamic programming --> 값들을 "저장"해두고 필요할 때 꺼내 쓴다.
# 피보나치 수열 정리 ★★★★
# 경우의 수 많은 경우 ---> dp 무조건 100% 활용하기
# bottom up 을
def solution(n):
answer = [0, 1] # F(0)=0, F(1)=1
for i in range(2, n + 1): # F(n) = (F(n-1) + F(n-2)) % 1234567
answer.append((answer[i - 1] + answer[i - 2]) % 1234567)
return answer[-1] # 마지막 결과를 return |
import sys
alpha = str(input())
if alpha.isupper() :
print(alpha + "는 대문자 입니다.")
else :
print(alpha + "는 소문자 입니다.") |
from collections import deque
import sys
dx = [1,-1,0,0]
dy = [0,0,-1,1]
def iswall(x,y):
if x<0 or y<0 :
return False
if x >= n or y >= m :
return False
if matrix[x][y] == 0 : # 방문한 경우
return False
return True # 그 외의 경우
def bfs(x,y):
queue = deque()
print(queue)
queue.append((x, y))
print(queue)
# queue = deque((x,y)) # 시작 지점을 넣는다.
while queue:
x,y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if iswall(nx,ny) and matrix[nx][ny]==1:
matrix[nx][ny] = matrix[x][y]+1
queue.append((nx,ny))
return matrix[n-1][m-1]
n,m = map(int,input().split())
matrix = [[1, 1, 0], [0, 1, 0], [0, 1, 1]]
print(bfs(0,0))
|
#'abcdef' 문자열의 각각의 문자를 키로 하고 0~5 사이의 정수를 값으로 하는 딕셔너리 객체를 생성하고,
# 이 딕셔너리 객체의 키와 값 정보를 출력하는 프로그램을 작성
data = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5}
for key in data:
print(key + ": " +str(data.get(key))) |
# 덧셈하여 타겟을 만들 수 있는 배열의 두 숫자 인덱스를 리턴하라
# enumerate를 활용하여 부르트 포스 알고리즘
nums = [2,7,11,15]
target = 9
sum =[]
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if target == nums[j] + nums[i]:
sum.append(i)
sum.append(j)
print(sum)
dict={}
for index,value in enumerate(nums):
dict[value] = index
print(dict)
for nums,index in dict.items():
if target - nums in dict:
l=[index,dict[target-nums]]
print(l.so) |
l=[]
l0=[]
for i in range(2):
l1=[]
l0.append(l1)
for i in range(3):
l2=[]
l1.append(l2)
for i in range(4):
l2.append(0)
print(l0) |
from sys import maxsize
__author__ = "Grzegorz Holak"
# I decided to make first name and last name without default value, as rest can be blank
# only these 2 I decided to must have in each contact, so I changed order of parameters in method to make
# it easier. After all we could test more possibilities, fill some parts and left rest etc.
# init new contact
class Contact:
def __init__(self, first_name, last_name, email=None, mobile_phone=None, middle_name=None, nick=None, title=None
, company=None
, address=None, home_phone=None, work_phone=None, fax=None, email2=None, email3=None, homepage=None
, birthday_year=None, ann_year=None, address2=None, home_phone2=None, notes=None, birthday_day=0
, birthday_month=0, ann_month=0, ann_day=0, contact_id=None, all_phones_from_home_page=None
, all_emails_from_home_page=None):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.mobile_phone = mobile_phone
self.middle_name = middle_name
self.nick = nick
self.title = title
self.company = company
self.address = address
self.home_phone = home_phone
self.work_phone = work_phone
self.fax = fax
self.email2 = email2
self.email3 = email3
self.homepage = homepage
self.birthday_year = birthday_year
self.ann_year = ann_year
self.address2 = address2
self.home_phone2 = home_phone2
self.notes = notes
# these are for options but in script need add 2 to this, dunno why, but it is working OK.
self.birthday_day = birthday_day + 2
self.birthday_month = birthday_month + 1
self.ann_month = ann_month + 1
self.ann_day = ann_day + 2
self.contact_id = contact_id
self.all_phones_from_home_page = all_phones_from_home_page
self.all_emails_from_home_page = all_emails_from_home_page
def __repr__(self):
return "%s:%s %s: %s: %s" % (self.contact_id, self.first_name, self.last_name, self.mobile_phone, self.email)
def __eq__(self, other):
return (self.contact_id is None or other.contact_id is None or self.contact_id == other.contact_id)\
and self.first_name == other.first_name and self.last_name == other.last_name
def id_or_max(self):
if self.contact_id:
return int(self.contact_id)
else:
return maxsize
|
# 6. Write a Python program to find the three elements that sum to zero from a set (array) of n real numbers.
class Triples:
def find_triplets(self, arr):
result = []
list_set = set(arr)
len_list = len(list_set)
for i in range(len_list - 1):
for j in range(i + 1, len_list):
for k in range(j + 1, len_list):
l = [arr[i], arr[j], arr[k]]
if not sum(l):
result.append(l)
return result
arr1 = [0, -1, 2, -3, 1]
print(Triples().find_triplets(arr1))
|
# 4. Write a Python class to get all possible unique subsets from a set of distinct integers. -
class SubSets:
@staticmethod
def subsets(arr):
result = []
for i in range(2 ** len(arr)):
subs = [arr[j] for j in range(len(arr)) if not i & (2**j)]
result.append(subs)
return result
def sub_sets(self, s_set):
return self.subsets_recur([], s_set)
def subsets_recur(self, current, s_set):
if s_set:
return self.subsets_recur(current, s_set[1:]) + self.subsets_recur(current + [s_set[0]], s_set[1:])
return [current]
d = [1, 2, 3, 5]
print(SubSets().subsets(d))
print(SubSets().sub_sets(d))
|
from sys import argv
script, filename = argv
#open a text file
txt = open(filename)
print "Here's your file %r:" % filename
#Display the content
print txt.read()
print "Type the filename again:"
#Prompt the user to re enter the filename
file_again = raw_input("> ")
#open it again
txt_again = open(file_again)
#read it again
print txt_again.read() |
# NOTE: This is a directional graph
# Need more logic for a unidirectional graph - need to copy edges into both graphs
import random
class GenerateGraphDict():
def __init__(self, verticies, max_edges=False):
self.verticies = verticies
if max_edges is False:
self.max_edges = verticies
else:
self.max_edges = max_edges
def generate_graph(self):
graph = dict()
for i in range(1, self.verticies+1):
edges = set()
for j in range(1, random.randint(3, self.max_edges)):
random_int = random.randint(1, self.verticies)
if random_int != i:
edges.add(random_int)
graph[i] = list(edges)
# for k, v in graph.items():
# print('key', k, 'value', v)
return graph |
# Verilen sayıyı kendi basamakları ile çarp: 29 2 * 9 = 18, 1 * 8 = 8
# Eğer çıkan sonuç tek basamaksa direk döndür
def persistence(n):
counter = 0
mylist = []
while len(str(n)) != 1: # n'in uzunluğu 1 olunca dur
for i in str(n): # Bütün haneleri bir listeye koy
mylist.append(i)
#print(n)
result = 1
for x in mylist: # Bütün haneleri birbiri ile çarp
result *= int(x)
n = result
mylist = []
#print(result)
counter += 1
return counter
|
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
sentences = ["I love my dog",
"I love my cat",
"You Love my Dog!"]
tokenizer=Tokenizer(num_words=100)
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
print(word_index)
"""
Tokenization in Tensorflow are classificed into 4 types
* hashing_trick(...): Converts a text to a sequence of indexes in a fixed-size hashing space.
* one_hot(...): One-hot encodes a text into a list of word indexes of size n.
* text_to_word_sequence(...): Converts a text to a sequence of words (or tokens).
* tokenizer_from_json(...): Parses a JSON tokenizer configuration file and returns a
""" |
# this file is code for the rod problem
# problem statement:
# given a length n, rod, we could cut the rod in any we like. Obviously, it should in int size, and we also get the price of each size rods. Our goal is to compute the max revenue we could get by cutting the rod.
# author: Jianbin hong
# Date: 15/11/2013
import numpy as np
def rod_problem_solving(rod_n, price_n):
"""
Input:
- rod_n: the length of rod
- price_n: the prices of array
Output:
- the max revenue
"""
if isinstance(rod_n, int): print "Error, the input %s is not expected type" % rod_n
else: None
if rod_n == 0: return "Error! input %s " %rod_n
else:
T = np.array((len(rod_n), len(rod_n)))
price_n = [0.0].extend(price_n)
for i in range(1, rod_n + 1):
for k in range(0, i + 1):
T[i, k] = price_n[k] + max(T[i - 1, :])
return max(T[n, :])
|
#Warren Green
#006314031
#takes user input
x = int(input("enter a number:"))
i = x
print("list of divisors")
# This loop calculates the divisors of whatever number is chosen
while i>0:
if x%i ==0:
print (i)
i -=1
else:
i -=1 |
#!/usr/bin/env python3
"""
This module should introduce you to basic plotting routines
using matplotlib.
We will be plotting quadratic equations since we already
have a module to calculate them.
"""
# Matplotlib is a module with routines to
# plot data and display them on the screen or save them to files.
# The primary plotting module is pyplot, which is conventionally imported
# as plt
import matplotlib.pyplot as plt
import numpy as np
# This is our quadratic_equation class, rename as QE for shortness
from quad_class import quadratic_Equation as QE
def simplePlot(quadEqn, xlim):
"""
This function will plot a quadratic equation, using
the quadratic_Equation module.
inputs:
quadEqn -- instance of QE --
the quadratic equation to plot
xlim -- list of [float, float] or None --
This will define the limits for which x is plotted.
If xlim is None, Matplotlib will auto-scale the axis.
"""
# Enforce that quadEqn MUST be a QE object.
# The isinstance function checks if the variable is of type QE,
# and returns true if and only if it is.
if not isinstance(quadEqn, QE):
# RuntimeError is a built in exception class
raise RuntimeError(msg='provided quadEqn is NOT of type QE')
# Define the x values we are going to plot
# np.arange is a function similiar to range, except
# can use floats as well as integers.
x_vals = np.arange(xlim[0], xlim[1], .01) #go from xlim[0] to xlim[1] in step sizes of .01
# Define the y values to plot. This should be the value of our quadratic equation at each
# value of x.
# NOTE: x_vals and y_vals MUST have the same length to plot
y_vals = [quadEqn(x) for x in x_vals]
# Create a simple plot
plt.plot(x_vals, y_vals)
# Display the plot on the screen
plt.show()
# We are introducing a new python object called None here.
# In python, None represents that nothing is there.
# So in the following definition we are saying that
# by default ylim will be a nothing.
def plotQE(quadEqn, xlim, ylim=None):
"""
This function will plot a quadratic equation, using
the quadratic_Equation module.
inputs:
quadEqn -- instance of QE --
the quadratic equation to plot
xlim -- list of [float, float] or None --
This will define the limits for which x is plotted.
If xlim is None, Matplotlib will auto-scale the axis.
optional inputs:
ylim=None -- list of [float, float] or None --
This will define the limits for which y is plotted.
If ylim is None, Matplotlib will auto-scale the axis.
"""
# Ensure quadEqn is of type QE
if not isinstance(quadEqn, QE):
raise RuntimeError(msg='provided quadEqn is NOT of type QE')
# Define the x values to plot
x_vals = np.arange(xlim[0], xlim[1], .01) #go from xlim[0] to xlim[1] in step sizes of .01
# Define the y values to plot.
y_vals = [quadEqn(x) for x in x_vals]
# Plot the function, but make it red, and only plot the actual data points without a line
plt.plot(x_vals, y_vals, 'ro')
# Set the plot so it only shows the defined x range
plt.xlim(xlim)
# If ylim was provided, set the y limits of the plot
if ylim is not None:
plt.ylim(ylim)
# Label the axes
plt.xlabel('x')
plt.ylabel('y')
# Display the plot on the screen
plt.show()
def plotRoots(quadEqn, xlim=None, ylim=None):
"""
This function will plot a quadratic equation,
along with vertical bars at its roots.
inputs:
quadEqn -- instance of QE --
the quadratic equation to plot
optional inputs:
xlim=None -- list of [float, float] or None --
This will define the limits for which x is plotted.
If xlim is None, will only plot just beyond the roots of the function.
If the roots are not real, an Exception will be raised.
ylim=None -- list of [float, float] or None --
This will define the limits for which y is plotted.
If ylim is None, the limits will be chosen to fit the plot tightly.
"""
# Ensure quadEqn is of type QE
if not isinstance(quadEqn, QE):
raise RuntimeError(msg='provided quadEqn is NOT of type QE')
# find the roots
neg_root = quadEqn.root(False)
pos_root = quadEqn.root(True)
# if xlim not provided, set just further than the roots as the limits
if xlim is None:
# define padding of a tenth of the distance between the roots
pad = pos_root - neg_root
pad *= .1
xlim = [min(neg_root, pos_root) - pad, max(neg_root, pos_root) + pad]
# Define the x values to plot
x_vals = np.arange(xlim[0], xlim[1], .01) #go from xlim[0] to xlim[1] in step sizes of .01
# Define the y values to plot.
y_vals = [quadEqn(x) for x in x_vals]
# Create a plot of the equation, with a solid red line. Give it a label
plt.plot(x_vals, y_vals, linestyle='-', color='red', label='Quad. Eqn.')
# Set the plot so it only shows the defined x range
plt.xlim(xlim)
if ylim is not None:
# If ylim was provided, set the y limits of the plot
plt.ylim(ylim)
else:
# squeeze the y limits to just cover y-values
plt.ylim([min(y_vals), max(y_vals)])
# Plot a blue vertical bar at the the negative root, with a label
plt.axvline(neg_root, color='blue', label='neg. root')
# Plot a purple vertical bar at the the positive root, with a label
plt.axvline(pos_root, color='purple', label='pos. root')
# add a legend to the plot
plt.legend()
# add a title to the plot
plt.title('root plot')
# display the plot
plt.show()
def test_plots():
"""
A simple method to demonstrate the three plotting routines.
"""
myeqn = QE(.8, 3, -2)
simplePlot(myeqn, [-5,3])
plotQE(myeqn, [-5,3])
plotRoots(myeqn)
if __name__ == '__main__':
test_plots()
|
#!/usr/bin/env python3
"""
This script is intended to demonstrate the following built in data
structures in python:
dictionaries
This script acts better as a series of commands to enter
into the interactive python interpreter
See https://docs.python.org/3.4/library/stdtypes.html
"""
# To import just 1 class or function from a module,
# you can use the from <module> import <class>
#
# In this case we are importing the function pprint
# from the pprint module. This function allows us to
# print the data structures in a more readable format than
# the default print statement
from pprint import pprint
# This defines an empty dictionary
a_dict = {}
# This defines a non-empty dictionary
b_dict = {'key_1':'value_1', 'key2':15}
# Dictionaries use 'keys' to access 'values' rather than integer indices.
# Values can be anything.
# assign a series of items to a, using numbers and strings as keys
a_dict['key1'] = 'string key'
a_dict[15] = 'integer key'
a_dict[26.25] = 'float key'
pprint(a_dict)
# Any immutable object can be a key - such as tuples
a_dict[(1,2,3)] = 'tuple key'
pprint(a_dict)
# Lists and dictionaries are mutable, so CANNOT be keys
try:
a_dict[ [1,2,3] ] = 'list key'
except Exception as e:
print(e.args)
# Values in dictionaries can be anything, including lists
a_dict['list'] = [1,2,3]
a_dict['dic'] = {'t':15, (1,2):[4,5,6,'hello']}
pprint(a_dict)
# The length of a dictionary is the number of keys it has
print(len(a_dict))
# You can overwrite the value stored in a key. But each key remains unique to the dictionary.
pprint(a_dict)
a_dict[15] = 'updated integer key'
pprint(a_dict)
# you can test if a key is in a dictionary using the in keyword
print(15 in a_dict)
print(16 in a_dict)
# You can get a list of keys or values using the dictionary functions keys() and values()
pprint(a_dict.keys())
pprint(a_dict.values())
# You can get a list of key, value pairs using the items keyword
pprint(a_dict.items())
|
"""Homework. Advanced level
The Guessing Game
Write a program that generates a random number between
1 and 10 and lets the user guess what number was
generated.
The result should be sent back to the user via a print
statement."""
import random
user_input = input("What number am I thinking of? From 1 to 10 only: ")
def guessing_game(typed_input):
guess = random.randint(1, 10)
typed_input = user_input
if len(typed_input) > 2:
print('Please fill in a number from 0 to 10!')
else:
try:
typed_input = int(user_input)
except ValueError:
print('Hey, please make sure you type in a number, not letters or something else!')
else:
if type(typed_input == int):
if typed_input <= 10:
if guess < typed_input:
print(f'It should have been a little lower, it was {str(guess)}.')
elif guess > typed_input:
print(f'It should have been higher...uf, it was {str(guess)}.')
else:
print(f'Wow, you guessed it was {str(guess)} unbelievable!')
else:
if typed_input > 10:
print('The number is greater than 10, please fill in another!')
if __name__ == '__main__':
guessing_game(user_input)
|
'''
преобразователь ПП в бинарный вид
прописать в правилах, что новая каждая команда на новой строчке и заканчивается запятой
'''
def hex2bin(str, form=16):
"""
Переводчик hex, oct str в bin str
"""
a = int(str, form)
return format(a, '0>16b')
def to_binary_pp(filename):
temp = {}
with open(filename, 'r') as file:
for line in file:
line = line.replace(' ', '')
line = line.replace('\t', '')
if line[:2] == '0,':
temp[count_et].append('0000000000000000')
continue
for i in range(len(line)):
if line[0] == '/':
break
elif (line[i] == ',') and (line[0:2] == '0x'):
temp[count_et].append(hex2bin(line[1:i], 16))
break
elif (line[i] == ',') and (line[0] == '0'):
temp[count_et].append(hex2bin(line[1:i], 8))
break
elif (line[i] == ':') and (line[0] == 'E'):
count_et = int(line[1:-2])
temp[count_et] = []
break
elif line[i] == ',' and (not line[0] == 'x') and (not line[0] == '0') and (not line[0] == 'E'):
temp[count_et].append(hex2bin(line[0:i], 10))
break
return temp
|
class BySubjectGradeBook(object):
def __init__(self):
self._grades = {}
def add_student(self, name):
self._grades[name] = {}
def report_grade(self, name, subject, grade):
by_subject = self._grades[name]
grade_list = by_subject.setdefault(subject, [])
grade_list.append(grade)
return self._grades[name]
book = BySubjectGradeBook()
book.add_student('bondaica')
book.report_grade('bondaica', 'math', 75)
book.report_grade('bondaica', 'physics', 80)
# Một kiến thức cơ bản mà bạn chưa biết đó là
lst = [1, 2, 3]
another_lst = lst
another_lst[0] = 0
print(lst)
# [0, 2, 3]
print(another_lst)
# [0, 2, 3]
dic = {}
another_dict = dic
another_dict['item'] = 'first item'
print(dic)
# {'item': 'first item'}
print(another_dict)
# {'item': 'first item'}
# Edit: để có thể tránh được tình huống này
lst = [1, 2, 3]
another_lst = lst[:] # same as list(lst)
another_lst[0] = 0
print(lst)
# [1, 2, 3]
print(another_lst)
# [0, 2, 3]
dic = {}
another_dict = dic.copy() # same as dict(dic)
another_dict['item'] = 'first item'
print(dic)
# {}
print(another_dict)
# {'item': 'first item'}
# Bạn lưu ý một chỗ này cho mình, nó chỉ copy những cái con thôi nhé.
# Nếu nó là con của con thì nó sẽ không được như mong muốn đâu
lst = [[1, 2, 3], [4, 5, 6]]
another_lst = lst[:]
another_lst[0][0] = 10
print(lst)
# [[10, 2, 3], [4, 5, 6]]
print(another_lst)
# [[10, 2, 3], [4, 5, 6]]
# Mình gợi ý cách sau đây
lst = [[1, 2, 3], [4, 5, 6]]
another_lst = [x[:] for x in lst]
another_lst[0][0] = 10
print(lst)
# [[1, 2, 3], [4, 5, 6]]
print(another_lst)
# [[10, 2, 3], [4, 5, 6]]
|
import pandas as pd
'''
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
'''
a = [1, 7, 2]
myvar1 = pd.Series(a)
print(myvar1)
# Labels
print(myvar1[0])
# Create labels
a = [1, 7, 2]
myvar2 = pd.Series(a, index=["x", "y", "z"])
print(myvar2)
print(myvar2["y"])
# Key/Value Objects as Series
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar3 = pd.Series(calories)
print(myvar3)
myvar4 = pd.Series(calories, index = ["day1", "day2"])
print(myvar4)
# DataFrames
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
myvar5 = pd.DataFrame(data)
print(myvar5) |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 24 08:02:02 2015
@author: Jared J. Thompson
"""
import psycopg2
from psycopg2.extras import DictCursor
def connect_to_db(name, user, host, password ):
try:
conn = psycopg2.connect(database=name, user=user, \
host=host, password=password)
conn.autocommit=True
except:
print "Unable to connect to the database"
cursor = conn.cursor()
cursor.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
return cursor, conn
def connect_to_local_db(name, user, password='user'):
try:
conn = psycopg2.connect(database=name, user=user, host='localhost', password=password)
conn.autocommit=True
except:
print "Unable to connect to the database"
cursor = conn.cursor()
cursor.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
return cursor, conn
def sample_local_db_dict_cursor(name, user, password='user'):
try:
conn = psycopg2.connect(database=name, user=user, host='localhost', password=password)
except:
print "Unable to connect to the database"
cursor = conn.cursor(cursor_factory=DictCursor)
cursor.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
return cursor, conn
def table_exists(cur, table_str):
exists = False
if cur.closed==True:
print "cursor is closed."
return False
try:
cur.execute("SELECT EXISTS(SELECT relname FROM pg_class WHERE relname='" + table_str + "')")
exists = cur.fetchone()[0]
except psycopg2.Error as e:
print e
return exists
def drop_table(cur, table_name):
if table_exists(cur, table_name):
if cur.closed==False:
cur.execute("DROP TABLE %s" % (table_name))
else:
print 'cursor is closed.' |
from tkinter import *
def readdata():
print("Clicked ReadData: You typed:", textval.get())
def removedata():
print("Clicked RemoveData")
win1 = Tk()
win1.title("Read from Textbox using a Button")
win1.geometry("200x200+100+600")
# Button class is used to add a button to the window
# use command property of the Button class to add functionality
# Use Entry() class to create a textbox
# Use variables to store values from functions delared as below:
# var = StringVar()/IntVar()/DoubleVar()/BooleanVar()
# Then use textvariable property of Entry() class to assign value
# to variable delared earlier. Always declare vars after window initialization
# To read a variable from function use the varname.get() method
# Use font=## to manipulate the font sizes
# To print a value from var in a label use lab10 = Label(text=textval)
textval = StringVar()
lab1 = Label(text='Your Name:', fg='lemon chiffon', bg='saddle brown').grid(row=0, column=0)
but1 = Button(text='Read', bg='wheat', fg='brown', command=readdata).grid(row=3, column=0)
but2 = Button(text='Remove', bg='wheat', fg='brown', command=removedata).grid(row=3, column=1)
text1 = Entry(textvariable=textval).grid(row=0, column=1)
# To keep the window visible, use mainloop()
win1.mainloop()
|
import pandas as pd
aus_weather = pd.DataFrame({
'city': ['Brissie', 'Sydney', 'Canberra'],
'temp': [55, 32, 16],
'wind': [66,50,80]
})
print(aus_weather)
us_weather = pd.DataFrame({
'city': ['Boston', 'Califonia', 'Dallas'],
'temp': [20, 33, 46],
'wind': [90,32,36]
})
print(us_weather)
# Join DF together
all_cities = pd.concat([aus_weather, us_weather], ignore_index=True)
print(all_cities)
all_cities = pd.concat([aus_weather, us_weather], keys=['Aus', 'US'])
print(all_cities)
print(all_cities.loc['US'])
temp_df = pd.DataFrame({
'city': ['Syd', 'Can', 'Mel'],
'temp': [20,30,40]
})
wind_df = pd.DataFrame({
'city': ['Syd', 'Can', 'Mel'],
'wind': [70,80,90]
})
df2 = pd.concat([temp_df, wind_df])
print(df2)
'''
This prints below incorrectly
city temp wind
0 Syd 20.0 NaN
1 Can 30.0 NaN
2 Mel 40.0 NaN
0 Syd NaN 70.0
1 Can NaN 80.0
2 Mel NaN 90.0
'''
df2 = pd.concat([temp_df, wind_df], axis=1)
print(df2) |
import pandas as pd
# PIVOT
df1 = pd.read_csv('files/city-weather.csv')
print(df1)
df2 = df1.pivot(index='Date', columns='City')
print(df2) # Displays full pivot table
df2 = df1.pivot(index='Date', columns='City', values=['Forecast', 'Wind'])
print(df2) # Displays full pivot table
# PIVOT TABLE
df3 = pd.read_csv('files/city-weather-same-day.csv', parse_dates=True) # Parse dates does not work for some reason
print(df3)
df4 = df3.pivot_table(index='Date', columns='City')
print(df4) # Prints average for the day as default
df4 = df3.pivot_table(index='Date', columns='City', aggfunc='count')
print(df4) # Prints aggregate based on the function
df4 = df3.pivot_table(index='Date', columns='City', aggfunc='max', margins=True)
print(df4) # Prints aggregate with all column
# Grouping
print(type(df3['Date'][0])) # Date column is read as a string
df3['Date'] = pd.to_datetime(df3['Date']) # Converted to date using the pd.to_datetime() func
# This beloe statement will fail without the date conversion
df5 = df3.pivot_table(index=pd.Grouper(freq='m', key='Date'), columns='City')
print(df5) |
import pandas as pd
import numpy as np
df1 = pd.read_csv('files/replace.csv')
print('DF1:\n', df1)
# Replace using a list of values in the entire DF
df2 = df1.replace([-9999, -8888], np.NaN)
print('DF2:\n', df2)
# Replace using a list of values in a dictionary
df3 = df1.replace({
'temparature': [-9999, -8888],
'wind': 112,
'event': ['0', '-']
}, np.NaN)
print('DF3:\n', df3)
# Replace using a map across the dataframe
df4 = df1.replace({
-9999: np.NaN,
112: np.NaN,
'-': 'No Event',
'0': 'No Event'
})
print('DF4:\n', df4)
# Replace using a regular expression only in temp and wind columns
df5 = df1.replace('[A-Za-z]', '', regex=True) # Replaces all characters inc event row
print('DF5:\n', df5)
df5 = df1.replace({
'temparature': '[A-Za-z]',
'wind': '[A-Za-z]'
}, '', regex=True) # Using a disctionary
print('DF5 Again:\n', df5)
df6 = pd.read_csv('files/students.csv')
print('DF8:\n', df6)
print(df6.replace(['Exceptional', 'Great', 'Average', 'Poor', 'Hopeless'], [10,5,4,3,2])) |
class Person:
def __init__(self, name, age):
print("Hello there, {}".format(name))
self.name = name
self.age = age
def __str__(self):
return "Name: {}\nAge:{}".format(self.name, self.age)
class Teacher(Person):
def __init__(self, name, age, sub):
Person.__init__(self, name, age)
self.sub = sub
def __str__(self):
return Person.__str__(self)+"\nSub: {}".format(self.sub)
t1 = Teacher("Roger", 54, 'Economics')
print(t1.name, t1.age, t1.sub)
print(t1)
'''
Output:
----------------------
Hello there, Roger
Roger 54 Economics
Name: Roger
Age:54
Sub: Economics
''' |
# Exponentials
num = int(input("Please enter a number: "))
exp = int(input("Please enter an exponent: "))
total = 1
for i in range(1,exp+1):
total = total * num
print("The result is: ", total)
'''
Output:
---------------
Please enter a number: 2
Please enter an exponent: 3
The result is: 8
''' |
# Continue statement demo
i = 1
while i < 10:
i = i + 1
if i < 8:
continue
print(i*10)
'''
Output:
-----------
5
6
7
8
9
10
''' |
from tkinter import *
win1 = Tk() # object of class Tk
win1.title("My First PyGUI Window") # Adds title to the window
win1.geometry("400x400+100+600")
lab1 = Label(win1, text='Your Name:', fg='Navy', bg='Teal')
# lab1.pack() # Places the element in the center of the window
# lab1.place(x=0, y=0) # places the element wrt the left top corner
lab1.grid(row=0, column=0, sticky='w') # Places in a grid ref by rows and columns
lab2 = Label(win1, text='Enter your Email:', fg='dark red', bg='coral')\
# lab2.pack()
# lab2.place(x=0, y=20)
lab2.grid(row=2, column=0, sticky='w')
# Creating Second Window
# Pass the object name of the window as a property to each element
win2 = Tk()
win2.title('My Second Window')
win2.geometry("400x400+600+600")
lab3 = Label(win2, text='Name: ', bg='coral', fg='dark red').place(x=0, y=0)
lab4 = Label(win2, text='Email: ', bg='coral', fg='dark red').place(x=0, y=20)
# To keep the window visible, use mainloop()
win1.mainloop()
# win2.mainloop()
|
def str_len(str1):
if isinstance(str1, int): # You can also use type(str1) == int
print('Integer is not supported')
elif type(str1) == float:
print('Floating point values are also not support at this stage')
else:
return len(str1)
str_len(233.5)
# ---------------------------------------------
def cel_to_far(cel):
if cel < -273:
print('Invalid value: please enter a value over -273')
else:
far = cel * 9 / 5 + 32
return far
print(cel_to_far(-272))
|
class Playing_card:
def __init__(self, card_num, card_suit):
self.rank = card_num
self.suit = card_suit
@property
def color(self):
if self.suit.lower() == "hearts" or self.suit.lower() == "diamonds":
return "red"
else:
return "black"
card_1 = Playing_card(1, "spades")
print(card_1.color) |
# (1) Scoop class -- each instance is one scoop of ice cream
#
# s1 = Scoop('chocolate')
# s2 = Scoop('vanilla')
# s3 = Scoop('coffee')
#
# print(s1.flavor) # chocolate
#
# for one_scoop in [s1, s2, s3]:
# print(one_scoop.flavor) # chocolate, vanilla, coffee
#
# (2) Person class -- name, e-mail address, and phone number
#
# Create several people, and iterate over them in a list
# and print their names (similar to a phone book)
#
# Change the e-mail address of one person, and show
# that it has changed by printing your list a second time
#
# (3) Create a BankAccount class. It'll have a single
# attribute (per instance), transactions -- a list of floats
#
# Every time you deposit, append a positive float
# Every time you withdraw, append a negative float
#
# (a) create two different accounts
# (b) add a number of transactions +/- to each account
# (c) show, for each account, the number of transactions
# and the average amount per transaction, as well as
# the current balance. (assume it starts at 0)
#
#
# 27 December 2020 - TB/SpaceOres
#
# EXERCISE ONE - SCOOP CLASS
class Scoop():
# defining scoop class
def __init__(self, flavor):
self.flavor = flavor
s1 = Scoop("chocolate")
s2 = Scoop("Vanilla")
s3 = Scoop("coffee")
print(s1.flavor)
for one_scoop in [s1, s2, s3]:
print(one_scoop.flavor)
# EXERCISE TWO - PERSON CLASS
class person():
def __init__(self, name, email, phone_number):
self.name = name
self.email = email
self.phone_number = phone_number
person_one = person("Bruce", "bShort1@gmail.com", "5805830912")
person_two = person("Clover", "cloDev@hotmail.com", "9996660934")
person_three = person("Buddy", "mountainLyon@gmail.com", "8595592483")
person_four = person("Lily", "bananasrul3@live.com", "3606549383")
people = [person_one, person_two, person_three, person_four]
for information in people:
print(f"{information.name}'s email and phone number is: {information.email}, {information.phone_number}")
person_one.email = "bruceBanner@gmail.com"
for information in people:
print(f"{information.name}'s email and phone number is: {information.email}, {information.phone_number}")
# EXERCISE THREE - BANKACCOUNT CLASS
|
import math
if __name__ == "__main__":
value = float(input())
mean = float(input())
stdev = float(input())
mid = float(input())
z = float(input())
ci_value = z * (stdev / math.sqrt(value))
print(round(mean - ci_value, 2))
print(round(mean + ci_value, 2)) |
def cat_and_mouse(cat_x, cat_y, mouse_z):
distanceA = abs(cat_x - mouse_z)
distanceB = abs(cat_y - mouse_z)
if distanceA > distanceB:
return 'Cat B'
elif distanceA == distanceB:
return 'Mouse C'
else:
return 'Cat A'
if __name__ == '__main__':
q = int(input())
for _ in range(q):
xyz = input().split()
x = int(xyz[0])
y = int(xyz[1])
z = int(xyz[2])
result = cat_and_mouse(x, y, z)
print(result + '\n') |
import math
def cumulative_distribution(mu, sigma, x):
"""
In a certain plant, the time taken to assemble a car is a random variable, X,
having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours.
What is the probability that a car can be assembled at this plant in:
1. Less than 19.5 hours?
2. Between 20 and 22 hours?
:param mu: mean
:param sigma: standard deviation
:param x: input value
:return: cumulative distribution
"""
return 0.5 * (1 + math.erf((x - mu) / (sigma * (2 ** 0.5))))
if __name__ == "__main__":
mu_and_sigma = list(map(int, input().rstrip().split()))
less_than = float(input())
between_a_b = list(map(int, input().rstrip().split()))
mu = mu_and_sigma[0]
sigma = mu_and_sigma[1]
a = between_a_b[0]
b = between_a_b[1]
print(round(cumulative_distribution(mu, sigma, less_than), 3))
print(round(cumulative_distribution(mu, sigma, b) - cumulative_distribution(mu, sigma, a), 3)) |
from scipy import stats
def find_mean_median_mode(n, _array):
"""
Print lines of output in the following order:
* Print the mean on a new line, to a scale of 1 decimal place (i.e., 12.3, 7.0).
* Print the median on a new line, to a scale of 1 decimal place (i.e., 12.3, 7.0).
* Print the mode on a new line; if more than one such value exists, print the numerically smallest one.
:param n: the number of elements in the array
:param _array: n space-separated integers describing the array's elements.
:return: mean, median, mode
"""
mean = sum(_array) / n
sorted_array = sorted(_array)
if len(sorted_array) % 2 == 0:
median = (sorted_array[n // 2 - 1] + sorted_array[n // 2]) / 2
else:
median = sorted_array[n // 2]
get_mode = stats.mode(_array)
print(f"{mean}\n{median}\n{get_mode[0][0]}")
if __name__ == '__main__':
N = int(input())
array_items = input().rstrip().split()
input_array = list(map(int, array_items))
find_mean_median_mode(N, input_array) |
#!/bin/python3
import sys
def lowestTriangle(base, area):
height = int(round(area*2/base))
new_area = int(round(height*base/2))
if new_area >= area:
return height
else:
return height + 1
base, area = input().strip().split(' ')
base, area = [int(base), int(area)]
height = lowestTriangle(base, area)
print(height) |
def picking_numbers(arr):
"""
Given an array of integers, find and print the maximum number of integers you can select from the
array such that the absolute difference between any two of the chosen integers is less than or equal to 1.
:param arr: an array of integers
:return: an integer that represents the length of the longest array that can be created
"""
multiset_max_len = 0
multiset = []
for i in range(len(a)):
if i not in multiset:
max_cnt = max((arr.count(arr[i]) + arr.count(a[i] + 1)), (arr.count(arr[i]) + arr.count(a[i] - 1)))
if max_cnt > multiset_max_len:
multiset_max_len = max_cnt
multiset.append(i)
return multiset_max_len
if __name__ == '__main__':
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
result = picking_numbers(a)
print(str(result) + '\n')
|
def summingSeries(n):
"""
For each test case, print the required answer in a line.
:param n: a single integer
:return: answer % modulo
"""
modulo = 1000000007
answer = n * n % modulo
return answer
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
result = summingSeries(n)
print(str(result) + '\n') |
def sum_digits(num):
r = 0
while num:
r, num = r + num % 10, num // 10
return r
if __name__ == '__main__':
n = int(input())
divisors = []
for i in range(1, n + 1):
if n % i == 0:
divisors.append(i)
print(max(divisors, key=sum_digits))
|
def climbing_leaderboard(leaderboard, alice_scores):
rankings = createRankings(leaderboard)
i = len(leaderboard) - 1
for score in alice_scores:
flag = True
while flag:
if i == -1:
print(1)
flag = False
elif score < leaderboard[i]:
print(rankings[i] + 1)
flag = False
elif score == leaderboard[i]:
print(rankings[i])
flag = False
elif score > leaderboard[i]:
i -= 1
return
def createRankings(leaderboard):
rankings = [1]
rank = 1
for i in range(1, len(leaderboard)):
if leaderboard[i] < leaderboard[i - 1]:
rank += 1
rankings.append(rank)
return rankings
if __name__ == "__main__":
scores_count = int(input())
scores = list(map(int, input().rstrip().split()))
alice_count = int(input())
alice = list(map(int, input().rstrip().split()))
climbing_leaderboard(scores, alice)
|
print("===== program pembagian ======")
def pembagian(a,b):
return a/b
try:
penyebut = int(input("masukan angka penyebut :"))
pembilang = int(input("masukan angka pembilang :"))
print ( pembagian ( penyebut, pembilang ) )
except ValueError: # cara menangkap keywordl error
print("input yang anda msukan bukan angka!!!!")
print("di luar error") |
# # membuat proram menampilkan bilangan prima
array = []
def bilangan_prima():
for i in range(1,36):
if i < 36:
array.append(i)
print(array)
bilangan_prima()
array2 = []
user = int(input("masukan batas deretan bilangan :"))
for a in range(2,user):
mod = 1
print(a)
for b in range(2,a):
print(b)
if a % b == 0:
mod = 0
if mod == 1:
array2.append(a)
print(array2)
# # program mencari bilangan prima
# angka = int(input("Masukkan angka: "))
# # mengecek bilangan prima selalu lebih besar dari 1
# if angka > 1:
# # mengecek faktor pembagi dengan operasi modulus
# for i in range(2,angka):
# if (angka % i) == 0:
# print (angka,"bukan bilangan prima")
# print ("karena", i,"dikalikan",angka//i,"hasilnya adalah",angka)
# break
# else:
# print( angka,"adalah bilangan prima")
# # keluaran jika sebuah bilangan kurang dari atau sama dengan 1
# else:
# print (angka,"adalah bilangan prima")
|
# operasi logika
# NOT,OR ,AND ,XOR
# NOT (kebalikan dari nilai oeprasi logika)
print("=====NOT=====")
a = True
d = False
print("operasi a =", a, "operasi d =", d)
hasil = not a
print("NOT a =", hasil)
hasil = not d
print("NOT d =", hasil)
# OR (jika salah satu bernilai true maka hasil akan true)
print("====OR====")
x = False
z = False
hasil = x or z
print(x, "or", z, "=", hasil)
x = True
z = False
hasil = x or z
print(x, "or", z, "=", hasil)
x = True
z = True
hasil = x or z
print(x, "or", z, "=", hasil)
x = False
z = True
hasil = x or z
print(x, "or", z, "=", hasil)
# AND (semuanya harus bernilai true maka hasil akan true)
print("====AND====")
x = False
z = False
hasil = x and z
print(x, "and", z, "=", hasil)
x = True
z = False
hasil = x and z
print(x, "and", z, "=", hasil)
x = True
z = True
hasil = x and z
print(x, "and", z, "=", hasil)
x = False
z = True
hasil = x and z
print(x, "and", z, "=", hasil)
# XOR (jika hanya satu nilai bernilai true maka hasil true,jika dua nilai bernilai sama maka hasil false )
print("====XOR====")
x = False
z = False
hasil = x ^ z
print(x, "^", z, "=", hasil)
x = True
z = False
hasil = x ^ z
print(x, "^", z, "=", hasil)
x = True
z = True
hasil = x ^ z
print(x, "^", z, "=", hasil)
x = False
z = True
hasil = x ^ z
print(x, "^", z, "=", hasil)
|
tahun = int(input("masukan tahun :"))
if tahun % 4 == 0:
if tahun % 100 == 0:
if tahun % 400 == 0:
print("tahun ini kabisat")
else:
print("tahun ini bukan kabisat")
else:
print("tahun ini kabisat 1")
else:
print("sudah pasti bukan tahun kabisat")
#
# tahun = int(input("Input tahun: "))
#
# if (tahun % 4) == 0:
# if (tahun % 100) == 0:
# if (tahun % 400) == 0:
# print( "Tahun Kabisat")
# else:
# print( "Bukan Tahun Kabisat 1")
# else:
# print( "Tahun Kabisat 1")
# else:
# print( "Bukan Tahun Kabisat") |
# program menentukan bilangan genap ganjil
angka = int(input("mencari angka ganjil genap!!\nmasukan angka: "))
for i in range(1,angka+1):
if i % 2 == 0 :
print(i,"= bilangan genap")
else:
print(i," = bilangan ganjil") |
# +++++++++3--------------10++++++++++++
# masukan angka kurang dari 3 atau lebih besar dari 10
inputUser = float(input(" masukan angka\n kurang dari 3\n atau\n lebih dari 10 :"))
kurangDari = inputUser < 3
lebihBesarDari = inputUser > 10
print("angka yang anda masukan \n kurang dari 3 :",kurangDari,"\n atau \n lebih besar dari 10 :",lebihBesarDari)
hasilKeduaBilangan = kurangDari or lebihBesarDari
print("angka yang anda masukan adalah :",hasilKeduaBilangan)
# ------3++++++++++++10---------------
# masukan angka lebih dari 3 dan kurang dari 10 (kasus irisan)
print("============================")
inputUser = float(input("masukan angka \n lebih besar dari 3 :\n dan \n lebih kecil dari 10 :"))
lebihBesarDari = inputUser > 3
kurangDari = inputUser < 10
print("angka yang anda masukan \n lebih dari 3 :",lebihBesarDari,"\n dan \n lebih kecil dari 10 :",kurangDari)
hasilKeduaBilangan = lebihBesarDari and kurangDari
print("angka yang anda masukan adalah :",hasilKeduaBilangan)
|
import pickle
'''
The pickle module allows us to serialize and de-serialize Python objects. In other words, it can transform an object into a tech stream before saving it into a file. The reverse is also possible and referred to as de-serializing.
Here we can create a constructor that sets the initial state of an originator object to none by typing self._state = None
memento object, the name of the method is create_memento. Type "return pickle.dumps(vars(self))". All this does is using the pickle module method called dumps and turns an originator object into a character stream. By the way, the VARS method is a built in Python function that returns a dictionary containing all the attribute value pairs of an object.
The next method set_memento allows us to restore the previous state of an object. We first de-serialize our memento object, which provides the snapshot of the previous state of the object. Type "previous_state = pickle.loads(memento)". Then we use the VARS function to wipe out the current state. vars(self).clear(). Finally, we replace the current state with the previous state. vars(self).update(previous_state)
'''
class Originator:
def __init__(self):
self._state = None
def create_memento(self):
return pickle.dumps(vars(self))
def set_memento(self, memento):
previous_state = pickle.loads(memento)
vars(self).clear
vars(self).update(previous_state)
def main():
originator = Originator()
#We then print the current state of the originator.
print(vars(originator))
memento = originator.create_memento()
originator._state = True
print(vars(originator))
originator.set_memento(memento)
print(vars(originator))
if __name__ == "__main__":
main()
|
#
# Example file for working with functions
#
# define a basic function
def func1():
print("I am a function")
# function that takes arguments
def func2(arg1, arg2):
print(arg1, " ", arg2)
# function that returns a value
def cube(x):
return x*x*x
# function with default value for an argument
def power(num, x=1):
result = 1
for i in range(x):
result = result * num
return result
#function with variable number of arguments, we can combine the variable arguments with the fixed args but in that case variable args should always be at the end
def multi_add(*args):
result = 0
for x in args:
result = result + x
return result
# function is being called directly and executes the contents of the function
func1()
#function is also being called inside the print function,
#so the output is the same as in the first case, but then the outer print statement executes,
#and since our function doesn't return a value,
#Python evaluates the return value to be the Python constant of none,
#and then just prints the string representation of that.
print(func1())
#function itself is not being executed at all since we're not including those little parentheses that would call the function.
#We're just printing the value of the function definition itself,
#which evaluates to this string that you see here.
#This just demonstrates that functions themselves are objects that can be passed around to other pieces of Python code.
print(func1)
func2(10, 20)
print(func1)
print(func2(10, 20))
print(cube(3))
print(power(2))
print(power(2, 3))
print(power(x=3, num=2))
print(multi_add(4, 5, 10, 4))
|
secret = "swordfish"
pw = " "
count = 0
auth = False
max_attempt = 5
while pw != secret:
count+=1
if count>max_attempt: break # it will break all the way out of the loop skip the else block
if count == 3 :continue # It just goes up at line 7 and checks the condition so instead of 5 trials only 4 trials
pw = input(f"{count} What's the secret word? ")
else:
auth = True
print("Authorized" if auth else "Calling the FBI ...")
animals = ("bear","bunny","dog","cat","velociraptor")
for pet in animals:
if pet == "dog" :continue # shortcuts the loop to top
if pet == "velociraptor" : break
print(pet)
else:
print("that is all of the animals") |
#!/usr/bin/env python3
""" Three philosophers, thinking and eating sushi """
'''
Now that we've figured out how to avoid a deadlock between our two philosophers using chopsticks we can return to our routine of eating and philosophizing. I'm ready for another piece of sushi so I'll pick up the first chopstick, then the second one. And I think I left the refrigerator open. - Well that was rude of him. We've entered another form of a deadlock through thread death. If one thread or process acquires a lock and then terminates because of some unexpected reason it may not automatically release the lock before it disappears. That leaves others tasks like me stuck waiting for a lock that will never be released and getting hungry. - Sorry about that. Let's look at some code.
'''
import threading
chopstick_a = threading.Lock()
chopstick_b = threading.Lock()
chopstick_c = threading.Lock()
sushi_count = 100000
def philosopher(name, first_chopstick, second_chopstick):
global sushi_count
while sushi_count >0 :
with first_chopstick:
with second_chopstick:
if sushi_count >0:
sushi_count-=1
print(name, 'took a piece! Sushi remaining:', sushi_count)
if sushi_count ==0:
print(1/0)
#while sushi_count > 0: # eat sushi until it's all gone
#first_chopstick.acquire()
#second_chopstick.acquire()
#try:
#if sushi_count > 0:
#sushi_count -= 1
#print(name, 'took a piece! Sushi remaining:', sushi_count)
#finally:
#second_chopstick.release()
#first_chopstick.release()
if __name__ == '__main__':
threading.Thread(target=philosopher, args=(
'Divya', chopstick_a, chopstick_b)).start()
threading.Thread(target=philosopher, args=(
'Shree', chopstick_b, chopstick_c)).start()
threading.Thread(target=philosopher, args=(
'Ansh', chopstick_a, chopstick_c)).start()
|
#!/usr/bin/env python3
""" Generators are the best way to iterate through large or complex data sets, especially when performance and memory are of concern.
The generator function returns a generator object and that generator object will yield the values. Now, you may have heard that generators yield rather than return, which is true.
"""
def even_integers_function(n):
for i in range(n):
if i % 2 == 0:
yield i # return a generator object
print(list(even_integers_function(10)))
|
import platform
def main():
message()
x = 'Hello World "{1:<09}" "{0:>09}"'.format(8,9)
y = 10
a = 42
b = 73
r = f'I am f string ====> {y} {a}'
print(r)
def message():
print("This is python version {}" .format(platform.python_version()));print("I am {}".format(x));print("Just Checking %d" % y)
print(f"hehaww. {y}")
if False:
print("I am False")
else:
print("not True")
if a < b:
z= 112
print('a < b: a is {} and b is {}'.format(a, b))
elif a > b:
print('a > b: a is {} and b is {}'.format(a, b))
elif a == b:
print('a == b: a is {} and b is {}'.format(a, b))
else:
print("do something")
print("Print value of z as block does not define scope is . {}".format(z))
words = ['one','true','three','four','five']
n = 0
while(n<5):
print(words[n])
n +=1
for i in words:
print(i)
def function(n =1):
print("Result of function method +++++ {}".format(n))
# Takes default value n =1
function()
# Takes passed value
function(42)
c = function(17)
# Since function method does not return any specific value so default is None
print(c)
def me(n =1):
return n * 2
print(me())
#By having this conditional statement at the bottom that calls main, it actually forces the interpreter to read the entire script before #it executes any of the code. This allows a more procedural style of programming, and it's because Python requires that a function is #defined before it's called.
if __name__ == '__main__': main()
|
pos = -1
def search(list,n):
i=0
for i in range(6):
i<len(list)
if list[i]==n:
globals()['pos']=i
return True
i=i+1;
return False
list=[5,9,122,90,45,6]
n=6
if search(list,n):
print("found at",pos)
else:
print("not found")
|
# -*- coding: UTF-8 -*-
# 通常一个切片操作要提供三个参数 [start_index: stop_index: step]
# start_index是切片的起始位置
# stop_index是切片的结束位置(不包括)
# step可以不提供,默认值是1,步长值不能为0,不然会报错ValueError。
# 取一个list或者tuple的部分元素
L = ['Michael','Sarah','Tracy','Bob','Jack']
# 取 L的 前三个元素
# 法一 笨方法: L[0] L[1] l[2]
# 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环
# 取 L 的前三个元素
def test(n):
r = []
for i in range(n):
r.append(L[i])
return r
print(test(3))
# 利用python提供的切片(Slice)操作符,大大简化操作
# 用切片取 L 的前三个元素
print(L[0:3]) # ['Michael', 'Sarah', 'Tracy']
# 切片 相关解释
L[0:3] # 表示,从索引0开始取,直到索引3为止,但不包括索引3.即索引0、1、2,正好是3个元素。如果第一个索引是0,还可以省略‘:’ 即L[:3]
print(L[1:3]) # ['Sarah', 'Tracy']
# python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片
L[-2:] # 【'Bob','Jack']
L[-2:-1] # ['Bob']
# 记住: 倒数第一个元素的索引是-1
# 切片操作十分有用
LL = list(range(100)) # 创建一个0-99的数列 [0,1,2,3,...,99]
#通过数列轻松取出一段数列
ll = LL[:10] # 前10个 [0,1,2,3,4,5,6,7,8,9]
ll = LL[-10:] # 后10个 [90,91,92,93,...,99]
ll = LL[10:20] # 前11-20个 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
ll = LL[:10:2] # 前10个数,每2个取一个 [0,2,4,6,8]
ll = LL[::5] # 所有数,每5个取一个 [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
# 什么都不写,只写:就可以原样复制一个list
ll = LL[:] # [0,1,2,3,...,99]
# tuple 也是一种list 唯一区别是tuple不可变,因此,tuple也可以用切片操作,只是操作的结果仍是tuple
(0,1,2,3,4,5)[:3] # (0,1,2)
# 字符串 ‘XXX’ 也可以看成是一种list,每个元素就是一个字符。因此字符串也可以用切片操作,操作的结果仍是字符串
'ABCDEFG'[:3] # 'ABC'
# 练习
# 利用 ‘切片’ 实现 字符串的strip功能(去掉字符串的首位空格)
def trim(s):
if not isinstance(s, (str)) :
raise TypeError("arg error")
if s == '':
return s
# 左判断
while 0<len(s) and ' ' == s[0:1] :
s = s[1:]
# 右判断
while 0<len(s) and ' ' == s[-1] :
s = s[0:-1]
return s
# 测试
def main():
if trim('hello ') != 'hello':
print('测试失败!')
elif trim(' hello') != 'hello':
print('测试失败!')
elif trim(' hello ') != 'hello':
print('测试失败!')
elif trim(' hello world ') != 'hello world':
print('测试失败!')
elif trim('') != '':
print('测试失败!')
elif trim(' ') != '':
print('测试失败!')
else:
print('测试成功!')
main() |
# Program to guess a number from 1 to 9 and tell whether the number is too close, too far or exact.
# Give the user option to exit when he types "exit" and also show how many guesses he made at the end.
import random
import sys
a = random.randint(1, 9)
stop = False
count = 0
while stop == False:
count += 1
userGuess = input("Enter your Guess: ")
if str(userGuess) in ['exit', 'Exit']:
sys.exit()
elif abs(a - int(userGuess)) >= 5:
print('Your Guess is too far from the number')
elif abs(a - int(userGuess)) != 0 and abs(a - int(userGuess)) < 5:
print('Your Guess is close to the number')
else:
print('Your Guess is Right')
print('It took you ' + str(count) + ' Guesses to get this correct!')
stop = True
|
""" Convolutional Neural Network.
Build and train a convolutional neural network with TensorFlow.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
This example is using TensorFlow layers API, see 'convolutional_network_raw'
example for a raw implementation with variables.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
"""
from __future__ import division, print_function, absolute_import
from collections import namedtuple
import itertools
import glob
import logging
import os
import re
import numpy as np
from PIL import Image
import tensorflow as tf
from tqdm import tqdm
import windows as win
import salt_data as sd
import salt_pixelNN as sNN
import salt_baseline as sb
import tang_feat as otf
from kaggle_prec import kaggle_prec
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pdb
# Training Parameters
learning_rate = 0.00001
batch_size = 8
num_steps = 300
# Network Parameters
num_classes = 2 # MNIST total classes (0-9 digits)
dropout = 0.25 # Dropout, probability to drop a unit
layerO = namedtuple('layerO', ['strides', 'padding'])
winO = namedtuple('winO', ['nfilt', 'filters', 'filter_params', 'kernel_size'])
def scat2d(x, win_params, layer_params):
"""Single layer of 2d scattering
Args:
x is input with dim (batch, height, width, 1)
win_params.filters is complex with dim ......... (depth, height, width, channels)
"""
real1 = tf.layers.conv2d(
x,
win_params.nfilt,
win_params.kernel_size,
strides=layer_params.strides,
padding=layer_params.padding,
dilation_rate=(1,1),
activation=None,
use_bias=False,
kernel_initializer=tf.constant_initializer(win_params.filters.real, dtype=tf.float32),
trainable=False,
name=None
)
imag1 = tf.layers.conv2d(
x,
win_params.nfilt,
win_params.kernel_size,
strides=layer_params.strides,
padding=layer_params.padding,
dilation_rate=(1,1),
activation=None,
use_bias=False,
kernel_initializer=tf.constant_initializer(win_params.filters.imag, dtype=tf.float32),
trainable=False,
name=None
)
return tf.abs(tf.complex(real1, imag1))
def wst2d_to_2d_2layer(x, reuse=tf.AUTO_REUSE):
bs = batch_size
kernel_size = [1,7,7]
max_scale = 3
K = 3
psis = [None,None]
layer_params = [None,None,None]
psiO = win.tang_psi_factory(max_scale, K, kernel_size)
psiO = winO(psiO.nfilt, psiO.filters.squeeze(), psiO.filter_params, kernel_size[1:])
phiO = win.tang_phi_window_3D(max_scale, kernel_size)
phiO = winO(phiO.nfilt, phiO.filters.squeeze(), phiO.filter_params, kernel_size[1:])
with tf.variable_scope('TangNet2d', reuse=reuse):
psis[0] = psiO
layer_params[0] = layerO((1,1), 'valid')
# 107, 107
U1 = scat2d(x, psis[0], layer_params[0])
layer_params[1] = layerO((1,1), 'valid')
U2s = []
# only procede with increasing frequency paths
for res_i, used_params in enumerate(psis[0].filter_params):
if used_params[0] < max_scale - 1:
psiO_inc = win.tang_psi_factory(max_scale, K, kernel_size, used_params[0]+1)
psiO_inc = winO(psiO_inc.nfilt, psiO_inc.filters.squeeze(), psiO_inc.filter_params, kernel_size[1:])
U2s.append(scat2d(U1[:,:,:,res_i:(res_i+1)], psiO_inc, layer_params[1]))
# 101, 101
U2 = tf.concat(U2s, 3)
# swap to (batch, chanU2, h, w)
U2 = tf.transpose(U2, [0,3,1,2])
# reshape to (batch, h,w, 1)
U2os = U2.get_shape()
U2 = tf.reshape(U2, (bs*U2.get_shape()[1], U2.get_shape()[2],U2.get_shape()[3],1))
# swap to (batch, chanU1, h, w)
U1 = tf.transpose(U1, [0,3,1,2])
# reshape to (batch, h,w, 1)
U1os = U1.get_shape()
U1 = tf.reshape(U1, (bs*U1.get_shape()[1], U1.get_shape()[2], U1.get_shape()[3], 1))
# now lo-pass
# each layer lo-passed differently so that (h,w) align bc we
# want to be able to do 2d convolutions afterwards again
layer_params[2] = layerO((1,1), 'valid')
phi = win.fst2d_phi_factory([5,5])
# filter and separate by original batch via old shape
S0 = scat2d(x[:,6:-6, 6:-6, :], phi, layer_params[2])
S0 = tf.reshape(S0, (bs, 1, S0.get_shape()[1], S0.get_shape()[2]))
S1 = scat2d(U1[:,3:-3,3:-3,:], phi, layer_params[2])
S1 = tf.reshape(S1, (bs, U1os[1], S1.get_shape()[1],S1.get_shape()[2]))
S2 = scat2d(U2, phi, layer_params[2])
S2 = tf.reshape(S2, (bs, U2os[1], S2.get_shape()[1], S2.get_shape()[2]))
# (batch, chan, h,w)
feat2d = tf.concat([S0,S1,S2], 1)
return tf.transpose(feat2d, [0,2,3,1])
def scat2d_to_2d_2layer(x, reuse=tf.AUTO_REUSE):
"""
Args:
x: in (batch, h, w, 1) shape
Returns
(batch, h, w, channels)
"""
psis = [None,None]
layer_params = [None,None,None]
with tf.variable_scope('scat2d_to_2d_2layer', reuse=reuse):
# TF Estimator input is a dict, in case of multiple inputs
# x = tf.reshape(x, shape=[-1, 113, 113, 1])
bs = batch_size
psis[0] = win.fst2d_psi_factory([17, 17], include_avg=False, filt_steps_ovr=[9, 9])
layer_params[0] = layerO((1,1), 'valid')
# 107, 107
U1 = scat2d(x, psis[0], layer_params[0])
psis[1] = win.fst2d_psi_factory([17, 17], include_avg=False, filt_steps_ovr=[9, 9])
layer_params[1] = layerO((1,1), 'valid')
U2s = []
# only procede with increasing frequency paths
for res_i, used_params in enumerate(psis[0].filter_params):
increasing_psi = win.fst2d_psi_factory(psis[1].kernel_size, used_params)
if increasing_psi.nfilt > 0:
U2s.append(scat2d(U1[:,:,:,res_i:(res_i+1)], increasing_psi, layer_params[1]))
# 101, 101
U2 = tf.concat(U2s, 3)
# swap to (batch, chanU2, h, w)
U2 = tf.transpose(U2, [0,3,1,2])
# reshape to (batch, h,w, 1)
U2os = U2.get_shape()
U2 = tf.reshape(U2, (bs*U2.get_shape()[1], U2.get_shape()[2],U2.get_shape()[3],1))
# swap to (batch, chanU1, h, w)
U1 = tf.transpose(U1, [0,3,1,2])
# reshape to (batch, h,w, 1)
U1os = U1.get_shape()
U1 = tf.reshape(U1, (bs*U1.get_shape()[1], U1.get_shape()[2], U1.get_shape()[3], 1))
# now lo-pass
# each layer lo-passed differently so that (h,w) align bc we
# want to be able to do 2d convolutions afterwards again
layer_params[2] = layerO((1,1), 'valid')
phi = win.fst2d_phi_factory([7,7])
# filter and separate by original batch via old shape
S0 = scat2d(x[:,16:-16, 16:-16, :], phi, layer_params[2])
S0 = tf.reshape(S0, (bs, 1, S0.get_shape()[1], S0.get_shape()[2]))
S1 = scat2d(U1[:,8:-8,8:-8,:], phi, layer_params[2])
S1 = tf.reshape(S1, (bs, U1os[1], S1.get_shape()[1],S1.get_shape()[2]))
S2 = scat2d(U2, phi, layer_params[2])
S2 = tf.reshape(S2, (bs, U2os[1], S2.get_shape()[1], S2.get_shape()[2]))
# (batch, chan, h,w)
feat2d = tf.concat([S0,S1,S2], 1)
return tf.transpose(feat2d, [0,2,3,1])
# Create the neural network
def conv_net(x_dict, n_classes, dropout, reuse, is_training):
# Define a scope for reusing the variables
with tf.variable_scope('ConvNet', reuse=reuse):
# TF Estimator input is a dict, like in MNIST example
x = x_dict['images']
feat = scat2d_to_2d_2layer(x, reuse)
mlt = 4
# 1x1 conv replaces PCA step
conv1 = tf.layers.conv2d(feat, 16*mlt, 1)
# Convolution Layer with 64 filters and a kernel size of 3
conv2 = tf.layers.conv2d(conv1, 16*mlt, 3, activation=tf.nn.relu, padding='same')
# Max Pooling (down-sampling) with strides of 2 and kernel size of 2
conv2 = tf.layers.max_pooling2d(conv2, 2, 2) # 52
conv3 = tf.layers.conv2d(conv2, 32*mlt, 3, activation=tf.nn.relu, padding='same')
conv3 = tf.layers.max_pooling2d(conv3, 2, 2) # 26
conv4 = tf.layers.conv2d(conv3, 64*mlt, 3, activation=tf.nn.relu, padding='same')
conv4 = tf.layers.max_pooling2d(conv4, 2, 2) # 13
# Flatten the data to a 1-D vector for the fully connected layer
fc1 = tf.contrib.layers.flatten(conv4)
# Fully connected layer (in tf contrib folder for now)
fc1 = tf.layers.dense(fc1, 1024*mlt)
# Apply Dropout (if is_training is False, dropout is not applied)
fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)
fc2 = tf.layers.dense(fc1, 250*mlt)
# Output layer, class prediction
out = tf.layers.dense(fc2, n_classes)
return out
# Define the model function (following TF Estimator Template)
def model_fn(features, labels, mode):
# Build the neural network
# Because Dropout have different behavior at training and prediction time, we
# need to create 2 distinct computation graphs that still share the same weights.
logits_train = conv_net(features, num_classes, dropout, reuse=False,
is_training=True)
logits_test = conv_net(features, num_classes, dropout, reuse=True,
is_training=False)
# Predictions
pred_classes = tf.argmax(logits_test, axis=1)
pred_probas = tf.nn.softmax(logits_test)
# If prediction mode, early return
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)
# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits_train, labels=tf.cast(labels, dtype=tf.int32)))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op,
global_step=tf.train.get_global_step())
# Evaluate the accuracy of the model
acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)
FP_op = tf.metrics.false_positives(labels, pred_classes)
FN_op = tf.metrics.false_negatives(labels, pred_classes)
TP_op = tf.metrics.true_positives(labels, pred_classes)
mask_predicted_rate_op = tf.metrics.mean(pred_classes)
prec_op = tf.metrics.precision(labels, pred_classes)
kaggle_op = kaggle_prec(labels, pred_classes)
myevalops = {
'accuracy': acc_op,
'mask_presence/false_positives': FP_op,
'mask_presence/false_negatives': FN_op,
'mask_presence/true_positives': TP_op,
'mask_presence/mask_prediction_rate': mask_predicted_rate_op,
'mask_presence/mask_rate': tf.metrics.mean(labels),
'mask_presence/precision': prec_op,
'mask_presence/kaggle': kaggle_op}
# TF Estimators requires to return a EstimatorSpec, that specify
# the different ops for training, evaluating, ...
estim_specs = tf.estimator.EstimatorSpec(
mode=mode,
predictions=pred_classes,
loss=loss_op,
train_op=train_op,
eval_metric_ops=myevalops)
return estim_specs
from window_plot import ScrollThruPlot
def scat2d_eg():
files = glob.glob('/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/train/images/*.png')
# find a particular example of interest
cool_eg = '/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/train/images/0a1742c740.png'
cool_eg_idx = re.search(cool_eg, ''.join(files)).start() // len(cool_eg)
x = tf.placeholder(tf.float32, shape=(8,113,113,1))
feat = scat2d_to_2d_2layer(x)
egbatch = get_salt_images()
egbatch = egbatch[cool_eg_idx:(cool_eg_idx+8),:,:,:]
sess = tf.Session()
sess.run(tf.global_variables_initializer())
feed_dict = {x: egbatch}
myres = sess.run(feat, feed_dict)
# now lets look at them
X = myres[0,:,:,:]
fig, ax = plt.subplots(1, 1)
tracker = ScrollThruPlot(ax, X, fig)
fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
plt.show()
pdb.set_trace()
plt.imsave('/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/scat_eg/input.png', egbatch[0,:,:,0], cmap=cm.gray)
for c_idx in range(X.shape[2]):
plt.imsave('/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/scat_eg/channels/%03d.png' % c_idx, X[:,:,c_idx], cmap=cm.gray)
def get_salt_images(folder='mytrain'):
image_list = []
for filename in glob.glob('/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/%s/images/*.png' % folder): #assuming gif
im=Image.open(filename).convert('L')
npim = np.array(im, dtype=np.float32) / 255.0
npim_padded = np.pad(npim, ((12,0),(12,0)), 'reflect')
image_list.append(npim_padded)
im.close()
image_list = np.array(image_list)
return np.expand_dims(image_list, -1)
def get_decisions(foldername='test', model_dir=None, outfile=None):
"""
change the first two vars to run on different sets
"""
valX = get_salt_images(folder=foldername)
fileids = sb.clean_glob(glob.glob('/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/%s/images/*.png' % foldername))
setsize = len(fileids)
headsz = int(setsize / float(batch_size)) * batch_size
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images': valX[:headsz,:,:,:]},
batch_size=batch_size, shuffle=False)
# '/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/models/binary1'
bin_model = tf.estimator.Estimator(model_fn, model_dir=model_dir)
gen = bin_model.predict(input_fn)
id_to_pred = {}
for file_i, prediction in enumerate(tqdm(gen, total=headsz)):
fileid, file_extension = os.path.splitext(fileids[file_i])
id_to_pred[fileid] = prediction
# now get the tail
input_fn = tf.estimator.inputs.numpy_input_fn(x={'images': valX[-batch_size:,:,:,:]},
batch_size=batch_size, shuffle=False)
gen = bin_model.predict(input_fn)
for file_i, prediction in enumerate(gen):
idx = setsize-batch_size+file_i
fileid, file_extension = os.path.splitext(fileids[idx])
id_to_pred[fileid] = prediction
# '/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/models/binary1/test_bin_pred'
if outfile:
np.save(outfile, id_to_pred)
return id_to_pred
def view_mistakes():
foldername = 'myval'
id_to_pred = get_decisions(foldername, '/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/models/binary13b')
fileids = sb.clean_glob(glob.glob('/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/%s/images/*.png' % foldername))
# imgs = sd.get_salt_labels(folder='myval')
# imgs = np.reshape(imgs, (imgs.shape[0], 101,101))
imgs = sd.get_salt_images(folder='myval')
val_pix_num = sd.salt_pixel_num(folder='myval')
valY = np.array(val_pix_num > 0).astype(int)
mistake_i = 0
for file_id_i, file_id in enumerate(fileids):
fileid, file_extension = os.path.splitext(file_id)
if valY[file_id_i] != id_to_pred[fileid]:
imgs[mistake_i,:,:] = imgs[file_id_i,:,:]
mistake_i += 1
print('made %i mistakes' % mistake_i)
X = np.swapaxes(np.swapaxes(imgs[:mistake_i,:,:],0,2),0,1).astype(float)
fig, ax = plt.subplots(1, 1)
tracker = ScrollThruPlot(ax, X, fig)
fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
plt.show()
def save_test_dec():
mymodel = '/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/models/binary13b'
myoutfile = '/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/models/binary13b/val_bin_pred.npy'
get_decisions(foldername='myval', model_dir=mymodel, outfile=myoutfile)
def main():
trainX = get_salt_images(folder='mytrain')
train_pix_num = sd.salt_pixel_num(folder='mytrain')
trainY = np.array(train_pix_num > 0).astype(int)
valX = get_salt_images(folder='myval')
val_pix_num = sd.salt_pixel_num(folder='myval')
valY = np.array(val_pix_num > 0).astype(int)
# Build the Estimator
model_dir = '/scratch0/ilya/locDoc/data/kaggle-seismic-dataset/models/binary13b'
model = tf.estimator.Estimator(model_fn, model_dir=model_dir)
for i in range(100000):
# Define the input function for training
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images': trainX[:3584,:,:,:]}, y=trainY[:3584],
batch_size=batch_size, num_epochs=1, shuffle=True)
# Train the Model
tf.logging.set_verbosity(tf.logging.INFO)
model.train(input_fn, steps=None)
# if i % 2 == 0:
# Evaluate the Model
# Define the input function for evaluating
input_fn = tf.estimator.inputs.numpy_input_fn(
x={'images': valX[:384,:,:,:]}, y=valY[:384],
batch_size=batch_size, shuffle=False)
# Use the Estimator 'evaluate' method
e = model.evaluate(input_fn)
print("Testing Accuracy:", e['accuracy'])
if __name__ == '__main__':
scat2d_eg()
# lets look at the result images with the scroll thru vis
# then do the mnist like network on binary and see results (with PCA layer in between)
# and research what they do for semantic segmentation, u net like stuff
# later concatenate in 2d wavelet features
|
from cs50 import get_int
from cs50 import get_float
def main():
money = get_money()
cents = round(money * 100)
coins = 0
while cents >= 25:
cents = cents - 25
coins = coins + 1
while cents >= 10:
cents = cents - 10
coins = coins + 1
while cents >= 5:
cents = cents - 5
coins = coins + 1
while cents >= 1:
cents = cents - 1
coins = coins + 1
print(f"{coins}")
def get_money():
while True:
n = get_float("Changed owed: ")
if n > 0:
break
return n
main() |
# NR法 関数の解を求める
import numpy as np
def f(x):
return x**2-2*np.sin(x)
def divf(x):
return 2*x-2*np.cos(x)
# 初期値
x = [1]
# 相対誤差
z = ["-"]
# 許容誤差
ips = 10**(-4)
xi = x[0]
zi = ips + 1
i = 0
print("初期値: " + str(xi))
print("許容誤差: " + str(ips))
print("")
while zi > ips:
print(str(i + 1) + "周目")
xi = x[i] - f(x[i]) / divf(x[i])
print("x: " + str(xi))
x.append(xi)
zi = abs((x[i + 1] - x[i]) / x[i])
print("z: " + str(zi))
z.append(zi)
i += 1
print("")
print("解: " + str(xi))
print("誤差: " + str(zi))
|
#!/usr/bin/env python
from hashlib import md5
from itertools import count
key, h5, h6 = input(), 0, 0
for i in count(1):
h = md5(f"{key}{i}".encode()).hexdigest()
# The nested conditions speed up evaluation
if h.startswith("00000"):
if not h5:
h5 = i
if h6:
break
if not h6 and h.startswith("000000"):
h6 = i
if h5:
break
print(h5)
print(h6)
|
import unittest
from python_example_project.number_class import Number
unittest.main(argv=['first-arg-is-ignored'], exit=False)
class test_number(unittest.TestCase):
def test_float(self):
n = Number(2.)
self.assertEqual(n.square(), 4.)
self.assertEqual(n.cube(), 8.)
def test_int(self):
n = Number(2)
self.assertEqual(n.square(), 4)
self.assertEqual(n.cube(), 8)
|
# Import modules to use
from words import words
import random
from colorama import Fore,Style
# 1. Welcome
print("Welcome to the game hangman in Python")
# 2. Function to get word
def get_valid_word(words):
word = random.choice(words)
# Choose a good word
while '-' in word or ' ' in word: # While - or ' '
word = random.choice(words)
return word
# Display word and its length
my_word = get_valid_word(words)
print(my_word + '\n',len(my_word))
# Una función que despliegue los guiones
# dependiendo el tamaño de la palabra
# Ejemplo:
# A N O N Y M O U S
# _ _ _ _ _ _ _ _ _
print(Fore.RED+"-"*len(my_word)) |
numero_de_convidados = input('Quantas pessoas vao pra festa? ')
lisa_de_convidados = []
i = 1
while i <= int(numero_de_convidados):
nome_de_convidado = input('Coloque o nome do convidado ' + str(i)+ ': ')
lisa_de_convidados.append(nome_de_convidado)
i += 1
print('Serao chamados ' + numero_de_convidados , 'convidados')
print('\nLISTA DE CONVIDADOS')
for convidado in lisa_de_convidados:
print(convidado)
opcao_1 = str(input('Quer quer adicionar mais alguem?'))
if opcao_1 == 'sim':
lisa_de_convidados.append(input('Escreva o nome para adicionar: '))
print('\nSerao Chamados ' + numero_de_convidados, 'convidados')
print('\nLista de convidados')
for convidado in lisa_de_convidados:
print(convidado)
opcao_2 = str(input('QUer remover alguem?'))
print('\n')
if opcao_2 == 'sim':
lisa_de_convidados.remove(input('Escreva o nome para remover: '))
print('\nSerao Chamados ' + numero_de_convidados, 'convidados')
print('\nLista de convidados')
for convidado in lisa_de_convidados:
print(convidado)
opcao_3 = str(input('Quer sair? '))
if opcao_3 == 'sim':
exit(input('Escreva 0 para sair: '))
print('\nSerao Chamados ' + numero_de_convidados, 'convidados')
print('\nLista de convidados')
for convidado in lisa_de_convidados:
print(convidado)
|
from random import uniform
# Animal names and IDs
species = {
'Monkey': 0,
'Giraffe': 1,
'Elephant': 2
}
class Animal:
""" Parent animal object """
def __init__(self):
self.health = 100.00
self.is_dead = False
self.name = type(self).__name__
def tick(self):
""" Method called every hour of simulation time """
# Do not process animal's tick if its dead.
if self.is_dead:
return
# Generate a random float value between 0-20 to two decimal places.
self.health -= uniform(0, 20)
# Check the animal's condition. I call a separate method here as they will all differ.
self.check_condition()
def feed(self, value):
""" Method is called when an animal is fed. """
if self.is_dead:
return
self.health += value
if self.health > 100.0:
self.health = 100.0
def _check_condition(self):
""" Intenal method is called to check a certain animal's condition. """
pass
def get_health(self):
""" Returns the animal health as a string to two decimal places. """
return '{0:.2f}'.format(self.health)
def __str__(self):
return self.name
class Monkey(Animal, object):
def __init__(self):
self.species = species['Monkey']
super(Monkey, self).__init__()
def check_condition(self):
if self.health < 30.0:
self.is_dead = True
class Giraffe(Animal, object):
def __init__(self):
self.species = species['Giraffe']
super(Giraffe, self).__init__()
def check_condition(self):
if self.health < 50.0:
self.is_dead = True
class Elephant(Animal, object):
def __init__(self):
self.species = species['Elephant']
self.can_walk = True
super(Elephant, self).__init__()
def check_condition(self):
if self.health < 70.0 and self.can_walk == False:
self.is_dead = True
elif self.health < 70.0:
self.can_walk = False
elif self.health >= 70.0:
self.can_walk = True |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 08 18:09:13 2015
@author: Stephane
"""
"""This is a small script to demonstrate using Tk to show PIL Image objects.
The advantage of this over using Image.show() is that it will reuse the
same window, so you can show multiple images without opening a new
window for each image.
This will simply go through each file in the current directory and
try to display it. If the file is not an image then it will be skipped.
Click on the image display window to go to the next image.
Noah Spurrier 2007
"""
import os
import Tkinter
import Image, ImageTk
def button_click_exit_mainloop (event):
event.widget.quit() # this will cause mainloop to unblock.
import os
import os.path
class ProcessImage(object):
clicked = False
def __init__(self, filename):
self.root = Tkinter.Tk()
self.root.bind("<Button>", button_click_exit_mainloop)
self.root.geometry('+%d+%d' % (100,100))
self.filename = filename
self.clicked = False
self.prepareDisplay(filename)
def prepareDisplay(self,fileName):
pass
def process(self):
image1 = Image.open(self.filename)
self.root.geometry('%dx%d' % (image1.size[0],image1.size[1]))
tkpi = ImageTk.PhotoImage(image1)
label_image = Tkinter.Label(self.root, image=tkpi)
label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])
self.root.title(self.filename)
self.root.mainloop()
self.finish()
def processFrame(self, frame):
raise Exception ("To be defined !!!!!!!!!!!!!!!!!" )
def finish(self):
pass
def test():
dirlist = os.listdir('.')
for f in dirlist:
try:
pi = ProcessImage(f)
pi.process()
except Exception as e:
# This is used to skip anything not an image.
# Image.open will generate an exception if it cannot open a file.
# Warning, this will hide other errors as well.
print e
if __name__ == '__main__':
test()
|
#return just the even items
my_array = [1,2,3,4,5,6]
def is_even(num) :
return num % 2 == 0
result = filter(is_even, my_array)
for item in result :
print(item) |
file = open('test.txt').read().strip('\n')
test = file.splitlines()
def solution(down, right, area):
count = 0
x = 0
y = 0
while True:
y = y + down
if y >= len(area):
break
x = (x + right) % len(area[y])
if area[y][x] == "#":
count = count + 1
return count
print(solution(1, 3, test))
|
from fantasy import positions, relevant_stats
import pandas as pd
import numpy as np
def last_n_weeks(df, stub, career_game, n):
"""
Given the player's data stored in df, find the stats for the player's last n games
prior to career_game if they exist. Wrapping to previous year if necessary. If n > game
will return whatever games are available so that returned df is smaller than expected.
df: dataframe of player stats. Must have columns 'stub', 'career_game'
stub: stub from pro football reference, guarenteed to be unique for each player
career_game: career_game to look back from
n: The number of weeks to look back.
Returns: last n weeks for the player before the given date
"""
last_n = df[(df['stub'] == stub) & (df['career_game'] >= career_game - n) & (df['career_game'] < career_game)]
# append 0 values to fill in missing values if career_game < n. Could maybe
# add college stats but that would be a later addition
if career_game < n:
zero_rows = pd.DataFrame([[0] * last_n.shape[1]] * (n - career_game), columns=last_n.columns)
return zero_rows.append(last_n, ignore_index=True)
return last_n
def construct_model_vector(df, n):
"""
Convert a dataframe to an array of numpy vectors which are of the form
[(1-hot encoding of position), (game stats for n games leading up to this
one for a given player)]. If there are p positions and s stats this
vector will be of dimension p + s * n.
df: dataframe of game values
n: number of games to include in analysis
Returns:
"""
data = []
years = []
for game in df.iterrows():
pos = np.zeros(len(positions.keys()))
pos[positions[game[1]['pos']]] = 1
age = np.array([game[1]['age']])
prev_games = last_n_weeks(df, game[1]['stub'], int(game[1]['career_game']), n)
games_vec = prev_games[relevant_stats].to_numpy().flatten()
final_vec = np.concatenate((pos, age, games_vec))
data.append(final_vec)
years.append(game[1]['year'])
return np.stack(data), years
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.