text
stringlengths 37
1.41M
|
---|
import random
uppercase_gens = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase_gens = uppercase_gens.lower()
digits_gens = "0123456789"
symbols_gens = ":()[]{},.;'>?</\\ #$%^&*@!"
upper, lower, digits, symbols = True,True,True,True
temp = ""
if upper:
temp += uppercase_gens
if lower:
temp += lowercase_gens
if digits:
temp += digits_gens
if symbols:
temp += symbols_gens
length = int(input("Please Enter The Lenghth of the Password: \n"))
amount = int(input("Please Enter The Ammount of the Password to be Generated: \n"))
#THIS IS NOT RECOMMENDED
#To Always get the same password we can use random.seed()
#the generator creates a random number based on the seed value, so if the seed value is 10, you will always get same as the first random number.
# for_same_pass_everytime = "Shahriar_xD"
# random.seed(for_same_pass_everytime)
for x in range(amount): # loop runing the amount number of times
password = "".join(random.sample(temp,length))
print(password)
# What is random.sample?
# Ans :
# import random
# list1 = [1, 2, 3, 4, 5, 6]
# print(random.sample(list1, 3))
# Output: [3, 1, 2]
|
import numpy as np
def step_function(sum_of):
if sum_of >= 1:
return 1
else:
return 0
# sigmoid muito usada para retornar probabilidades
def sigmoid_function(sum_of) -> float:
return 1 / 1 + np.exp(-sum_of)
def sigmoid_derivative(x):
return x * (1 - x)
def tahn_function(sum_of):
""" Hyperbolic tanget """
return (np.exp(sum_of) - np.exp(-sum_of)) / (np.exp(sum_of) + np.exp(-sum_of))
def relu_function(sum_of):
if sum_of >= 0:
return sum_of
return 0
def linear_function(sum_of):
return sum_of
def softmax_function(sum_of):
ex = np.exp(sum_of)
return ex / ex.sum()
def mean_absolute_error(x: [(int, float)]):
result = 0
for (expect, error) in x:
result += abs(expect - error)
return result / len(x)
def mean_square_error(x: [(int, float)]):
result = 0
for (expect, error) in x:
result += (expect - error) ** 2
return 1 / len(x) * result
def mean_root_error(x: [(int, float)]):
result = 0
for (expect, error) in x:
result += (expect - error) ** 2
return np.sqrt(1 / len(x) * result)
|
import os
import csv
import pandas as pd
election_csv = os.path.join("Resources", "election_data.csv")
analysis_path = os.path.join("Analysis", "analysis.txt")
#df=pd.read_csv(election_csv)
#print(df.groupby(['Candidate'],as_index=False).count())
#print(df.count())
candidates = []
#candidate dictionary for vote_tally
candidate_dict = {}
total_count = 0
# tally the total number of votes excluding the header row
def vote_counter():
#call global variable
global total_count
#open and read file
with open(election_csv) as election:
reader = csv.reader(election, delimiter=",")
for row in reader:
#ignore header row
if row[0] == 'Voter ID':
pass
else:
total_count = total_count + 1
return total_count
# create a list of candidates in the election
def candidates_list():
global candidates
with open(election_csv) as election:
reader = csv.reader(election, delimiter=",")
#skip header row
next(reader)
#add candidates if they are not already on the list
for row in reader:
if row[2] not in candidates:
candidates.append(row[2])
else:
pass
return candidates
# get a tally of votes and percent of votes for each candidate
def vote_tally():
global candidate_dict
global total_count
#add candidates to candidate dictionary
for candidate in candidates:
candidate_dict[candidate] = [0,0]
with open(election_csv) as tally:
reader = csv.reader(tally, delimiter=",")
next(reader)
for row in reader:
for key, value in candidate_dict.items():
if key == row[2]:
value[1] = value[1] + 1
value[0] = round(((value[1] / total_count) * 100), 1)
else:
pass
return candidate_dict
#find the winner of the election
winner = "none"
def find_winner():
#initialize leader variable
leader = 0
global winner
for key, value in candidate_dict.items():
if value[1] > leader:
leader = value[1]
winner = key
else:
pass
return winner
#run and print results
vote_counter()
print("The total votes were: " + str(total_count))
candidates_list()
print("Candidates in the election: " + str(candidates))
vote_tally()
print("The % and total votes for each candidate were: " + str(candidate_dict))
find_winner()
print("And the winner was: " + str(winner) + "!")
#print analysis to text file
a = open(analysis_path, "w+")
a.write('Election Voting Results')
a.write('\n' + ('-' * 25))
a.write('\n' + 'Total Votes: ' + str(total_count))
a.write('\n' + ('-' * 25))
for key, value in candidate_dict.items():
a.write('\n' + key + ': ' + str(value[0]) + '% (' + str(value[1])+ ')')
a.write('\n' + ('-' * 25))
a.write('\n' + 'Winner: ' + winner)
a.write('\n' + ('-' * 25))
|
import random
import datetime
def bubble_sort(list):
start = datetime.datetime.now()
for i in range(len(list)-1):
for j in range(len(list)-1):
print("Before Swap: " + str(list))
if list[j]>list[j+1]:
(list[j], list[j+1])= (list[j+1], list[j])
print("After Swap: " + str(list))
end = datetime.datetime.now()
return end-start
mylist = [6,5,3,1,8,7,2,4]
bubble_sort(mylist)
randomList =[]
for index in range(100):
randomList.append(random.randint(0,10000))
print('Random Number list of 100 values')
bubble_sort(randomList)
|
import random
import datetime
def bubble_sort(list):
start = datetime.datetime.now()
for i in range(len(list)):
for j in range(len(list) - 1):
if (list[j] > list[j + 1]):
(list[j], list[j + 1]) = (list[j + 1], list[j]) # tuple swap
end = datetime.datetime.now()
return end - start
# create list of random values
sampleList = []
for index in range(100):
sampleList.append(random.randint(0, 10001))
print('sampleList before bubble_sort():\n' + str(sampleList))
executionTime = bubble_sort(sampleList)
print('\nsampleList after bubble_sort():\n' + str(sampleList))
print('\ntotal execution time (hh:mm:ss.microsecs): ' + str(executionTime))
|
from flask import Flask, render_template, session, request, redirect
import random
app = Flask(__name__)
app.secret_key = 'my_secret_key'
@app.route('/')
def index():
if not 'gold' in session:
session['gold'] = 0
if not 'activities' in session:
session['activities'] = []
return render_template('index.html')
@app.route('/process', methods = ['POST'])
def process():
buildings = {
'farm':random.randint(5,10),
'casino':random.randint(-50,50),
'cave':random.randint(0,30),
'house':random.randint(0,5)
}
if request.form['building'] in buildings:
print buildings[request.form['building']]
return redirect('/')
if __name__ == '__main__':
app.run(debug = True)
"""
Explain line 24!
basically, when we hit submit and it gets posted, the information that is posted is the request.form. So if ‘building’ is in the dictionary buildings, which its value - ‘farm’ is, then it prints. And when it prints, it basically uses the dictionary buildings to activate, and since it uses [request.form[‘building’]], it refers back to what was submitted/posted, which had the value of farm. so in the dictionary, farm gets a random number between 5 and 10 which is printed to the terminal.
"""
|
def CoinToss():
import random
newArr = []
tails = 0
heads = 0
for count in range(1000):
random_num = random.random()
newArr.append(round(random_num))
for count in range(len(newArr)):
if(newArr[count] > 0):
heads += 1
elif(newArr[count] == 0):
tails += 1
print 'Number of Head Tosses: ', heads
print 'Number of Tails Tosses: ', tails
|
def multiply(a, num):
for x in range(0, len(a)):
a[x] = a[x] * num
return a
a = [2, 4, 10,16]
print multiply(a, 5)
|
'''
Create a program that simulates tossing a coin 5,000 times.
Your program should display how many times the head/tail appears.
'''
import random
head_count = 0
tail_count = 0
string_result = 'invalid'
print('Lets start tossing that coin...')
for index in range(1, 5001):
toss_result = round(random.random())
if (toss_result == 1): # heads
head_count += 1
string_result = 'heads'
else:
tail_count += 1
string_result = 'tails'
print('Coin Toss {}: {} -> [ total heads: {}, total tails {}]'.format(index, string_result, head_count, tail_count))
print('5000 tosses, you must be tired...let\'s stop now.')
|
import re
def get_matching_words():
words = ["aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight", "hobgoblin", "iconoclast", "issue", "kebab", "kilo", "laundered", "mattress", "millennia", "natural", "obsessive", "paranoia", "queen", "rabble", "reabsorb", "sacrilegious", "schoolroom", "tabby", "tabloid", "unbearable", "union", "videotape"]
print [word for word in words if re.search(r".*v", word)]
print [word for word in words if re.search(r".*ss", word)]
print [word for word in words if re.search(r"e$", word)]
print [word for word in words if re.search(r".*b.*b", word)]
print [word for word in words if re.search(r".*b.b", word)]
print [word for word in words if re.search(r".*b.*b", word)]
print [word for word in words if re.search(r"\a\e\i\o\u", word)]
print [word for word in words if re.search(r".r.e.g.u.l.a.r .e.x.p.r.e.s.s.i.o.n", word)]
print [word for word in words if re.search(r"\w\w", word)]
get_matching_words()
|
ex = ' vvalley the word for bo0000bby in assassin the aeiou regular regula'
import re
# re.search(pattern, string) finds the first thing that passes what you're looking for and stops there. you use print match.group() to see what you got
#re.findall(patter, string) finds all instances that match your search paramter and returns them in a list, use print [variable name] to see the list
match = re.search(r'v',ex)
# searches for the first instance of a single v
# if there is a v, it is stored inside match, this if statement checks if match is true or has anything in it, then you can print whatever match has with that function, if it was just one instance
match2 = re.findall(r's{2}',ex)
# searches for double s right next to each other, all instances, the curly braces specifically only searches for 2
match3 = re.findall(r'e\b',ex)
#searches for an e that is at the end of the word, the \b counts as the boundary between a world and non word so both a space and the end of the string can count, all instances
match4 = re.findall(r'b.b',ex)
# searches for a b with any character except a new line \n and another b. the period stands for any character except new line, all instances
match5 = re.findall(r'b.b',ex)
# the same thing as four
match6 = re.findall(r'b.*b',ex)
# searches for anything that has one b followed by any character besides new line(.) and any number of characters between the first b and a second b(*), all instances
match7 = re.findall(r'aeiou',ex)
# searches for the 5 vowels in order in any words
match8 = re.findall(r'[regula]+',ex)
match = re.findall(r'(.)\2',ex)
|
def odd_even(a,b):
for x in range(1,2000):
if x % 2 == 1:
print 'Number is ' + str(x) + '. This is an odd number.'
else:
print 'Number is ' + str(x) + '. This is an even number.'
|
my_list = [4, 'dog', 99, ['list', 'inside', 'another'],'hello world!']
for element in my_list:
print element
|
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
for index in range(len(students)):
string =''
for key,val in students[index].items():
string += val + ' '
print string
for key,val in users.items():
print key
for i in range(len(val)):
answer = ''
length = 0
for v in val[i].values():
answer += v + ' '
length += len(v)
print '{} - {}- {}'.format((i + 1), answer, length)
|
#Create a program that prints the sum of all the values in the list:
a = [1,2,5,10,255,3]
b = sum(a)
print b
|
from flask import Flask, render_template, session, request, redirect
import random
app = Flask(__name__)
app.secret_key = 'my_secret_key'
@app.route('/')
def index():
if not 'gold' in session:
session['gold'] = 0
if not 'activities' in session:
session['activities'] = []
return render_template('index.html')
@app.route('/process', methods = ['POST'])
def process():
buildings = {
'farm':random.randint(5,10),
'casino':random.randint(-50,50),
'cave':random.randint(0,30),
'house':random.randint(0,5)
}
if request.form['building'] in buildings:
""" OMG What???"""
result = buildings[request.form['building']]
session['gold'] = session['gold']+result
result_dictionary = {
'class': ('red','green')[result > 0],
'activity': "You went to the {} and {} {} gold!".format(request.form['building'], ('lost','gained')[result > 0], result)
}
session['activities'].append(result_dictionary)
return redirect('/')
if __name__ == '__main__':
app.run(debug = True)
"""
Explain line 24 - 31. Will it work? How, where what? why!?
Line 24: is another way of saying 'this code looks whack'
Line 25 - 31: Checks if the post info that was submitted had a value in the dictionary. The value farm exists. Then, it creates a variable called 'result', which activates the farm key in buildings. Farm key makes var 'result', equal a number between 5 and 10. Then it makes the session[‘gold’] which is currently 0, equal to itself plus the random number. A new dictionary with two keys is created. The first key, 'class', has the value of 'red' and 'green'. Green is selected by the index value, random integer result compared to 0. In the above code sampling, it is always true and equals 1. Green is the the index value of 1. Green is always set. In the same way, 'gained' is always set. It then appends the string of text to the 'activities' session. and updates the page.
And, the html,
"""
|
def selection_sort(list):
for item in range(len(list)):
min = list[item]
for ele in range(item, len(list)):
if min >= list[ele]:
min = list[ele]
index = ele
if
temp = list[item]
list[item] = min
list[index] = temp
return list
list = [4,2,9,7,5,5,6,5,5]
print(selection_sort(list))
|
import random
import datetime
def selectsort(list):
start = datetime.datetime.now()
for i in range(len(list)):
minIndex = i
for j in range(i,len(list)):
if list[minIndex] > list[j]:
minIndex=j
#print('List before swap: ', str(list))
(list[minIndex], list[i])=(list[i], list[minIndex])
#print('List after swap: ', str(list))
end = datetime.datetime.now()
return end - start
sample= [9,8,3,4,0,1]
selectsort(sample)
randomList =[]
for index in range(10000):
randomList.append(random.randint(0,10000))
print('Random Number list of 10000 values')
runningtime = selectsort(randomList)
print('Starting list: ', randomList)
selectsort(randomList)
print('Ending list: ', randomList)
print( 'Running time: (hh:mm:ss.microsec) ',runningtime )
|
import re
def get_matching_words(regex):
words = ["aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight", "hobgoblin", "iconoclast", "issue", "kebab", "kilo", "laundered", "mattress", "millennia", "natural", "obsessive", "paranoia", "queen", "rabble", "reabsorb", "sacrilegious", "schoolroom", "tabby", "tabloid", "unbearable", "union", "videotape"]
return [word for word in words if re.search(regex, word)]
# 1 All Words that contain v
print(get_matching_words(r'.*v'))
print
#2 All words that contain a double-"s"
print(get_matching_words(r's{2}'))
print
#3 all words that end with an "e"
print(get_matching_words(r'e$'))
print
#4 all words that contain a 'b' and any than another'b'
print(get_matching_words(r'b.b+'))
print(get_matching_words(r'b\wb+'))
print
#5 all words that contain a 'b' at least one character any than another'b'
print(get_matching_words(r'b.*b'))
print
#6 all words that contain a 'b' any number of character (including zero) than another b
print(get_matching_words(r'b{0}b'))
print
# 7 All words that incldes the five vowell in order
print(get_matching_words(r'a.*e.*i.*o.*u.*'))
print
#8 All words that only use the letter in Regular Expression <- Could not come uo with th answer
print(get_matching_words(r'.*r.*e.*g.*u.*l.*a.*x.*p.*r.*s.*i.*o.*n'))
#9 All words that contain a double letter<- Could not come uo with th answer
print(get_matching_words(r'\w{0,}\w'))
print
|
import unittest
from data_structures import heap_pq
class TestHeapQueue(unittest.TestCase):
ascending_list = [i for i in range(0, 11, 1)]
descending_list = [i for i in range(10, -1, -1)]
@staticmethod
def less_than_function(a, b):
return a < b
@staticmethod
def greater_than_function(a, b):
return a > b
def test_basic_heap_function(self):
min_heap_queue = heap_pq.HeapPriorityQueue(self.less_than_function,
self.descending_list)
max_heap_queue = heap_pq.HeapPriorityQueue(self.greater_than_function,
self.ascending_list)
# Assert Heapify - intializing heap with prior data
self.assertEqual(len(max_heap_queue), 11)
self.assertEqual(len(min_heap_queue), 11)
# Test Peek
self.assertEqual(min_heap_queue.peek(), 0)
self.assertEqual(max_heap_queue.peek(), 10)
# Test Push
min_heap_queue.push(-100) # Smallest element in heap
max_heap_queue.push(100) # largest element in heap
self.assertEqual(min_heap_queue.peek(), -100)
self.assertEqual(max_heap_queue.peek(), 100)
self.assertEqual(len(min_heap_queue), 12)
self.assertEqual(len(max_heap_queue), 12)
# Test Pop
self.assertEqual(min_heap_queue.pop(), -100) # Smallest element in heap
self.assertEqual(min_heap_queue.pop(), 0)
self.assertEqual(max_heap_queue.pop(), 100) # largest element in heap
self.assertEqual(max_heap_queue.pop(), 10)
self.assertEqual(len(min_heap_queue), 10)
self.assertEqual(len(max_heap_queue), 10)
def test_assert_empty_throws(self):
def pop_empty_queue():
queue = heap_pq.HeapPriorityQueue(self.less_than_function)
queue.pop()
def pop_non_empty_queue():
queue = heap_pq.HeapPriorityQueue(self.less_than_function, [12, 34, 12, 12])
result = [queue.pop() for i in range(len(queue))]
self.assertListEqual([12, 12, 12, 34], result)
queue.pop() # Pop empty queue
self.assertRaises(IndexError, pop_empty_queue)
self.assertRaises(IndexError, pop_non_empty_queue)
if __name__ == '__main__':
unittest.main()
|
import time
import datetime as dt
import calendar as cal
import pandas as pd
import numpy as np
# New cities can be added here without requiring changes to the funtions
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
city_opts = ['chicago', 'new york city', 'washington']
month_opts = list(cal.month_name)
month_opts.append('All')
day_opts = list(cal.day_name)
day_opts.append('All')
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(int) month - number of the month to filter by (1-12), or 13 to apply no month filter
(int) day - number of the day of week to filter by (0-6 mon-sun), or 7 to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington)
while True:
city_lines = '\n'.join(['{} {}'.format(str(i+1), m) for i, m in enumerate(city_opts)]).title()
city_lines = '\nFirst, choose a city to analyze:\n\n' + \
'{}\n\nPlease enter 1-{}:\n\n'.format(city_lines, len(city_opts))
city = input(city_lines).strip()
# validate and format input
if city in [str(i) for i in range(1,4)]:
city = city_opts[int(city) - 1]
break
elif city.lower() in (city_opts):
city = city.lower()
break
else:
print('\nPlease enter the corresponding number only (you entered "{}")'.format(city))
# get user input for month (all, january, february, ... , june)
while True:
month_lines = '\n'.join(['{} {}'.format(str(i+1), m) for i, m in enumerate(month_opts[1:])])
month_lines = '\nNext, choose a month to analyze:\n\n' + \
'{}\n\nPlease enter 1-13:\n\n'.format(month_lines)
month = input(month_lines).lower().strip()
# validate and format input
if month in [str(i) for i in range(1,14)]:
month = int(month)
break
else:
print('\nPlease enter the corresponding number only (you entered "{}")'.format(month))
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day_lines = '\n'.join(['{} {}'.format(str(i+1), m) for i, m in enumerate(day_opts)])
day_lines = '\nFinally, choose a day of the week to analyze:\n\n' + \
'{}\n\nPlease enter 1-8:\n\n'.format(day_lines)
day = input(day_lines).lower().strip()
# validate and format input
if day in [str(i) for i in range(1,9)]:
day = int(day) - 1
break
else:
print('\nPlease enter the corresponding number only (you entered "{}")'.format(day))
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(int) month - number of the month to filter by (1-12), or 13 to apply no month filter
(int) day - number of the day of week to filter by (0-6 mon-sun), or 7 to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month and day of week from Start Time to create new columns
df['Month'] = df['Start Time'].dt.month
df['Day of Week'] = df['Start Time'].dt.dayofweek
# filter by month if applicable
if month != 13:
# filter by month to create the new dataframe
df = df[df['Month'] == month]
# filter by day of week if applicable
if day != 7:
# filter by day of week to create the new dataframe
df = df[df['Day of Week'] == day]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
month_mode = df['Month'].mode()[0]
print('\nThe most common month is {}.'.format(month_opts[month_mode]))
# display the most common day of week
day_mode = df['Day of Week'].mode()[0]
print('The most common day of week is {}.'.format(day_opts[day_mode]))
# display the most common start hour
hour_mode = df['Start Time'].dt.hour.mode()[0]
print('The most common start hour is {}:00.\n'.format(hour_mode))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
start_station_mode = df['Start Station'].mode()[0]
print('The most common start station is {}.'.format(start_station_mode))
# display most commonly used end station
end_station_mode = df['End Station'].mode()[0]
print('The most common end station is {}.'.format(end_station_mode))
# display most frequent combination of start station and end station trip
trip_mode = (df['Start Station'] + ' to ' + df['End Station']).mode()[0]
print('The most common trip is {}.'.format(trip_mode))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
sec_sum = int(round(df['Trip Duration'].sum()))
total_travel_time = str(dt.timedelta(seconds=sec_sum))
print('The total travel time is {} (to the nearest second).'.format(total_travel_time))
# display mean travel time
sec_mean = int(round(df['Trip Duration'].mean()))
mean_travel_time = str(dt.timedelta(seconds=sec_mean))
print('The mean travel time is {} (to the nearest second).'.format(mean_travel_time))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
user_type_counts = df['User Type'].groupby(df['User Type']).count()
user_type_list = ' and '.join('{} {}s'.format(v, k) for k, v in user_type_counts.items())
print('There are {}.'.format(user_type_list))
# Display counts of gender
if 'Gender' in df:
gender_counts = df['Gender'].groupby(df['Gender']).count()
gender_list = ' and '.join('{} {}s'.format(v, k) for k, v in gender_counts.items())
print('There are {}.'.format(gender_list))
else:
print('No gender data is available.')
# Display earliest, most recent, and most common year of birth
if 'Birth Year' in df:
earliest_birth = int(df['Birth Year'].min())
latest_birth = int(df['Birth Year'].max())
birth_mode = int(df['Birth Year'].mode()[0])
print('The earliest year of birth is {}.'.format(earliest_birth))
print('The latest year of birth is {}.'.format(latest_birth))
print('The most common year of birth is {}.'.format(birth_mode))
else:
print('No date of birth data is available.')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
# Show raw data 5 lines at a time if requested
more= ''
line = 0
show_lines = 5
total_lines = len(df.index)
while line < total_lines:
# Check how many lines are left, adjust message and data displayed if less than 5
remaining_lines = total_lines - line
if remaining_lines < show_lines:
show_lines = remaining_lines
# Check user wants to continue
raw = input('\nWould you like to see {} {}lines of raw data?'.format(show_lines, more) + \
' Enter Y to see them,or anything else to skip:\n\n')
if raw.lower() != 'y' and raw.lower() != 'yes':
break
else:
# Show data
print(df.iloc[line:line + show_lines])
# Adjust message for second batch onwards
if line == 0:
more = 'more '
# Update starting line for next batch
line += show_lines
# Show end message if all data has been displayed
if line >= total_lines:
print('End of data')
restart = input('\nWould you like to restart? Enter Y to restart, or anything else to quit:\n\n')
if restart.lower() != 'y' and restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
def factorial(n):
#espaios en blanco causan problemas
i = 2
temp = 1
while i <= n:
temp = temp*i
i = i+1
return temp
if __name__ == "__main__":
a = int(input("ingresa un numero"))
print(factorial(a))
|
from typing import List
import networkx
class OrdinalAgent(object):
def best_room(self, prices: List[int]) -> int:
"""
INPUT: the prices of the n rooms.
OUTPUT: the index of room that the agent most prefers in therese prices. index is between 0 and n-1.
"""
raise NotImplemented()
class Alice(OrdinalAgent):
def best_room(self, prices: List[int]) -> int:
return 0
class Bob(OrdinalAgent):
def best_room(self, prices: List[int]) -> int:
return 1
class Charlie(OrdinalAgent):
def best_room(self, prices: List[int]) -> int:
return 2
def find_almost_envy_free(agens:List[OrdinalAgent], totalRent:int):
shiz = []
for agent, room, price in shiz:
print("Agent %d recives room %d for %d shekels" % (agent, room, price))
alice = Alice()
bob = Bob()
charlie = Charlie()
find_almost_envy_free([alice, bob, charlie], 5000)
|
txt = "belajar Python Sangat Menyenangkan"
x = txt.capitalize()
print (x)
txt = "belajar python sangat menyenangkan"
x = txt.capitalize()
print (x)
txt = "belajar PYTHON SANGAT MeNyEnAnGkAn"
x = txt.capitalize()
print (x)
|
list_buah = ['Apel', 'Jeruk', 'Mangga', 'Pisang']
print("List buah :", list_buah)
# menampilkan posisi buah apel
print("Indeks buah apel :", list_buah.index('Apel'))
# menampilkan posisi buah anggur, yang tidak ada di dalam list
print("Indeks buah anggur :", list_buah.index('Anggur'))
|
bil = 10 # variable bil dengan tipe integer
bil_string = str(bil) # varible bil di casting kedalam string
bil_integer = int(bil) # variable bil di casting kedalam integer
bil_float = float(bil) # variable bil di casting kedalam float
print(bil_string)
print(type(bil_string))
print(bil_integer)
print(type(bil_integer))
print(bil_float)
print(type(bil_float))
|
txt = "12345"
x = txt.isdigit()
print(x)
txt = "0.123"
x = txt.isdigit()
print(x)
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
print(a.isdigit())
print(b.isdigit())
|
x = 15
y = 10
print(x == y)
print(x != y)
print(x > y)
print(x < y)
print(x >= y)
print(x <= y)
|
dict_mahasiswa = {"nama":"Nursalim", "npm":"201843500121", "jurusan":"Teknik Informatika", "ipk":3}
print("dict_mahasiswa :", dict_mahasiswa)
# menggunakan get() untuk mendapatkan nama, NPM, jurusan dan IP
print("Nama :", dict_mahasiswa.get("nama"))
print("NPM :", dict_mahasiswa.get("npm"))
print("Jurusan :", dict_mahasiswa.get("jurusan"))
print("IPK :", dict_mahasiswa.get("ipk"))
# Mencari value berdasarkan alamat yang tidak ada di dict menggunakan method get()
print("Alamat :", dict_mahasiswa.get("alamat"))
# Mencari value berdasarkan alamat yang tidak ada di dict menggunakan dict['key]
print("Alamat :", dict_mahasiswa["alamat"])
|
# Iterator tuple
tuple_buah = ("Apel", "Mangga", "Jeruk", "Anggur")
iter_buah = iter(tuple_buah)
print(next(iter_buah))
print(next(iter_buah))
# iterator pada set
set_mobil = {"Honda", "Suzuki", "Mazda", "BMW"}
iter_mobil = iter(set_mobil)
print(next(iter_mobil))
print(next(iter_mobil))
# iterator string
txt = "Python"
iter_string = iter(txt)
print(next(iter_string))
print(next(iter_string))
print(next(iter_string))
print(next(iter_string))
print(next(iter_string))
print(next(iter_string))
|
from datetime import datetime
import pytz
def float_hour_to_time(fh):
h, r = divmod(fh, 1)
m, r = divmod(r*60, 1)
return (
int(h),
int(m),
int(r*60),
)
def get_date_time(value):
dt = datetime.fromordinal(datetime(1900, 1, 1).toordinal() + int(value) - 2)
hour, minute, second = float_hour_to_time(value % 1)
dt = dt.replace(hour=hour, minute=minute, second=second)
dt_str = dt.astimezone(pytz.utc)
return dt_str.strftime("%Y-%m-%d %H:%M:%S")
|
#Anton Gefvert antge210, Aleksi Evansson aleev379
#3. Bearbetning av listor
#Uppgift 3A
"""
vikho394: OK!
Enkelt och bra. Inga konstigheter. Ni har dock docstrings som är längre än 79
tecken. De bör göras radbrytningar :) om man ska vara petig
"""
def split_it(string):
"""
Given a string, returns two new strings, where the first contains all lowercase letters, "." and "_"
and the second contains all uppercase letters, " " and "|", iteratively
"""
ret_str1 = ""
ret_str2 = ""
for char in string:
if char.islower() or char in "_.":
ret_str1 += char
elif char.isupper() or char in " |":
ret_str2 += char
return ret_str1, ret_str2
def split_rec(string):
"""
Given a string, returns two new strings, where the first contains all lowercase letters, "." and "_"
and the second contains all uppercase letters, " " and "|", recursively
"""
if not string:
return "",""
left,right = split_rec(string[1:])
if string[0].islower() or string[0] in "_.":
return string[0] + left, right
elif string[0].isupper() or string[0] in " |":
return left, string[0] + right
return left, right
|
"""Simple timer for Pomodoro technique, etc."""
import sys
from PyQt5 import Qt, QtCore, QtGui, QtWidgets
def time_to_text(t):
"""Convert time to text."""
if t <= 0:
return '--:--'
elif t < 3600:
minutes = t // 60
seconds = t % 60
return '{:02d}:{:02d}'.format(minutes, seconds)
else:
hours = t // 3600
minutes = t % 3600 // 60
seconds = t % 60
return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
class Timer(QtCore.QTimer):
"""Keep track of time and call handlers."""
def __init__(self, on_update, on_end):
super().__init__()
self.on_update = on_update
self.on_end = on_end
self.timeout.connect(self.tick)
self.time_total = None
self.time_remaining = None
def _check_and_show_remaining(self):
"""Check if the timer has expired and show remaining time."""
if self.time_left is None:
self.on_update(0, 0)
elif self.time_left <= 0:
self.on_end(self.time_total)
self.stop_timer()
else:
self.on_update(self.time_total, self.time_left)
def is_active(self):
"""Return True if timer is active."""
return self.time_total is not None
def set_timer(self, seconds):
"""Set timer for specified number of seconds."""
self.time_total = seconds
self.time_left = seconds
self.start(1000)
self._check_and_show_remaining()
def stop_timer(self):
"""Stop the timer."""
self.time_total = None
self.time_left = None
self.stop()
self._check_and_show_remaining()
def tick(self):
"""One more second passed."""
self.time_left -= 1
self._check_and_show_remaining()
def add_time(self, seconds):
"""Add more time (`seconds` can be negative to subtract)."""
if self.time_total is None:
if seconds > 0:
self.set_timer(seconds)
else:
self.time_left = max(0, self.time_left + seconds)
self.time_total = max(0, self.time_total + seconds)
self._check_and_show_remaining()
class TimerTrayIcon(QtWidgets.QSystemTrayIcon):
"""Autoupdating timer tray icon."""
icon_size = 44
radius = 16
small_radius = 5
def __init__(self):
super().__init__()
self.pixmap = QtGui.QPixmap(self.icon_size, self.icon_size)
self.update_time_display(0, 0)
def update_time_display(self, total, left):
"""Display time on the icon and in the tooltip."""
self.setToolTip(time_to_text(left))
self.repaint_icon(total, left)
def repaint_icon(self, total, left):
"""Draw the timer icon based on total and remaining time."""
background = Qt.QColor(220, 220, 220, 255)
black = Qt.QColor(40, 40, 40, 255)
white = Qt.QColor(255, 255, 255, 255)
painter = QtGui.QPainter(self.pixmap)
painter.setRenderHint(painter.Antialiasing)
painter.setBackground(background)
painter.eraseRect(0, 0, self.icon_size, self.icon_size)
painter.translate(self.icon_size / 2, self.icon_size / 2)
painter.setBrush(white)
painter.setPen(black)
r = self.radius
painter.drawEllipse(-r, -r, r * 2, r * 2)
painter.setBrush(black)
if total != 0:
fc = 5760 # Full clircle.
start = fc / 4 # 12 o'clock.
span = fc * left / total
painter.drawPie(-r, -r, r * 2, r * 2, start, span)
painter.setBrush(white)
painter.setPen(white)
sr = self.small_radius
painter.drawEllipse(-sr, -sr, sr * 2, sr * 2)
self.icon = QtGui.QIcon(self.pixmap)
self.setIcon(self.icon)
class MenuButton(QtWidgets.QPushButton):
"""Narrow button for inserting into the popup menu."""
def __init__(self, title, target):
super().__init__(title)
self.setStyleSheet('padding: 3px');
self.clicked.connect(target)
class TimerApplication(QtWidgets.QApplication):
"""Timer that sits in system dock."""
def __init__(self, argv):
super().__init__(argv)
self.timer = Timer(self.time_tick, self.time_out)
self._make_tray_icon()
def _make_tray_icon(self):
"""Create tray icon and add menu to it."""
self.tray_icon = TimerTrayIcon()
self.tray_icon.activated.connect(self.icon_activated)
self._make_menu()
self.tray_icon.show()
def _make_menu(self):
"""Create popup menu for the tray icon."""
menu = self.menu = QtWidgets.QMenu()
self.tray_icon.setContextMenu(self.menu)
time_action = QtWidgets.QWidgetAction(menu)
self.time_label = QtWidgets.QLabel('--:--')
self.time_label.setStyleSheet('padding: 7px;')
time_action.setDefaultWidget(self.time_label)
menu.addAction(time_action)
menu.addSeparator() # --------------------------------------
button_action = QtWidgets.QWidgetAction(menu)
button_box = QtWidgets.QWidget()
button_layout = QtWidgets.QHBoxLayout()
button_layout.addWidget(MenuButton('-5', self.minus5))
button_layout.addWidget(MenuButton('-1', self.minus1))
button_layout.addWidget(MenuButton('+1', self.plus1))
button_layout.addWidget(MenuButton('+5', self.plus5))
button_box.setLayout(button_layout)
button_action.setDefaultWidget(button_box)
menu.addAction(button_action)
menu.addSeparator() # --------------------------------------
menu.addAction('5 minutes', self.start5)
menu.addAction('10 minutes', self.start10)
menu.addAction('25 minutes', self.start25)
menu.addAction('45 minutes', self.start45)
menu.addAction('cancel timer', self.timer.stop_timer)
menu.addSeparator() # --------------------------------------
menu.addAction('exit', self.exit)
def time_tick(self, total, left):
"""One second passed."""
self.update_time_display(total, left)
def update_time_display(self, total, left):
"""Update time display."""
self.time_label.setText(time_to_text(left))
self.tray_icon.update_time_display(total, left)
def time_out(self, total):
"""Time is up."""
self.update_time_display(total, 0)
minutes = total // 60
if minutes == 1:
message = 'One minute is over'
else:
message = '{} minutes are over'.format(minutes)
self.tray_icon.showMessage('Time is up', message, 0)
def icon_activated(self, reason):
"""Handle clicks on the icon."""
if reason == QtWidgets.QSystemTrayIcon.Trigger:
if not self.timer.is_active():
self.start25()
def start5(self):
"""Set timer for 5 minutes."""
self.timer.set_timer(300)
def start10(self):
"""Set timer for 10 minutes."""
self.timer.set_timer(600)
def start25(self):
"""Set timer for 25 minutes."""
self.timer.set_timer(1500)
def start45(self):
"""Set timer for 45 minutes."""
self.timer.set_timer(2700)
def plus1(self):
"""Add one minute to the timer."""
self.timer.add_time(60)
def plus5(self):
self.timer.add_time(300)
def minus1(self):
self.timer.add_time(-60)
def minus5(self):
self.timer.add_time(-300)
def main():
app = TimerApplication(sys.argv)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
|
class Problem(object):
def __init__(self, state):
self.action_sequence = []
self.state = state
self.goal = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
def goal_test(self):
print("Checking Goal")
if self.state == self.goal:
return True
return False
def actions(self):
action_list = ["up", "down", "left", "right"]
if 0 in self.state[0]:
action_list.remove("up")
elif 0 in self.state[2]:
action_list.remove("down")
if 0 in [row[0] for row in self.state]:
action_list.remove("left")
elif 0 in [row[2] for row in self.state]:
action_list.remove("right")
return action_list
def public_actions(self, pre_state):
action_list = ["up", "down", "left", "right"]
if 0 in pre_state[0]:
action_list.remove("up")
elif 0 in pre_state[2]:
action_list.remove("down")
if 0 in [row[0] for row in pre_state]:
action_list.remove("left")
elif 0 in [row[2] for row in pre_state]:
action_list.remove("right")
return action_list
def result(self, pre_state, action):
next_state = pre_state[:]
x, y = self.find(0, next_state)
if action is "up":
next_state[x][y], next_state[x - 1][y] = next_state[x - 1][y], next_state[x][y]
elif action is "down":
next_state[x][y], next_state[x + 1][y] = next_state[x + 1][y], next_state[x][y]
elif action is "left":
next_state[x][y], next_state[x][y - 1] = next_state[x][y - 1], next_state[x][y]
elif action is "right":
next_state[x][y], next_state[x][y + 1] = next_state[x][y + 1], next_state[x][y]
return next_state
@staticmethod
def find(c, state):
for i, sublist in enumerate(state):
if c in sublist:
return i, sublist.index(c)
print("NOT FOUND")
return -1
def show(self):
print(self.state)
print("=========================")
|
import os
import sqlite3
from sqlite3 import Error
def database_connection(): # Conexão com o banco de dados
path = "menu_database.db"
con = None
try:
con = sqlite3.connect(path)
except Error as ex:
print(ex)
return con
def query(connection, sql): # INSERT, DELETE e UPDATE
try:
c = connection.cursor()
c.execute(sql)
connection.commit()
except Error as ex:
print(ex)
finally:
print("Operação realizada com sucesso")
os.system("pause")
connection.close()
def just_check(connection, sql): # SELECT
c = connection.cursor()
c.execute(sql)
result = c.fetchall()
return result
def main_options():
os.system("cls")
print("1 - Inserir Novo Registro")
print("2 - Deletar Registro")
print("3 - Atualizar Registro")
print("4 - Visualizar Registros")
print("5 - Buscar Registros por Nome")
print("6 - Mostrar Cardápio Mais Barato")
print("7 - Mostrar Cardápio Mais Caro")
print("8 - Sair")
def inside_options():
os.system("cls")
print("1 - Entrada")
print("2 - Prato Principal")
print("3 - Sobremesa")
print("4 - Bebida")
print("5 - Voltar")
def choose_table(choice):
if choice == '1':
table = 'tb_starters'
elif choice == '2':
table = 'tb_main'
elif choice == '3':
table = 'tb_desserts'
elif choice == '4':
table = 'tb_drinks'
elif choice == '5':
table = 0
else:
table = None
print("Opção inválida! Escolher novamente...")
os.system("pause")
return table
def menu_insert(table_name):
os.system("cls")
print("INSERIR NOVO REGISTRO\n\n")
name = input("Digite o nome: ")
code = input("Digite o código: ")
price = input("Digite o preço: R$ ")
vsql = "INSERT INTO '"+table_name+"'(NAME, CODE, PRICE) VALUES('" + \
name+"', '"+code+"', '"+price+"')"
vcon = database_connection() # Abrir o banco de dados
query(vcon, vsql)
vcon.close() # Fechar o banco de dados
def menu_delete(table_name):
os.system("cls")
print("DELETAR REGISTRO\n\n")
del_code = input("Digite o código do registro a ser deletado: ")
vsql = "DELETE FROM '"+table_name+"' WHERE CODE="+del_code
vcon = database_connection()
query(vcon, vsql)
vcon.close()
def menu_update(table_name):
os.system("cls")
print("ATUALIZAR REGISTRO")
up_code = input("Digite o código do registro a ser alterado: ")
vcon = database_connection()
check = just_check(vcon, "SELECT * FROM '"+table_name +
"' WHERE CODE="+up_code+" ")
rcode = check[0][0]
rname = check[0][1]
rprice = check[0][2]
print(f'Código: {rcode}')
print(f'Nome: {rname}')
print(f'Preço: R$ {rprice}\n')
print("Aperte ENTER caso não queira alterar algum dos campos.")
new_code = input("Digite o novo código: ")
new_name = input("Digite o novo nome: ")
new_price = input("Digite o novo preço: ")
if (len(new_code) == 0):
new_code = rcode
if (len(new_name) == 0):
new_name = rname
if (len(new_price) == 0):
new_price = str(rprice)
vsql = "UPDATE '"+table_name+"' SET CODE = '"+new_code+"', NAME = '" + \
new_name+"', PRICE = '"+new_price+"' WHERE CODE="+up_code
query(vcon, vsql)
vcon.close()
def menu_view(table_name):
os.system("cls")
print("VISUALIZAR REGISTROS\n")
vsql = "SELECT * FROM '"+table_name+"' "
vcon = database_connection()
check = just_check(vcon, vsql)
limit_size = 10
count = 0
print('CÓDIGO'+' '*5 + 'NOME' + ' '*26 + 'PREÇO(R$)' + ' '*4 + '\n')
for column in check:
print(
f"{column[0]:<10} {column[1]:<30} {column[2]:<4}")
count += 1
if (count >= limit_size):
count = 0
os.system("pause")
os.system("cls")
print("\nFim da lista")
os.system("pause")
vcon.close()
def menu_check(table_name):
os.system("cls")
print("BUSCAR REGISTROS POR NOME\n")
s_name = ''
while len(s_name) == 0:
s_name = input("Digite o nome: ")
vsql = "SELECT * FROM '"+table_name+"' WHERE NAME LIKE '%"+s_name+"%'"
vcon = database_connection()
check = just_check(vcon, vsql)
limit_size = 10
count = 0
print('\nCÓDIGO'+' '*5 + 'NOME' + ' '*26 + 'PREÇO(R$)' + ' '*4 + '\n')
for column in check:
print(
f"{column[0]:<10} {column[1]:<30} {column[2]:<4}")
count += 1
if (count >= limit_size):
count = 0
os.system("pause")
os.system("cls")
print("\nFim da lista")
os.system("pause")
vcon.close()
def cheaper_calculations(t_name):
vcon = database_connection()
check = just_check(vcon, "SELECT * FROM '"+t_name+"'")
cheap = {
'NAME': '',
'CODE': '',
'PRICE': 9999
}
for iprice in check:
a = float(iprice[2])
if a < cheap['PRICE']:
cheap['PRICE'] = a
cheap['NAME'] = iprice[1]
cheap['CODE'] = iprice[0]
vcon.close()
return cheap
def expensive_calculations(t_name):
vcon = database_connection()
check = just_check(vcon, "SELECT * FROM '"+t_name+"'")
expensive = {
'NAME': '',
'CODE': '',
'PRICE': 0
}
for iprice in check:
a = float(iprice[2])
if a > expensive['PRICE']:
expensive['PRICE'] = a
expensive['NAME'] = iprice[1]
expensive['CODE'] = iprice[0]
vcon.close()
return expensive
option = ''
while option != '8':
main_options()
option = input("Digite o número da operação que deseja realizar: ")
if option == '1' or option == '2' or option == '3' or option == '4' or option == '5':
choice_table = None
while choice_table is None:
inside_options()
i_option = input(
"Digite o número do banco de dados que deseja acessar: ")
choice_table = choose_table(i_option)
if choice_table != 0:
if option == '1':
menu_insert(choice_table)
elif option == '2':
menu_delete(choice_table)
elif option == '3':
menu_update(choice_table)
elif option == '4':
menu_view(choice_table)
elif option == '5':
menu_check(choice_table)
else:
pass
elif option == '6':
os.system("cls")
menu_cheap = []
starters_cheap = cheaper_calculations('tb_starters')
main_cheap = cheaper_calculations('tb_main')
desserts_cheap = cheaper_calculations('tb_desserts')
drinks_cheap = cheaper_calculations('tb_drinks')
total_cheap = starters_cheap['PRICE'] + main_cheap['PRICE'] + \
desserts_cheap['PRICE'] + drinks_cheap['PRICE']
menu_cheap.extend((starters_cheap, main_cheap,
desserts_cheap, drinks_cheap))
menu_names = ['ENTRADA', 'PRATO PRINCIPAL', 'SOBREMESA', 'BEBIDA']
print("\n**** CARDÁPIO MAIS BARATO ****\n")
for i in range(len(menu_names)):
print(f'**** {menu_names[i]} ****')
print(
f" NOME: {menu_cheap[i]['NAME']}\n CÓDIGO: {menu_cheap[i]['CODE']}\n PREÇO: R$ {menu_cheap[i]['PRICE']}\n")
print(f'TOTAL: R$ {total_cheap:.2f}')
os.system("pause")
os.system("cls")
elif option == '7':
os.system("cls")
menu_expensive = []
starters_expensive = expensive_calculations('tb_starters')
main_expensive = expensive_calculations('tb_main')
desserts_expensive = expensive_calculations('tb_desserts')
drinks_expensive = expensive_calculations('tb_drinks')
total_expensive = starters_expensive['PRICE'] + main_expensive['PRICE'] + \
desserts_expensive['PRICE'] + drinks_expensive['PRICE']
menu_expensive.extend(
(starters_expensive, main_expensive,
desserts_expensive, drinks_expensive)
)
menu_names = ['ENTRADA', 'PRATO PRINCIPAL', 'SOBREMESA', 'BEBIDA']
print("\n**** CARDÁPIO MAIS CARO ****\n")
for i in range(len(menu_names)):
print(f'**** {menu_names[i]} ****')
print(
f" NOME: {menu_expensive[i]['NAME']}\n CÓDIGO: {menu_expensive[i]['CODE']}\n PREÇO: R$ {menu_expensive[i]['PRICE']}\n")
print(f'TOTAL: R$ {total_expensive:.2f}')
os.system("pause")
os.system("cls")
elif option == '8':
os.system("cls")
print("Programa Finalizado")
else:
os.system("cls")
print("Opção inválida")
os.system("pause")
os.system("pause")
|
"""simple BTree database
The ``btree`` module implements a simple key-value database using external
storage (disk files, or in general case, a random-access `stream`). Keys are
stored sorted in the database, and besides efficient retrieval by a key
value, a database also supports efficient ordered range scans (retrieval
of values with the keys in a given range). On the application interface
side, BTree database work as close a possible to a way standard `dict`
type works, one notable difference is that both keys and values must
be `bytes` objects (so, if you want to store objects of other types, you
need to serialize them to `bytes` first).
The module is based on the well-known BerkelyDB library, version 1.xx.
Example::
import btree
# First, we need to open a stream which holds a database
# This is usually a file, but can be in-memory database
# using uio.BytesIO, a raw flash partition, etc.
# Oftentimes, you want to create a database file if it doesn't
# exist and open if it exists. Idiom below takes care of this.
# DO NOT open database with "a+b" access mode.
try:
f = open("mydb", "r+b")
except OSError:
f = open("mydb", "w+b")
# Now open a database itself
db = btree.open(f)
# The keys you add will be sorted internally in the database
db[b"3"] = b"three"
db[b"1"] = b"one"
db[b"2"] = b"two"
# Assume that any changes are cached in memory unless
# explicitly flushed (or database closed). Flush database
# at the end of each "transaction".
db.flush()
# Prints b'two'
print(db[b"2"])
# Iterate over sorted keys in the database, starting from b"2"
# until the end of the database, returning only values.
# Mind that arguments passed to values() method are *key* values.
# Prints:
# b'two'
# b'three'
for word in db.values(b"2"):
print(word)
del db[b"2"]
# No longer true, prints False
print(b"2" in db)
# Prints:
# b"1"
# b"3"
for key in db:
print(key)
db.close()
# Don't forget to close the underlying stream!
f.close()
"""
from typing import Any, Optional, Iterable, Tuple
class _BTree:
def close(self) -> None:
"""Close the database. It's mandatory to close the database at the end of
processing, as some unwritten data may be still in the cache. Note that
this does not close underlying stream with which the database was opened,
it should be closed separately (which is also mandatory to make sure that
data flushed from buffer to the underlying storage).
"""
...
def flush(self) -> None:
"""Flush any data in cache to the underlying stream."""
...
def __getitem__(self, key: bytes) -> bytes:
...
def get(self, key: bytes, default: Optional[bytes] = None) -> Optional[bytes]:
...
def __setitem__(self, key: bytes, val: bytes) -> None:
...
def __detitem__(self, key: bytes) -> None:
...
def __contains__(self, key: bytes) -> bool:
...
def __iter__(self) -> Iterable[bytes]:
"""A BTree object can be iterated over directly (similar to a dictionary)
to get access to all keys in order.
"""
...
def keys(self, start_key: bytes = None, end_key: bytes = None, flags: int = None) -> Iterable[bytes]:
...
def values(self, start_key: bytes = None, end_key: bytes = None, flags: int = None) -> Iterable[bytes]:
...
def items(self, start_key: bytes = None, end_key: bytes = None, flags: int = None) -> Iterable[Tuple[bytes, bytes]]:
...
def open(stream: Any, *, flags: int = 0, pagesize: int = 0, cachesize: int = 0,
minkeypage: int = 0) -> _BTree:
...
INCL: int
DESC: int
|
'''
4-10. Slices: Using one of the programs you wrote in this chapter, add several
lines to the end of the program that do the following:
• Print the message The first three items in the list are:. Then use a slice to
print the first three items from that program’s list.
• Print the message Three items from the middle of the list are:. Use a slice to
print three items from the middle of the list.
• Print the message The last three items in the list are:. Use a slice to print the
last three items in the list.
'''
colors = ["blue", "green", "yellow", "red", "black", "white", "pink"];
print(f'The first three items in the list are: {colors[:3]}.');
print(f'Three items from the middle of the list are: {colors[2:5]}.');
print(f'The last three items in the list are: {colors[-3:]}.');
|
'''
4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1
(page 56). Make a copy of the list of pizzas, and call it friend_pizzas.
Then, do the following:
• Add a new pizza to the original list.
• Add a different pizza to the list friend_pizzas.
• Prove that you have two separate lists. Print the message My favorite
pizzas are:, and then use a for loop to print the first list. Print the message
My friend’s favorite pizzas are:, and then use a for loop to print the second
list. Make sure each new pizza is stored in the appropriate list.
'''
my_hobbies = ["sketching", "blogging", "programming"];
friend_hobbies = my_hobbies;
my_hobbies.append("reading");
friend_hobbies.append("swimming");
print(f'My hobbies include: {my_hobbies}.');
print(f"My friend’s hobbies are: {friend_hobbies}.");
print("\nMy friend's hobbies include the following:");
for hobby in friend_hobbies:
print(hobby);
|
'''
2-4. Name Cases: Use a variable to represent a person’s name, and then print
that person’s name in lowercase, uppercase, and title case.
'''
name = "Zhaozhi Li";
print(name.upper());
print(name.lower());
print(name.title());
|
'''
5-10. Checking Usernames: Do the following to create a program that simulates
how websites ensure that everyone has a unique username.
• Make a list of five or more usernames called current_users.
• Make another list of five usernames called new_users. Make sure one or
two of the new usernames are also in the current_users list.
• Loop through the new_users list to see if each new username has already
been used. If it has, print a message that the person will need to enter a
new username. If a username has not been used, print a message saying
that the username is available.
• Make sure your comparison is case insensitive. If 'John' has been used,
'JOHN' should not be accepted. (To do this, you’ll need to make a copy of
current_users containing the lowercase versions of all existing users.)
'''
current_users = ["zhaozhi_li", "jason_rivera", "callan_davey", "christine_david", "terence_ow"];
new_users = ["zhaozhi_li", "jason_rivera", "edward_micthell", "ted_anderson", "bryan_baland"];
for new_users in new_users:
if new_users in current_users:
print("Sorry, please select a different username.");
else:
print("The username is available");
print("Click here to sign up.");
#review this exercise
|
'''
4-3. Counting to Twenty: Use a for loop to print the numbers from 1 to 20,
inclusive.
'''
count = [value for value in range(1, 21)];
print(count);
|
'''
5-5. Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-elifelse
chain.
• If the alien is green, print a message that the player earned 5 points.
• If the alien is yellow, print a message that the player earned 10 points.
• If the alien is red, print a message that the player earned 15 points.
• Write three versions of this program, making sure each message is printed
for the appropriate color alien.
'''
alien_color = " ";
score = 0;
if alien_color == "green":
print("You just earned 5 points!");
score = score + 5;
elif alien_color =="yellow":
print("You just earned 10 points!");
score = score + 10;
elif alien_color == "red":
print("You just earned 15 points!");
score = score + 15;
print(f'Your score is {score}.');
|
'''
3-5. Changing Guest List: You just heard that one of your guests can’t make the
dinner, so you need to send out a new set of invitations. You’ll have to think of
someone else to invite.
• Start with your program from Exercise 3-4. Add a print() call at the end
of your program stating the name of the guest who can’t make it.
• Modify your list, replacing the name of the guest who can’t make it with
the name of the new person you are inviting.
• Print a second set of invitation messages, one for each person who is still
in your list.
'''
#print out the original guest list
guest_list = ['Jason', 'Callan', 'Xuanbin'];
print(f'The original guest list includes {guest_list[0]}, {guest_list[1]}, and {guest_list[2]}.');
#remove the guest using the pop() method.
removed_guest = guest_list.pop(0)
print(f"Unfortunately, {removed_guest} can't make the dinner.");
#replaced the removed guest with the new guest using insert().
guest_list.insert(0, "Chris");
#send invitations
print(f'Hi {guest_list[0]}, are you willing to join my dinner?');
print(f'Hi {guest_list[1]}, are you willing to join my dinner?');
print(f'Hi {guest_list[-1]}, are you willing to join my dinner?');
|
import time
class Playlist:
"""This class describes the playlist"""
time = ''
def __init__(self, song, play=False):
"""Initialization method."""
self.song = song
self.title = song[0]
self.time = song[1]
self.name = song[2]
self.album = song[3]
self.year = song[4]
self.play = play
self.now_time = song[1]
Playlist.time = song[1]
def play_music(self, new_command):
"""Turn on the player."""
if new_command is not None:
status_play = ''
if new_command == 'on':
self.play = True
status_play = 'Player on.'
return status_play
else:
print('Error.')
def stop_music(self, new_command):
"""Turn off the player."""
if self.play is True:
status_play = ''
if new_command == 'off':
self.play = False
status_play = 'Player off.'
else:
print('Error!')
return status_play
if self.play is False:
print('You haven\'t turned on.')
def what_song(self):
"""Method that returns the song name."""
s = ''
if self.play is True:
s += f'"{self.title}"'
else:
s += 'Turned on player.'
return s
def time_music_go(self):
"""Time of song."""
if self.play is True:
time_go = Playlist.timer(Playlist.time)
time.sleep(1)
time_go -= 1
self.now_time = Playlist.timer(time_go)
Playlist.time = self.now_time
print(self.now_time)
else:
print('you didn\'t turn on the player.')
def del_song(self):
"""Method for deleting a song."""
del self.song
@classmethod
def timer(cls, time):
"""Converting time to seconds."""
if isinstance(time, str):
mint = time.split(':')[0]
sec = time.split(':')[1]
if mint == '00' and sec == '00':
print('error')
time = None
return time
else:
if mint[0] == '0':
mint = int(mint[1])
else:
mint = int(mint)
if sec[0] == '0':
sec = int(sec[1])
else:
sec = int(sec)
result = mint*60 + sec
return result
if isinstance(time, int):
n = 0
time_ = time
while time_ > 60:
time_ -= 60
n += 1
mint = n
sec = time - 60 * n
if mint == 0:
mint = '00'
elif len(str(mint)) == 1:
mint = '0' + str(mint)
if sec == 0:
sec = '00'
if len(str(sec)) == 1:
sec = '0' + str(sec)
result = '{}:{}'.format(str(mint), str(sec))
return result
def __str__(self):
"""String method."""
s = ''
s += '**********_DOCUMENTATION LINE_**********' + '\n'
s += f'TITLE: {self.title}' + '\n'
s += f'BY {self.name} iN {self.year}' + '\n'
s += f'ALBUM: {self.album}' + '\n'
s += f'TIME: {self.time}' + '\n'
s += f'________________________________________'
return s
def __repr__(self):
return str(self.title)
|
"""Your task is to code up and run the randomized contraction algorithm for the min cut problem
and use it on the above graph to compute the min cut (i.e., the minimum-possible number of crossing edges).
"""
from random import choice
from copy import deepcopy
def contract(v1, v2, G):
"""Contracts two vertices from random edge in graph G into single vertex
:param vert1: first vertex
:param vert2: second vertex
:param G: input graph
"""
G[v1].extend(G[v2]) # add v2's list to v1's
for adj_v in G[v2]: # look at every adjacent node of v2
new_l = G[adj_v]
for i in range(0, len(new_l)): # scan and swap v1 for v2
if new_l[i] == v2:
new_l[i] = v1
while v1 in G[v1]: # remove loop in v1
G[v1].remove(v1)
del G[v2] # remove v2 from graph
def find_min_cut(G):
"""Find the minimum cut in graph G using Karger's algorithm
:param G: input graph
"""
while len(G) > 2: # while more than two vertices in G
v1 = choice(list(G.keys())) # first random vertex
v2 = choice(G[v1]) # second random vertex
contract(v1, v2, G) # contract v2 into v1
return len(G.popitem()[1]) # pop item and return len, which is min cut
def run_find_mincut(cut_range, file_path):
"""Find the minimum cut in G using Karger's algorithm.
"""
f = open(file_path, 'r')
lines = f.readlines()
G = {int(line.split()[0]): [int(v) for v in line.split()[1:] if v] for line in lines if line}
min_cut = float("inf")
for i in range(cut_range):
curr = find_min_cut(deepcopy(G))
if curr < min_cut:
min_cut = curr
print "The min cut is:", min_cut
if __name__ == '__main__':
cut_range = ''
file_path = '/users/timallard/git_repo/coursera_design_analysis_algorithms/Week3/kargerMinCut.txt'
run_find_mincut(cut_range, file_path)
|
# Sales by Match
# Problem Statement:
# There is a large pile of socks that must be paired by color.
# Given an array of integers representing the color of each sock,
# determine how many pairs of socks with matching colors there are.
# Example
# arr = [10, 20, 20, 10, 10, 30, 50, 10, 20]
# There is two pair of color 10 and one of color 20.
# There are three odd socks left, one of each color (30, 50, 20 ).
# The number of pairs is 3.
def sock_merchant(socks):
x = {}
count = 0
for sock in socks:
if x.get(sock) is None:
x.update({sock: 1})
else:
x.pop(sock)
count += 1
return count
if __name__ == "__main__":
arr = [10, 20, 20, 10, 10, 30, 50, 10, 20]
pairs = sock_merchant(arr)
print(pairs)
arr2 = [1, 1, 2, 2, 3, 2, 1, 4, 5, 3, 1, 2]
pairs2 = sock_merchant(arr2)
print(pairs2)
|
#! /usr/bin/python
weekdays = {
0 : "Monday",
1 : "Tuesday",
2 : "Wednesday",
3 : "Thursday",
4 : "Friday",
5 : "Saturday",
6 : "Sunday",
}
start = ( 0, 0, 1901 )
end = ( 30, 11, 2000 )
dayspermonth = {
0 : 31,
1 : 28,
2 : 31,
3 : 30,
4 : 31,
5 : 30,
6 : 31,
7 : 31,
8 : 30,
9 : 31,
10 : 30,
11 : 31
}
day = 365 % 7
count = 0
for year in range(start[2],end[2]+1) :
leapyear = False
if year % 4 == 0 :
leapyear = True
if year % 100 == 0 :
leapyear = False
if year % 400 == 0 :
leapyear = True
if leapyear == True :
dayspermonth[1] = 29
else :
dayspermonth[1] = 28
for month in dayspermonth :
if day == 6 :
count = count + 1
day += dayspermonth[month]
day %= 7
print "year: %d leap: %d month: %d firstday: %d count: %d" % (year,leapyear,month,day,count)
|
#! /usr/bin/python
def letterStats(letters) :
stats = {}
for letter in letters :
if not stats.has_key(letter) :
stats[letter] = 0
stats[letter] += 1
for letter in stats.keys() :
print str(letter) + " = " + str(stats[letter])
letters = []
cipher = ""
f = file("59_cipher1.txt")
for line in f.readlines() :
for letter in line.split(",") :
letters.append(letter)
letters[-1] = letters[-1].rstrip("\r\n")
for letter in letters :
cipher += chr(int(letter))
password = [ord("g"),ord("o"),ord("d")]
#print letters
#for a in range(len(password)) :
# print str(a) + " {"
# letterStats(letters[a::len(password)])
# print "}"
letters2 = []
sum = 0
i = 0
for letter in letters :
i = i % 3
letters2.append(int(letter)^password[i])
sum += letters2[-1]
i += 1
decipher = ""
i = 0
for letter in letters2 :
i = i % 3
#if i == 0 :
# decipher += " "
decipher += chr(int(letter))
i += 1
print decipher
print sum
|
#! /usr/bin/python
dict = {
1 : "one",
2 : "two",
3 : "three",
4 : "four",
5 : "five",
6 : "six",
7 : "seven",
8 : "eight",
9 : "nine",
10 : "ten",
11 : "eleven",
12 : "twelve",
13 : "thirteen",
14 : "fourteen",
15 : "fifteen",
16 : "sixteen",
17 : "seventeen",
18 : "eighteen",
19 : "nineteen",
20 : "twenty",
30 : "thirty",
40 : "forty",
50 : "fifty",
60 : "sixty",
70 : "seventy",
80 : "eighty",
90 : "ninety",
100 : "hundred",
1000 : "onethousand" }
charcount = 0
charcount += len(dict[1000])
# 1 to 999
for nr in range(1,1000) :
hun = nr / 100
ten = (nr-hun*100)/10
last = (nr-hun*100-ten*10)
word = ""
if( hun > 0 ) :
word += dict[hun]
word += dict[100]
if( ten > 0 or last > 0 ) :
word += "and"
if( ten == 1 ) :
word += dict[ten*10+last]
last = 0
if( ten > 1 ) :
word += dict[ten*10]
if( last > 0 ) :
word += dict[last]
charcount += len(word)
print "%d %d %d %d %s" % (nr,hun,ten,last,word)
print charcount
|
def 입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴01(x) : return x * 2
print(list(map(입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴01, [1, 2, 3, 4])))
# [2, 4, 6, 8]
print(list(map(lambda a : a * 2, [1, 2, 3, 4])))
# [2, 4, 6, 8]
def 입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴02(x):
return x + 1
print(list((map(입력받은자료형의각요소가함수f에의해수행된결과를묶어서리턴02, [1, 2, 3, 4]))))
# [2, 3, 4, 5]
인수로반복가능한자료형을입력받아그최대값을리턴하는함수01 = max([1, 2, 3])
print(인수로반복가능한자료형을입력받아그최대값을리턴하는함수01)
# 3
인수로반복가능한자료형을입력받아그최대값을리턴하는함수02 = max("python")
print(인수로반복가능한자료형을입력받아그최대값을리턴하는함수02)
# y
인수로반복가능한자료형을입력받아그최소값을리턴하는함수01 = min([1, 2, 3])
print(인수로반복가능한자료형을입력받아그최소값을리턴하는함수01)
# 1
인수로반복가능한자료형을입력받아그최소값을리턴하는함수02 = min("python")
print(인수로반복가능한자료형을입력받아그최소값을리턴하는함수02)
# h
정수형태의숫자를8진수문자열로바꾸어리턴01 = oct(34)
print(정수형태의숫자를8진수문자열로바꾸어리턴01)
# 0o42
정수형태의숫자를8진수문자열로바꾸어리턴02 = oct(12345)
print(정수형태의숫자를8진수문자열로바꾸어리턴02)
# 0o30071
문자의아스키코드값을리턴01 = ord('a')
print(문자의아스키코드값을리턴01)
# 97
문자의아스키코드값을리턴02 = ord('0')
print(문자의아스키코드값을리턴02)
# 48
x의y제곱한결과값을리턴01 = pow(2, 4)
print(x의y제곱한결과값을리턴01)
# 16
x의y제곱한결과값을리턴02 = pow(3, 3)
print(x의y제곱한결과값을리턴02)
# 27
입력받은숫자에해당되는범위의값을반복가능한객체01 = list(range(5))
print(입력받은숫자에해당되는범위의값을반복가능한객체01)
# [0, 1, 2, 3, 4]
입력받은숫자에해당되는범위의값을반복가능한객체02 = list(range(5, 10))
print(입력받은숫자에해당되는범위의값을반복가능한객체02)
# [5, 6, 7, 8, 9]
입력받은숫자에해당되는범위의값을반복가능한객체03 = list(range(1, 10, 2))
print(입력받은숫자에해당되는범위의값을반복가능한객체03)
# [1, 3, 5, 7, 9]
입력받은숫자에해당되는범위의값을반복가능한객체04 = list(range(0, -10, -1))
print(입력받은숫자에해당되는범위의값을반복가능한객체04)
# [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
입력값을정렬한후그결과를리스트로리턴01 = sorted([3, 1, 2])
print(입력값을정렬한후그결과를리스트로리턴01)
# [1, 2, 3]
입력값을정렬한후그결과를리스트로리턴02 = sorted(['a', 'c', 'b'])
print(입력값을정렬한후그결과를리스트로리턴02)
# ['a', 'b', 'c']
입력값을정렬한후그결과를리스트로리턴03 = sorted("zero")
print(입력값을정렬한후그결과를리스트로리턴03)
# ['e', 'o', 'r', 'z']
입력값을정렬한후그결과를리스트로리턴04 = sorted((3, 2, 1))
print(입력값을정렬한후그결과를리스트로리턴04)
# [1, 2, 3]
문자열형태로객체를변환하여리턴01 = str(3)
print(문자열형태로객체를변환하여리턴01)
# 3
문자열형태로객체를변환하여리턴02 = str('hi')
print(문자열형태로객체를변환하여리턴02)
# hi
문자열형태로객체를변환하여리턴03 = str('hi'.upper())
print(문자열형태로객체를변환하여리턴03)
# HI
반복가능한자료형을입력받아튜플형태로바꾸어리턴01 = tuple("abc")
print(반복가능한자료형을입력받아튜플형태로바꾸어리턴01)
# ('a', 'b', 'c')
반복가능한자료형을입력받아튜플형태로바꾸어리턴02 = tuple([1, 2, 3])
print(반복가능한자료형을입력받아튜플형태로바꾸어리턴02)
# (1, 2, 3)
반복가능한자료형을입력받아튜플형태로바꾸어리턴03 = tuple((1, 2, 3))
print(반복가능한자료형을입력받아튜플형태로바꾸어리턴03)
# (1, 2, 3)
입력값의자료형이무엇인지알려줌01 = type("abc")
print(입력값의자료형이무엇인지알려줌01)
# <class 'str'>
입력값의자료형이무엇인지알려줌02 = type([])
print(입력값의자료형이무엇인지알려줌02)
# <class 'list'>
입력값의자료형이무엇인지알려줌03 = type(open("test", 'w'))
print(입력값의자료형이무엇인지알려줌03)
# <class '_io.TextIOWrapper'>
동일한개수로이루어진자료형을묶어주는역할01 = list(zip([1, 2, 3], [4, 5, 6]))
print(동일한개수로이루어진자료형을묶어주는역할01)
# [(1, 4), (2, 5), (3, 6)]
동일한개수로이루어진자료형을묶어주는역할02 = list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
print(동일한개수로이루어진자료형을묶어주는역할02)
# [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
동일한개수로이루어진자료형을묶어주는역할03 = list(zip("abc", "def"))
print(동일한개수로이루어진자료형을묶어주는역할03)
# [('a', 'd'), ('b', 'e'), ('c', 'f')]
|
prompt = """
1. Add
2. Del
3. List
4. Quit
Enter number:
"""
number = 0
while number != 4:
print(prompt)
number = int(input())
#
coffee = 10
while True:
money = int(input("돈을 넣어주세요: "))
if money == 300:
print("커피를 줍니다.")
coffee = coffee - 1
elif money > 300:
print("거스름돈 %d를 주고 커피를 줍니다." % (money - 300))
coffee = coffee - 1
else:
print("돈을 다시 돌려주고 커피를 주지 않습니다.")
print("남은 커피의 양은 %d개입니다." % coffee)
if not coffee:
print("커피가 다 떨어졌습니다. 판매를 중지합니다.")
break
#
|
s1 = set([1, 2, 3])
print(s1)
# {1, 2, 3}
s2 = set("Hello")
print(s2)
# {'o', 'e', 'H', 'l'}
l1 = list(s1)
print(l1)
# [1, 2, 3]
print(l1[0])
# 1
t1 = tuple(s1)
print(t1)
# (1, 2, 3)
print(t1[0])
# 1
s1 = set([1, 2, 3, 4, 5, 6])
s2 = set([4, 5, 6, 7, 8, 9])
교집합 = s1 & s2
print(교집합)
# {4, 5, 6}
교집합02 = s1.intersection(s2)
print(교집합02)
# {4, 5, 6}
합집합 = s1 | s2
print(합집합)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
합집합02 = s1.union(s2)
print(합집합02)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
차집합 = s1 - s2
print(차집합)
# {1, 2, 3}
차집합02 = s2 - s1
print(차집합02)
# {8, 9, 7}
차집합03 = s1.difference(s2)
print(차집합03)
# {1, 2, 3}
차집합04 = s2.difference(s1)
print(차집합04)
# {8, 9, 7}
값1개추가하기 = set([1, 2, 3])
값1개추가하기.add(4)
print(값1개추가하기)
# {1, 2, 3, 4}
값여러개추가하기 = set([1, 2, 3])
값여러개추가하기.update([4, 5, 6])
print(값여러개추가하기)
# {1, 2, 3, 4, 5, 6}
특정값제거하기 = set([1, 2, 3])
특정값제거하기.remove(2)
print(특정값제거하기)
# {1, 3}
|
#das brauche ich später noch um die dateien mit funktionen abzurufen
"""class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + "." + last + "@gmx.at"
def fullname(self):
return "{} {}".format(self.first, self.last)
def all(self):
return "{} {}".format(self.fullname(), self.pay)"""
#zuerst habe ich mal einen int definiert damit die while schleife weis wie oft ich sie ausführen will
#da muss ich mir noch etwas besseres einfallen lassen vlt mit break ?!?!
i = 0
while i <= 2:
#zuerst öffne ich meine .txt damit ich darauf zugreifen kann und "a" damit ich etwas hinzufügen kann
new = open("Employee.txt", "a")
#Hier frage ich diverse dinge ab die ich in meiner .txt haben möchte
first = input("Geben sie den Vornamen ein: ")
last = input("Geben sie den Nachnamen ein: ")
pay = input("Geben sie ihr Gehalt ein: ")
#Kurze bestätigung für den user, dass es funktioniert hat
print("Angestellter " + str(i+1) + " wurde hinzugefügt")
#dann formatiere ich den input in einer liste so wie ich ihn gerne hätte
emp = [first, last, pay]
#hier füge ich es der .txt. hinzu
new.write(("Emp" + str(i+1) + " = " + str(emp)))
new.write("\n")
i += 1
#dann öffne ich noch einmal die .txt datei nur um sie lesen zu können
text = open("Employee.txt", "r")
#hier hätte ich gerne das er mir nun alle Zeilen ausgibt jedoch gibt er mir immer wieder eine Zeile zu wenig aus ?!
for line in text:
print(line)
#hier schließe ich die .txt wieder
text.close()
|
class Stack(object):
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def __str__(self):
return str(self.stack) + ' <-Enter'
def __bool__(self):
if self.stack:
return True
else:
return False
# stack = Stack()
# print(stack)
# stack.push(2)
# print(stack)
# stack.push(3)
# print(stack)
# stack.pop()
# print(stack)
# stack.push(4)
# print(stack)
# stack.push(5)
# print(stack)
|
class Person:
# 情報(属性)
def __init__(self, name):
self.name = name
# 機能(メソッド)
def greet(self):
print('hello')
def sleep(self):
print('zzz')
def run(self):
print('run!!!')
Alice = Person('Alice')
Alice.sleep()
# zzz
Alice.run()
# run!!!
|
# What's today?
day = int(input('Day (0-6)? '))
if day == 0:
print('Today is Sunday.')
elif day == 1:
print('Today is Monday.')
elif day == 2:
print('Today is Tuesday.')
elif day == 3:
print('Today is Wednesday.')
elif day == 4:
print('Today is Thursday.')
elif day == 5:
print('Today is Friday.')
elif day == 6:
print('Today is Saturday.')
else:
print('Please type a number 0-6.')
# Do I have to work today?
if day >= 1 and day <= 5:
print('It\'s a weekday. Time to go to work.')
elif day == 0 or day == 6:
print('It\'s the weekend! You\'re free to sleep-in.')
|
def jogar():
print('################################')
print('### Seja bem-vindo a Forca! ###')
print('################################')
palavra_secreta = "uva"
letras_acertadas = []
for letra in palavra_secreta:
letras_acertadas.append('_')
acertou = False
enforcou = False
erros = 0
print(letras_acertadas)
while (not acertou and not enforcou):
chute = input('Qual a letra? ')
if chute in palavra_secreta:
posicao = 0
for letra in palavra_secreta:
if chute.upper() == letra.upper():
letras_acertadas[posicao] = letra
posicao += 1
else:
erros += 1
acertou = '_' not in letras_acertadas
enforcou = erros == 6
print(letras_acertadas)
if acertou:
print('Parabéns, você acertou a palavra!')
elif not acertou and enforcou:
print('Os seus 6 chutes acabaram, fim de jogo!')
elif not acertou and not enforcou:
print('Você errou o chute! Cê ainda têm {}'.format(6 - erros))
jogar()
|
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
import os
import socket
import threading
import SocketServer
SERVER_HOST = "localhost"
SERVER_PORT = 0 # Lells the kernel to pick up a port dynamically
BUF_SIZE = 1024
def client(ip, port, message):
""" A client to test threading mixin server """
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
sock.sendall(message)
response = sock.recv(BUF_SIZE)
print "Client reveiced: %s" % response
finally:
sock.close()
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
""" An example of threaded TCP request handler """
def handle(self):
data = self.request.recv(BUF_SIZE)
current_thread = threading.current_thread()
response = "%s: %s" % (current_thread.name, data)
self.request.sendall(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
"""Nothing to add here, inherited everything necessary from parents """
pass
if __name__ == "__main__":
# Run server
server = ThreadedTCPServer((SERVER_HOST, SERVER_PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address; # reveice ip address
# start a therad with the server -- one thread per request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread exits
server_thread.setDaemon = True
server_thread.start()
print "Server loop running on thread: %s" % server_thread.name
# Run clients
client(ip, port, "hello from client1")
client(ip, port, "hello from client2")
client(ip, port, "hello from client3")
# server cleanup
server.shutdown()
|
#!/usr/bin/python
#-*- coding:utf-8 -*-
# a=input('>>>')
# print(a)
# b=[]
# for i in range(len(a)):
# if a[i]=='[' or a[i]==']' or a[i]==',':
# continue
# else:
# b.append(int(a[i]))
# print(b)
b=[]
a=[1,[[2],3,4,5,6]]
# a=str(a)
# for i in range(len(a)):
# if a[i] =='[' or ']' or ' ' or ',':
# break
# else:
b.append(a[0])
print(b)
# c=a.replace(']' or '[' or ' ' or '\[[' or '\]]','')
# for i in range(len(a)):
# if i =='[' or ',' or ' ' or ']':
# continue
# else:
# b.append(int(a[i]))
# print(b)
|
#Desafio 1 Daily coding problems
'''
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
numList = [10,15,3,5]
k = 20
# Usando While
def desafio1_1(list, num):
i1 = 0
while i1 <= len(list)-1:
num1 = list[i1]
i2 = 0
while i2 <= len(list)-1:
if i1 != i2:
num2 = list[i2]
if (num1+num2) == num:
return print([num1, num2])
break
i2+=1
i1+=1
return print("Nenhuma combinação somada resulta em {0}".format(num))
# Usando List Comprehension
# List comprehension não tem como dar break no loop
def desafio1_2(list, num):
listRet = [[val1,val2] for i1,val1 in enumerate(list) for i2,val2 in enumerate(list) if (i1!=i2) & ((val1+val2) == num)]
if listRet:
return print(listRet[0])
else:
return print("Nenhuma combinação somada resulta em {0}".format(num))
# Usando For
def desafio1_3(list, num):
for i1,val1 in enumerate(list):
for i2, val2 in enumerate(list):
if (i1 != i2) & ((val1 + val2) == num):
return print([val1, val2])
break
return print("Nenhuma combinação somada resulta em {0}".format(num))
desafio1_1(numList, k)
desafio1_2(numList, k)
desafio1_3(numList, k)
|
#Neil Moran 27th March 2019
#Solution Question9 second.py
#This imports the sys module to take in the file name as an arguement and assign it to a variable for the filename to be read
import sys
# The line below sys.argv[1] was adapted from the program test.py from this link https://www.tutorialspoint.com/python/python_command_line_arguments.htm
# It used the module sys and the function argv, this takes the name of the program and any text after and creates a list of arguements, the name of the program second.py is sys.argv[0]
# The 1st arguement after the program name sys.argv[1] is the file name, this is assigned to the variable file in line 10 below
file = sys.argv[1]
# the with statement is the recommended way to open a file
with open(file, 'r') as f:
#linenumber is an integer variable to count or keep track of the current line number this is used to print every 2nd line of the file, linenumbers initial value is 0 so the first line in the file is linenumber 0
linenumber = 0
# The for loop reads each line of the file that was opened
for line in f:
# The line.rstrip strips the carraige return from each line as its read from the file, this removes the space as the line is read from the file.
line = line.rstrip("\n")
#The if statement checks if the linenumber is odd or even, if even it prints the line, therefore printing every 2nd line, ie line 0, 2, 4, 6, etc
if linenumber % 2 == 0:
print(line)
#linenumber is increased by 1 for the next line
linenumber = linenumber + 1
|
#Neil Moran
#Solution Question1 sumupto.py
#Prompts the user to enter a positive integer and assigns the value to x
x = int(input("Please enter a positive integer: "))
#This while loop checks the inputed value of x to ensure it is a positive integer.
#If it isn't it prompts the user to try again.
while (x < 1):
print("This is not a positive integer! Please try again")
x = int(input("Please enter a positive integer: "))
# y is an integer variable for the counter in the while loop
y = 0
#z is an integer variable for the calculated value
z = 0
#As long as the counter y is less than or equal to the entered number x the while loop adds the next number to the sum until the number given x is reached
# y is also incremented by 1 each time the while loop executes
while y <= x:
z = z + y
y = y + 1
#When y greater that x exit the while loop and print the summed total z
print(z)
|
mes=int(input("Ingrese el numero de mes para obtener su nombre y cantidad de dias que este posee: "))
if mes == 1:
print("Enero = 31")
if mes == 2:
print("Febrero = 28")
if mes == 3:
print("Marzo = 31")
if mes == 4:
print("Abril = 30")
if mes == 5:
print("Mayo = 31")
if mes == 6:
print("Junio = 30")
if mes == 7:
print("Julio = 31")
if mes == 8:
print("Agosto = 30")
if mes == 9:
print("Septiembre = 31")
if mes == 10:
print("Octubre = 31")
if mes == 11:
print("Noviembre = 30")
if mes == 12:
print("Diciembre = 31")
if mes>12:
print("Error, mes no identificado")
|
def sumofsquares(x):
return sum([i ** 2 for i in range(1, x + 1)])
def squareofsum(y):
return sum(range(1, y + 1)) ** 2
print squareofsum(100) - sumofsquares(100)
|
#!/usr/bin/python
import re
def main():
n = int(raw_input())
strings = [raw_input() for i in xrange(n)]
regex = re.compile('^hi [^d]', re.IGNORECASE)
for s in strings:
if regex.search(s):
print s
if __name__=="__main__":
main()
|
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur,prev = head,None
while cur:
cur.next,prev,cur = prev,cur,cur.next
return prev
|
# f(n) = f(n-1) + f(n-2)
from functools import lru_cache
class Solution:
@lru_cache(None)
def climbStairs(self, n: int) -> int:
if (n <= 2): return n
return self.climbStairs(n-1) + self.climbStairs(n-2)
|
# Rock Paper Scissors
from random import randint
options = ['rock', 'paper', 'scissors']
rock = {
"beats": "scissors",
"beaten_by": "paper"
}
scissors = {
"beats": "paper",
"beaten_by": "rock"
}
paper = {
"beats": "rock",
"beaten_by": "scissors"
}
print(options)
print(options[0])
print(rock["beats"])
computer_choice = options[randint(0, 2)]
# print("Computer chose %s" % computer_choice)
def define_user_choice(message):
global user_choice
user_choice = raw_input(message)
define_user_choice("Make your choice: ")
if not user_choice or user_choice not in options:
define_user_choice("Invalid input. Please try again: ")
global result
print(user_choice[0])
# if user_choice["beats"] == computer_choice:
# result = "User wins"
# elif user_choice["beaten_by"] == computer_choice:
# result = "Computer wins"
# else:
# result = "Draw"
#
# print("User selected %s and computer selected %s. %s" % user_choice, computer_choice, result)
|
#Codeacademy's Madlibs
from datetime import datetime
now = datetime.now()
print(now)
story = "%s wrote this story on a %s line train to test Python strings. Python is better than %s but worse than %s -------> written by %s on %02d/%02d/%02d at %02d:%02d"
story_name = raw_input("Enter a name: ")
story_line = raw_input("Enter a tube line: ")
story_programme_one = raw_input("Enter a programme: ")
story_programme_two = raw_input("Enter another programme: ")
print story % (story_name, story_line, story_programme_one, story_programme_two, story_name, now.day, now.month, now.year, now.hour, now.minute)
|
import pandas as pd
'''
recebe uma lista de listas
basicamente recebe várias séries
primeiro argumento do dataframe: dados em si
segundo argumento do dataframe: nome das séries
'''
df = pd.DataFrame([
['fchollet/keras', 11302],
['openai/universe', 4350],
['pandas/dev/pandas', 8168]
], columns=['repository', 'stars'])
# verificar qual é a dimensão do dataframe (neste caso três linhas e duas colunas)
print('total numbers of lines/colums: ', df.shape)
'''
para acessar, quando definidas as colunas, deverá ser repassado no índice o
nome da série.
'''
print('accessing the repository series: ', df['repository'])
'''
calculando a média (por exemplo) de uma das séries de dados
'''
print('mean of stars: ', df['stars'].mean())
'''
calculando a mediana (por exemplo) de uma das séries de dados
'''
print('mean of stars: ', df['stars'].median())
'''
caso queira especificamente uma linha (sem chamar pelo nome da série),
utilizar o método iloc
'''
print('repository by line number: ', df.iloc[0])
|
# Importando las librerias
from tkinter import*
#Declaracion de variables (operadores de asignacion)
a = 10
#funciones
def ejecutar():
texto = txt_entrada.get()
#print("El texto de la caja de texto es: ",texto)
texto2 = txt_entrada2.get()
#print("En texto de la caja 2 es", texto2)
#Convertir el texto de las cajas de texto a numero
numero1 = float(texto)
numero2 = float(texto2)
suma = numero1 + numero2
suma = round(suma,2)
sub["text"] = ("Resultado = " + str(suma))
print("La suma de los numeros es = ", numero1 + numero2)
# lIMPIAR LASA CAJITAS DE TEXTO
txt_entrada.delete(0,END)
txt_entrada2.delete(0,END)
# Colocar un cero automaticamente
txt_entrada.insert(0,"0")
txt_entrada2.insert(0,"0")
txt_entrada.focus()
# crear un espacio donde vivira mi aplicacion (Contenedor[screen 1])
screen = Tk() # Crear una screen
screen.geometry("700x500") # Definir el tamaño de la pantalla
screen.resizable(False, False) # Cogelamos la dimension del screen
screen.title("Mi Super App") # Ponemos el titulo
screen.config(bg = "#00A5F7") # Color de fondo de la screen
titulo = Label(screen, text = "Bienvenido a mi App") # crear un Label
titulo.pack(side = TOP) #Ubicamos nuestro texto Arriba, abajo, izquierda y derecha
titulo.config(bg = "#00A5F7", fg = "white", font = ("Corbel",20))
sub = Label(screen, text = "Texto prueba")
sub.place(x = 290, y = 50)
sub.config (bg = "#00A5F7", fg = "white", font = ("Consolas",16), justify = CENTER)
# Crear caja de Texto
txt_entrada = Entry(screen, width = 20, font = ("Consolas",15), fg = "blue")
txt_entrada.place(x=270, y=80)
txt_entrada.config(justify = CENTER) # justify = [CENTER,RIGHT]
txt_entrada.config(state = NORMAL) # state = [NORMAL, DISABLED]
#txt_entrada.config(show = "*") # Para ocultar las letras cuando escribimos
txt_entrada2 = Entry(screen, width = 20, font = ("Consolas",15), fg = "blue")
txt_entrada2.place(x=270, y=110)
txt_entrada2.config(justify = CENTER) # justify = [CENTER,RIGHT]
txt_entrada2.config(state = NORMAL) # state = [NORMAL, DISABLED]
# Crear un boton
btn_click = Button(screen, text = "Presioname", width = 15, height = 1)
btn_click.place(x = 280, y = 150)
btn_click.config(bg = "green", fg = "white",font = ("consolas",15), command = ejecutar)
screen.mainloop() #Se mantiene abierta la screen
|
####There are many procedures and functions built into
####Python without any prerequisites needed. A simple example is print.
####Modules ( or Libraries) are collections of extra, pre-written functions and procedures.
####These are available to use, but we need to import them into our code at the start.
import math
number = float(input("Enter a number:"))
answer = math.sqrt(number)
print(answer)
####
|
#### A while loop will continue to execute a block of code while a condition is True.
#### If the condition is never True then the while loop will never start.
# number = 1
# while number < 5:
# print(number)
# number += 1
####+= this adds one to the variable preventing the loop from running infiintley
####so it will add one until the conditional becomes invalid and then moves onto next block of code
####This is because it is now invallid - doesnt fulfill condition
####FOR LOOPS
# people = ["Victoria", "John", "Rob", "James"]
# for person in people:
# print(person)
#### most of the time people use i - to identify the variable
# people = ["Victoria", "John", "Rob", "James"]
# for i in people:
# print(i)
#### Often ranges are used for For loops
# for number in range(10):
# print(number)
####with strings
# for book_title in "This is the end of the show":
# print(book_title)
#### ADDING BREAKS AND CONTINUE
for number in range(10):
print(number)
if number == 7:
break
for number in range(10):
print(number)
if number == 7:
continue
|
#Anton Danylenko
#05/15/19
# A): Number of Games=255168
# B1): X Wins=131184
# B2): O Wins=77904
# B3): Draws=46080
# C): Number of Intermediate+Final Boards=5478
# D): Number of Unique Boards=765
cliques = [
[0,1,2], [3,4,5], [6,7,8],
[0,3,6], [1,4,7], [2,5,8],
[0,4,8], [2,4,6]
]
def printBoard(board):
for i in range(3):
row = ""
for ii in range(3):
if board[i*3+ii]==1:
row+='x '
elif board[i*3+ii]==0:
row+='o '
else:
row+='_ '
print(row)
# print("--------------------")
class TicTacToe:
def __init__(self):
self.win_x = 0
self.win_o = 0
self.draw = 0
self.all_boards = set([])
self.unique_boards = set([])
def __str__(self):
return "Win_x: " + str(self.win_x) + ", win_o: " + str(self.win_o) + ", draw: " + str(self.draw) + \
"\nNum All Boards: " + str(len(self.all_boards)) + ", Num Unique Boards: " + str(len(self.unique_boards))
def addBoardToList(self, board):
# print(board)
possibilities = [board[:]]
# print(list(reversed(board[:3]))+(list(reversed(board[3:6]))))
possibilities.append(list(reversed(board[:3]))+(list(reversed(board[3:6])))+(list(reversed(board[6:]))))
possibilities.append(list(reversed(board[6:]))+(list(reversed(board[3:6])))+(list(reversed(board[:3]))))
possibilities.append(board[6:]+board[3:6]+board[:3])
temp = [board[6]]+[board[3]]+[board[0]]+[board[7]]+[board[4]]+[board[1]]+[board[8]]+[board[5]]+[board[2]]
possibilities.append(temp[:])
possibilities.append(list(reversed(temp[:3]))+(list(reversed(temp[3:6])))+(list(reversed(temp[6:]))))
possibilities.append(list(reversed(temp[6:]))+(list(reversed(temp[3:6])))+(list(reversed(temp[:3]))))
possibilities.append(temp[6:]+temp[3:6]+temp[:3])
for b in possibilities:
if str(b) in self.unique_boards:
return
else:
self.unique_boards.add(str(board))
return
def count_games_total(self, board, mark):
count = 0
self.all_boards.add(str(board))
self.addBoardToList(board)
for i in range(9):
if board[i]=='_':
board[i] = mark
self.all_boards.add(str(board))
self.addBoardToList(board)
not_win=True
for clique in cliques:
if not_win and i in clique:
num_filled=0
for spot in clique:
if board[spot]==mark:
num_filled+=1
if num_filled>2:
if mark==1:
self.win_x+=1
else:
self.win_o+=1
count+=1
not_win=False
if not_win:
count+=self.count_games_total(board[:],1-mark)
board[i]='_'
if not '_' in board:
self.draw+=1
count+=1
return count
def main():
game = TicTacToe()
board = ['_' for x in range(9)]
print("Total number of games: ", game.count_games_total(board, 1))
print(game)
# board = [0,1,2,3,4,5,6,7,8]
# possibilities = [board[:]]
# # print(list(reversed(board[:3]))+(list(reversed(board[3:6]))))
# possibilities.append(list(reversed(board[:3]))+(list(reversed(board[3:6])))+(list(reversed(board[6:]))))
# possibilities.append(list(reversed(board[6:]))+(list(reversed(board[3:6])))+(list(reversed(board[:3]))))
# possibilities.append(board[6:]+board[3:6]+board[:3])
# temp = [board[6]]+[board[3]]+[board[0]]+[board[7]]+[board[4]]+[board[1]]+[board[8]]+[board[5]]+[board[2]]
# possibilities.append(temp[:])
# possibilities.append(list(reversed(temp[:3]))+(list(reversed(temp[3:6])))+(list(reversed(temp[6:]))))
# possibilities.append(list(reversed(temp[6:]))+(list(reversed(temp[3:6])))+(list(reversed(temp[:3]))))
# possibilities.append(temp[6:]+temp[3:6]+temp[:3])
# print(possibilities)
main()
|
class PQueue:
def OrdinaryComparison(self,a,b):
if a < b: return -1
if a == b: return 0
return 1
def __init__(self, comparator = None):
if comparator == None:
comparator = self.OrdinaryComparison
self.queue = [0]
self.length = 1
self.cmpfunc = comparator
def __str__(self):
return "[[[" + '\n'.join([str(i) for i in self.queue]) + "]]]"
def switch(self, a, b):
temp = self.queue[a]
self.queue[a] = self.queue[b]
self.queue[b] = temp
def push(self, data):
if len(self.queue)>self.length:
self.queue[self.length] = data
else:
self.queue.append(data)
self.length+=1
index = self.length-1
while (index//2!=0 and self.cmpfunc(data, self.queue[index//2])==-1):
self.switch(index, index//2)
index = index//2
def pop(self):
if self.length>1:
root = self.queue[1]
#print("self.length: " + str(self.length))
#print("len(self.queue): " + str(len(self.queue)))
if self.length>2:
self.queue[1] = self.queue[self.length-1]
self.length-=1
index = 1
while(index*2<self.length):
#print("index: " + str(index))
if (index*2+1<self.length):
if (self.cmpfunc(self.queue[index],self.queue[index*2+1])==1 and
self.cmpfunc(self.queue[index*2+1],self.queue[index*2])==-1):
self.switch(index, index*2+1)
index = index*2+1
elif (self.cmpfunc(self.queue[index],self.queue[index*2])==1):
self.switch(index, index*2)
index = index*2
else:
index = self.length
elif (self.cmpfunc(self.queue[index],self.queue[index*2])==1):
#print("index: " + str(index))
self.switch(index, index*2)
index = index*2
else:
index = self.length
else:
self.queue[1] = None
self.length-=1
return root
return None
def peek(self):
if len(self.queue)>1:
return self.queue[1]
def tolist(self):
list = []
while (self.peek()!=None):
list.append(self.pop())
return list
def push_all(self, list):
for x in range(len(list)):
self.push(list[x])
def internal_list(self):
list = []
index = 1
while (index<self.length):
list.append(self.queue[index])
index+=1
return list
def main():
p=PQueue()
p.push_all(list('PETERBR'[::-1]))
print(p.internal_list())
p.pop()
p.pop()
print(p.internal_list())
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print ("hello,world")
print(45678+0x12fd2)
print("Learn Python")
print(0xff==255)
a = 'imooc' # a变为字符串
print (a)
print u'中文'
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)
L = ['Adam', 'Lisa', 'Bart']
L.append('Paul')
print L
['Adam', 'Lisa', 'Bart', 'Paul']
t = ('Adam', 'Lisa', 'Bart')
age = 20
if age >= 18:
print 'your age is', age
print 'adult'
print 'END'
if age >= 18:
print 'adult123'
elif age >= 6:
print 'teenager'
elif age >= 3:
print 'kid'
else:
print 'baby'
L = ['Adam', 'Lisa', 'Bart']
for name in L:
print name
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print ("你好,世界")
print(4+5)
print(1 + 2*3)
print(2**3)
print( 9*7 + 5*7 )
print( (17*6) - (9*7 + 5*7) )
print((3 + 32) - 15//2)
print((1 + 2 + 4)/13)
# " // "来表示整数除法,返回不大于结果的一个最大的整数,而" / " 则单纯的表示浮点数除法
print(15//2)
# floating-point number
print(3/4)
print(3 + 2.5)
print(16/4)
print(16//4)
print(int(49.9))
print(float(3278+273827))
print(0.2)
print(0.2 + 0.2 + 0.2)
# Traceback(回溯)表示“程序出错而停止时正在执行的内容”!
#print(4/0)
manila_pop = 15
manila_area = 3
manila_pop_density = manila_pop/manila_area
print(manila_pop_density)
#变量名中只能使用普通字母、数字和下划线,且以字母或下划线开头。
#变量命名有一些不能用于变量名的保留字
#虽然在变量名中使用任何内置的标识符不会立即导致错误,但我们也不建议使用
manila_pop +=3
manila_pop -= 2
manila_pop *= 0.9
manila_pop /= 2
print(manila_pop)
#此代码使用科学计数法定义大的数字。4.445e8 等于 4.445 * 10 ** 8,也等于 444500000.0。
a = 4.445e8
fall = 5e6
fall = fall*(1 - 0.1)
a += fall
a += a*0.05
a -= a*0.05
a -= 2.5e5
print(a)
savings, salary = 514.86, 320.51
manila_pop = 1780148
manila_area = 16.56
manila_pop_density = manila_pop/manila_area
print(int(manila_pop_density))
rainfall = 5
# decrease the rainfall variable by 10% to account for runoff
rainfall *= .9
print(rainfall)
print(1 < 2)
str_1 = 'qbc'
str_2 = 'ABLVG'
print(str_1 + str_2)
salesman = '"I think you\'re an encyclopaedia salesman"'
print(salesman)
ai_length = len("dflkjdlkfjdljf");
print(ai_length)
print(type(6))
print(type('6'))
print(type(6.56))
count = int(4.0)
print(count)
print(type(count))
mon_sales = "121"
tues_sales = "105"
wed_sales = "110"
thurs_sales = "98"
fri_sales = "95"
total_sales = int(mon_sales) + int(tues_sales) + int(wed_sales) + int(thurs_sales) + int(fri_sales)
str_total_sales = str(total_sales)
print("This week's total sales: " + str_total_sales)
#title 方法。该方法返回首字母大写的字符串,即每个单词的第一个字母都被大写。
print("charlotte hippopotamus turner".title())
#islower 返回一个布尔值,说明该字符串对象中的字母是否都是小写字母(不区分大小写的字符不计算在内,比如标点符号)。
print("charlotte hippopotamus turner".islower())
num = 'ad '.islower()
print(num)
prophecy = "And"
vowel_count = 0
prophecy = prophecy.lower()
print(prophecy)
vowel_count = prophecy.count('a') + prophecy.count('e') + prophecy.count('i') + prophecy.count('o') + prophecy.count('u')
# Print the final count
print(vowel_count)
user_ip = '208.94.117.90'
url = 'classroom.udacity.com'
now = '16:04'
log_message = "IP address {} accessed {} at {}".format(user_ip, url, now)
print(log_message)
name = 'li'
age = 24
sex = 'female'
alert = "Hello dear {} ,I know your age is {},your sex is {}.".format(name, age, sex)
print(alert)
mon_sales = "121"
tues_sales = "105"
wed_sales = "110"
thurs_sales = "98"
fri_sales = "95"
total_sales = int(mon_sales) + int(tues_sales) + int(wed_sales) + int(thurs_sales) + int(fri_sales)
str_total_sales = str(total_sales)
print("This week's total sales: " + str_total_sales)
#python 保留字
import keyword
print(keyword.kwlist)
if True:
print('true')
else:
print('false')
print('hello\nrunoob')
print(r'hello\nrunoob')
#print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end="":
print(3**2)
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
rainfall = 5
# decrease the rainfall variable by 10% to account for runoff
rainfall *= .9
print(rainfall)
print(1 < 2)
str_1 = 'qbc'
str_2 = 'ABLVG'
print(str_1 + str_2)
salesman = '"I think you\'re an encyclopaedia salesman"'
print(salesman)
ai_length = len("dflkjdlkfjdljf");
print(ai_length)
print(type(6))
print(type('6'))
print(type(6.56))
count = int(4.0)
print(count)
print(type(count))
mon_sales = "121"
tues_sales = "105"
wed_sales = "110"
thurs_sales = "98"
fri_sales = "95"
total_sales = int(mon_sales) + int(tues_sales) + int(wed_sales) + int(thurs_sales) + int(fri_sales)
str_total_sales = str(total_sales)
print("This week's total sales: " + str_total_sales)
#title 方法。该方法返回首字母大写的字符串,即每个单词的第一个字母都被大写。
print("charlotte hippopotamus turner".title())
#islower 返回一个布尔值,说明该字符串对象中的字母是否都是小写字母(不区分大小写的字符不计算在内,比如标点符号)。
print("charlotte hippopotamus turner".islower())
num = 'ad '.islower()
print(num)
prophecy = "And"
vowel_count = 0
prophecy = prophecy.lower()
print(prophecy)
vowel_count = prophecy.count('a') + prophecy.count('e') + prophecy.count('i') + prophecy.count('o') + prophecy.count('u')
# Print the final count
print(vowel_count)
user_ip = '208.94.117.90'
url = 'classroom.udacity.com'
now = '16:04'
log_message = "IP address {} accessed {} at {}".format(user_ip, url, now)
print(log_message)
name = 'li'
age = 24
sex = 'female'
alert = "Hello dear {} ,I know your age is {},your sex is {}.".format(name, age, sex)
print(alert)
def cylinder_volume(height, radius):
pi = 3.14159
return height * pi * radius ** 2
cylinder_volume(10, 3)
mv_population = 74728
mv_area = 11.995
mv_density = mv_population/mv_area
print(mv_density)
print(.1)
a = [1, 5, 8]
b = [2, 6, 9, 10]
c = [100, 200]
print(len(b))
print(max([len(a), len(b), len(c)]))
print(min([len(a), len(b), len(c)]))
names = ["Carol", "Albert", "Ben", "Donna"]
print(" & ".join(sorted(names)))
fruit = {"apple", "banana", "orange", "grapefruit"} # define a set
print("watermelon" in fruit) # check for element
fruit.add("watermelon") # add an element
print(fruit)
print(fruit.pop()) # remove a random element
print(fruit)
#元组是一种不可变有序元素数据类型
#集合是一个包含唯一元素的可变无序集合数据类型
#字典是可变数据类型,其中存储的是唯一键到值的映射
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
print(elements['hydrogen']['is_noble_gas'])
print(elements['helium']['is_noble_gas'])
|
# -*- coding: utf-8 -*-
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
# list 是一种有序的集合,支持添加和删除元素,类似php中的索引数组。
# len() 函数可以获得集合中元素个数,类似php中的count()函数
# 索引越界会抛出IndexError的错误,想要获取最后一个元素的索引是len(classmates) - 1。
# -1做索引,直接获取最后一个元素,-2 ...
# format() 是一种格式化字符串的方法,参数会填充占位符位置的内容
def get_first_record_of_texts(texts):
first_text = texts[0]
return "First record of texts, {} texts {} at time {}".format(first_text[0],first_text[1],first_text[2])
print(get_first_record_of_texts(texts))
def get_last_record_of_calls(calls):
last_text = calls[-1]
return "Last record of calls, {} calls {} at time {}, lasting {} seconds".format(last_text[0],last_text[1],last_text[2],last_text[3])
print(get_last_record_of_calls(calls))
|
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务4:
电话公司希望辨认出可能正在用于进行电话推销的电话号码。
找出所有可能的电话推销员:
这样的电话总是向其他人拨出电话,
但从来不发短信、接收短信或是收到来电
请输出如下内容
"These numbers could be telemarketers: "
<list of numbers>
电话号码不能重复,每行打印一条,按字典顺序排序后输出。
"""
# 所有被叫电话
def get_phones(calls):
phones = set()
for call in calls:
phones.add(call[1])
return phones
# 所有接/收短信电话
def get_texts(texts):
text_phones = set()
for text in texts:
text_phones.add(text[0])
text_phones.add(text[1])
return text_phones
called_phone = get_phones(calls)
text_phones = get_texts(texts)
tel_phones = set()
for call in calls:
if call[0] not in called_phone and call[0] not in text_phones:
tel_phones.add(call[0])
print('These numbers could be telemarketers: ')
for tel in sorted(list(tel_phones)):
print('<{}>'.format(tel))
|
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。
输出信息:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
提示: 建立一个字典,并以电话号码为键,通话总时长为值。
这有利于你编写一个以键值对为输入,并修改字典的函数。
如果键已经存在于字典内,为键所对应的值加上对应数值;
如果键不存在于字典内,将此键加入字典,并将它的值设为给定值。
"""
# 统计通话时间最长的号码
def get_long_time_mobile(calls):
long_time_number = {}
for call in calls:
call_mobile = call[0]
called_mobile = call[1]
long_time_number[call_mobile] = long_time_number.get(call_mobile, 0) + int(call[3])
long_time_number[called_mobile] = long_time_number.get(called_mobile, 0) + int(call[3])
max_call_time_sum = 0
max_call_mobile = ''
for phone_number in long_time_number:
if long_time_number[phone_number] > max_call_time_sum:
max_call_mobile = phone_number
max_call_time_sum = long_time_number[phone_number]
return [max_call_mobile, max_call_time_sum]
long_mobile = get_long_time_mobile(calls)
print("{} spent the longest time, {} seconds, on the phone during September 2016".format(long_mobile[0],long_mobile[1]))
|
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务1:
短信和通话记录中一共有多少电话号码?每个号码只统计一次。
输出信息:
"There are <count> different telephone numbers in the records."
"""
text1 = []
text2 = []
lists = texts + calls
for list_a in lists:
if list_a[0] not in text1:
text1.append(list_a[0])
if list_a[1] not in text2:
text2.append(list_a[1])
temp_lists = text1 + text2
print(format(len(set(temp_lists))))
# print(type(temp_lists))
# print(temp_lists[1])
# print(temp_lists.count('90365 06212'))
|
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务4:
电话公司希望辨认出可能正在用于进行电话推销的电话号码。
找出所有可能的电话推销员:
这样的电话总是向其他人拨出电话,
但从来不发短信、接收短信或是收到来电
请输出如下内容
"These numbers could be telemarketers: "
<list of numbers>
电话号码不能重复,每行打印一条,按字典顺序排序后输出。
"""
def get_called_telephones(calls):
"""
获取所有的被叫电话集合
:param calls:
:return:
"""
telephones = set()
for call in calls:
telephones.add(call[1])
return telephones
def get_text_user_telephones(texts):
"""
获取所有的有短信接发的电话
:param texts:
:return:
"""
telephones = set()
for text in texts:
telephones.add(text[0])
telephones.add(text[1])
return telephones
def get_telemarketers_telephones(calls, texts):
"""
获取疑似推销员的电话
:param calls:
:param texts:
:return:
"""
called_telephones = get_called_telephones(calls)
text_user_telephones = get_text_user_telephones(texts)
telephones = set()
for call in calls:
caller_telephone = call[0]
if caller_telephone not in called_telephones and caller_telephone not in text_user_telephones:
telephones.add(caller_telephone)
return sorted(list(telephones))
print("These numbers could be telemarketers: ")
telemarketers_telephones = get_telemarketers_telephones(calls, texts)
for telephone in telemarketers_telephones:
print(telephone)
|
# -*- coding: utf-8 -*-
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
t_tels = set()
c_tels = set()
s_tels = set()
for text in texts:
t_tels.add(text[0])
t_tels.add(text[1])
for call in calls:
c_tels.add(call[1])
for call in calls:
if call[0] not in t_tels and call[0] not in c_tels:
s_tels.add(call[0])
print("These numbers could be telemarketers: ")
for tel in sorted(list(s_tels)):
print(tel)
|
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务4:
电话公司希望辨认出可能正在用于进行电话推销的电话号码。
找出所有可能的电话推销员:
这样的电话总是向其他人拨出电话,
但从来不发短信、接收短信或是收到来电
请输出如下内容
"These numbers could be telemarketers: "
<list of numbers>
电话号码不能重复,每行打印一条,按字典顺序排序后输出。
"""
phones = set()
def get_phones(calls):
for call in calls:
phones.add(call[1])
return phones
receive_phones = set()
def get_texts(texts):
for text in texts:
receive_phones.add(text[0])
receive_phones.add(text[1])
return receive_phones
# 所有被叫电话
call_phones = get_phones(calls)
# 所有接/收短信的电话
text_phones = get_texts(texts)
sale_tel_phones = set()
for call in calls:
if call[0] not in call_phones and call[0] not in text_phones:
sale_tel_phones.add(call[0])
print('These numbers could be telemarketers: ')
for tel in sorted(sale_tel_phones):
print('<{}>'.format(tel))
|
import pprint
import math
width = 4
height = 4
players = ['x', 'o']
def print_board(board):
for row in range(height):
print(" ".join(board[row]))
def make_move(board, player_idx, column):
player = players[player_idx]
if board[0][column] != '-':
# column full
return False
last_empty_row = 0
while last_empty_row < height - 1 and board[last_empty_row+1][column] == '-':
last_empty_row = last_empty_row + 1
board[last_empty_row][column] = player
return True
def check_winner_small(board):
# horizontally
for row in range(height):
for col in range(width-2):
if (
board[row][col] != '-'
and board[row][col] == board[row][col+1]
and board[row][col] == board[row][col+2]
):
return board[row][col]
# vertically
for row in range(height-2):
for col in range(width):
if (
board[row][col] != '-'
and board[row][col] == board[row+1][col]
and board[row][col] == board[row+2][col]
):
return board[row][col]
# diagonally (primary)
for row in range(height-2):
for col in range(width-2):
if (
board[row][col] != '-'
and board[row][col] == board[row+1][col+1]
and board[row][col] == board[row+2][col+2]
):
return board[row][col]
# diagonally (secondary)
for row in range(height-2):
for col in range(2, width):
if (
board[row][col] != '-'
and board[row][col] == board[row+1][col-1]
and board[row][col] == board[row+2][col-2]
):
return board[row][col]
# if there are empty space no one won yet
for col in range(width):
if board[0][col] == '-':
return '-'
# if there aren't the game is over on a tie
return 't'
def check_winner(board):
# horizontally
for row in range(height):
for col in range(width-3):
if (
board[row][col] != '-'
and board[row][col] == board[row][col+1]
and board[row][col] == board[row][col+2]
and board[row][col] == board[row][col+3]
):
return board[row][col]
# vertically
for row in range(height-3):
for col in range(width):
if (
board[row][col] != '-'
and board[row][col] == board[row+1][col]
and board[row][col] == board[row+2][col]
and board[row][col] == board[row+3][col]
):
return board[row][col]
# diagonally (primary)
for row in range(height-3):
for col in range(width-3):
if (
board[row][col] != '-'
and board[row][col] == board[row+1][col+1]
and board[row][col] == board[row+2][col+2]
and board[row][col] == board[row+3][col+3]
):
return board[row][col]
# diagonally (secondary)
for row in range(height-3):
for col in range(3, width):
if (
board[row][col] != '-'
and board[row][col] == board[row+1][col-1]
and board[row][col] == board[row+2][col-2]
and board[row][col] == board[row+3][col-3]
):
return board[row][col]
# if there are empty space no one won yet
for col in range(width):
if board[0][col] == '-':
return '-'
# if there aren't the game is over on a tie
return 't'
def get_possible_next_positions(board, player_idx):
simulated_boards = []
for col in range(width):
if board[0][col] == '-':
new_board = [[board[i][j] for j in range(width)] for i in range(height)]
make_move(new_board, player_idx, col)
simulated_boards.append((new_board, col))
return simulated_boards
def minmax(board, player_idx, alpha, beta):
winner = check_winner_small(board)
if winner != '-':
return {
"eval": {
players[0]: 1,
players[1]: -1,
't': 0,
}[winner],
"move": -1
}
possible_boards = get_possible_next_positions(board, player_idx)
if player_idx == 0:
max_eval = -math.inf
next_move = -1
for next_board in possible_boards:
if alpha < beta:
simulation = minmax(next_board[0], (player_idx + 1) % 2, alpha, beta)
if simulation["eval"] > max_eval:
max_eval = simulation["eval"]
next_move = next_board[1]
alpha = max(alpha, simulation["eval"])
return {
"eval": max_eval,
"move": next_move
}
if player_idx == 1:
min_eval = math.inf
next_move = -1
for next_board in possible_boards:
if alpha < beta:
simulation = minmax(next_board[0], (player_idx + 1) % 2, alpha, beta)
if simulation["eval"] < min_eval:
min_eval = simulation["eval"]
next_move = next_board[1]
beta = min(beta, simulation["eval"])
return {
"eval": min_eval,
"move": next_move
}
def game():
board = [['-' for _ in range(width)] for _ in range(height)]
player_idx = 1
while check_winner_small(board) == '-':
if player_idx == 1:
# computer turn
simulation = minmax(board, player_idx, -math.inf, math.inf)
make_move(board, player_idx, simulation["move"])
else:
print("Tabuleiro:")
print_board(board)
print("\nSua vez!", players[player_idx])
print("Digita a coluna em que quer jogar: ")
column = int(input())
while column < 0 or column >= width:
print("Coluna inválida. Digite um número entre 0 e {}: ".format(width-1))
column = int(input())
valid_move = make_move(board, player_idx, column)
while not valid_move:
print("Coluna cheia. Escolha outra: ")
column = int(input())
while column < 0 or column >= width:
print("Coluna inválida. Digite um número entre 0 e {}: ".format(width-1))
column = int(input())
valid_move = make_move(board, player_idx, column)
player_idx = (player_idx + 1) % 2
print_board(board)
print("Vencedor: ", check_winner_small(board))
game()
|
#! /usr/bin/python3
""" This script is used to find duplicate files in folder provided by user."""
__author__ = '__tp__'
import os
import sys
import hashlib
import argparse
parser = argparse.ArgumentParser(description="Find duplicate files in given folder !!!")
parser.add_argument('-p', '--path', help='Path of folder', required=True)
result = parser.parse_args()
def main():
list_of_files = []
try:
if len(sys.argv) != 3:
print(result)
sys.exit(1)
mainPath = str(sys.argv[2])
if not mainPath.endswith('/'):
mainPath+"/"
for (dirPath, dirName, fileNames) in (os.walk(mainPath)):
for file in fileNames:
# Get absolute path of file
full_path = os.path.join(dirPath, file)
# Get hash value of a file
hash_value = md5_for_file(full_path)
print("I saw : ", full_path)
# Create list of file and hash value.
list_of_files.append([full_path, hash_value])
# If you want to see the pair of file name and its hash value then uncomment following
# print("List", *list_of_files, sep="\n")
compair(list_of_files)
except Exception as e:
print(str(e))
# This is main function which compares the files and finds similar files.
def compair(list_of_files):
new_list = []
set_to_check = set()
list_of_files.sort()
new_pre_list = []
# Take one by one files.
for file in list_of_files:
# check if the file is in set() as Sets can't contain duplicates
if (file[1] not in set_to_check):
set_to_check.add((file[1]))
new_pre_list.append(file)
else:
new_list.append(file)
"""
Now we have collected original file list - new_pre_list[] and new file list - new_list[] which contains duplicate files only.
"""
# print('All : ', *new_pre_list, sep="\n")
# print('New : ', *new_list, sep="\n")
print("\nHey TP ... I got following duplicate files\n")
# Take one file from original file list without duplicate contains.
for file1 in new_pre_list:
# Take one file from new_list which contains duplicate files only
for file2 in new_list:
if file1[1] == file2[1]:
print("File 1 : ", file1[0])
print("File 2 : ", file2[0])
print()
# This function becomes slower for big files.
#
# def get_hash_value(file_name):
# with open(file_name, 'rb') as file:
# byte_file = file.read()
# readable_hash = hashlib.sha1(byte_file).hexdigest()
# return (readable_hash)
# gets md5 hash value and this function works faster as its block size is larger.
def md5_for_file(f, block_size=2 ** 20):
md5 = hashlib.md5()
with open(f, 'rb') as file:
while True:
data = file.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
main()
|
#!/usr/bin/python
import random
arith = ['+', '-', '/', '*', '//', '%']
logic = ['or', 'and', '^']
compare = ['>', '>=', '==', '<', '<=', '<>']
def generate(mode, depth):
random.seed()
operation = random.randint(0, 2)
print '(',
if (operation == 0) or (depth == 0) : # literal
if mode == 0 : # logic
random.seed()
print random.choice([True, False]),
else : # arith
random.seed()
print random.randint(-29999, 29999),
elif operation == 1 : # unary operation
if mode == 0 :
print 'not',
else :
print '-',
generate(mode, depth - 1)
else : # binary operation
if mode == 1 :
generate(1, depth - 1)
random.seed()
print random.choice(arith),
generate(1, depth - 1)
else :
random.seed()
opt = random.randint(0, 1)
if opt == 0 : # comparator
generate(0, depth - 1)
random.seed()
print random.choice(logic),
generate(0, depth - 1)
else :
generate(1, depth - 1)
random.seed()
print random.choice(compare),
generate(1, depth - 1)
print ')',
if __name__ == '__main__':
random.seed()
n = random.randrange(10 ** 3)
while n > 0 :
random.seed()
mode = random.randint(0, 1)
generate(mode, 4)
n -= 1
print
|
from tp3 import *
print ("|####################################################|")
print ("| |1| |2| |3| |4| |5| |6| |7| |8| |9| |10| |11| |12| |")
print ("|Para salir ingrese --------------------------->|13| |")
print ("|####################################################|")
a = int(input("INGRESE EL N° DE OPCIÓN: "))
while a != 13:
if a == 1:
suma()
elif a == 2:
resta()
elif a == 3:
producto()
elif a == 4:
max()
elif a == 5:
min()
elif a == 6:
max_de_tres()
elif a == 7:
vocal()
elif a == 8:
inversa()
elif a == 9:
es_palindromo()
elif a == 10:
len_cadena()
elif a == 11:
superposicion()
elif a == 12:
generar_n_caracteres()
else:
print("No tengo esa opción")
print ("")
print ("|####################################################|")
print ("| |1| |2| |3| |4| |5| |6| |7| |8| |9| |10| |11| |12| |")
print ("|Para salir ingrese --------------------------->|13| |")
print ("|####################################################|")
a = int(input("INGRESE EL N° DE OPCIÓN: "))
print("Fin del programa.")
|
movies_list_master = [
{"movie_name": "Black Panther",
"director": "j ross",
"release_year": 2007,
"genre": ("action", "sci-fi"),
"actors": ("Chadwick Boseman", "Lupita Nyong")
},
{"movie_name": "Inception",
"director": "Christopher",
"release_year": 2010,
"genre": ("action", "sci-fi"),
"actors": ("Leonardo Dicaprio", "Joseph")},
{"movie_name": "Avenger Endgame",
"director": "Joe Ross",
"release_year": 2019,
"genre": ("action", "sci-fi"),
"actors": ("Chrish hamsscotch", "Scarlett Johnson", "Robert downy jr")},
{"movie_name": "DDLJ",
"director": "Aditya Chopra",
"release_year": 1995,
"genre": ("Drama", "Romance"),
"actors": ("Sharukh", "Kajol")}
]
def get_all_cur_movies_from_masterlist():
return f"Movies in the master list count was {len(movies_list_master)} adding new movie:\n{movies_list_master}"
print("Before: ", get_all_cur_movies_from_masterlist())
def input_movie_details_byconsole():
movie_name = input("Movie Name: ")
director_name = input("Director Name: ")
release_year = int(input("Release Year: "))
genre = input("genre (separated by comma): ")
actors = input("Actors Names (separated by comma): ")
movie_by_user = {"movie_name": movie_name,
"director": director_name,
"release_year": release_year,
"genre": genre,
"actors": actors}
return movie_by_user
def add_movie_to_masterlist(movie_by_console):
movies_list_master.append(movie_by_console)
# below are testing section
movie_dict = input_movie_details_byconsole()
add_movie_to_masterlist(movie_dict)
print("After: ", get_all_cur_movies_from_masterlist())
|
import os.path
i = 0
contador_coluna = 0
palavra = ""
class lista:
def __init__(self):
self.raiz = None
def push(self, classe, lexema):
novo_token = token(classe = classe, lexema = lexema)
if(self.raiz == None):
self.raiz = novo_token
return
self.raiz.anterior = novo_token
novo_token.proximo = self.raiz
self.raiz = novo_token
def procura_na_lista(self, lexema):
temp = self.raiz
while temp:
if temp.lexema == lexema:
break
temp = temp.proximo
if temp == None:
return False
return temp
class token:
def __init__(self, proximo=None, anterior=None, classe=None, lexema=None, tipo=None):
self.proximo = proximo
self.anterior = anterior
self.classe = classe
self.lexema = lexema
self.tipo = "Nulo"
class analisador:
lista = lista()
def scanner(self):
global contador_coluna
contador_coluna += 1
i = 0
return self.q0()
def q0(self):
global contador_coluna
global i
if palavra[i:i+1].isdigit():
contador_coluna += 1
i += 1
return self.q1()
elif '"' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q7()
elif '{' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q9()
elif '<' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q13()
elif '=' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q17()
elif '>' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q18()
elif '+' == palavra[i:i+1] or '-' == palavra[i:i+1] or '*' == palavra[i:i+1] or '/' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q20()
elif '(' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q21()
elif ')' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q22()
elif ';' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q23()
elif ',' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q24()
elif 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q27()
elif 'f' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q38()
elif 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q53()
elif 'l' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q64()
elif 'r' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q70()
elif 'v' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q74()
elif 's' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q86()
elif palavra[i:i+1].isalpha():
contador_coluna += 1
i += 1
return self.q11()
elif '\\' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q26()
else:
contador_coluna += 1
i += 1
return self.q25(1)
def q1(self): # token *num*
global contador_coluna
global i
if palavra[i:i+1].isdigit():
contador_coluna += 1
i += 1
return self.q1()
elif '\\.' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q2()
elif 'e' == palavra[i:i+1] or 'E' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q4()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('NUM', palavra[i:i+1])
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q2(self):
global contador_coluna
global i
if palavra[i:i+1].isdigit():
contador_coluna += 1
i += 1
return self.q3()
else:
return self.q25(1)
def q3(self): # token *num*
global contador_coluna
global i
if palavra[i:i+1].isdigit():
contador_coluna += 1
i += 1
return self.q3()
elif 'e' == palavra[i:i+1] or 'E' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q4()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('NUM', palavra[i:i+1])
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q4(self):
global contador_coluna
global i
if palavra[i:i+1].isdigit():
contador_coluna += 1
i += 1
return self.q6()
elif '+' == palavra[i:i+1] or '-' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q5()
else:
return self.q25(1)
def q5(self):
global contador_coluna
global i
if palavra[i:i+1].isdigit():
contador_coluna += 1
i += 1
return self.q6()
else:
return self.q25(1)
def q6(self): # token *num*
global contador_coluna
global i
if palavra[i:i+1].isdigit():
contador_coluna += 1
i += 1
return self.q6()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('NUM', palavra[i:i+1])
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q7(self):
global i
global contador_coluna
if palavra[i:i+1] == '\\.':
contador_coluna += 1
i += 1
return self.q7()
elif palavra[i:i+1] == '"':
contador_coluna += 1
i += 1
return self.q8()
else:
return self.q25(1)
def q8(self): # token *lit*
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('lit', palavra[i:i+1])
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(2)
def q9(self): #Abre { comentário
global i
global contador_coluna
while palavra[i:i+1]:
contador_coluna += 1
i += 1
if palavra[i:i+1] == '}':
return self.q10()
return self.q25(1)
def q10(self): # fecha } comentário
if palavra[i:i+1].isspace():
return None
else:
return self.q25(3)
def q11(self): # reconhece *id*
global i
global contador_coluna
if palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', palavra[i:i+1])
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q12(self): # reconhece *EOF*
if palavra[i:i+1] == '$':
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('EOF', '$')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q13(self): # reconhece *<*
global i
global contador_coluna
if palavra[i:i+1] == '-':
contador_coluna += 1
i += 1
return self.q16()
elif palavra[i:i+1] == '=':
contador_coluna += 1
i += 1
return self.q15()
elif palavra[i:i+1] == '>':
contador_coluna += 1
i += 1
return self.q14()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPR', '<')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q14(self): # diferente <>
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPR', '<>')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q15(self): # menor igual <=
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPR', '<=')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q16(self): # atribuicao <-
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPR', '<-')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q17(self): # =
global i
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPR', '=')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q18(self): # reconhece *>
global i
global contador_coluna
if palavra[i:i+1] == '=':
contador_coluna += 1
i += 1
return self.q19()
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPR', '>')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q19(self): # maior igual >=
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPR', '>=')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q20(self): # operadores + - * /
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('OPM', palavra[i:i+1])
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q21(self): # (
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('AB_P', '(')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q22(self): # )
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('FC_P', ')')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q23(self): # ;
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('PT_V', ';')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q24(self): # ,
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('VIR', ',')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q25(self, entrada): # erro
return self.erro(entrada)
def q26(self): # \t \s \n
if 'n' == palavra[i:i+1] or 's' == palavra[i:i+1] or 't' == palavra[i:i+1]:
return None
else:
return self.q25(1)
def q27(self):
global i
global contador_coluna
if 'n' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q28()
elif 's' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q32()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'e')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q28(self):
global i
global contador_coluna
if 't' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q29()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'en')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q29(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q30()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'ent')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q30(self):
global i
global contador_coluna
if 'o' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q31()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'enta')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q31(self): # reconhece entao
if palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('entao', 'entao')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q32(self):
global i
global contador_coluna
if 'c' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q33()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'es')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q33(self):
global i
global contador_coluna
if 'r' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q34()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'esc')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q34(self):
global i
global contador_coluna
if 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q35()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'escr')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q35(self):
global i
global contador_coluna
if 'v' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q36()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'escre')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q36(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q37()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'escrev')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q37(self): #reconhece escreva
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('escreva', 'escreva')
return lista.procura_na_lista(palavra[i:i+1])
def q38(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q39()
elif 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q45()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'f')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q39(self):
global i
global contador_coluna
if 'c' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q40()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'fa')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q40(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q41()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'fac')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q41(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q42()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'faca')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q42(self):
global contador_coluna
global i
if 't' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q43()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'facaa')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q43(self):
global i
global contador_coluna
if 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q44()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'facaat')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q44(self): # reconhece *facaate*
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('facaate', 'facaate')
return lista.procura_na_lista(palavra[i:i+1])
def q45(self):
global i
global contador_coluna
if 'm' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q46()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'fi')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q46(self):
global i
global contador_coluna
if 'f' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q47()
elif 's' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q51()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('fim', 'fim')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q47(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q48()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'fimf')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q48(self):
global i
global contador_coluna
if 'c' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q49()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'fimfa')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q49(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q50()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'fimfac')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q50(self): # reconhece *fimfaca*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('fimfaca', 'fimfaca')
return lista.procura_na_lista(palavra[i:i+1])
def q51(self):
global i
global contador_coluna
if 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q51()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'fims')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q52(self): # reconhece *fimse*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('fimse', 'fimse')
return lista.procura_na_lista(palavra[i:i+1])
def q53(self):
global i
global contador_coluna
if 'n' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q54()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'i')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q54(self):
global i
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q55()
elif 't' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q59()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'in')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q55(self):
global i
global contador_coluna
if 'c' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q56()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'ini')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q56(self):
global i
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q57()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'inic')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q57(self):
global i
global contador_coluna
if 'o' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q58()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'inici')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q58(self): # reconhece *inicio*
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('inicio', 'inicio')
return lista.procura_na_lista(palavra[i:i+1])
def q59(self):
global i
global contador_coluna
if 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q60()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'int')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q60(self):
global i
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q61()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'inte')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q61(self):
global i
global contador_coluna
if 'r' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q62()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'intei')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q62(self):
global i
global contador_coluna
if 'o' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q62()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'inteir')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q63(self): # reconhece *inteiro*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
push('inteiro', 'inteiro')
return lista.procura_na_lista(palavra[i:i+1])
def q64(self):
global i
global contador_coluna
if 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q65()
elif 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q68()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'l')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q65(self):
global i
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q66()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'le')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q66(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q67()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'lei')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q67(self): # reconhece *leia*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
push('leia', 'leia')
return lista.procura_na_lista(palavra[i:i+1])
def q68(self):
global i
global contador_coluna
if 't' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q69()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'li')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q69(self): # reconhece *lit*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
push('lit', 'lit')
return lista.procura_na_lista(palavra[i:i+1])
def q70(self):
global i
global contador_coluna
if 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q71()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'r')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q71(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q72()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 're')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q72(self):
global i
global contador_coluna
if 'l' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q73()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'rea')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q73(self): # reconhece *real*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
push('real', 'real')
return lista.procura_na_lista(palavra[i:i+1])
def q74(self):
global i
global contador_coluna
if 'a' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q75()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'v')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q75(self):
global i
global contador_coluna
if 'r' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q76()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'va')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q76(self):
global i
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q77()
elif 'f' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q83()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'var')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q77(self):
global i
global contador_coluna
if 'n' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q78()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'vari')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q78(self):
global i
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q79()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'varin')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q79(self):
global i
global contador_coluna
if 'c' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q80()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'varini')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q80(self):
global i
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q81()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'varinic')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q81(self):
global i
global contador_coluna
if 'o' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q82()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'varinici')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q82(self): # reconhece o estado *varinicio*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('varinicio', 'varinicio')
return lista.procura_na_lista(palavra[i:i+1])
def q83(self):
global contador_coluna
if 'i' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q84()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'varf')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q84(self):
global i
global contador_coluna
if 'm' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q85()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 'varfi')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q85(): # reconhece o estado *varfim*
global i
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('varfim', 'varfim')
return lista.procura_na_lista(palavra[i:i+1])
def q86(self):
global i
global contador_coluna
if 'e' == palavra[i:i+1]:
contador_coluna += 1
i += 1
return self.q87()
elif palavra[i:i+1].isdigit() or palavra[i:i+1].isalpha() or palavra[i:i+1] == '_':
contador_coluna += 1
i += 1
return self.q11()
elif palavra[i:i+1].isspace():
lista = lista()
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('id', 's')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q87(self): # reconhece o estado *se*
global i
lista = lista()
if palavra[i:i+1].isspace():
if not lista.procura_na_lista(palavra[i:i+1]):
lista.push('se', 'se')
return lista.procura_na_lista(palavra[i:i+1])
else:
return self.q25(1)
def q88(self):
global i
if palavra[i:i+1].isspace():
return None
else:
return self.q25(1)
def erro(self, cod):
if(cod==2):
print("Erro " + cod + ". Aspas vêm ao final de constantes literais. Linha " + contador_linha + ", coluna " + contador_coluna + ".\n")
elif(cod==3):
print("Erro " + cod + ". Chaves devem fechar comentários. Linha " + contador_linha + ", coluna " + contador_coluna + ".\n")
else:
print("Erro " + cod + ". caractere inválido, linha " + contador_linha + ", coluna " + contador_coluna + ".\n")
def main():
if not os.path.exists('fonte.txt'):
print("Arquivo não encontrado.\n")
else:
fonte = open('fonte.txt', 'r+')
fonte.write("$")
l = lista()
ana = analisador()
l.push('inicio', 'inicio')
l.push('varinicio', 'varinicio')
l.push('varfim', 'varfim')
l.push('escreva', 'escreva')
l.push('leia', 'leia')
l.push('se', 'se')
l.push('entao', 'entao')
l.push('fimse', 'fimse')
l.push('facaate', 'facaate')
l.push('fimfaca', 'fimfaca')
l.push('fim', 'fim')
l.push('inteiro', 'inteiro')
l.push('lit', 'lit')
l.push('real', 'real')
global contador_linha
global contador_coluna
contador_linha = 0
for line in fonte:
contador_linha += 1
contador_coluna = 0
for word in line.split():
palavra = word
retorno_scanner = ana.scanner()
if(retorno_scanner.casefold() == "erro*"):
ana.erro(int(retorno_scanner[5:6]))
else:
print("Classe: " + retorno_scanner.classe + ", lexema: " + retorno_scanner.lexema + ", tipo: " + retorno_scanner.tipo + ".\n")
#if _name_ == '_main_':
# main()
|
import copy
class Solution:
"""
@param S: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, S):
# write your code here
result =[]
# Input Validations
if S is None or len(S) == 0:
return result
return self.subsetsHelper(0, sorted(S), [], result)
def subsetsHelper(self, pos, S, curr, ra):
ra.append(copy.deepcopy(curr))
for i in range(pos, len(S)):
if i!=pos and S[i] == S[i-1]:
continue
curr.append(S[i])
ra = self.subsetsHelper(i+1, S, curr, ra)
curr.remove(S[i])
return ra
|
nums = [1, 2, 3, 4, 8, 6, 9]
def bubble_sort(arr):
for i in range(len(arr)):
print(i)
isSorted = True
for idx in range(len(arr) - i - 1):
if arr[idx] > arr[idx + 1]:
isSorted = False
# swap(arr, i, i + 1)
# replacement for swap function
arr[idx], arr[idx + 1] = arr[idx + 1], arr[idx]
# if swapping didn't occur, we're good.
if isSorted:
break
print("PRE SORT: {0}".format(nums))
bubble_sort(nums)
print("POST SORT: {0}".format(nums))
def swap(arr, index_1, index_2):
temp = arr[index_1]
arr[index_1] = arr[index_2]
arr[index_2] = temp
|
# a = [1, 2, 3, 4, 5]
# a.append(10)
# a.append(20)
# print(a.pop())
# print(a.pop())
# print(a.pop())
# print(a.pop())
# print(a.pop())
# word = input('Input a word : ')
# word_list = list(word)
#
# result = []
# for _ in range(len(word_list)):
# result.append(word_list.pop())
# print(result)
# print(word[::-1])
a = [1, 2, 3, 4, 5]
a.append(10)
a.append(20)
print(a.pop(0))
print(a.pop(0))
print(a.pop(0))
print(a.pop(0))
print(a.pop(0))
print(a.pop())
|
from collections import deque
deque_list = deque()
for i in range(5):
deque_list.append(i)
print(deque_list)
deque_list.appendleft(10)
print(deque_list)
deque_list.rotate(2)
print(deque_list)
print(deque(reversed(deque_list)))
|
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
print('\n\n')
mylist = ["a", "b", "c", "d"]
a = list(enumerate(mylist))
print(a)
b = {i: j for i, j in enumerate('Gachon University is an academic institute\
located in South Korea'.split())}
print(b)
print("\n\n")
a_list = ['a1', 'a2', 'a3']
b_list = ['b1', 'b2', 'b3']
for a, b in zip(a_list, b_list):
print(a, b)
a, b, c = zip((1, 2, 3), (10, 20, 30), (100, 200, 300))
print(a, b, c)
d = [sum(x) for x in zip((1, 2, 3), (10, 20, 30), (100, 200, 300))]
print(d)
print('\n\n')
a_list = ['a1', 'a2', 'a3']
b_list = ['b1', 'b2', 'b3']
for i, (a, b) in enumerate(zip(a_list, b_list)):
print(i, a, b)
|
vector_a = [1, 2, 10] # List로 표현했을 경우
vector_b = (1, 2, 10) # Tuple로 표현했을 경우
vector_c = {'x': 1, 'y': 2, 'z': 10} # Dict로 표현했을 경우
print(vector_a, vector_b, vector_c)
u = [2, 2]
v = [2, 3]
z = [3, 5]
result = []
for i in zip(u, v, z):
result.append(sum(i))
print(result)
result = [sum(t) for t in zip(u, v, z)]
print(result)
u = [1, 2, 3]
v = [4, 5, 6]
alpha = 2
result = [alpha*sum(t) for t in zip(u, v)]
print(result)
matrix_a = [[3, 6], [4, 5]] # List로 표현했을 경우
matrix_b = [(3, 6), (4, 5)] # Tuple로 표현했을 경우
matrix_c = {(0, 0): 3, (0, 1): 6, (1, 0): 4, (1, 1): 5} # Dict로 표현했을 경우
matrix_a = [[3, 6], [4, 5]]
matrix_b = [[5, 8], [6, 7]]
result = [[sum(row) for row in zip(*t)] for t in zip(matrix_a, matrix_b)]
print(result)
alpha = 4
result = [[alpha * element for element in t] for t in matrix_a]
print(result)
matrix_a = [[1, 2, 3], [4, 5, 6]]
result = [[element for element in t] for t in zip(*matrix_a)]
print(result)
matrix_a = [[1, 1, 2], [2, 1, 1]]
matrix_b = [[1, 1], [2, 1], [1, 3]]
result = [[sum(a*b for a, b in zip(row_a, column_b))
for column_b in zip(*matrix_b)] for row_a in matrix_a]
print(result)
def vector_addition(*args):
return [sum(t) for t in zip(*args)]
print(vector_addition([1, 2], [2, 3], [3, 4]))
|
# General
result = []
for i in range(10):
result.append(i)
print(result)
# List comprehension
result = [i for i in range(10)]
print(result)
result = [i for i in range(10) if i % 2 == 0]
print(result)
print('\n\n')
word_1 = 'Hello'
word_2 = 'World!'
result = [i+j for i in word_1 for j in word_2]
print(result)
print('\n\n')
case_1 = ['A', 'B', 'C']
case_2 = ['D', 'E', 'A']
result = [i+j for i in case_1 for j in case_2]
print(result)
result = [i+j for i in case_1 for j in case_2 if not(i == j)]
print(result) # if 문에서 'AA'가 빠짐
print('\n\n')
words = "The quick brown fox jumps over the lazy dog".split()
result = [[w.upper(), w.lower(), len(w)] for w in words]
print(result)
print('\n\n')
case_1 = ['A', 'B', 'C']
case_2 = ['D', 'E', 'A']
result = [i+j for i in case_1 for j in case_2]
print(result)
result = [[i+j for i in case_1] for j in case_2]
print(result)
result_2 = [element for x in result for element in x]
print(result_2)
|
a = 'Hello World!'
print(a)
print(len(a))
print(a.upper())
print(a.lower())
print(a.capitalize())
print(a.title())
print(a.count('abc'))
print(a.find('abc'))
print(a.rfind('abc'))
print(a.startswith('abc'))
print(a.endswith('abc'))
print(a.split(" "))
print(a.split(" ")[0])
print(a.split(" ")[1])
print(a.split("o"))
b = "It\'s OK."
c = 'He said "Legeno"'
print(b, c)
|
#!python2
"""
(C) Michael Kane 2017
Student No: C14402048
Course: DT211C
Date: 29/09/2017
Title: Master Forgery Assignment.
Introduction:
1. Clean Boss.bmp to give a more convincing and usable signature for your forged documents.
2. Make sure the system cleans the whole picture and not just the signature.
Challenge : Find, isolate and clean the signature pictured in 'Trump.jpg'
Step-by-step:
1. Open a signature of your choice.
2. Convert the image to its grayscale version.
3. Find the area where the signature is located using np.argwhere(grayScaleMask==0). This selects the black pixels in the image.
4. Plot the points of the returned value of np.argwhere using points = np.fliplr(points) then x, y, width, height = cv2.boundingRect(points)
5. Crop both the grayscale and original image.
6. Get the ROI of the original image by getting the reverse mask of it then anding itwith itself.
7. Create a blank background image by getting to shape of the original image, then use np.zeros((height, width, 3), np.uint8) to create the image
8. Change the background to full white then add the background and ROI together.
9. Write the image to an image file, return the image and display it.
Give an overview:
The purpose of this application is to allow a user to input an image of a signature,
and recieve an image back with the signature isolated and background completely white.
Comment on experiments:
1. Tried to get blue signatures to appear clearer, but it seems any blue signature I pass in, unless it has been created in paint appears gray.
Green signatures dont seem to work very well.
Any signatures I try off the interent dont work as well as they should, I get a 50/50 working ration on the ones I picked.
2. Sucessfully implemented a version which placed the image onto a signed form, the issue was that it was not to scale and would appear squashed.
This was done by cropping the signature which can be found below, rezising the form and combinging the ROI for the signature and the form.
After completing this however it was revealed that it is not the objective of the assignment so I reverted to a simpler version.
Link to the git version with the code.
https://github.com/MichaelKane428/ImageProcessing/commit/736ac1edc6fc626ce3d79d24015580cb994fc487#diff-be144f71162553069eb09260442b8921
References:
Convert References to harvard style.
1. Stack Overflow, SO. (2017)How to detect edge and crop an image in Python.
Available at: https://stackoverflow.com/questions/44383209/how-to-detect-edge-and-crop-an-image-in-python(12/10/2017)
2. Stack Overflow, SO. (2017)How to fill OpenCV image with one solid color?.
Available at: https://stackoverflow.com/questions/4337902/how-to-fill-opencv-image-with-one-solid-color(12/10/2017)
"""
# import the necessary packages:
import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib import image as image
import easygui
class forgery():
"""
Purpose of function:
Allow portablity of the forge signature code
Example Function:
instance = forgery()
Args:
None
return:
None
"""
def getImage(self):
"""
Purpose of function:
Allow a user to select an image.
Example Function:
instance.getImage()
Args:
None
return:
None
"""
try:
#Opening an image from a file:
print("Please Select a Signature you wish to forge:")
file = easygui.fileopenbox()
image = cv2.imread(file)
forged_image = self.forgeSignature(image)
except:
print("User failed to select an image.")
while True:
# Showing an image on the screen (OpenCV):
cv2.imshow("Signature", forged_image)
key = cv2.waitKey(0)
# if the 'q' key is pressed, quit:
if key == ord("q"):
break
def forgeSignature(self, image):
"""
Purpose of function:
The purpose of this function is to isolate a signature and place it on a fully white background,
then return it to the getImage function to be displayed.
Example Function:
variable = self.forgeSignature(param1)
Args:
param1 (numpy.ndarray): This is the first paramter. Which will be an image a user has selected.
return:
The return value (numpy.ndarray): This will return a forged version of the original signature.
"""
# Create a grayscale mask for the signature.
grayScale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayScaleHistogram = cv2.equalizeHist(grayScale)
grayScaleMask = cv2.adaptiveThreshold(grayScaleHistogram, maxValue = 255,
adaptiveMethod = cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
thresholdType = cv2.THRESH_BINARY,
blockSize = 11,C = 30)
# The next six lines of code are from reference Number 1.
# Crop the area where the signature is located.
points = np.argwhere(grayScaleMask==0)
points = np.fliplr(points)
x, y, width, height = cv2.boundingRect(points)
x, y, width, height = x-50, y-50, width+100, height+70
croppedColorImage = image[y:y+height,x:x+width]
croppedGrayScaleImage = grayScaleMask[y:y+height,x:x+width]
# Extracted signature.
reverseSignature = cv2.bitwise_not(croppedGrayScaleImage)
regionOfInterestOne = cv2.bitwise_and(croppedColorImage,croppedColorImage,mask=reverseSignature)
# Line 101 and 102 are referenced by reference Number 2.
# Apply the extracted Signature to the background.
reverseBackground = cv2.bitwise_not(reverseSignature)
height, width = croppedGrayScaleImage.shape
background = np.zeros((height, width, 3), np.uint8)
background[:] = (255,255,255)
regionOfInterestTwo = cv2.bitwise_and(background,background,mask=reverseBackground)
forged_signature = regionOfInterestOne + regionOfInterestTwo
# Create an image of the signature.
cv2.imwrite('forgedSignature.jpg', forged_signature)
return forged_signature
if __name__ == "__main__":
forged_signature = forgery()
forged_signature.getImage()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.