blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
3af2df1e2785fc87579ae86f465bcaf223c6627c | PaulKitonyi/Python-Practise-Programs | /Q22.py | 81 | 3.59375 | 4 | def squareroot(n):
num=0
while num*num<n:
num +=1
return num
|
3990f9350a0aba106a6a7838232d88427172116a | PaulKitonyi/Python-Practise-Programs | /testing_functions/test_cities.py | 460 | 3.546875 | 4 | import unittest
from city_functions import city_details
class TestCityDetails(unittest.TestCase):
def test_city_details(self):
testcitydetails = city_details('santiago','chile')
self.assertEqual(testcitydetails,'Santiago, Chile')
def test_city_details_population(self):
testcitydetails = city_details('santiago','chile','10000')
self.assertEqual(testcitydetails, 'Santiago, Chile - population 10000')
unittest.main() |
9bbcaaf745be9fa4593dd73e52cfc6421991f3c6 | PaulKitonyi/Python-Practise-Programs | /testing_classes/Survey/survey.py | 694 | 3.828125 | 4 | class AnonymousSurvey():
"""A class to collect anonymous answers to a survey Question"""
def __init__(self, question):
"""Store a Question and prepare to store reponses"""
self.question = question
self.responses = []
def show_question(self):
"""Display the Question"""
return self.question
def store_response(self, new_response):
"""Stores responses to Question"""
self.responses.append(new_response)
def show_results(self):
"""Displays the stored responses"""
print('*'*5+ " printing responses in a while........ "+'*'*5 )
for response in self.responses:
print('-' + response)
|
b73d22e4ea3551f30ab26f5a89cdc4aac7ed66f3 | PaulKitonyi/Python-Practise-Programs | /Q12.py | 524 | 4.03125 | 4 | # Question:
# Write a program, which will find all such numbers between 1000 and 3000
# (both included) such that each digit of the number is an even number.
# The numbers obtained should be printed in a comma-separated sequence
# on a single line.
values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0 and int(s[0])!=0 )and (int(s[1])%2==0 and int(s[1]) !=0) and (int(s[2])%2==0 and int(s[2]) !=0) and (int(s[3])%2==0 and int(s[3])!=0):
values.append(s)
print (",".join(values))
|
46a974a2c8f90592ae25e92e1acd58e6b468bbc3 | farbodp/just_codes | /exercises_solutions.py | 7,964 | 4.21875 | 4 | '''-MixUp
Given strings a and b, return a single string with a and b separated
by a space '<a> <b>', except swap the first 2 chars of each string.
e.g.
'mix', 'pod' -> 'pox mid'
'dog', 'dinner' -> 'dig donner'
Assume a and b are length 2 or more.'''
def mix_up(a, b):
return b[:2] + a[2:] + ' ' + a[:2] + b[2:]
''' -verbing
Given a string, if its length is at least 3,
add 'ing' to its end.
Unless it already ends in 'ing', in which case
add 'ly' instead.
If the string length is less than 3, leave it unchanged.
Return the resulting string.'''
def verbing(s):
# +++your code here+++
return
'''Write a Python function to remove the nth index character from a nonempty string.'''
def remove_char(s, n):
return s[:n] + s[n+1:]
'''Write a Python program to change a given string to a new string
where the first and last chars have been exchanged.'''
def change_string(str1):
# +++your code here+++
return
'''Write a Python function to insert a string in the middle of a string'''
def insert_string_middle(s, word):
# +++your code here+++
return
'''-donuts
Given an int count of a number of donuts, return a string
of the form 'Number of donuts: <count>', where <count> is the number
passed in. However, if the count is 10 or more, then use the word 'many'
instead of the actual count.
So donuts(5) returns 'Number of donuts: 5'
and donuts(23) returns 'Number of donuts: many'''
def donuts(count):
if count >=10:
return 'Number of donuts: many'
else:
return 'Number of donuts: {}'.format(count)
'''-both_ends
Given a string s, return a string made of the first 2
and the last 2 chars of the original string,
so 'spring' yields 'spng'. However, if the string length
is less than 2, return instead the empty string.'''
def both_ends(s):
# +++your code here+++
return
''' -front_back
Consider dividing a string into two halves.
If the length is even, the front and back halves are the same length.
If the length is odd, we'll say that the extra char goes in the front half.
e.g. 'abcde', the front half is 'abc', the back half 'de'.
Given 2 strings, a and b, return a string of the form
a-front + b-front + a-back + b-back'''
def front_back(a, b):
# +++your code here+++
return
'''-fix_start
Given a string s, return a string
where all occurences of its first char have
been changed to '*', except do not change
the first char itself.
e.g. 'babble' yields 'ba**le'
Assume that the string is length 1 or more.
Hint: s.replace(stra, strb) returns a version of string s
where all instances of stra have been replaced by strb.'''
def fix_start(s):
return s[0] + s[1:].replace(s[0], '*')
''' The goal of this exercise is to convert a string to a new string
where each character in the new string is '(' if that character
appears only once in the original string, or ')' if that character
appears more than once in the original string. Ignore capitalization
when determining if a character is a duplicate.
Examples:
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
'''
def duplicate_encode(word):
# +++your code here+++
return
''' This time no story, no theory. The examples below show you how to write function accum:
Examples:
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"
The parameter of accum is a string which includes only letters from a..z and A..Z.
'''
def accum(word):
new_list = []
for item in enumerate(word):
new_list.append(item[1].upper()+item[1].lower()*item[0])
return '-'.join(new_list)
''' The parameter weekday is True if it is a weekday,
and the parameter vacation is True if we are on vacation.
We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in.
sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True '''
def sleep_in(weekday, vacation):
if weekday==True and vacation==False:
return False
else:
return True
''' Write a function called accept_login(users, username, password)
with three parameters: users a dictionary of username
keys and password values, username a string for a login name and
password a string for a password. The function should return
True if the user exists and the password is correct and False otherwise'''
def accept_login(users, username, password):
return username in users.keys() and users[username]==password
'''Write a function that takes in a string of one or more words,
and returns the same string, but with all five or more letter words reversed
Strings passed in will consist of only letters and spaces.
Spaces will be included only when more than one word is present.
Examples:
spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
spinWords( "This is a test") => returns "This is a test"
spinWords( "This is another test" )=> returns "This is rehtona test"
'''
def spin_words(sentence):
words = sentence.split()
new_words = []
for word in words:
if len(word)>=5:
new_words.append(word[::-1])
else:
new_words.append(word)
return ' '.join(new_words)
''' -match_ends
Given a list of strings, return the count of the number of
strings where the string length is 2 or more and the first
and last chars of the string are the same.
Note: python does not have a ++ operator, but += works.
examples:['aba', 'xyz', 'aa', 'x', 'bbb'] should return 3
['', 'x', 'xy', 'xyx', 'xx'] should return 2 '''
def match_ends(words):
count = 0
for word in words:
if len(word)>=2 and word[0]==word[-1]:
count += 1
return count
''' -front_x
Given a list of strings, return a list with the strings
in sorted order, except group all the strings that begin with 'x' first.
e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
Hint: this can be done by making 2 lists and sorting each of them
before combining them.'''
def front_x(words):
x_words = []
others = []
for word in words:
if word[0]=='x':
x_words.append(word)
else:
others.append(word)
return sorted(x_words) + sorted(others)
''' -Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.'''
def remove_adjacent(nums):
# +++your code here+++
return
def last_elem(t):
return t[-1]
''' -sort_last
Given a list of non-empty tuples, return a list sorted in increasing
order by the last element in each tuple.
e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
[(2, 2), (1, 3), (3, 4, 5), (1, 7)]
Hint: use a custom key= function to extract the last element form each tuple.'''
def sort_last(tuples):
return sorted(tuples, key=last_elem)
''' -Given two lists sorted in increasing order, create and return a merged
list of all the elements in sorted order. You may modify the passed in lists.
Ideally, the solution should work in "linear" time, making a single
pass of both lists.'''
def linear_merge(list1, list2):
# +++your code here+++
return
'''John has invited some friends. His list is:
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
Could you make a program that
makes this string uppercase
gives it sorted in alphabetical order by last name.
When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma.
So the result of function meeting(s) will be:
"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
'''
def meeting(s):
# +++your code here+++
return
# when you run this file, the program starts from here:
if __name__=='__main__':
pass
|
65bf2ef38e2682fecab3c046a7e343d9ad9b5cee | Chalayyy/challenge_solutions | /escape_pod.py | 9,859 | 3.6875 | 4 | """
The problem:
Given a list of entrances, a list of exits (which are
disjoint from the entrances), and a matrix indicating the maximum
number of individuals that can travel down a hallway each time unit
from one room(the matrix row) to another (the matrix column), find the
maximum number of individuals that can be sent from the entrances to
the exits.
The solution:
To solve this, start from the exits and note how many
individuals each room receives and how many it sends to already-visited
rooms (assuming entrances can receive an infinite amount and exits can
send an infinite amount. Move to all the rooms that sent to the last
set of rooms and see how many it sends/ receives. If a room ever sends
more than it receives, then starting at previous set of rooms it sent
to, find if any rooms receive more than it sends. Reduce how many
individuals a room receives if it can't send them all first by reducing
from the room that sent too many (if the two rooms are directly
connected). Repeat until no rooms so far visited take more than they
send. If this doesn't sufficiently reduce how many the over-sending
room sends, then reduce how many it sends, first to rooms which haven't
been visited(and therefore may or may not lead to the end), then to
rooms which have been visited (which now have been reduced to only
receive what they can send).
All rooms from the end up to this point now receive at least as many as
they send. Proceed to move back to rooms which send to the current set
and repeat the process.
"""
def solution(entrances, exits, path):
# change useless pathways to 0. These are pathways leading to the room it came
# from, back to the original entrance, from the exits, or from rooms that
# don't receive bunnies.
for x in range(len(path)):
path[x][x] = 0
for y in entrances:
path[x][y] = 0
for z in exits:
path[z][x] = 0
if sum([path[y][x]] == 0 for y in range(len(path))):
for y in range(len(path)):
path[x][y] = 0
# if a spot sends more than it recieves, reduce how much it sends to match how much it receives
# start at end, work backwards
# repeat until no more changes
at = exits[:] # start at ending
coming_from = [x for x in range(len(path)) if any(
path[x][y] != 0 for y in at)] # rooms that send to "at"
all_coming_from = [] # keep track of sets of rooms for backtracking
all_coming_from.append(at)
visited = [] # keep track of what spots are confirmed leading to the end
visited.extend(at)
# repeat until reached beginning
while set(at) and not all(entrance in set(at) for entrance in entrances):
all_coming_from.append(coming_from)
each_receives = [sum(path[x][y] for x in range(len(path)))
for y in at] # sum of column for each value in "at"
each_sends = [sum(path[x][y] for y in visited)
for x in at] # sum of row for each value in "at"
# adjust entrance receives / exit sends values to match how much they send/receive respectively, rather than infinite.
for spot in at:
if spot in entrances:
each_receives[at.index(spot)] = each_sends[at.index(spot)]
if spot in exits:
each_sends[at.index(spot)] = each_receives[at.index(spot)]
# as long as any current spot sends more than it receives, reduce how much it sends to match how much it gets.
while any([each_sends[x] > each_receives[x] for x in range(len(at))]):
# check each room one at a time
for k in range(len(at)):
while each_sends[k] > each_receives[k]:
# if a spot is sending more than it gets, see which future spots are receiving more than they send and reduce how many they receive
index = -1
# start at set of rooms that the over-sending room sends to
start = all_coming_from[index-1]
# continue until we would try to start at the exits
while set(start) != set(exits):
# ignore entrances since no room sends to entrances
going_to = [
spot for spot in all_coming_from[index-2] if spot not in entrances]
going_receives = [
sum(path[x][y] for x in range(len(path))) for y in going_to]
going_sends = [sum(path[x][y]
for y in visited) for x in going_to]
for x in going_to:
if x in exits:
going_sends[going_to.index(
x)] = going_receives[going_to.index(x)]
# if any spot gets more than it sends, reduce how much it gets (does not affect its output)
while any([going_receives[x] > going_sends[x] for x in range(len(going_to))]):
for j in range(len(going_to)):
# reduce how much it gets from direct sources that are sending too much
if going_receives[j] > going_sends[j]:
# if the one getting too much is getting from the one sending more than it receives, reduce how much is sent
if path[at[k]][going_to[j]] > 0:
path[at[k]][going_to[j]] -= min(
going_receives[j] - going_sends[j], path[at[k]][going_to[j]])
# continue moving forward towards exit to find any other rooms that get too much
start = going_to[:]
index -= 1
# recalculate how much each room receives and sends
# sum of column for each value in "at"
each_receives = [sum(path[x][y]
for x in range(len(path))) for y in at]
each_sends = [sum(path[x][y] for y in visited)
for x in at] # sum of row for each value in "at"
# adjust entrance receives / exit sends values to match how much they send/receive respectively, rather than infinite.
for spot in at:
if spot in entrances:
each_receives[at.index(
spot)] = each_sends[at.index(spot)]
if spot in exits:
each_sends[at.index(
spot)] = each_receives[at.index(spot)]
# if a spot still sends more than it gets, reduce how much it sends, first to non-visited spots
if each_sends[k] > each_receives[k]:
smallest = float("inf")
y_index = 0
for y in range(len(path)):
if y not in visited: # check non-visited spots first
if path[at[k]][y] < smallest and path[at[k]][y] > 0:
smallest = path[at[k]][y]
y_index = y
# if room doesn't send to non-visited spots, reduce how many are sent to visited spots
if smallest == float("inf"):
for y in visited:
if path[at[k]][y] < smallest and path[at[k]][y] > 0:
smallest = path[at[k]][y]
y_index = y
# don't reduce more than the value itself
reduction = min(
path[at[k]][y_index], (each_sends[k] - each_receives[k]))
path[at[k]][y_index] -= reduction
# recalculate how much each room receives and sends
# sum of column for each value in "at"
each_receives = [sum(path[x][y]
for x in range(len(path))) for y in at]
# sum of row for each value in "at"
each_sends = [sum(path[x][y]
for y in visited) for x in at]
# adjust entrance receives / exit sends values to match how much they send/receive respectively, rather than infinite.
for spot in at:
if spot in entrances:
each_receives[at.index(
spot)] = each_sends[at.index(spot)]
if spot in exits:
each_sends[at.index(
spot)] = each_receives[at.index(spot)]
# next step back to rooms that send to current set of rooms
visited.extend(at)
visited = list(set(visited))
# recalculate coming_from for any changes
coming_from = [x for x in range(len(path)) if any(
path[x][y] != 0 for y in at)]
at = coming_from[:]
# recalculate coming_from based on new at
coming_from = [x for x in range(len(path)) if any(
path[x][y] != 0 for y in at)]
# return sum of values sent directly to exit rooms since these are confirmed bunnies
return sum(path[x][y] for x in range(len(path)) for y in exits)
# Example case:
print(solution([0, 1], [4, 5], [[0, 0, 4, 6, 0, 0], [0, 0, 5, 2, 0, 0], [
0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 6, 6], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]))
|
c609b30525e3cfb50004bb57bb50efd5daa4f3bd | markcassar/data_analyst | /Project 1/program_files/turnstile_weather_predict_svm.py | 5,952 | 3.796875 | 4 | import numpy as np
import pandas as pd
from ggplot import *
#from sklearn import linear_model
#, svm
#from sklearn.ensemble import RandomForestClassifier
import statsmodels.api as sm
#import itertools
import matplotlib.pyplot as plt
#import operator
#import csv
def normalize_features(df):
"""
Normalize the features in the data set.
"""
mu = df.mean()
sigma = df.std()
if (sigma == 0).any():
raise Exception("One or more features had the same value for all samples, and thus could " + \
"not be normalized. Please do not include features with only a single value " + \
"in your model.")
df_normalized = (df - df.mean()) / df.std()
return df_normalized, mu, sigma
def compute_cost(features, values, theta):
"""
Compute the cost function given a set of features / values,
and the values for our thetas.
This can be the same code as the compute_cost function in the lesson #3 exercises,
but feel free to implement your own.
"""
m = len(values)
sum_of_square_errors = np.square(np.dot(features, theta) - values).sum()
cost = sum_of_square_errors / (2*m)
return cost
def gradient_descent(features, values, theta, alpha, num_iterations):
"""
Perform gradient descent given a data set with an arbitrary number of features.
"""
m = len(values)
cost_history = []
for i in range(0, num_iterations):
cost = compute_cost(features, values, theta)
cost_history.append(cost)
h = np.dot( features, theta)
h_values = values - h
theta += (alpha / m) * np.dot( np.transpose(features), h_values )
return theta, pd.Series(cost_history)
def compute_r_squared(data, predictions):
# Write a function that, given two input numpy arrays, 'data', and 'predictions,'
# returns the coefficient of determination, R^2, for the model that produced
# predictions.
r_squared = 1 - ( np.sum( np.square(data - predictions) ) / np.sum( np.square( data - np.mean(data) ) ) )
return r_squared
def predictions(dataframe):
'''
The NYC turnstile data is stored in a pandas dataframe called weather_turnstile.
Using the information stored in the dataframe, let's predict the ridership of
the NYC subway using linear regression with gradient descent.
You can download the complete turnstile weather dataframe here:
https://www.dropbox.com/s/meyki2wl9xfa7yk/turnstile_data_master_with_weather.csv
Your prediction should have a R^2 value of 0.20 or better.
You need to experiment using various input features contained in the dataframe.
We recommend that you don't use the EXITSn_hourly feature as an input to the
linear model because we cannot use it as a predictor: we cannot use exits
counts as a way to predict entry counts.
'''
# Select Features (try different features!)
# feature_lst = [ 'fog','pressurei', 'meanpressurei', 'tempi', 'wspdi', 'precipi', 'rain', 'meantempi', 'latitude', 'longitude', 'meanwspdi', 'meanprecipi', 'hour']
feature_lst = [ 'fog','pressurei', 'tempi', 'wspdi', 'precipi', 'rain', 'meantempi', 'meanwspdi', 'meanprecipi', 'hour']
features = dataframe[ feature_lst ]
# Add features using dummy variables
dummy_units = pd.get_dummies(dataframe['UNIT'], prefix='unit')
dummy_day_week = pd.get_dummies(dataframe['day_week'], prefix='day')
# dummy_station = pd.get_dummies(dataframe['station'], prefix='station')
dummy_conds = pd.get_dummies(dataframe['conds'], prefix='conds')
features = features.join(dummy_units)
features = features.join(dummy_day_week)
# features = features.join(dummy_station)
features = features.join(dummy_conds)
# Values
values = dataframe['ENTRIESn_hourly']
m = len(values)
features, mu, sigma = normalize_features(features)
features['ones'] = np.ones(m) # Add a column of 1s (y intercept)
# Convert features and values to numpy arrays
features_array = np.array( features)
values_array = np.array(values)
# this model works
# clf = linear_model.LinearRegression()
# results = clf.fit(features_array, values_array)
# prediction = results.predict(features_array)
# this model does not yet work
# model = RandomForestClassifier()
# y, _ = pd.factorize(dataframe['ENTRIESn_hourly'])
# results = model.fit(features_array, values_array)
# prediction = model.predict(features_array)
# this model takes too long to calculate, if indeed it does actually calculate the predictions properly (I didn't wait for it to finish)
# model = svm.SVR(kernel='linear', C=1e3)
# results = model.fit(features_array, values_array.astype(np.float))
# prediction = results.predict(features_array)
model = sm.OLS(values_array, features_array)
results = model.fit()
prediction = results.predict(features_array)
print( compute_r_squared(values, prediction) )
# print(results.summary())
plt.scatter(values_array, prediction-values_array)
# plt.xticks(range(len(feature_r_squared_dict)), feature_r_squared_dict.keys(), rotation='vertical')
plt.show()
return prediction #, plot
def plot_cost_history(alpha, cost_history):
"""This function is for viewing the plot of your cost history.
If you want to run this locally, you should print the return value
from this function.
"""
cost_df = pd.DataFrame({
'Cost_History': cost_history,
'Iteration': range(len(cost_history))
})
return ggplot(cost_df, aes('Iteration', 'Cost_History')) + \
geom_point() + ggtitle('Cost History for alpha = %.3f' % alpha )
if __name__=='__main__':
df = pd.read_csv("c:\\users\\bonnie\\desktop\\mark_work\\nanodegree\\intro_to_data_science\\improved-dataset\\turnstile_weather_v2.csv")
predictions(df)
|
dbb3b5ae73df7d9dae41309f01181eeed824376a | vlad271828/- | /цветок 10.py | 225 | 4.03125 | 4 | import turtle
turtle.shape('turtle')
def o(n):
turtle.left(n)
for i in range(1,120):
turtle.forward(1)
turtle.left(3)
turtle.right(n)
for h in range(0,360,60):
o(h)
|
b686ef732e4c2be80a6fa65c6f5c5ad39f503665 | ingako/MachineLearningKata | /viterbi/constructTransitions.py | 1,255 | 3.578125 | 4 | import numpy as np
## This function constructs tranisition matricies for lowercase characters.
# It is assumed that the file 'filename' only contains lowercase characters
# and whitespace.
## INPUT
# filename is the file containing the text from which we wish to develop a
# Markov process.
#
## OUTPUT
# p is a 26 x 26 matrix containing the probabilities of transition from a
# state to another state, based on the frequencies observed in the text.
# prior is a vector of prior probabilities based on how often each character
# appears in the text
#
## Read the file into a string called text
def constructTransitions(filename):
p = np.zeros(shape=(26, 26)) # transition matrix
prior = np.zeros(shape=(26, 1)) # prior vector
with open(filename) as f:
for line in f:
for word in line.split():
for i, c in enumerate(word):
to_c = ord(c) - ord('a')
prior[to_c] += 1
if i == 0:
continue
from_c = ord(word[i - 1]) - ord('a')
p[from_c][to_c] += 1
for i in range(0, 26):
p[i] /= sum(p[i])
prior /= sum(prior)
return (p, prior) |
c821a3d084e84ec8731bc1b7a3414a26b37e5bf5 | JamesLegros/online_courses | /edX/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python/Week 1/Problem Set/vowelCount.py | 413 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 15:04:49 2016
@author: jameslegros
"""
# Assume s is a string of characters
s = 'azcbobobegghakl'
#Length
length = len(s)
#String increment
i = 0
#Vowel count
count = 0
while (length > i):
if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u':
count += 1
i += 1
print ("Number of vowels: " + str(count)) |
ad36914dfa98a46eedb31e2d48c248ab6c7ea0b9 | 2019-reu-cmp/assignments-mcgille4 | /Day03/sunspots.py | 1,464 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 22:15:32 2019
@author: Emily
"""
#Read the contents of the file.
with open('sunspots.txt', 'r') as f:
entire_file = f.read()
list_of_data = entire_file.split("\n")
#Dictionary not necessary for this application, but useful for other applications.
dict_of_sunspots = {}
#List containing the daily sunspot values.
sunspot_values_list = []
#Add data which was read from file to list.
for n in list_of_data:
n = n.split("\t")
dict_of_sunspots[int(n[0])] = float(n[1])
sunspot_values_list.append(float(n[1]))
print(sunspot_values_list)
#Average = mean = total number of sunspots/total number of days.
#Add up total number of days.
number_of_days = len(sunspot_values_list)
#Add up total number of sunspots.
spot_sum = 0
for item in sunspot_values_list:
spot_sum += item
#Calculate and return mean.
average_spot = spot_sum / number_of_days
print("Average of number of sunspots: " + str(round(average_spot, 2)))
#Implement a count(high, low) function which returns the number of days with sunspots above low and above high.
def count(low, high, data = sunspot_values_list):
too_low = 0
too_high = 0
for n in data:
if n < low:
too_low += 1
elif n > high:
too_high += 1
within_range = len(data) - (too_low + too_high)
return within_range
print(count(40, 60))
|
d1ec467f22622f4156419a80c0a4f744a1733560 | jossthomas/Enigma-Machine | /components/Enigma_Components.py | 5,749 | 4 | 4 | from string import ascii_uppercase #I'll use the index of letters in this to create the rotors
class rotor:
"""These map letters to reciprocal non identical letters and have the ability to rotate and thereby change the key"""
def __init__(self, output_sequence, position, turnover_notches):
self.position = position
self.input_sequence = ascii_uppercase[self.position:] + ascii_uppercase[:self.position]
self.output_sequence = output_sequence
self.turnover_notches = turnover_notches #Only useful for debugging
if turnover_notches is not None:
self.turnover_indexes = [self.input_sequence.index(i) + 1 for i in turnover_notches] #We need the turnover position as an int so it matches the position, + 1 as the rotation occurs after the letter not before
else:
self.turnover_indexes = None #will never turn
def set_position(self, position):
"""Set the rotor so encoding/decoding starts on same setting"""
self.position = position
def rotate(self, step=1): #May add additional step functionality later but currently redundant.
"""Rotate the rotor +1 and adjust input string accordingly"""
self.position += step
if self.position == 26: #rotor has performed a full rotation so reset
self.position = 0
self.input_sequence = ascii_uppercase[self.position:] + ascii_uppercase[:self.position] #Using ascii uppercase here avoids step increasing each time.
def encode_letter(self, letter):
"""First time through the rotors forwards"""
input_index = self.input_sequence.index(letter)
output_letter = self.output_sequence[input_index]
return output_letter
def reverse_encode_letter(self, letter):
"""second time through rotors backwards"""
input_index = self.output_sequence.index(letter)
output_letter = self.input_sequence[input_index]
return output_letter
def __str__(self): #Print out the current rotor details for debugging
variables = [self.input_sequence,
self.output_sequence,
self.position + 1,
self.input_sequence[self.position],
self.turnover_notches,
self.turnover_indexes
]
return('In: {0[0]}\nOut: {0[1]}\nCurrent Position {0[2]} ({0[3]})\nTurnover Notches {0[4]} ({0[5]})\n'.format(variables))
class reflector:
"""This maps each letter to another reciprocal and non-identical letter"""
def __init__(self):
self.l_index = ascii_uppercase
self.reciprocal = None
def set(self, reciprocal):
self.reciprocal = reciprocal
def reflect(self, letter):
letter_index = self.l_index.index(letter)
return self.reciprocal[letter_index]
def __str__(self):
return "Reflector:\nIn: {0}\nOut: {1}".format(self.l_index, self.reciprocal)
class entry_wheel:
"""Acts to connect the keyboard and rotors, generally has no effect on mapping"""
def __init__(self):
self.l_index = ascii_uppercase
self.reciprocal = None
def set(self, reciprocal):
self.reciprocal = reciprocal
def forwards_encode(self, letter):
letter_index = self.l_index.index(letter)
return self.reciprocal[letter_index]
def backwards_encode(self, letter):
letter_index = self.reciprocal.index(letter)
return self.l_index[letter_index]
def __str__(self):
return "Entry Wheel:\nIn: {0}\nOut: {1}\n".format(self.l_index, self.reciprocal)
class rotor_array:
"""This acts as a container for the rotors and allows for iteration over them in a consistent order"""
def __init__(self):
self.rotors = [] # a place to store any number of rotors!
def add_rotor(self, output_sequence, position, turnover_notches):
rotor_init = rotor(output_sequence, position, turnover_notches)
self.rotors.append(rotor_init)
def encode(self, letter):
"""Iterates through all rotors pre reflector"""
for i in self.rotors:
letter = i.encode_letter(letter)
return letter
def reverse_encode(self, letter):
"""Iterates through all rotors post reflector"""
reverse_rotors = self.rotors[::-1] #Reverse the set for ease
for i in reverse_rotors:
letter = i.reverse_encode_letter(letter)
return letter
def rotate_rotors(self):
"""Rotate first rotor and check if others need rotating"""
current_rotor = 0
self.rotors[current_rotor].rotate() #first rotor always rotates
while self.rotors[current_rotor].position in self.rotors[current_rotor].turnover_indexes: #check if we need to rotate the next rotor
current_rotor += 1
self.rotors[current_rotor].rotate()
class plugboard:
"""The plugboard swaps pairs of letters pre encoding. Usually supplied with 10 wires allowing for 10 AB pairs"""
def __init__(self):
self.used_letters = []
self.letter_pairs = {}
def set(self, pairs):
"""Create random letter swaps"""
assert len(''.join(pairs)) == len(set(''.join(pairs))), "Letter contained in plugboard twice!"
for pair in pairs:
first, second = pair[0], pair[1]
self.letter_pairs[first] = second
self.letter_pairs[second] = first
def substitute(self, letter):
"""If no plug set then letter passes through"""
return self.letter_pairs.get(letter, letter)
def __str__(self):
return '\nPlugboard:\n' + ' '.join([''.join(i) for i in self.letter_pairs.items()]) |
a0a8ad2bd0e252390dceec9f9f163d013ed6941f | lucaslzl/datacleaner | /cleaner.py | 2,373 | 3.5 | 4 | import pandas as pd
"""
Class specialized in cleaning files by removing columns
"""
class DataCleaner:
def __init__(self, old_separator=',', new_separator='\t'):
self.old_separator = old_separator
self.new_separator = new_separator
def validate_formatting(self, data_header):
try:
columns = len(data_header['columns'])
types = len(data_header['types'])
positions = len(data_header['positions'])
ignore_nan = len(data_header['ignore_nan'])
if columns == 0 or types == 0 or positions == 0 or ignore_nan == 0:
raise Exception('Empty data header.')
elif not (columns == types and types == positions and positions == ignore_nan):
raise Exception('Missing values in data header.')
except KeyError:
raise Exception('Invalid or unformatted data header.')
return True
def read_data(self, file, data_header):
data_file = open(file, 'r')
data_rows = []
first_size = 0
for line in data_file:
line = line.strip().split(self.old_separator)
if len(line) != first_size:
if first_size != 0:
continue
first_size = len(line)
item = {}
all_ok = True
for indx, column in enumerate(data_header['columns']):
try:
position = data_header['positions'][indx]
column_type = data_header['types'][indx]
ignore_nan = data_header['ignore_nan'][indx]
if not ignore_nan and (line[position].strip() == '' or line[position] == '0'):
all_ok = False
break
item[column] = column_type(line[position])
except ValueError:
raise Exception('Invalid data type at column {0}, data {1}, expected type {2}.'.format(column, line[position], column_type))
if all_ok:
data_rows.append(item)
data_file.close()
data_cleaned = pd.DataFrame(data_rows)
return data_cleaned
def clean(self, file, data_header):
if self.validate_formatting(data_header):
data_cleaned = self.read_data(file, data_header)
data_cleaned.to_csv('cleaned_' + file, sep=self.new_separator, encoding='utf-8', index=False)
if __name__ == '__main__':
# Data from the city of Chicago
# https://data.cityofchicago.org/
file = 'crimes_2018_chicago.csv'
data_header = {'columns': ['Date', 'Type', 'Latitude', 'Longitude'],\
'types': [str, str, float, float],\
'positions': [1, 4, 15, 16],\
'ignore_nan': [0, 0, 0, 0]}
dc = DataCleaner()
dc.clean(file, data_header) |
6db0d373294a30889bc58af255a044a630b001c2 | Ignl94/OOP_Challenge | /person.py | 809 | 3.9375 | 4 |
class Person:
def __init__(self, name, age, fav_color):
self.name = name
self.age = age
self.fav_color = fav_color
def say_hello(self):
print(f'Hi, my name is {self.name}')
def change_fav_color(self, new_color):
self.fav_color = new_color
class Swimmer(Person):
has_trunks = True
def __init__(self, name, age, fav_color, trunks_color="Blue"):
super().__init__(name, age, fav_color)
self.trunks_color = trunks_color
def say_hello(self):
print(f'Hi, I am {self.name}, I love swimming')
def takes_swim(self):
print(f'{self.name} is enjoying a swim.')
def change_trunks(self, new_color):
self.trunks_color = new_color
example_person = Person("Paul", 23, "Gold")
example_person.say_hello()
|
81f17c765090682ea97cc89b1ab8e078420b6149 | PARKINHYO/Algorithm | /python algorithm interview/8장 연결 리스트/Q18. 홀짝 연결 리스트.py | 938 | 3.84375 | 4 | """
fixme
https://leetcode.com/problems/odd-even-linked-list/
Q18. 홀짝 연결 리스트
연결 리스트를 홀수 노드 다음에 짝수 노드가 오도록 재구성하라. 공간 복잡도 O(1), 시간 복잡도 O(n)에 풀이하라.
입력 : 1 → 2 → 3 → 4 → 5 → NULL
출력 : 1 → 3 → 5 → 2 → 4 → NULL
입력 : 2 → 1 → 3 → 5 → 6 → 4 → 7 → NULL
출력 : 2 → 3 → 6 → 7 → 1 → 5 → 4 → NULL
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head: ListNode):
if head is None:
return None
odd = head
even = head.next
even_head = head.next
while even and even.next:
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
odd.next = even_head
return head
|
47c435abe8ff3e753a90c65615d1e9cf9c5e0759 | PARKINHYO/Algorithm | /BOJ/2675/2675.py | 274 | 3.625 | 4 | S = int(input())
R = [[x for x in input().split()] for y in range(S)]
word=""
word2=""
word3=""
for i in range(S):
word = R[i][1]
for j in range(len(word)):
word2 = word[j]*int(R[i][0])
word3+=word2
print(word3)
word3="" |
8f8e65c5ddfff031204d5d14b1dc382640fd4842 | PARKINHYO/Algorithm | /BOJ/14681/14681.py | 382 | 3.625 | 4 | import sys
input = sys.stdin.readline
class Solution:
def section(self, x: int, y: int):
if x > 0:
if y > 0:
return 1
else:
return 4
else:
if y > 0:
return 2
else:
return 3
x = int(input())
y = int(input())
print(Solution().section(x, y)) |
ee9b6ec021050ea49e7f49bd70a80872d8e0d7c6 | PARKINHYO/Algorithm | /BOJ/4344/4344.py | 564 | 3.578125 | 4 | from sys import stdin
if __name__ == '__main__':
C = int(stdin.readline())
answers = []
for i in range(0, C):
case = list(map(int, stdin.readline().split()))
sum = 0
for j in range(1, len(case)):
sum += case[j]
average = sum / case[0]
count = 0
for j in range(1, len(case)):
if average < case[j]:
count += 1
answer = float(count / case[0] * 100)
answers.append(answer)
for L in answers:
print('%.3f' % L, end="")
print("%")
|
3cd9373974ec8d9e6cf48ae07df009ae08c7467d | PARKINHYO/Algorithm | /python algorithm interview/7장 배열/Q08. 빗물 트래핑.py | 1,717 | 3.828125 | 4 | """
fixme. https://leetcode.com/problems/trapping-rain-water/
fixme. Q08. 빗물 트래핑
fixme. 높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라.
fixme. Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
fixme. Output: 6
fixme. Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
fixme. In this case, 6 units of rain water (blue section) are being trapped.
fixme. Input: height = [4,2,0,3,2,5]
fixme. Output: 9
"""
from typing import List
class Solution:
def trapTwoPointer(self, height: List[int]) -> int:
if not height:
return 0
volume = 0
left, right = 0, len(height) - 1
left_max, right_max = height[left], height[right]
while left < right:
left_max, right_max = max(left_max, height[left]), max(right_max, height[right])
if left_max <= right_max:
volume += left_max - height[left]
left += 1
else:
volume += right_max - height[right]
right -= 1
return volume
def trapStack(self, height: List[int]) -> int:
stack = []
volume = 0
for i in range(len(height)):
while stack and height[i] > height[stack[-1]]:
print(i)
top = stack.pop()
if not len(stack):
break
distance = i - stack[-1] - 1
waters = min(height[i], height[stack[-1]]) - height[top]
volume += distance * waters
stack.append(i)
print(stack)
return volume
Solution().trapStack([0,1,0,2,1,0,1,3,2,1,2,1]) |
a6be9f5148c961aa5db5db0756ee37aa7288c5c9 | PARKINHYO/Algorithm | /BOJ/11651/11651.py | 196 | 3.5 | 4 | N = int(input())
YX = []
for i in range(N):
x, y = map(int, input().split())
YX.append([y, x])
YX.sort()
for i in range(N):
print(YX[i][1], end=" ")
print(YX[i][0]) |
842e5340ebd05a930d99cfca329c1b2561b69717 | PARKINHYO/Algorithm | /BOJ/10816/10816.py | 642 | 3.5 | 4 | from typing import List
import collections
from sys import stdin
class Solution:
def numberCard2(self, N: int, cards: List[int], M: int, problems: List[int]) -> List[int]:
answer = []
counter = collections.Counter(cards)
for problem in problems:
if problem in counter:
answer.append(counter[problem])
else:
answer.append(0)
return answer
N = int(stdin.readline())
cards = list(map(int, stdin.readline().split()))
M = int(stdin.readline())
problems = list(map(int, stdin.readline().split()))
print(*Solution().numberCard2(N, cards, M, problems))
|
96f8cc0fb564055d1f19450dac272a0831d2d698 | PARKINHYO/Algorithm | /python algorithm interview/8장 연결 리스트/Q16. 두 수의 덧셈.py | 1,775 | 3.546875 | 4 | """
fixme.
https://leetcode.com/problems/reverse-linked-list/
Q16. 두 수의 덧셈
역순으로 저장된 연결 리스트의 숫자를 더하라.
입력
(2 → 4 → 3) + (5 → 6 → 4)
출력
7 → 0 → 8
"""
from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode):
node, prev = head, None
while node:
next, node.next = node.next, prev
prev, node = node, next
return prev
def toList(self, node: ListNode) -> List:
list: List = []
while node:
list.append(node.val)
node = node.next
return list
def toReversedLinkedList(self, result: str) -> ListNode:
prev: ListNode = None
for r in result:
node = ListNode(r)
node.next = prev
prev = node
return node
def addTwoNumbersChangeDataType(self, l1: ListNode, l2: ListNode) -> ListNode:
a = self.toList(self.reverseList(l1))
b = self.toList(self.reverseList(l2))
resultStr = int(''.join(str(e) for e in a)) + \
int(''.join(str(e) for e in b))
return self.toReversedLinkedList(str(resultStr))
def addTwoNumbersFulladder(self, l1: ListNode, l2: ListNode) -> ListNode:
root = head = ListNode(0)
carry = 0
while l1 or l2 or carry:
sum = 0
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
carry, val = divmod(sum + carry, 10)
head.next = ListNode(val)
head = head.next
return root.next
|
5996622953fc825a749142f8261eeb22764ba0cd | PARKINHYO/Algorithm | /BOJ/1427/1427.py | 131 | 3.828125 | 4 | number = [int(i) for i in input()]
number.sort()
number.reverse()
for i in range(len(number)):
print(number[i], end="") |
284cfbf93ef9d67e6b1dc89d7aebb6b32b65462a | PARKINHYO/Algorithm | /python algorithm interview/8장 연결 리스트/Q15. 역순 연결 리스트.py | 974 | 3.78125 | 4 | """
fixme
https://leetcode.com/problems/reverse-linked-list/
Q15. 역순 연결 리스트
연결 리스트를 뒤집어라.
입력 : 1 → 2 → 3 → 4 → 5 → NULL
출력 : 5 → 4 → 3 → 2 → 1 → NULL
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseListRecur(self, head: ListNode) -> ListNode:
def reverse(node: ListNode, prev: ListNode = None):
if not node:
return prev
next, node.next = node.next, prev
print(prev.val)
return reverse(next, node)
return reverse(head)
def reverseListList(self, head: ListNode) -> ListNode:
node, prev = head, None
while node:
next, node.next = node.next, prev
prev, node = node, next
return prev
Solution().reverseListRecur(ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))))
|
f47742566b3032e9bb543eec8ec45e556e2478e5 | PARKINHYO/Algorithm | /BOJ/2588/2588번.py | 219 | 3.515625 | 4 | def myfunc(a, b, b2):
if b2 == 0:
print(a*b)
return
print(a * (b2 % 10))
myfunc(a, b, b2//10)
if __name__ == '__main__':
n1 = int(input())
n2 = int(input())
myfunc(n1, n2, n2)
|
e2598f39a718b6908ae87bf5cf46f91329ba7891 | karan6181/AStarSearchAlgorithm | /src/heuristic.py | 6,292 | 3.921875 | 4 | """
File: heuristic.py
Language: Python 3.5.1
Author: Aravindh Kuppusamy (axk8776@g.rit.edu)
Deepak Sharma (ds5930@g.rit.edu)
Karan Jariwala (kkj1811@g.rit.edu)
Description: Various heuristic functions that returns the heuristic distance
from one state to the goal state.
"""
import copy
import math
__author__ = 'Aravindh Kuppusamy, Deepak Sharma, Karan Jariwala'
class Heuristic:
"""
The class Heuristic contains all the static methods to calculate
various heuristics.
"""
@staticmethod
def manhattan(curState, problem):
"""
The Manhattan distance heuristic for the current state.
:param curState: The current search state
:param problem: The A* search problem instance for this maze
:return: The Manhattan distance between the current's state position &
goal position
"""
# Manhattan distance is the sum of the vertical and horizontal
# distances between two points.
pos1 = curState.getPos()
pos2 = problem.getGoalPosition()
dx, dy = Heuristic.finddXdY(pos1, pos2)
return dx + dy
@staticmethod
def euclidean(curState, problem):
"""
The Euclidean distance heuristic for the current state.
:param curState: The current search state
:param problem: The A* search problem instance for this maze
:return: The Euclidean distance between the current's state position &
goal position
"""
# Euclidean distance is the distance of the straight line that
# connects two points.
pos1 = curState.getPos()
pos2 = problem.getGoalPosition()
dx, dy = Heuristic.finddXdY(pos1, pos2)
return math.sqrt(dx * dx + dy * dy)
@staticmethod
def diagonal(curState, problem):
"""
The Diagonal distance heuristic for the current state.
:param curState: The current search state
:param problem: The A* search problem instance for this maze
:return: The Diagonal distance between the current's state position &
goal position
"""
pos1 = curState.getPos()
pos2 = problem.getGoalPosition()
dx, dy = Heuristic.finddXdY(pos1, pos2)
return min(dx, dy) * math.sqrt(2) + abs(dx - dy)
@staticmethod
def finddXdY(pos1, pos2):
"""
Calculates the Horizontal and Vertical distances between two points.
:param pos1: First position
:param pos2: Second Position
:return: The Diagonal distance between the current's state position &
goal position
"""
dx = abs(pos1[0] - pos2[0])
dy = abs(pos1[1] - pos2[1])
return dx, dy
@staticmethod
def fancy_manhattan(curState, problem):
"""The fancy Manhattan distance heuristic for the current state.
:param curState: The current search state
:param problem: The A* search problem instance for this maze
:return: The Manhattan distance between the current's state position &
goal position with additional award based on success rate of
passing goal test
"""
manhattanDist = Heuristic.manhattan(curState, problem)
pos1 = curState.getPos()
pos2 = problem.getGoalPosition()
dx = (pos1[0] - pos2[0])
dy = (pos1[1] - pos2[1])
rewardA = rewardB = 0
if abs(dx) < 2 or abs(dy) < 2:
temp_dice = copy.deepcopy(curState.getDice())
if dx > 0:
for moves in range(abs(dx) % 4):
temp_dice.moveLeft()
else:
for moves in range(abs(dx) % 4):
temp_dice.moveRight()
if dy > 0:
for moves in range(abs(dy) % 4):
temp_dice.moveNorth()
else:
for moves in range(abs(dy) % 4):
temp_dice.moveSouth()
if temp_dice.top == 1:
rewardA = -.50
temp_dice = copy.deepcopy(curState.getDice())
if dy > 0:
for moves in range(abs(dy) % 4):
temp_dice.moveNorth()
else:
for moves in range(abs(dy) % 4):
temp_dice.moveSouth()
if dx > 0:
for moves in range(abs(dx) % 4):
temp_dice.moveLeft()
else:
for moves in range(abs(dx) % 4):
temp_dice.moveRight()
if temp_dice.top == 1:
rewardB = -.50
return manhattanDist + min(rewardA, rewardB)
@staticmethod
def forecast_manhattan(curState, problem):
"""The Forecast Manhattan distance heuristic for the current state.
:param curState: The current search state
:param problem: The A* search problem instance for this maze
:return: The Manhattan distance between the current's state position &
goal position with additional penalty based on success rate
of neighbour's legality.
"""
manhattanDist = Heuristic.manhattan(curState, problem)
neighbours = problem.maze.getValidNeighbors(curState.getxCoordinate(),
curState.getyCoordinate(),
curState.getDice())
validNeighbours = [neighbour for neighbour in neighbours
if neighbour[2] != 6]
totalPenalty = 0
if len(validNeighbours) == 1:
return manhattanDist + 1
# penalty = []
# for childState in validNeighbours:
# childDice = Dice(childState[2], childState[3], childState[4])
# temp = problem.maze.getValidNeighbors(childState[0], childState[1], childDice)
# validChildNeighbours = [childNeighbour for childNeighbour in temp if childNeighbour[2] != 6]
# penalty += [1 if len(validChildNeighbours) == 1 else 0]
#
# childPenalty = len([p for p in penalty if p == 1])
#
# if len(validNeighbours) == childPenalty:
# totalPenalty = 2
# else:
# totalPenalty = 1 + childPenalty * .2
return manhattanDist + totalPenalty |
8d7e16afde1e254e84e849e79bd96ab82d7cf733 | torreskatherine/08-course-grader | /course_grader.py | 595 | 3.609375 | 4 | def course_grader(test_scores):
test_avg = sum(test_scores)/len(test_scores)
if test_avg >= 70 and min(test_scores) > 50:
return("pass")
elif test_avg < 70 or min(test_scores) <= 50:
return("fail")
def main():
print(course_grader([100,75,45])) # "fail"
print(course_grader([100,70,85])) # "pass"
print(course_grader([80,60,60])) # "fail"
print(course_grader([80,80,90,30,80])) # "fail"
print(course_grader([70,70,70,70,70])) # "pass"
print(course_grader([60,80,80,70,70])) # "pass"
if __name__ == "__main__":
main()
|
bd697ef5acedaf9c3bbc127dfde88c7d4fd0feea | ottocode/archives | /seniorproject/docs/grammer/arrangeterminals.py | 3,376 | 3.65625 | 4 | ### Arrange terminals of grammar
# ========================================================================
#
# Convert my text-representation of the grammer into a data-structure that
# can be used in a program
#
# The format will be:
# G = [[symbol0, [p0], [p1], [p2]],
# [symbol1, [p0], [p1], [p2]],
# ...]
#
#
# Last Modified: 3/19/14
# Contributor(s): Nicholas Otto
##
### Create Production
# -----------------
# From a string, create a production for a symbol.
# Productions are represented as [symbol0, symbol1, ...]
# Terminals are symbols, but represented as 'terminal'
#
# params: a class containing the global parameters
# line: the line containing the production
#
# returns: A list containing the production
##
def createProduction(params, line):
if params.debug():
print "Inside createProduction"
production = line.split()
if params.debug():
print "string split is:" + str(production)
for i in range(0, len(production)):
if production[i][0] == '/':
pass#production[i] = production[i][1:]
return production
### Create Grammar Line
# -------------------
# Build an entry in the grammar.
# Entries are of the form:
# [symbol, [production0], [production1], ...]
#
# params: a class containing the global parameters
# filep: a pointer to a file object to read in the grammar line
#
# returns: A list containing a grammar entry,
# None if no more entries can be read or error.
##
def createGrammarLine(params, filep):
if params.debug():
print "Inside createGrammarLine"
newRule = []
line = filep.readline().strip()
if len(line) > 0:
newRule.append(line) #add symbol
line = filep.readline().strip()
while len(line) > 0: #stop when finished with all productions
nextProd = createProduction(params, line)
newRule.append(nextProd) #add production
line = filep.readline().strip()
return newRule
### Arrange Terminals
# -----------------
# Arrange the terminals of a grammar from text file
# Terminals in text file are formatted the following way:
# symbol0
# symbol symbol
# symbol
# /terminal
#
# where the first '/' is not significant when determining a terminal
# All terminals and symbols extend from the first character (except the '/' in
# the case of terminals) to the first whitespace
#
# params: a class containing the global parameters
# filep: The file pointer to the text file containing the grammar in text form
#
# returns: The grammar in the form:
# G = [[symbol0, [p0], [p1], [p2]],
# [symbol1, [p0], [p1], [p2]],
# ...]
##
def arrangeTerminals(params, filep):
if params.debug():
print "Inside arrange terminals"
grammar = []
newRule = createGrammarLine(params, filep)
while newRule:
if params.verbose():
print "Adding rule:"
print "\t" + str(newRule)
grammar.append(newRule)
newRule = createGrammarLine(params, filep)
return grammar
if __name__ == "__main__":
print "Testing arrangeterminals"
### Function Title
# --------------
# Description of function
#
# parameter1: description of parameter
#
# returns: what it returns
##
|
91a33d5e596304be7ad9a9191b240672981b6259 | sherkhancrs/codeSignal | /arrayChange.py | 266 | 3.578125 | 4 | def arrayChange(inputArray):
count = 0;
for i in range(len(inputArray)-1):
if inputArray[i+1]<=inputArray[i]:
while inputArray[i+1]<=inputArray[i]:
inputArray[i+1]+=1
count+=1
return count
print(arrayChange([-1000, 0, -2, 0])) |
3ce244af7bb3acd2caee5a6813f35a27a7bf775e | LambdAurora/algoprog1 | /ch3/tp3_graph.py | 2,331 | 3.609375 | 4 | import graph
from random import randrange
def black_left_column(width, height, length):
for y in range(height):
for x in range(width):
if x < length:
graph.plot(y, x)
def black_rectangle(x1, x2, y1, y2):
for y in range(y1, y2):
for x in range(x1, x2):
graph.plot(y, x)
def inverted_rectangle(width, height, x1, x2, y1, y2):
for y in range(height):
for x in range(width):
if (x < x1 or x > x2) or (y < y1 or y > y2):
graph.plot(y, x)
def get_column_number(x, column_width):
return x // column_width
def rayures_verticales(width, height, column_width):
for y in range(height):
for x in range(width):
if get_column_number(x, column_width) % 2 != 0:
graph.plot(y, x)
def damier(width, height, length):
for y in range(height):
offset = 0
if get_column_number(y, length) % 2 != 0:
offset = 1
for x in range(width):
if get_column_number(x, length) % 2 - offset != 0:
graph.plot(y, x)
def get_random_color():
random = randrange(9)
if random == 0:
return "red"
elif random == 1:
return "green"
elif random == 2:
return "blue"
elif random == 3:
return "yellow"
elif random == 4:
return "cyan"
elif random == 5:
return "magenta"
elif random == 6:
return "orange"
elif random == 7:
return "darkgrey"
elif random == 8:
return "black"
def rainbow_damier(width, height, length):
cases = []
last_column = -1
for y in range(height):
offset = 0
y_column = get_column_number(y, length)
if last_column != y_column:
cases.append([get_random_color()])
last_column = y_column
if y_column % 2 != 0:
offset = 1
for x in range(width):
x_column = get_column_number(x, length)
if x_column == len(cases[y_column]):
cases[y_column].append(get_random_color())
if x_column % 2 - offset != 0:
graph.plot(y, x, cases[y_column][x_column])
_width = 600
_height = 400
graph.ouvre_fenetre(_height, _width)
rainbow_damier(_width, _height, 50)
graph.attend_fenetre()
|
6d63273b82815d33226d51ddf224e22434bbaded | WalterVives/Project_Euler | /4_largest_palindrome_product.py | 975 | 4.15625 | 4 | """
From: projecteuler.net
Problem ID: 4
Author: Walter Vives
GitHub: https://github.com/WalterVives
Problem:
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
part1 = []
part2 = []
result = 0
for i in range(100,1000):
for j in range(100,1000):
multiplication = i * j
multiplication = list(str(multiplication))
if len(multiplication) == 6:
part1 = multiplication[0], multiplication[1], multiplication[2]
part2 = multiplication[3], multiplication[4], multiplication[5]
# Palindrome
if part1[::-1] == part2:
# List of numbers to int number
num = int("".join(multiplication))
# Add the largest palindrome product
if num > result:
# result
result = num
# Number 1
x = i
# Number 2
y = j
#print(i, "*", j, "=", result)
print(x, "*", y, "=", result) |
8b70e1a09f0fbb6a6027b3f510bf408719c2176c | mikesamuel/randos | /pyparsepy/ops.py | 7,691 | 3.90625 | 4 | """
Defines operators for python, and an operator precedence function.
"""
from lex import Token
BRACKET_PAIRS = {
'(': ')',
'[': ']',
'{': '}',
'>>>': '<<<',
}
OPEN_BRACKETS = tuple(BRACKET_PAIRS.keys())
CLOSE_BRACKETS = tuple(BRACKET_PAIRS.values())
INFIX = 'INFIX'
POSTFIX = 'POSTFIX'
PREFIX = 'PREFIX'
TOKEN = 'TOKEN'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
class Operator:
"""
Information about a programming language operator.
"""
def __init__(self, tok, kind, prec, assoc=None, followers=()):
self.tok = tok
self.kind = kind
self.prec = prec
self.assoc = kind == INFIX and (assoc or LEFT) or None
self.followers = tuple(followers)
def __str__(self):
return 'Operator(%r, %s)' % (self.tok, self.kind)
def __repr__(self):
return 'Operator(%r, %r)' % (self.tok, self.kind)
class OperatorStackElement:
"""
A parse tree node in the process of being built.
See parse.py.
"""
def __init__(self, op):
self.op = op
self.node = []
self.left = None
self.right = None
def __str__(self):
return 'OSE(%r)' % self.node
def __repr__(self):
return 'OSE(op=%r, node=%r)' % (self.op, self.node)
OPERATORS = (
Operator('else', INFIX, -4, assoc=RIGHT),
Operator('elif', INFIX, -4, assoc=RIGHT),
Operator('except', INFIX, -4, assoc=RIGHT),
Operator('finally', INFIX, -4, assoc=RIGHT),
Operator('>>>', INFIX, -3, assoc=RIGHT),
Operator('def', PREFIX, -2),
Operator('for', PREFIX, -2),
Operator('if', PREFIX, -2),
Operator('assert', PREFIX, -2),
Operator('return', PREFIX, -2),
Operator('while', PREFIX, -2),
Operator('yield', PREFIX, -2),
Operator('\n', POSTFIX, -2),
Operator(':', INFIX, -1, assoc=RIGHT),
Operator(':', PREFIX, -1),
Operator(',', INFIX, 0, assoc=RIGHT),
Operator('for', INFIX, 1, followers=('in',)),
Operator('=', INFIX, 1, assoc=RIGHT),
Operator('+=', INFIX, 1, assoc=RIGHT),
Operator('-=', INFIX, 1, assoc=RIGHT),
Operator('*=', INFIX, 1, assoc=RIGHT),
Operator('/=', INFIX, 1, assoc=RIGHT),
Operator('//=', INFIX, 1, assoc=RIGHT),
Operator('%=', INFIX, 1, assoc=RIGHT),
Operator('@=', INFIX, 1, assoc=RIGHT),
Operator('&=', INFIX, 1, assoc=RIGHT),
Operator('|=', INFIX, 1, assoc=RIGHT),
Operator('^=', INFIX, 1, assoc=RIGHT),
Operator('>>=', INFIX, 1, assoc=RIGHT),
Operator('<<=', INFIX, 1, assoc=RIGHT),
Operator('**=', INFIX, 1, assoc=RIGHT),
# Special cased below since lambda can contain commas to separate formals.
Operator('lambda', PREFIX, 2, followers=(':',)),
Operator('if', INFIX, 3, followers=('else',)),
Operator('or', INFIX, 4),
Operator('and', INFIX, 5),
Operator('not', PREFIX, 6),
Operator('in', INFIX, 7),
Operator('is', INFIX, 7),
Operator('not in', INFIX, 7),
Operator('is not', INFIX, 7),
Operator('<', INFIX, 7),
Operator('<=', INFIX, 7),
Operator('>', INFIX, 7),
Operator('>=', INFIX, 7),
Operator('==', INFIX, 7),
Operator('!=', INFIX, 7),
Operator('|', INFIX, 8),
Operator('^', INFIX, 9),
Operator('&', INFIX, 10),
Operator('<<', INFIX, 11),
Operator('>>', INFIX, 11),
Operator('+', INFIX, 12),
Operator('-', INFIX, 12),
Operator('*', INFIX, 13),
Operator('@', INFIX, 13),
Operator('/', INFIX, 13),
Operator('//', INFIX, 13),
Operator('%', INFIX, 13),
Operator('+', PREFIX, 14),
Operator('-', PREFIX, 14),
Operator('~', PREFIX, 14),
Operator('**', INFIX, 15),
Operator('await', PREFIX, 16),
Operator('[', INFIX, 17),
Operator('(', INFIX, 17),
Operator('.', INFIX, 17),
Operator('[', PREFIX, 18),
Operator('(', PREFIX, 18),
Operator('{', PREFIX, 18),
)
ROOT_OPERATOR = Operator('', PREFIX, -100)
NOT_AN_OPERATOR = Operator(None, TOKEN, 100)
def is_nullary(stack_el):
"""
True for stack elements that consist solely of a zero argument operator.
"""
return False
def open_bracket_count(stack_el, result_if_negative=None):
"""
The count of open brackets minus the count of close brackets.
If any prefix of the stack_el's nodes contains more close brackets
than open, and result_if_negative is not None, returns that.
"""
if stack_el.op.tok == 'lambda':
# Not closeable until ':' seen.
count = 1
for child in stack_el.node:
if isinstance(child, Token) and child.tok == ':':
count = 0
break
return count
if stack_el.op.tok not in OPEN_BRACKETS:
return 0
count = 0
for child in stack_el.node:
if isinstance(child, Token):
tok = child.tok
if tok in CLOSE_BRACKETS:
count -= 1
if count < 0 and result_if_negative is not None:
return result_if_negative
elif tok in OPEN_BRACKETS:
count += 1
return count
def needs_close_bracket(stack_el):
"""
A node "needs" a close bracket if it has an open bracket like '('
without a corresponding ')'.
This tests whether the count of open brackets exceeds the count
of close brackets without worrying about whether open parenthesis ('(')
pairs properly close square (']').
For example, these need a close
foo(x // An incomplete application of an infix bracket operator
[ // An incomplete prefix bracket operation
{ stmt // Another incomplete prefix bracket operation with one operand.
but these do not
foo(x)
[]
{ stmt }
[ 0 , 1 )
( ) ) // Extra closed does not need a close
"""
return open_bracket_count(stack_el) > 0
def init():
"""
Defines a scope for side-tables for operator functions.
"""
grouped_operators = {}
follower_map = {}
for operator in OPERATORS:
key = (operator.tok, operator.kind)
if key not in grouped_operators:
grouped_operators[key] = []
grouped_operators[key].append(operator)
for follower in operator.followers:
if follower not in follower_map:
follower_map[follower] = set()
follower_map[follower].add(operator)
for key in grouped_operators:
grouped_operators[key] = tuple(grouped_operators[key])
def can_nest(outer, inner):
"""
True iff the operator stack element, inner, can nest in
the operator stack element, outer.
"""
# Special case lambda to allow commas between formal parameters
if (outer.op.tok == 'lambda' and open_bracket_count(outer) > 0
and inner.op.tok == ','):
return True
if inner.op is ROOT_OPERATOR:
return False
if outer.op.tok in OPEN_BRACKETS and outer.node:
return needs_close_bracket(outer)
if outer.op.prec < inner.op.prec:
return True
if (outer.op.prec == inner.op.prec
and (outer.op.assoc != RIGHT
or inner.op.kind == INFIX and not inner.node)):
return True
return False
def lookup_operators(tok, kind):
"""
A list of operators with the given token text and kind.
"""
return grouped_operators.get((tok, kind), ())
def followed_by(tok):
"""
A maximal set of operators, o, such that tok in o.followers.
"""
return follower_map.get(tok, ())
return can_nest, lookup_operators, followed_by
can_nest, lookup_operators, followed_by = init()
|
2d97dd0bbf8811c639f5847dc792800a7f974207 | zspann/cssi-prework-string-lab | /invitation.py | 1,083 | 3.78125 | 4 |
### Challenge 1 - Percy Replacement:
def percy_replacer(string_about_percy):
return string_about_percy.replace("Percy", "Ron")
### Challenge 2 - String Interpolation:
def weasley_invitation(name,day,date,month):
return "The family of {first_name} Weasley proudly invite you to celebrate their graduation from Hogwarts on {day} the {date} of {month}. Festivities will be held at The Burrow. See you then!".format(first_name = name, day = day, date = date, month = month)
### Challenge 3 - Seating Location
def seating_location(last_name):
location = "middle section."
rear_names = ["A", "B", "C", "D", "E", "F", "G"]
if last_name[0] in rear_names:
location = "rear section."
elif last_name[0] == "W":
location = "front row."
return "You have a reserved seat in the {seat}".format(seat = location)
###Challenge 4 - All Together
### Passing only one of the two tests - not sure why?
def create_invitation(first_name, last_name, message):
return "DEAR " + first_name.upper() + ",\n" + message + "\nP.S. " + seating_location(last_name)
|
1283dcd95c34498969dcd8cba8029f6217ae1180 | larryzju/zoj | /3519.py | 495 | 3.5625 | 4 | #!/usr/bin/env python
def who_is_the_smartest_man( caocao, peoples ):
peoples = sorted( peoples )
skipped = 0
for i in range( len(peoples) ):
if caocao < peoples[i]:
caocao += 2
else:
skipped += 1
caocao += skipped
print caocao
try:
while True:
_n, caocao = map( int, raw_input().split() )
peoples = map( int, raw_input().split() )
who_is_the_smartest_man( caocao, peoples )
except EOFError:
pass
|
01d0a4d96799d6c687dbd71fac774d8eff7823be | J-Farish24/OOP-Exercises | /RetailItemClass.py | 641 | 3.515625 | 4 | #Create Retail Item class
class RetailItem:
#Intialize object with data attributes
def __init__(self, descr, inv, price):
self.__description = descr
self.__units = inv
self.__price = price
#Mutator methods
def set_descr(self, descr):
self.__description = descr
def set_inventory(self, units):
self.__units = units
def set_price(self, price):
self.__price = price
#Accessor methods
def get_descr(self):
return self.__description
def get_inventory(self):
return self.__units
def get_price(self):
return self.__price |
d77fbc93d265064a7094d64f1c8f0e4f8408ec4d | Genskill2/02-bootcamp-estimate-pi-mkarth1k | /estimate.py | 1,840 | 3.53125 | 4 | import math
import unittest
import random
def wallis(n):
pi = 0.0
for i in range(1, n):
x = 4 * (i ** 2)
y = x - 1
z = float(x) / float(y)
if (i == 1):
pi = z
else:
pi *= z
pi *= 2
return pi
class TestWallis(unittest.TestCase):
def test_low_iters(self):
for i in range(0, 5):
pi = wallis(i)
self.assertTrue(abs(pi - math.pi) > 0.15, msg=f"Estimate with just {i} iterations is {pi} which is too accurate.\n")
def test_high_iters(self):
for i in range(500, 600):
pi = wallis(i)
self.assertTrue(abs(pi - math.pi) < 0.01, msg=f"Estimate with even {i} iterations is {pi} which is not accurate enough.\n")
def monte_carlo():
total_points = 0
within_circle = 0
for i in range (10000):
x = random.random()
y = random.random()
total_points += 1
distance = math.sqrt(x**2+y**2)
if distance < 1:
within_circle += 1
if total_points % 1000 == 0:
pi_estimate = 4 * within_circle / total_points
yield pi_estimate
class TestMC(unittest.TestCase):
def test_randomness(self):
pi0 = monte_carlo(15000)
pi1 = monte_carlo(15000)
self.assertNotEqual(pi0, pi1, "Two different estimates for PI are exactly the same. This is almost impossible.")
self.assertFalse(abs(pi0 - pi1) > 0.05, "Two different estimates of PI are too different. This should not happen")
def test_accuracy(self):
for i in range(500, 600):
pi = monte_carlo(i)
self.assertTrue(abs(pi - math.pi) < 0.4, msg=f"Estimate with even {i} iterations is {pi} which is not accurate enough.\n")
if __name__ == "__main__":
unittest.main()
|
74914ed8c197d826a7c557c8a1fcd3c8e3c805aa | aryanirani6/ICS4U-Classwork | /example.py | 866 | 4.5625 | 5 | """
create a text file with word on a number of lines
1. open the text file and print out 'f.read()'. What does it look like?
2. use a for loop to print out each line individually. 'for line in f:'
3. print our words only with "m", or some other specific letter.
"""
# with open("Some_file.txt", 'r') as f:
# print(f.read())
#2
#with open("Some_file.txt", 'r') as f:
# for line in f:
# print(line)
#3 to print the line it will give skip another line for each word
#4 with open("Some_file.txt", 'r') as f:
# for line in f:
# print(line.strip())
#4 print words only with m
#with open("Some_file.txt", 'r') as f:
# for line in f:
# if line.startswith("m"):
# print(line.strip())
#5 to check for both upper case and lower case letter
#with open("Some_file.txt", 'r') as f:
# for line in f:
# if line.lower().startswith("m"):
# print(line.strip())
|
6798074572ee5e82a5da113a6ace75b4670ae00c | aryanirani6/ICS4U-Classwork | /classes/classes2.py | 2,179 | 4.375 | 4 | """
name: str
cost: int
nutrition: int
"""
class Food:
""" Food class
Attributes:
name (str): name of food
cost (int): cost of food
nutrition (int): how nutritious it is
"""
def __init__(self, name: str, cost: int, nutrition: int):
""" Create a Food object.
Args:
name: name of food
cost: cost of food
nutrition: how nutritious it is
"""
self.name = name
self.cost = cost
self.nutrition = nutrition
class Dog:
""" Thing that goes ruff
Attributes:
breed (str): The dog's breed
name (str): The dog's name
happiness (int): The dog's happiness. Defualts to 100
"""
def __init__(self, breed: str, name: str):
""" Create a dog object.
Args:
breed: The breed of the dog
name: name of the dog.
"""
self.breed = breed
self.name = name
self.happiness = 100
def __str__(self):
return f"{self.happiness}, {self.name}"
def eat(self, food: Food):
""" Gets the dog to eat food.
increases dogs happiness by 10% of food eaten
Args:
food: The food for dog to eat.
"""
happiness_increase = food.nutrition * 0.1
self.happiness += happiness_increase
def bark(self):
""" Make the dog bark
"""
print("Ruff Ruff")
sausage = Food("Polish Sausage", 10, 100)
james = Dog("Husky", "James")
print(james)
print(james.happiness)
james.eat(sausage)
print(james.happiness)
james.bark()
"""if __name__ == "__main__":
main()
"""
""" Encapsulation
Basic definition: protecting your object's attributes.
"""
class Student:
def __init__(self, name: str, age: int):
self.name = name
self._age = age
def set_age(self, age: int):
if type(age) != int:
raise ValueError("Age must be an integer")
self._age = age
def age_in_5_years(self):
return self._age + 5
def get_age(self):
return self._age
s = Student("Sally", 15)
print(s.age_in_5_years())
print(s.get_age())
|
b4544106396d01246d77056efea9318d93c2e703 | Waqas-Ali-Azhar/programming_practice | /leetcode/merge-two-binary-trees.py | 2,810 | 3.984375 | 4 | #https://leetcode.com/problems/merge-two-binary-trees/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def mergeTrees(self, t1, t2):
mergedTree = None
q = deque()
triplet = []
if (t1 is not None and t2 is not None):
mergedTree = TreeNode(t1.val + t2.val)
triplet = [mergedTree, t1, t2]
elif (t1 is not None and t2 is None):
mergedTree = TreeNode(t1.val)
triplet = [mergedTree, t1, None]
elif (t1 is None and t2 is not None):
mergedTree = TreeNode(t2.val)
triplet = [mergedTree, None, t2]
if (len(triplet) > 0):
q.appendleft(triplet)
while (len(q) > 0):
triplet = q.pop()
newTriplet = []
if (triplet[1] is not None and triplet[2] is not None and triplet[1].left is not None and triplet[2].left is not None):
triplet[0].left = TreeNode(triplet[1].left.val + triplet[2].left.val)
newTriplet = [triplet[0].left, triplet[1].left, triplet[2].left]
elif ((triplet[1] is None or triplet[1].left is None) and (triplet[2] is not None and triplet[2].left is not None)):
triplet[0].left = TreeNode(triplet[2].left.val)
newTriplet = [triplet[0].left, None, triplet[2].left]
elif ((triplet[1] is not None and triplet[1].left is not None) and (triplet[2] is None or triplet[2].left is None)):
triplet[0].left = TreeNode(triplet[1].left.val)
newTriplet = [triplet[0].left, triplet[1].left, None]
if (len(newTriplet) > 0):
q.appendleft(newTriplet);
if (triplet[1] is not None and triplet[2] is not None and triplet[1].right is not None and triplet[2].right is not None):
triplet[0].right = TreeNode(triplet[1].right.val + triplet[2].right.val)
newTriplet = [triplet[0].right, triplet[1].right, triplet[2].right]
elif ((triplet[1] is None or triplet[1].right is None) and (triplet[2] is not None and triplet[2].right is not None)):
triplet[0].right = TreeNode(triplet[2].right.val)
newTriplet = [triplet[0].right, None, triplet[2].right]
elif ((triplet[1] is not None and triplet[1].right is not None) and (triplet[2] is None or triplet[2].right is None)):
triplet[0].right = TreeNode(triplet[1].right.val)
newTriplet = [triplet[0].right, triplet[1].right, None]
if (len(newTriplet) > 0):
q.appendleft(newTriplet);
return mergedTree
|
59b42a9927270598dd784b7c9d2da1de69bb3d28 | Waqas-Ali-Azhar/programming_practice | /codejam-2018/c.py | 440 | 3.609375 | 4 | # Incorrect
def make_rectangle(A):
board = [
['.' for i in range(1001)]
for j in range(1001)
]
print("{} {}".format(2, 2))
count = 3
i = 1
j = 1
while i > 0 and j > 0:
line = raw_input()
i = int(line.split(' ')[0])
j = int(line.split(' ')[1])
print("2 {}".format(count % A))
count = count + 1
count = int(raw_input())
for i in range(count):
A = int(raw_input())
make_rectangle(A)
|
5ca14ce2e84e1375c7b3198b6e4a4661d97f3d08 | Waqas-Ali-Azhar/programming_practice | /leetcode/middle-of-the-linked-list.py | 434 | 3.78125 | 4 | # https://leetcode.com/problems/middle-of-the-linked-list/description/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head):
first = head
second = head
while second and second.next:
first = first.next
second = second.next.next
return first
|
8028b7aa23465443d7966084002034b4b8f22934 | Waqas-Ali-Azhar/programming_practice | /leetcode/path-sum-iii.py | 985 | 3.71875 | 4 | # https://leetcode.com/problems/path-sum-iii/description/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
if not root:
return 0
path_count = 0
que = deque()
que.append((root, [root.val]))
while que:
node = que.popleft()
path_count += node[1].count(sum)
if node[0].left:
new_sum = [i + node[0].left.val for i in node[1]] + [node[0].left.val]
que.append((node[0].left, new_sum))
if node[0].right:
new_sum = [i + node[0].right.val for i in node[1]] + [node[0].right.val]
que.append((node[0].right, new_sum))
return path_count
|
c97104bba975c895bb153b100344ba8da1cd169a | Waqas-Ali-Azhar/programming_practice | /leetcode/keyboard-row.py | 623 | 3.578125 | 4 | #https://leetcode.com/problems/keyboard-row/
class Solution(object):
def findWords(self, words):
keyboard = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
op = []
for word in words:
if (word == ""):
op.append(word)
else:
valid = 1
for line in keyboard:
if (word[0].lower() in line):
for char in word:
if (not char.lower() in line):
valid = 0
if valid == 1:
op.append(word)
return op
|
9655d39628d7f2f93f9b77c9d9732af8ffc84bc4 | Waqas-Ali-Azhar/programming_practice | /leetcode/average-of-levels-in-binary-tree.py | 1,080 | 3.6875 | 4 | # https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
from statistics import mean
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
queue = deque()
levels = []
queue.append((root, 0))
while queue:
node_tuple = queue.popleft()
if node_tuple[0]:
if node_tuple[0].left:
queue.append((node_tuple[0].left, node_tuple[1] + 1))
if node_tuple[0].right:
queue.append((node_tuple[0].right, node_tuple[1] + 1))
if len(levels) > node_tuple[1]:
levels[node_tuple[1]].append(node_tuple[0].val)
else:
levels.append([node_tuple[0].val])
return [mean(level) for level in levels]
|
7416e1c946d17374332e7e4ebabb09eb159aaa97 | GribaHub/Python | /exercise15.py | 967 | 4.5 | 4 | # https://www.practicepython.org/
# PRACTICE PYTHON
# Beginner Python exercises
# Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
# clear shell
def cls():
print(50 * "\n")
# backwards order (loop)
def backwards(text):
result=text.split(" ")
lnth=len(result)
j=range(lnth)
text=[]
for i in j:
text.append(result[lnth-i-1])
result=[]
result=" ".join(text)
return(result)
# backwards order (reverse)
def backwards2(text):
result=text.split(" ")
result.reverse()
result=" ".join(result)
return(result)
# main program
cls()
print("Words in backwards order:",backwards(input("Enter a string containing multiple words: ")))
print()
print("Words in backwards order:",backwards2(input("Enter a string containing multiple words: ")))
|
c7d358369e2cebfb0bb62b58f6e3affc637675cc | GribaHub/Python | /exercise08.py | 2,137 | 4.09375 | 4 | # https://www.practicepython.org/
# PRACTICE PYTHON
# Beginner Python exercises
# Rock Paper Scissors
# Make a two-player Rock-Paper-Scissors game.
# Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game.
# Rock beats scissors
# Scissors beats paper
# Paper beats rock
# clear shell
def cls():
print(50 * "\n")
# player choice
def player_choice(player):
print("Player " + str(player) + ", what is your choice?")
for i in range(0, len(tab)):
print(str(i) + " - " + tab[i])
choice=-1
while choice not in ["0","1","2"]:
choice=input("Enter 0, 1 or 2: ")
print("\n")
return(choice)
# checking who is the winner
def check(pl1,pl2):
if pl1==pl2:
print("Nobody win!")
elif pl1-pl2==-1 or pl1-pl2==2:
print("Player 1 win, because " + tab[pl1] + " beats " + tab[pl2] + "!")
else:
print("Player 2 win, because " + tab[pl2] + " beats " + tab[pl1] + "!")
# one players game
def one_player():
player1=int(player_choice(1))
player2=random.randint(0,2)
print("Player1: ",tab[player1])
print("Player2 (computer): ",tab[player2])
check(player1,player2)
# two players game
def two_players():
player1=int(player_choice(1))
player2=int(player_choice(2))
print("Player 1: ",tab[player1])
print("Player 2: ",tab[player2])
check(player1,player2)
# main program
import random
tab=["paper", "rock", "scissors"]
new_game="y"
while new_game=="y":
cls()
print("Choose game mode.")
print("1 - one player game")
print("2 - two players game")
game_type=0
while game_type not in ["1","2"]:
game_type=input("Enter 1 or 2: ")
print("\n")
if game_type=="2":
two_players()
else:
one_player()
print("\n")
new_game=""
while new_game!="y" and new_game!="n":
new_game=input("Do you want to start a new game? (y/n)")
cls()
|
2c34d6968fe8ad668b7c8d443de19b381d45cba9 | GribaHub/Python | /exercise18.py | 2,915 | 3.96875 | 4 | # https://www.practicepython.org/
# PRACTICE PYTHON
# Beginner Python exercises
# Create a program that will play the “cows and bulls” game with the user. The game works like this:
# Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
# For every digit that the user guessed correctly in the correct place, they have a “cow”.
# For every digit the user guessed correctly in the wrong place is a “bull”.
# Every time the user makes a guess, tell them how many “cows” and “bulls” they have.
# Once the user guesses the correct number, the game is over.
# Keep track of the number of guesses the user makes throughout teh game and tell the user at the end.
import random
# clear shell
def cls():
print(50 * "\n")
# the game
def game(nr):
# checking if user input number and the number is in (1000-9999)
unr = 1
while (unr < 1000) or (unr > 9999):
unrtxt = input("Give me a 4-digit number (1000-9999) or press enter for quit: ")
if unrtxt == "": break
unr = 1
for i in unrtxt:
if i not in ch: unr = 0
if unr != 0: unr = int(unrtxt)
# counting cows and bulls
if unrtxt != "":
nrtemp=[]
for i in range(4): nrtemp.append(nr[i])
cows = 0
for i in range(0,4):
if nrtemp[i] == unrtxt[i]:
cows = cows + 1
nrtemp[i] = "x"
bulls=0
for i in range(0,4):
for j in range(0,4):
if nrtemp[i] == unrtxt[j]:
nrtemp[i] = "x"
bulls = bulls + 1
print("Cows:",cows)
print("Bulls:",bulls)
print()
# checking if user win
if cows == 4:
print("************\n* You win! *\n************\n")
print("Number of guesses:", itr)
unrtxt=""
else: print("\nThe number was:","".join(nr))
return unrtxt
# generating number (1000-9999) with different digits
def gen1():
nrg = []
nrg.append(str(random.randint(1,9)))
while len(nrg) < 4:
rnd=str(random.randint(0,9))
if rnd not in nrg: nrg.append(rnd)
# print(nrg)
return(nrg)
# generating number (1000-9999) (possible same digits)
def gen2():
nrg = []
nrg.append(str(random.randint(1,9)))
for i in range(3): nrg.append(str(random.randint(0,9)))
# print(nrg)
return(nrg)
# main program
cls()
print('For every digit that the user guessed correctly in the correct place, they have a “cow”.')
print('For every digit the user guessed correctly in the wrong place is a “bull".\n')
# preparing global variable 'ch' with digits as string
ch = []
for i in range(10):
ch.append(str(i))
nrgn = gen1()
itr = 1
while game(nrgn) != "": itr += 1
|
dca9c5f3548711b16c7736adc0588fff766c95a1 | kirubakaran28/Python-codes | /valid palindrome.py | 359 | 4.15625 | 4 | import re
def isPalindrome(s):
s = s.lower()
#removes anything that is not a alphabet or number
s = re.sub('[^a-z0-9]','',s)
#checks for palindrome
if s == s[::-1]:
return True
else:
return False
s = str(input("Enter the string: "))
print(isPalindrome(s)) |
97a07ff8610f9950da31b1891698fd8b4514b1aa | agchen92/CIAfactbook | /CIAfactbook.py | 2,209 | 4.125 | 4 | #This project, I will be working with the data from the CIA World
#Factbook, which is a compendium of statistics about all of the
#countries on Earth. This Factbook contains demographic information
#and can serve as an excellent way to practice SQL queries in
#conjunction with the capabilities of Python.
import pandas as pd
import sqlite3
#Making a connection to database.
conn = sqlite3.connect("factbook.db")
cursor = conn.cursor()
#Lets run a query that returns the first 5 rows of the facts
#table in the databaseto see how how the table looks like.
q1 = "SELECT * FROM sqlite_master WHERE type='table';"
pd.read_sql_query(q1, conn)
cursor.execute(q1).fetchall()
#Now that we know that the facts table looks like. Lets run a few
#queries to gain some data insights.
q2 = '''SELECT * FROM facts LIMIT 5'''
pd.read_sql_query(q2, conn)
q3 = '''
SELECT min(population) min_pop, max(population) max_pop,
min(population_growth) min_pop_grwth, max(population_growth) max_pop_grwth
FROM facts
'''
pd.read_sql_query(q3, conn)
q4 = '''
SELECT *
FROM facts
WHERE population == (SELECT max(population) FROM facts);
'''
pd.read_sql_query(q4, conn)
q5 = '''
SELECT *
FROM facts
WHERE population == (SELECT min(population) FROM facts);
'''
pd.read_sql_query(q5, conn)
#Now that we have gained some insight regarding the data
#let's try to create some visualization to better present our findings
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
q6 = '''
SELECT population, population_growth, birth_rate, death_rate
FROM facts
WHERE population != (SELECT max(population) FROM facts)
and population != (SELECT min(population) FROM facts);
'''
pd.read_sql_query(q6, conn).hist(ax=ax)
#Let's try to find which countries have the highest population.
q7 = '''SELECT name, CAST(population as float)/CAST(area as float) density
FROM facts
ORDER BY density DESC
LIMIT 20'''
pd.read_sql_query(q7, conn)
q7 = '''SELECT population, population_growth, birth_rate, death_rate
FROM facts
WHERE population != (SELECT max(population) FROM facts)
and population != (SELECT min(population) FROm facts);
'''
pd.read_sql_query(q7, conn) |
e1eba3ab225876a640cbe819447de603c0ff7727 | lu-jeremy/Python | /tkin/classquiz.py | 7,576 | 3.703125 | 4 | import tkinter
# quiz of five, show results at end
class quiz():
def __init__(self):
self.root = tkinter.Tk()
self.root.title('quiz')
self.frame1 = tkinter.Frame(self.root)
self.frame2 = tkinter.Frame(self.root)
self.frame3 = tkinter.Frame(self.root)
self.frame4 = tkinter.Frame(self.root)
self.frame5 = tkinter.Frame(self.root)
self.frame6 = tkinter.Frame(self.root)
self.score = 0
self.question_num = 1
self.q1()
def evaluation(self):
if self.question_num ==1:
if self.four.get() == 1:
self.score+=1
if self.one.get() == 1 and self.two.get() ==1 and self.three.get()==1:
self.score+=1
#forgetting frame will forget all of the other widgets in the frame
self.frame1.grid_forget()
print(self.score)
self.q2()
elif self.question_num==2:
var = self.u_answer.get(1.0,tkinter.END)
if 'soul' in var and 'study' in var and 'identity' in var and 'analogy' in var:
self.score+=1
self.frame2.grid_forget()
self.q3()
elif self.question_num ==3:
if self.two.get() ==2:
self.score+=1
self.frame3.grid_forget()
self.q4()
elif self.question_num ==4:
if self.entry.get() == 'Pneumonoultramicroscopicsilicovolcanoconiosis':
self.score+=1
self.frame4.grid_forget()
self.q5()
elif self.question_num ==5 :
if self.entry.get() == '(-b +-√(b^2-4ac))/2a':
self.score+=1
self.frame5.grid_forget()
self.result()
def q2(self):
self.question_num = 2
self.question = tkinter.Message(self.frame2, width = 800,text = 'Write reasons why the soul is not real. Explain in detail.')
self.u_answer = tkinter.Text(self.frame2)
self.f_score = tkinter.Label(self.frame2, text = 'Score:%s'%self.score)
self.next_q = tkinter.Button(self.frame2, text = 'Next Question ->', command = self.evaluation)
self.next_q.grid(row = 5, column = 0,sticky = 'E')
self.f_score.grid(row = 6, column = 0,sticky = 'E')
self.question.grid(row = 0, column = 0)
self.u_answer.grid(row = 1, column = 0)
self.frame2.grid(row = 0, column = 0)
def q3(self):
self.question_num = 3
self.question = tkinter.Message(self.frame3, bg = 'orange', width = 800, text = 'Pineapples grow on trees')
self.true = tkinter.Checkbutton(self.frame3, text = 'True', onvalue = 2, offvalue = 1,variable = self.one)
self.false = tkinter.Checkbutton(self.frame3, text = 'False', onvalue = 2, offvalue = 1, variable = self.two)
self.next_q = tkinter.Button(self.frame3, text = 'Next Question ->',command = self.evaluation)
self.f_score = tkinter.Label(self.frame3, text = 'Score:%s'%self.score)
self.question.grid(row = 0, column = 0)
self.true.grid(row = 1, column = 0, sticky = 'W')
self.false.grid(row =2 , column = 0, sticky = 'W')
self.next_q.grid(row = 3, column = 0, sticky = 'W')
self.f_score.grid(row = 4, column = 0,sticky = 'E')
self.frame3.grid(row =0, column = 0)
def q4(self):
self.question_num = 4
self.question = tkinter.Message(self.frame4, width = 800, text = 'The longest word in the dictionary is')
self.entry = tkinter.Entry(self.frame4)
self.f_score = tkinter.Label(self.frame4, text = 'Score:%s'%self.score)
self.next_q = tkinter.Button(self.frame4, text = 'Next Question ->', command = self.evaluation)
self.question.grid(row = 0, column = 0, sticky = 'W')
self.entry.grid(row = 0, column = 1, sticky = 'W')
self.next_q.grid(row = 1, column = 0,sticky = 'W')
self.f_score.grid(row = 2, column = 0,sticky = 'E')
self.frame4.grid(row = 0, column = 0)
def q5(self):
self.question_num = 5
self.question = tkinter.Message(self.frame5, width = 800, text = 'What is the Quadratic Formula?')
self.entry = tkinter.Entry(self.frame5)
self.f_score = tkinter.Label(self.frame5, text = 'Score:%s'%self.score)
self.next_q = tkinter.Button(self.frame5, text = 'Next Question ->', command = self.evaluation)
self.question.grid(row = 0, column = 0, sticky = 'W')
self.entry.grid(row = 1, column = 0, sticky= 'W')
self.f_score.grid(row = 3, column = 0, sticky = 'E')
self.next_q.grid(row = 2, column = 0, sticky = 'W')
self.frame5.grid(row = 0, column = 0)
def result(self):
self.question_num = 6
self.question_one = tkinter.Message(self.frame6, width = 800, text = 'The answer to question one is: All of the above')
self.question_two = tkinter.Message(self.frame6, width = 800, text = 'The answer to question two is correct if you included soul, identity, analogy, and study in your answer.')
self.question_three = tkinter.Message(self.frame6, width = 800, text = 'The answer to question three is: False')
self.question_four = tkinter.Message(self.frame6, width = 800, text = 'The answer to question four is: Pneumonoultramicroscopicsilicovolcanoconiosis')
self.question_five = tkinter.Message(self.frame6, width = 800, text = 'The answer to question five is: (-b +-√(b^2-4ac))/2a')
self.r = tkinter.Message(self.frame6, width = 800, text = 'And your final score is:%s'%self.score)
self.question_one.grid(row = 0, column = 0, sticky = 'W')
self.question_two.grid(row = 1, column = 0, sticky = 'W')
self.question_three.grid(row = 2, column = 0, sticky = 'W')
self.question_four.grid(row = 3, column = 0, sticky = 'W')
self.question_five.grid(row = 4, column = 0, sticky = 'W')
self.r.grid(row =5, column = 0, sticky = 'W')
self.frame6.grid(row = 0, column = 0)
def q1(self):
self.one = tkinter.IntVar()
self.two = tkinter.IntVar()
self.three = tkinter.IntVar()
self.four = tkinter.IntVar()
self.multiple_choice = tkinter.Message(self.frame1,bg = 'yellow',width = 800,text = 'If the zero of a polynomial function is 3-2i, then what is for certain another answer to this function?')
self.w_1 = tkinter.Checkbutton(self.frame1,text = '3+2i',onvalue = 1, offvalue = 0,variable = self.one)
self.w_2 = tkinter.Checkbutton(self.frame1,text = 'Its conjugate',onvalue = 1, offvalue = 0,variable = self.two)
self.w_3 = tkinter.Checkbutton(self.frame1,text = '(6+3i)-(3+i)',onvalue = 1, offvalue = 0, variable = self.three)
self.correct = tkinter.Checkbutton(self.frame1,text = 'All of the above',onvalue = 1, offvalue = 0, variable = self.four)
self.next_q = tkinter.Button(self.frame1, text = 'Next Question ->',command = self.evaluation)
self.f_score = tkinter.Label(self.frame1,text = 'Score:%s'%self.score)
self.multiple_choice.grid(row = 0, column = 0)
self.w_1.grid(row = 1, column = 0,sticky = 'W')
self.w_2.grid(row = 2, column = 0,sticky = 'W')
self.w_3.grid(row = 3, column = 0,sticky = 'W')
self.correct.grid(row = 4, column = 0,sticky = 'W')
self.next_q.grid(row = 5, column = 0,sticky = 'E')
self.f_score.grid(row = 6, column = 0, sticky = 'E')
self.frame1.grid(row = 0, column = 0)
def run(self):
self.root.mainloop()
q = quiz()
q.run()
|
b6f7f8d847619f22f33a7ce8b620eee712de2d20 | lu-jeremy/Python | /tkin/tkinterset1part7.py | 1,887 | 3.59375 | 4 | import tkinter
from tkinter import messagebox
import random
#images
root = tkinter.Tk()
root.title('3')
#root.geometry('400x400')
heads_img = tkinter.PhotoImage(file = "heads_coin.gif")
"""
panel = tkinter.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
"""
tails_img = tkinter.PhotoImage(file = "tails_coin.gif")
"""
panel = tkinter.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
"""
sides = ['Heads','Tails']
count = 0
score = 0
choice = random.choice(sides)
def t_choose():
global choice
global count
global score
tails = 'Tails'
if choice == tails:
tkinter.messagebox.showinfo('MESSAGE','You guessed RIGHT.')
score +=1
f_score['text'] = 'Score:'+str(score)
else:
tkinter.messagebox.showinfo('MESSAGE','You guessed WRONG.')
tails = tkinter.Button(root,text = 'Tails')
count+=1
choice = random.choice(sides)
def h_choose():
global count
global choice
global score
heads = 'Heads'
if choice == heads:
tkinter.messagebox.showinfo('MESSAGE','You guessed RIGHT.')
score += 1
f_score['text'] = 'Score:'+str(score)
else:
tkinter.messagebox.showinfo('MESSAGE','You guessed WRONG.')
heads = tkinter.Button(root,text = 'Heqds')
count+=1
choice = random.choice(sides)
tails = tkinter.Button(root, image = tails_img,command = t_choose)
heads = tkinter.Button(root, image = heads_img, command = h_choose)
real_choice = tkinter.Label(root, text = '')
f_score = tkinter.Label(root, text = 'Score:%s'%score)
heads.grid(column = 0, row = 0)
tails.grid(column = 0, row = 1)
real_choice.grid(column = 1, row = 0)
f_score.grid(column = 2, row = 0)
while True:
if count == 10:
score = 0
f_score['text'] = 'Score:%s'%score
root.update()
root.mainloop()
|
34a62cc6c91a41b745d0096fd13e365a43614131 | lu-jeremy/Python | /opencvcode/changingcolorspaces.py | 1,413 | 3.546875 | 4 | import cv2
#more efficient way of storing the information of rows and columns;store images
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
#frame (stored in frame) and whether it was successful or not (stored in underscore variable)
_, frame = cap.read()
# Convert BGR to HSV (hue saturated value)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([45,100,50]) # lowest blue color you want to detect
#everything between these two colors will be visible, everything else will not be
upper_blue = np.array([75,255,255]) # highest blue color you want to detect
# Threshold the HSV image to get only blue colors
#lower and upper blue range are used to set the 1's or white in the mask, everything else is set to 0
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# Bitwise-AND mask and original image
#result multiplies image; makes all xof the colors other than blue 0, and puts on the frame (destination)
res = cv2.bitwise_and(frame,frame,mask=mask)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
"""
>>> green = np.uint8([[[0,255,0 ]]])
>>> hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
>>> print hsv_green
add 10 to 60 and subtract 10 from 60
[[[ 60 255 255]]]"""
|
beb8400199329bb65c1b2dc92824cb15e68070a9 | lu-jeremy/Python | /python_exercises/Basic/youngwonksfibonacci.py | 443 | 3.734375 | 4 | def fibbonaci(n):
if n==0:
return [0]
if n==1:
return [0,1]
numbers=[0,1]
count=2
while count<n:
numbers.append(numbers[count-2]+numbers[count-1])
print(numbers[count-2]+numbers[count-1])
count=count+1
return numbers
var=fibbonaci(20)
print(var)
def fib(n):
if n==0:
return 0
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
var=fib(20)
print(var)
|
955cf5b2dc8d55bfb665114eca05da3438f3fa06 | yogi-katewa/Core-Python-Training | /Exercises/Daxita/FlowControl/reverse.py | 552 | 3.6875 | 4 | # string = raw_input("Enter list: ")
# list1 = list(string)
# temp = list1[0]
# list1[0] = list1[-1]
# list1[-1] = temp
# print "".join(list1[::-1])
n=input("How much number you want enter in 1st list: ")
list1=[]
for i in range(0,n):
a=raw_input("Enter element of 1st list: ")
list1.append(a)
# list1 = ["abcd","xyzw","jbjh","jkb"]
list2 = []
l=len(list1)
i=0
for i in range(0,l):
ans = list1[i]
a = list(ans)
temp = a[0]
a[0] = a[-1]
a[-1] = temp
x="".join(a)
list2.append(x)
i=i+1
print "Final list= ",list2 |
da6be4168e77e38aaa9e59515443bbaf9fa2c6ed | yogi-katewa/Core-Python-Training | /Exercises/Urvi/Flow and Control/p2.py | 166 | 3.65625 | 4 | name= input("Enter name:")
print (name)
m=list(name)
n=m[0]
#print (n)
#print (m)
x=len(m)
for i in range(1,x):
if(m[i]==n):
m[i]='$'
print ("".join(m))
|
34cf749145c20342b57bb30aaae55fbee8e00fc8 | yogi-katewa/Core-Python-Training | /Exercises/Deepak/Class and Object/p5.py | 395 | 3.6875 | 4 | class Student:
def __init__(self):
self.final = []
self.final = "".join(x for x in input("Enter Data : ")).split()
self.final1 = []
#print (self.final)
def print_data(self):
for i in range(0,len(self.final)-1,2):
self.final1.append([self.final[i],self.final[i+1]])
print(sorted(self.final1))
obj = Student()
obj.print_data()
|
cf7b552198679afbf41302a57fb3d1f7abe82cd2 | yogi-katewa/Core-Python-Training | /Exercises/Daxita/Collection&iterator/anagrams.py | 187 | 4.0625 | 4 | s = str(input('Enter string:'))
word=sorted(s)
alternatives = (list(str(ar) for ar in input('Enter string: ').split()))
for a in alternatives:
if word == sorted(a):
print (a)
|
770d009101a59d9c5d18661e88a25be0c6a28a4f | yogi-katewa/Core-Python-Training | /Exercises/Daxita/Class & Object/circle.py | 448 | 3.96875 | 4 | import math
class Circle:
def __init__(self,radius):
self.radius=radius
def area(self,radius):
self.radius=radius
a=math.pi*self.radius**2
return a
def parimeter(self,radius):
self.radius=radius
p=2*math.pi*self.radius
return p
r=int(input('Enter the radius of circle: '))
c=Circle(r)
area=c.area(r)
print('\nCircle Area is: {:0.2f}'.format(area))
parimeter=c.parimeter(r)
print('\nCircle Perimeter is: {:0.2f}'.format(parimeter)) |
dbb2e9c586952161a0dbfc60a5fc79908440938f | yogi-katewa/Core-Python-Training | /Exercises/Daxita/FlowControl/paramgram.py | 296 | 3.734375 | 4 | flist=[]
str1=raw_input("Enter any sentence for find paramgram or not..")
str2=str1.split(' ')
print str2
str3=''.join(str2)
print str3
str4=list(str3)
print str4
for i in str4:
if i not in flist:
flist.append(i)
print flist
l=len(flist)
if l == 26:
print "pangram"
else:
print "not pangram" |
f1673b7cdc71e508b92e646451d85a7202455c62 | yogi-katewa/Core-Python-Training | /Exercises/Urvi/class and Object/parent.py | 342 | 3.90625 | 4 | from abc import ABCMeta, abstractmethod
class Polygone:
__metaclass__ = ABCMeta
def __init__(self):
self.n = int(input("Enter the number of sides"))
self.list_size = [int(a) for a in input('Enter size of sides: ').split()]
@abstractmethod
def compute_Area(self):
"""Abstract method"""
return
|
4fc94027ff82cdb4e33ecb1d5a14d6a98b00de28 | kevinaloys/Kpython | /WebAnalytics/Prediction.py | 1,363 | 4.09375 | 4 | # Prediction
# Every week the number of unique visitors grows with 7% compared to the previous week.
# Giving an integer number N representing the number of unique visitors at the end of this week and an integer number W
# Your task is to
# write a function that prints to the standard output (stdout) the number of unique visitors we are going to have after W weeks
# please round the final result downwards to the nearest integer (e.g both 7.1 and 7.9 are rounded to 7)
# Note that your function will receive the following arguments:
# n
# which is an integer representing the number N described above
# w
# which is an integer representing the number W described above
# Data constraints
# the value for N will not exceed 10000
# the value for W will not exceed 50
# Example
# Input Output
# n: 10
# w: 3
# 12
# n: 40
# w: 1
# 42
__author__="Kevin Aloysius"
def compute_prediction(n,w):
visitor=n
# n is the number of unique visitors and w is the week,
# the following code predicts the number of unique visitors after w weeks if the
# traffic of unique visitors increases every week by 7%
for i in range(w):
n = n + n*0.07
final = int(round(n))
print "Given the Unique Visitors ",visitor," unique visitors after week ",w," will be ",final
compute_prediction(40,1)
|
45848f3c302f10ff1eb1e48363f4564253f02aa5 | kevinaloys/Kpython | /make_even_index_less_than_odd.py | 502 | 4.28125 | 4 | # Change an array, such that the indices of even numbers is less than that of odd numbers,
# Algorithnms Midterm 2 test question
def even_index(array):
index = []
for i in range(len(array)):
if(array[i]%2==1):
index.append(i) #Append the index of odd number to the end of the list 'index'
else:
index.insert(0,i) #Append the index of even number at the beginning of the list 'index'
for i in index:
print array[i],
a = [9,15,1,7,191,13,139,239,785,127,8786]
even_index(a) |
bf94c8922a49d0e1c39bd4b7d0a1155c49dff54c | kevinaloys/Kpython | /k_largest.py | 463 | 4.1875 | 4 | # Finding the k largest number in an array
# This is the Bubble Sort Variation
# Will be posting selection sort variation soon..
def k_largest(k,array):
for i in range(0,len(array)-1):
for j in range(0,len(array)-1):
if (array[j] < array[j+1]):
temp = array[j+1]
array[j+1] = array[j]
array[j] = temp
print "The",k,"largest numbers are"
for i in range(k):
print array[i]
a = [654,5487,546878,5,8,25,15,45,65,75,41,23,29]
k_largest(5,a)
|
c7e52c8a090a63d1d7de0a9993f663e993710bb5 | kevinaloys/Kpython | /WebAnalytics/Growth.py | 873 | 4.03125 | 4 | #coding: utf-8
# Growth
# Given two integer numbers d1 and d2 representing the unique visitors on a website on the first and second day since launch
# Your task is to
# write a function that prints to the standard output (stdout) the word:
# "Increase" if the number of unique visitors is higher or at least equal with the ones in the first day
# "Decrease" otherwise
# Note that your function will receive the following arguments:
# d1
# which is an integer representing the number of unique visitors for the first day
# d2
# which is an integer representing the number of unique visitors for the second day
# Data constraints
# the integer numbers will be in the [0 .. 1,000,000] range
__author__="Kevin Aloysius"
def check_growth(d1,d2):
if(d1>d2):
print "Decrease"
else:
print "Increase"
check_growth(4000,1000) |
73a55e71d28e290517f5a9e73d99052473d03f52 | talhaibnmahmud/Codeforces | /Python/In Search of an Easy Problem.py | 237 | 3.5 | 4 | """Codeforces problem 1030A "In Search of an Easy Problem"
"""
if __name__ == "__main__":
n = int(input())
answers = [int(x) for x in input().split()]
if any(answers):
print("HARD")
else:
print("EASY")
|
e25033a3260e03a93fdc9824780b942919d17393 | talhaibnmahmud/Codeforces | /Python/Hulk.py | 343 | 3.828125 | 4 | """Codeforces problem 705A - Hulk
"""
if __name__ == "__main__":
n = int(input())
FIRST_PHRASE = "I hate that "
SECOND_PHRASE = "I love that "
result = ""
for i in range(1, n + 1):
if i % 2 == 1:
result += FIRST_PHRASE
else:
result += SECOND_PHRASE
print(result[:-6], "it")
|
848895db1c5682788f09bd4902eb0c0e0d1b514c | AnnaVitry/python | /calculator.py | 3,121 | 3.953125 | 4 | #!/usr/bin/env python3
from tkinter import *
import math
window = Tk()
calc_input = ""
result = 0
def input_key(value):
global calc_input
if is_number(value) == False and float(result_text.get()) != 0:
calc_input = result_text.get()
calc_input += value
calc_input_text.set(calc_input)
def equal(operator):
global calc_input
if operator == "√":
result = str(eval("math.sqrt({})".format(calc_input)))
elif operator == "²":
float_calc_input = float(calc_input)
result = float_calc_input*float_calc_input
elif operator == "!" and calc_input.isnumeric():
int_calc_input = int(calc_input)
result = 1
while(int_calc_input > 0):
result *= int_calc_input
int_calc_input-=1
else:
result = str(eval(calc_input))
result_text.set(result)
def clear():
global calc_input
calc_input = ""
result = 0
result_text.set(result)
calc_input = ""
calc_input_text.set(calc_input)
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
Button(window, text=" clear ", command=lambda: clear()).grid(row=0, column=0)
Button(window, text=" close ", command=window.quit).grid(row=0, column=4)
Button(window, text=" 0 ", command=lambda: input_key("0")).grid(row=6, column=0)
Button(window, text=" 1 ", command=lambda: input_key("1")).grid(row=5, column=0)
Button(window, text=" 2 ", command=lambda: input_key("2")).grid(row=5, column=1)
Button(window, text=" 3 ", command=lambda: input_key("3")).grid(row=5, column=2)
Button(window, text=" 4 ", command=lambda: input_key("4")).grid(row=4, column=0)
Button(window, text=" 5 ", command=lambda: input_key("5")).grid(row=4, column=1)
Button(window, text=" 6 ", command=lambda: input_key("6")).grid(row=4, column=2)
Button(window, text=" 7 ", command=lambda: input_key("7")).grid(row=3, column=0)
Button(window, text=" 8 ", command=lambda: input_key("8")).grid(row=3, column=1)
Button(window, text=" 9 ", command=lambda: input_key("9")).grid(row=3, column=2)
Button(window, text=" + ", command=lambda: input_key("+")).grid(row=3, column=3)
Button(window, text=" - ", command=lambda: input_key("-")).grid(row=4, column=3)
Button(window, text=" * ", command=lambda: input_key("*")).grid(row=5, column=3)
Button(window, text=" / ", command=lambda: input_key("/")).grid(row=6, column=3)
Button(window, text=" . ", command=lambda: input_key(".")).grid(row=6, column=1)
Button(window, text=" % ", command=lambda: input_key("%")).grid(row=3, column=4)
Button(window, text=" ! ", command=lambda: equal("!")).grid(row=4, column=4)
Button(window, text=" √ ", command=lambda: equal("√")).grid(row=5, column=4)
Button(window, text=" ² ", command=lambda: equal("²")).grid(row=6, column=4)
Button(window, text=" = ", command=lambda: equal("=")).grid(row=6, column=2)
calc_input_text = StringVar()
Label(window, textvariable=calc_input_text).grid(row=1, column=0)
result_text = StringVar()
Label(window, textvariable=result_text).grid(row=2, column=0)
result_text.set(result)
window.mainloop() |
e6b0c382b6e3772efccebbb9fb4bf52641e1e5c4 | Yogessh3/Product-Companies | /delete_middle.py | 1,021 | 3.875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.head=None
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert(self,data):
if(self.head is None):
new_node=Node(data)
self.head=new_node
else:
new_node=Node(data)
curr=self.head
while(curr.next):
curr=curr.next
curr.next=new_node
def delete_middle(self):
curr=self.head
count=0
while(curr):
count+=1
curr=curr.next
middle=count//2
count=1
curr=self.head
while(count<middle):
curr=curr.next
count+=1
curr.next=curr.next.next
def print_list(self):
curr=self.head
while(curr):
print(curr.data,end=" ")
curr=curr.next
l=LinkedList()
num=[int(x) for x in input().split()]
for i in num:
l.insert(i)
l.delete_middle()
l.print_list()
|
900c930e7e598329b21b3d329e117e6e394a005b | SarinSwift/Graph-Challenges | /challenge_5.py | 4,801 | 4.15625 | 4 | import sys
class Vertex:
def __init__(self, v_name):
self.name = v_name
self.neighbors = {} # key: neigbor vertex object, value: weight of connecting edge
self.parent = None
def add_neighbor(self, v, w=0):
'''Given input is already a vertex object.
v: the connecting neighbor, w: the weight
'''
if v not in self.neighbors:
self.neighbors[v] = w
def __str__(self):
"""Output the list of neighbors of this vertex."""
return f"{self.name} adjacent to {[x.name for x in self.neighbors]}"
def get_neighbors(self):
"""Return the neighbors of this vertex."""
return self.neighbors.keys()
def get_edge_weight(self, vertex):
"""Return the weight of this connecting edge between self and the given vertex object."""
return self.neighbors[vertex]
class Graph:
vertices = {} # key: vertex name, value: vertex object
num_vertices = 0 # total count of vertices in the graph
edges = {}
num_edges = 0
def add_vertex(self, name):
'''Given input is the name of the vertex'''
self.num_vertices += 1
self.vertices[name] = Vertex(name)
return self.vertices[name]
def add_edge(self, name1, name2, cost=0):
# insert the new vertex of object1 if not yet in the graph
if name1 not in self.vertices:
self.add_vertex(name1)
# insert the new vertex of object2 if not yet in the graph
if name2 not in self.vertices:
self.add_vertex(name2)
# now we're sure there are both vertices in the graph, we can add negihbors to both
object1 = self.vertices[name1]
object2 = self.vertices[name2]
object1.add_neighbor(object2, cost)
self.num_edges += 1
def get_vertex(self, name):
"""Return the vertex if it exists."""
return self.vertices[name]
def get_vertices(self):
"""Return all the vertices in the graph."""
return list(self.vertices.keys())
def get_edges_weighted(self):
"""Return the list of edges with weights, as tuples."""
edges = []
for v in self.vertices.values():
for w in v.neighbors:
edges.append((v.name, w.name, v.neighbors[w]))
return edges
def is_eulerian_cycle(self):
""" Checks if this graph has a eulerian cycle. A eulerian cycle is when all vertices in the graph
have even number of edges"""
# loops through all the neighbor of all it's vertices in the graph
for vertex in self.vertices:
neighbors = self.vertices[vertex].neighbors
# number of neighbors must be even number or else we can return false straight away
if len(neighbors) % 2 != 0:
return False
return True
def __iter__(self):
"""
iterate over the vertex objects in the
graph, to use sytax: for v in g
"""
return iter(self.vertices.values())
def read_from_file(filename):
with open(filename, 'r') as file:
lines = file.readlines()
# make sure it's a graph
graph_str = lines[0].strip() if len(lines) > 0 else None
if graph_str != "G":
raise Exception("File must start with G.")
# is_bidirectional = graph_or_digraph_str == "G"
graph = Graph()
# add the vertices from the 2nd line
for vertex_name in lines[1].strip("() \n").split(","):
graph.add_vertex(vertex_name)
# add the edges by looping through the remaing lines in the file
# the line is (1,2,10) and so on...
for line in lines[2:]:
# getting rid of ',' and combining all the 2/3 values together
new_edge = line.strip("() \n").split(",")
if len(new_edge) < 2 or len(new_edge) > 3:
raise Exception("Lines adding edges must include 2 or 3 values")
# Get vertices from 'new_edge' from the first index to the second.
vertex1, vertex2 = new_edge[:2]
# Get weight if the len of 'new_edge' is 3. If the length is not 3, weight value will be None
weight = int(new_edge[2]) if len(new_edge) == 3 else None
# Add edge(s)!!
graph.add_edge(vertex1, vertex2, weight)
graph.add_edge(vertex2, vertex1, weight)
return graph
def main():
# read the file from argument given
filename = sys.argv[1]
g = read_from_file(filename)
# returns True if the graph has a Eulerian cyle
if g.is_eulerian_cycle():
print("This graph is Eulerian: TRUE")
else:
print("This graph is Eulerian: FALSE")
if __name__ == '__main__':
main()
|
d23398d61caee4d5b105ef6846c7b04adb8988c6 | dschradick/Python-Toolbox | /NLP.py | 8,767 | 3.578125 | 4 | ########## NATURAL LANGUAGE PROCESSING
#### Reguläre Ausdrücke
# split, findall, search, match:
# => siehe Regex.py
import re
my_string = "Dies ist der erste Satz! Ist das lustig? Denke schon. Sind das 4 Sätze? Oder wieviele Worte?"
# Satzenden finden
sentence_endings = "[.?!]"
print(re.split(sentence_endings, my_string))
# Grossgeschriebene Wörter
capitalized_words = "[A-Z]\w+"
print(re.findall(capitalized_words, my_string))
# Durch spaces trennen
spaces = "\s+"
print(re.split(spaces, my_string))
# Alle Zahlen finden
digits = "\d+"
print(re.findall(digits, my_string))
##### Tokenization
# String in mehrere Tokens konvertieren
# => bereitet Text für NLP vor
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
from nltk.tokenize import regexp_tokenize
from nltk.book import text6
from nltk.corpus import webtext
scene_one = webtext.raw("grail.txt")
sentences = sent_tokenize(holy_grail)
## Standard Regex + Tokenization
# Erstes auftreten von coconuts
match = re.search("coconuts", scene_one)
print(match.start(), match.end())
# Erster text in eckigen Klammern
pattern1 = r"\[.*\]"
print(re.search(pattern1, scene_one))
# Vierte Skript Notation => ARTHUR:
pattern2 = r"[\w\s]+:"
print(re.match(pattern2, sentences[3]))
### Word Tokenization
word_tokenize("Guten Tag!")
### Sentence Tokenization
holy_grail = webtext.raw("grail.txt")
sentences = sent_tokenize(holy_grail)
# Biespiel: Den vierten Satz word-tokenizen
tokenized_sent = word_tokenize(sentences[3])
unique_tokens = set(word_tokenize(holy_grail))
print(unique_tokens)
## Regex Tokenizer
from nltk.tokenize import regexp_tokenize
text = "Wann gehen wir Pizza essen? 🍕 Holst du mich mit dem Auto? 🚕 "
capital_words = r"[A-ZÜ]\w+"
print(regexp_tokenize(text, capital_words))
# Beispiel: Emojis filtern
text = "Wann gehen wir Pizza essen? 🍕 Holst du mich mit dem Auto? 🚕 "
emoji = "['\U0001F300-\U0001F5FF'|'\U0001F600-\U0001F64F'|'\U0001F680-\U0001F6FF'|'\u2600-\u26FF\u2700-\u27BF']"
print(regexp_tokenize(text, emoji))
## Tweet Tokenizer
tweets = ['Dies ist ein #np Parser in #python', '#nlp toll! <3 #lernen', 'Danke @daniel :) #nlp #python']
from nltk.tokenize import TweetTokenizer
# Hashtags finden
pattern1 = r"#\w+"
regexp_tokenize(tweets[0], pattern1)
# Hashtags und Mentions
pattern2 = r"([#|@]\w+)"
regexp_tokenize(tweets[-1], pattern2)
# Alle tweets in eine Liste
tknzr = TweetTokenizer()
all_tokens = [tknzr.tokenize(t) for t in tweets]
print(all_tokens)
#### Charts für NLP
import matplotlib.pyplot as plt
## Wort Frequenz
# Beispiel: Wörter pro Zeile
lines = holy_grail.split('\n')
# Sprecher entfernen -z.b. ARTHUR:
pattern = "[A-Z]{2,}(\s)?(#\d)?([A-Z]{2,})?:"
lines = [re.sub(pattern, '', l) for l in lines]
# Zeile tokenizen
tokenized_lines = [regexp_tokenize(s, "\w+") for s in lines]
line_num_words = [len(t_line) for t_line in tokenized_lines]
plt.hist(line_num_words)
plt.show()
#### Bag-of-words
# Grundlegende Methode um Topics im Text zu Finden
# 1. Tokens erzeugen,
# 2. Tokens zählen
# => je häufiger ein Wort desto wichtiger könnte es sein
from collections import Counter
tokens = word_tokenize(holy_grail)
lower_tokens = [t.lower() for t in tokens]
bow_simple = Counter(lower_tokens)
print(bow_simple.most_common(10)) # => die 10 häufigsten Wörter
# => beinhaltet z.B. noch Satzzeichen und Stopwörter => Preprocessing
#### Preprocessing
# Tokenization, Lowercasing,
# Lemmatization/Stemming = Wörter kürzen auf ihren Wortstamm
# Entfernen von Satzzeichen und weitere ungewollte Tokens wie
# Stop-Wörter = Wörter die keine große Bedeutung tragen wie "the", "a"
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
# Nur Wörter mit Buchstaben => keine Satzzeichen oder Zahlen
alpha_only = [t for t in lower_tokens if t.isalpha()]
# Stopwörter entfernen
no_stops = [t for t in alpha_only if t not in stopwords.words('english')]
# Lemmatisieren
wordnet_lemmatizer = WordNetLemmatizer()
lemmatized = [wordnet_lemmatizer.lemmatize(t) for t in no_stops]
# Bag-of-words
bow = Counter(lemmatized)
lemmatized
print(bow.most_common(10))
# => Resultat: Aufgräumtes Bag-of-words
#### Gensim
# NLP library für komplexere Aufgaben
# - Dokument oder word vectoren erstellen
# - Topic identifikation und Dokumenten Vergleich
# Word Embedding / Vector: mehrdimensionale Reprästentation eines Wortes -
# Großes array mit sparse features (viele nullen, wenige einsen)
# => erlaubt es basierend auf Nähe Verwandschaft zwischen Wörtern und Dokumenten zu sehen
# => oder auch vergleiche: Vektoroperation King-Queen ungefähr gleich zu Man-Woman
# bzw. Spanien ist zu Madrid wie Italien zu Rom
# => trainiert durch ein größeren Corpus
from gensim.corpora.dictionary import Dictionary
### Korpus erstellen
# Korpus = Menge von Texten
# Gensium erlaubt einfaches anlegen von einem Korpus
# Verwendet Bag-Of-Words model
# Erzeugt mapping: Id für jeden token
# => Dokumente dann repräsentiert durch Tokenids und wie häufig sie vorkommen
my_documents = ['The movie was about a spaceship and aliens.', 'I really liked the movie!',
'Awesome action scenes, but boring characters.', 'The movie was awful! I hate alien films.', 'Space is cool! I liked the movie.',
'More space films, please!',]
# Dokumente erzeugen
tokenized_docs = [word_tokenize(doc.lower()) for doc in my_documents]
# Dictonary aus Dokumenten erzugen
dictionary = Dictionary(tokenized_docs)
# id für "awesome"
awesome_id = dictionary.token2id.get("awesome")
# Id benutzen um das Wort auszugeben
print(dictionary.get(awesome_id))
dictionary.token2id
# Korpus erzeugen
corpus = [dictionary.doc2bow(doc) for doc in tokenized_docs]
corpus
# 10 häufigste Wörter im 5. Dokument
print(corpus[4][:10])
# LDA: Latent Dirichlet allocation
# kann mit gensim auf texte für topic analysis und modeling angewendet werden
### Häufigste Wöter in den Dokumenten
doc = corpus[4]
## Sortieren des dokuments nach frequenz
bow_doc = sorted(doc, key=lambda w: w[1], reverse=True)
## Top 5 Wörter mit Frequenz
for word_id, word_count in bow_doc[:5]:
print(dictionary.get(word_id), word_count)
## Top 5 Wörter in allen Dokumenten mit count
from collections import defaultdict
import itertools
total_word_count = defaultdict(int)
for word_id, word_count in itertools.chain.from_iterable(corpus):
total_word_count[word_id] += word_count
sorted_word_count = sorted(total_word_count.items(), key=lambda w: w[1], reverse=True)
for word_id, word_count in sorted_word_count[:5]:
print(dictionary.get(word_id), word_count)
#### tf-idf
# Term frequency - inverse document frequency
# Erblaubt es die wichtigsten Wörter und topics in
# einem Dokument eines Korpus (mit geiltem Vokabular) zu bestimmmen
#
# Idee: Korpus hat gemeinsame Wörter neben den Stopwörtern, welche aber nicht wichtig sind
# => diese sollen von der Wichtigkeit herabgewichtet werden
# Bsp: Computer in Informatik-Artikeln => soll weniger gewicht bekommen
# => stellt sicher, dass die (häufigen) Wörter, welche in allen Dokumenten vorbkommen
# nicht als Key-Wörter bestimmt werden
# sondern die Dokument-spezfischen Wörter mit hoher frequenz
# Formel: w_{i,j} = tf_{i,j} * log( N / df_i)
# w_{i,j} = tf-idf gewichtung des tokens i in dokument j
# => Wert von 0-1: abhängig vom ersten (tf) oder zweiten Faktor (log)
# tf_{if} = anzahl der vorkommen von token i in dokument j (tf = term frequency)
# N = Anzal der Dokumente
# df_i = anzahl der dokumente die token i enthalten (df = document frequency)
from gensim.models.tfidfmodel import TfidfModel
tfidf = TfidfModel(corpus)
tfidf_weights = tfidf[corpus[1]]
print(tfidf_weights)
text6.generate("In the beginning of his brother is a hairy man , whose top may reach")
# Sortieren der Gewichtungen
sorted_tfidf_weights = sorted(tfidf_weights, key=lambda w: w[1], reverse=True)
# Top 5 gewichtete Wörter
for term_id, weight in sorted_tfidf_weights[:5]:
print(dictionary.get(term_id), weight)
#!!! => je höher die Gewichtung eines Wortes desto eindeutiger bestimmt es das Topic
import spacy
from spacy import displacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(u'Apple is looking at buying U.K. startup for $1 billion')
displacy.serve(doc, style='dep')
for token in doc:
print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_,
token.shape_, token.is_alpha, token.is_stop)
import spacy
import codecs
nlp = spacy.load('de', tagger=False, parser=False, matcher=False)
with codecs.open('nachricht.txt', 'r', 'utf-8') as myfile:
data = myfile.read()
# Create a new document: doc
doc = nlp(data)
# Print all of the found entities and their labels
for ent in doc.ents:
print(ent.label_, ent.text)
|
54111ed1eb39ed206b8d14b320f99888f2dba378 | Environmental-Informatics/python-learning-the-basics-brucewong23 | /wang2846_assignment-01/wang2846_Exercise_3.3.py | 3,545 | 3.609375 | 4 | ####################
# Header
# Jan. 17 2020
# Shizhang Wang
# 0027521360
# the commented parts are different trials
# trial 1: 2 mins, trial 2: 8 mins, trial 3: more than I want to admit..
# more details in in-line comments
########## Trial 3 ############
def print_twice(x):
print(x, end=' ')
print(x, end=' ')
# left side of horizontal component(+----), effectively do_twice from
#last exercise
def h_left(f, x):
print('+', end=' ')
f(x)
f(x)
# combine two h_left, effectively do_four
def unit_one(f, x):
h_left(f, x)
h_left(f, x)
print('+') # automatively advance to next line w/o end=' '
# left side of the first repetitive segment of vertical component, do_twice
def v_left(f, x):
print('|', end=' ')
f(x)
f(x)
# combine two v_left, do_four
def unit_two(f, x):
v_left(f, x)
v_left(f, x)
print('|')
# newly defined do_twice calls function f1 twice, passing in two other
# variables f2 (indicating another function) and x
def do_twice(f1, f2, x):
f1(f2, x)
f1(f2, x)
# newly defined do_four, do_twice was called twice and the variables needed
# for do_twice is passing in through do_four here
def do_four(f1, f2, x):
do_twice(f1, f2, x)
do_twice(f1, f2, x)
# combination of unit_one and repetition of unit_two w/ do_four
def draw_figure(f1, f2, x1, x2):
unit_one(f2, x2)
do_four(f1, f2, x1)
unit_one(f2, x2)
do_four(f1, f2, x1)
unit_one(f2, x2)
draw_figure(unit_two, print_twice, ' ', '-')
# variable passed in is highly dependent on the require the shape, a more
# generalized program probably exist
######## trial 2 ################
#def plus():
# print('+', end=' ')
#
#def minus():
# print('-', end=' ')
#
#def vertical_line():
# print('|', end=' ')
#
#def space():
# print(' ', end=' ')
#
#def do_twice(f, x):
# f(x)
# f(x)
#
#def print_twice(x):
# print(x, end=' ')
# print(x, end=' ')
#
#def draw_horizontal(f, x):
# plus()
# do_twice(f, x)
# plus()
# do_twice(f, x)
# plus()
# print('')
#
#def draw_vertical(f, x):
# vertical_line()
# do_twice(f, x)
# vertical_line()
# do_twice(f, x)
# vertical_line()
# print('')
#
#def draw_figure():
# draw_horizontal(print_twice, '-')
# draw_vertical(print_twice, ' ')
# draw_vertical(print_twice, ' ')
# draw_vertical(print_twice, ' ')
# draw_vertical(print_twice, ' ')
# draw_horizontal(print_twice, '-')
# draw_vertical(print_twice, ' ')
# draw_vertical(print_twice, ' ')
# draw_vertical(print_twice, ' ')
# draw_vertical(print_twice, ' ')
# draw_horizontal(print_twice, '-')
# draw_figure()
############## trial 1 #######################
#def draw_figure():
# print('+','-','-','-','-','+','-','-','-','-','+')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('+','-','-','-','-','+','-','-','-','-','+')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('|',' ',' ',' ',' ','|',' ',' ',' ',' ','|')
# print('+','-','-','-','-','+','-','-','-','-','+')
# draw_figure() |
a8f50b8321af1c44645978eceb1d4dd2061d22fe | IreneLopezLujan/Fork_List-Exercises | /List Exercises/find_missing_&_additional_values_in_2_lists.py | 420 | 4.25 | 4 | '''Write a Python program to find missing and additional values in two lists.'''
list_1 = ['a','b','c','d','e','f']
list_2 = ['d','e','f','g','h']
missing_values_in_list_2 = [i for i in list_1 if i not in list_2]
additional_values_in_list_2 = [i for i in list_2 if i not in list_1]
print("Missing values in list 2: "+str(missing_values_in_list_2))
print("Additional values in list 2: "+str(additional_values_in_list_2))
|
975acb3772e411de687fe70e3f202841b38fb9d7 | IreneLopezLujan/Fork_List-Exercises | /List Exercises/retrurn_length_of_longest_word_in_given_sentence.py | 396 | 4.375 | 4 | '''Write a Python function that takes a list of words and returns the length of the longest one. '''
def longest_word(sentence):
words = sentence.split()
length_words = [len(i) for i in words]
return words[length_words.index(max(length_words))]
sentence = input("Enter a sentence: ")
print("Longest word: "+longest_word(sentence))
print("Length: "+str(len(longest_word(sentence))))
|
d0abab61584a1e26db983ed8b3e2d227b25fd98b | IreneLopezLujan/Fork_List-Exercises | /List Exercises/make_set_of_list.py | 367 | 4.0625 | 4 | '''Write a Python function that takes a list and returns a new list with unique
elements of the first list.'''
num_list = [1,2,2,2,3,3,4,4,4,4,5,5,5,5,5]
set(num_list) # is se set ban raha h list nahei ban rahi
'''for making list'''
unique_elements = []
for i in num_list:
if i not in unique_elements:
unique_elements.append(i)
print(unique_elements)
|
3404cfd776b2e315c91ebb8b816e89a86c8105ea | IreneLopezLujan/Fork_List-Exercises | /List Exercises/find_smallest_item_in_a_list.py | 169 | 4.09375 | 4 | '''Write a Python program to get the smallest number from a list'''
def smallest_item(items):
return(min(items))
items = [2,4,5,8,3,0]
print(smallest_item(items))
|
a00774543825bd9d420247b97688a7ac0c7cfeca | IreneLopezLujan/Fork_List-Exercises | /List Exercises/find_maximum_occurring_chars_in_given_str.py | 499 | 3.921875 | 4 | '''Write a Python program to find the maximum occurring character in a given string.'''
string = input("Enter an string: ")
chars = []
count = []
for i in string:
if i not in chars:
chars.append(i)
for i in chars:
n = 0
for j in list(string):
if i == j:
n+= 1
count.append(n)
print(i+": "+str(n))
max_index = count.index(max(count))
print("Miximum occuring chartacter is "+chars[max_index]+" which occurs "+str(count[max_index])+" times")
|
9130b28e64a5df4d24b46871593c865b2d5223a3 | aatarifi/ud120-projects | /svm/svm_author_id.py | 2,006 | 3.625 | 4 | # coding: utf-8
# !/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
import numpy as np
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
### your code goes here ###
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
clf = SVC(kernel='rbf', C=10000.0)
# features_train = features_train[:len(features_train)/100]
# labels_train = labels_train[:len(labels_train)/100]
print len(features_train)
print len(labels_train)
t0 = time()
clf.fit(features_train, labels_train)
print "training time", round(time() - t0, 3), "s"
t0 = time()
pred = clf.predict(features_test)
print "predicting time", round(time() - t0, 3), "s"
# print "The prediction for element 10 of the test set is: ", pred[0]
# print "The prediction for element 26 of the test set is: ", pred[26]
# print "The prediction for element 50 of the test set is: ", pred[50]
# Ahmad added
type(pred)
# Ahmad added the following code to answer lesson 3 question 37
def counter():
chris = 0
sara = 0
i = 0
for i in np.nditer(pred):
if i == 1:
chris += 1
if i == 0:
sara += 1
# print "prediction to be in the “Chris” (1) = ",chris
# print "prediction to be in the “Sara” (0) = ",sara
# return chris, sara
return chris, sara
print "prediction to be in the “Chris” (1) and “Sara” (0) is: ", counter()
print accuracy_score(pred, labels_test)
#########################################################
|
cac1cd414b24faec5a590d2855c847c3230de769 | aadankan/Cwiczenia | /frame.py | 358 | 3.515625 | 4 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Hi!')
root.iconbitmap(r'C:\Users\aadan\Desktop\2.ico')
frame = LabelFrame(root, padx=50, pady=50)
frame.pack(padx=10, pady=10)
b = Button(frame, text="Don't click me!")
b2 = Button(frame, text="... or here!")
b.grid(row=0, column=0)
b2.grid(row=1, column=1)
root.mainloop()
|
022fa12e7245d3d42f206df2ccc062185df6146c | MaciejNessel/algorithms | /graphs/alg_kruskal.py | 918 | 3.796875 | 4 | # Implementation of Kruskal algorithm
class Node:
def __init__(self, val):
self.val = val
self.rank = 0
self.parent = self
def find(x):
if x != x.parent:
x.parent = find(x.parent)
return x.parent
def union(x,y):
x = find(x)
y = find(y)
if x == y:
return
if x.rank > y.rank:
y.parent = x
else:
x.parent = y
if x.rank == y.rank:
y.rank += 1
def kruskal(g):
n = len(g)
g.sort(key = lambda x: x[2])
A = []
arr = [Node(i) for i in range(n)]
for i in range(0, n):
x = arr[g[i][0]]
y = arr[g[i][1]]
x = find(x)
y = find(y)
if x != y:
union(x, y)
A.append([g[i][0], g[i][1]])
print(A)
# Example:
graph = [(0, 1, 7), (0, 2 ,2), (0, 3, 8), (0, 5, 3), (1, 3, 1), (2, 4, 5), (3, 4, 4), (3, 5, 12), (4, 5, 6)]
kruskal(graph) |
72da947d4566bf7079103ade6adb65fdfa13a06f | MaciejNessel/algorithms | /sort/quick_sort.py | 2,170 | 3.796875 | 4 | # QuickSort (partition Hoare):
def partition_hoare(array, low, high):
pivot = array[low]
(i, j) = (low - 1, high + 1)
while True:
while True:
i = i + 1
if array[i] >= pivot:
break
while True:
j = j - 1
if array[j] <= pivot:
break
if i >= j:
return j
array[i], array[j] = array[j], array[i]
def quicksort_hoare(array, low, high):
if low >= high:
return
pivot = partition_hoare(array, low, high)
quicksort_hoare(array, low, pivot)
quicksort_hoare(array, pivot + 1, high)
# QuickSort (partition Lomuto)
def partition_lomuto(array, p, r):
x = array[r]
i = p - 1
for j in range(p, r):
if array[j] <= x:
i += 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[r] = array[r], array[i + 1]
return i+1
def quicksort_lomuto(array, p, r):
while p < r:
q = partition_lomuto(array, p, r)
if q - p < r - q:
quicksort_lomuto(array, p, q - 1)
p = q + 1
else:
quicksort_lomuto(array, q + 1, r)
r = q - 1
# Quick Sort (iterative)
from queue import Queue
def quicksort_iterative(array):
stack = Queue()
stack.put((0, len(array) - 1))
while stack.qsize() > 0:
p, r = stack.get()
if p < r:
q = partition_lomuto(array, p, r)
stack.put((p, q-1))
stack.put((q+1, r))
return array
# Examples:
from time import time
from random import randint, seed
seed(42)
n = 10000
print("Iterative:")
data = [randint(1, 100) for _ in range(n)]
start = time()
quicksort_iterative(data)
end = time()
print(f"Sorted: {data} \n time: {(end - start)} sec \n")
print("Horae:")
data = [randint(1, 100) for _ in range(n)]
start = time()
quicksort_hoare(data, 0, len(data) - 1)
end = time()
print(f"Sorted: {data} \n time: {(end - start)} sec \n")
print("Lomuto:")
data = [randint(1, 100) for _ in range(n)]
start = time()
quicksort_lomuto(data, 0, len(data) - 1)
end = time()
print(f"Sorted: {data} \n time: {(end - start)} sec")
|
2792529dbdd4db606fb737815d68411593c9e185 | MaciejNessel/algorithms | /graphs/dfs.py | 1,360 | 3.515625 | 4 | #Implementation of DFS
def dfs_arr(graph):
def dfs_visit_arr(g, u):
print(u, end=' ')
nonlocal time
time += 1
visited[u] = True
for v in g[u]:
if not visited[v]:
parent[v] = u
dfs_visit_arr(g, v)
time += 1
time = 0
n = len(graph)
visited = [False for _ in range(n)]
parent = [None for _ in range(n)]
for u in range(n):
if not visited[u]:
dfs_visit_arr(graph, u)
def dfs_matrix(graph):
def dfs_visit_matrix(g, u):
print(u, end=' ')
nonlocal time
time += 1
visited[u] = True
for i in range(n):
if g[u][i] == 1:
if not visited[i]:
parent[i] = u
dfs_visit_matrix(g, i)
time += 1
time = 0
n = len(graph)
visited = [False for _ in range(n)]
parent = [None for _ in range(n)]
for u in range(n):
if not visited[u]:
dfs_visit_matrix(graph, u)
# Examples:
g_matrix= [[0, 1, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 1],
[0, 1, 0, 1, 1, 1],
[0, 0, 1, 0, 0, 1],
[1, 1, 1, 0, 0, 1],
[0, 1, 1, 1, 1, 0]]
g_arr = [[4, 1], [0, 4, 5, 2], [1, 5, 3, 4], [2, 5], [0, 1, 2, 5], [1, 2, 4, 3]]
dfs_matrix(g_matrix)
print()
dfs_arr(g_arr) |
a2780f68141a881296b02d60fe576a3f5d7a230b | sagarkrkv/Search-Algorithms | /solver16.py | 6,318 | 3.75 | 4 | import sys
import heapq
'''
This program may cost about 10 seconds to get the result,
so please wait for a while.
Our heuristic function is calculate the distance position from goal board firstly.
For example:
[[1, 14, 3, 4], row1 => (0, 0) (0, -1) (0, 0) (0, 0)
[8, 2, 6, 7], row2 => (-1, 0) (0, -1) (-1, 0) (-1, 0)
[9, 5, 11, 12], row3 => (0, 0) (-1,-1) (0, 0) (0, 0)
[13, 10, 15, 16]] row4 => (0, 0) (0, -1) (0, 0) (0, 0)
Then, for each row, we calculate the maximum of x minus the minimum of x,
it is 0 + 1 + 1 + 0 = 2;
Then, for each column, we calculate the maximum of x minus the minimum of y,
it is 0 + 0 + 0 + 0 = 0;
So the heuristic function is eaqual to 2.
The result of
5 7 8 1
10 2 4 3
6 9 11 12
15 13 14 16
"L4 R1 D4 R2 L3 D2 U4 L2 D3 L3 U2 R3 L4 U3 R4 D3"
'''
class Board(object):
__slots__ = ('tile_container', 'action_list')
def __init__(self, tile_container=None):
self.tile_container = tile_container or []
self.action_list = []
def __eq__(self, board):
for i in range(4):
for j in range(4):
if self.tile_container[i][j] != board.tile_container[i][j]:
return False
return True
def __hash__(self):
hash_code = 1
for row in self.tile_container:
hash_code *= hash(tuple(row))
return hash_code
def copy(self):
#
tile_container = []
for raw in self.tile_container:
tile_container.append(raw[:])
new_board = Board(tile_container=tile_container)
new_board.action_list = self.action_list[:]
return new_board
def move_right(self, row):
self.action_list.append("R%s"%row)
index = row - 1
self.tile_container[index] = [self.tile_container[index][-1]]\
+ self.tile_container[index][:-1]
def move_left(self, row):
index = row - 1
self.action_list.append("L%s"%row)
self.tile_container[index] = self.tile_container[index][1:]\
+ [self.tile_container[index][0]]
def move_up(self, column):
index = column - 1
self.action_list.append("U%s"%column)
t0 = self.tile_container[0][index]
t1 = self.tile_container[1][index]
t2 = self.tile_container[2][index]
t3 = self.tile_container[3][index]
self.tile_container[0][index] = t1
self.tile_container[1][index] = t2
self.tile_container[2][index] = t3
self.tile_container[3][index] = t0
def move_down(self, column):
index = column - 1
self.action_list.append("D%s"%column)
t0 = self.tile_container[0][index]
t1 = self.tile_container[1][index]
t2 = self.tile_container[2][index]
t3 = self.tile_container[3][index]
self.tile_container[0][index] = t3
self.tile_container[1][index] = t0
self.tile_container[2][index] = t1
self.tile_container[3][index] = t2
def _cal_distance_pos(self, p1, p2):
x = p1[0] - p2[0]
if x == 3:
x = -1
if x == -3:
x = 1
y = p1[1] - p2[1]
if y == 3:
y = -1
if y == -3:
y = 1
return x,y
def get_heuristic(self):
sum_num = 0
dis_matrix = []
for i in range(4):
row = []
for j in range(4):
pos = i, j
number = self.tile_container[i][j]
goal_pos = ((number-1)/4, (number-1)%4)
row.append(self._cal_distance_pos(pos, goal_pos))
dis_matrix.append(row)
for row in dis_matrix:
sum_num += max(row, key=lambda x:x[1])[1] - min(row, key=lambda x:x[1])[1]
for i in range(4):
colum = [dis_matrix[j][i] for j in range(4)]
sum_num += max(colum, key=lambda x:x[0])[0] - min(colum, key=lambda x:x[0])[0]
return sum_num
def get_f(self):
return self.get_heuristic() + len(self.action_list)
def gen_child(self):
# for row
for i in range(1, 4+1):
board = self.copy()
board.move_left(i)
yield board
board = self.copy()
board.move_right(i)
yield board
# for column
for i in range(1, 4+1):
board = self.copy()
board.move_down(i)
yield board
board = self.copy()
board.move_up(i)
yield board
@classmethod
def generate_goal_board(cls):
board = cls()
for i in range(4):
t = [i*4+j for j in range(1,5)]
board.tile_container.append(t)
return board
Board.GOAL_BOARD = Board.generate_goal_board()
if __name__ == "__main__":
print 'This program may cost some time to get the result, so please wait for a while.'
filename = sys.argv[1]
tile_container = []
with open(filename, "r") as f:
for line in f:
tile_container.append([int(i) for i in line.split()])
initial_board = Board(tile_container=tile_container)
opened = []
opened_set = set()
heapq.heapify(opened)
closed = set()
heapq.heappush(opened, (initial_board.get_f(), initial_board))
opened_set.add(initial_board)
i = 0
while len(opened):
_, board = heapq.heappop(opened)
opened_set.remove(board)
closed.add(board)
if board == Board.GOAL_BOARD:
print " ".join(board.action_list)
break
for child_board in board.gen_child():
if child_board not in closed:
if child_board in opened_set:
if len(child_board.action_list) > len(board.action_list) + 1:
heapq.heappush(opened, (child_board.get_f() ,child_board))
opened_set.add(child_board)
elif child_board not in opened_set:
heapq.heappush(opened, (child_board.get_f() ,child_board))
opened_set.add(child_board)
else:
del child_board
|
6379eb42726147b4875e8e682f2f8e9097789ad6 | sarahchen6/112-Term-Project | /mazeGenerationAndSolution.py | 6,356 | 3.59375 | 4 | ########################################
# Ho Ho Home: the Santa Maze Game
# (mazeGenerationAndSolution.py)
# By: Sarah Chen (sarahc2)
########################################
# Maze Generation & Solution
########################################
import random
def generateMazeDict(n):
mazeDict = {}
lastPoint = (0,0)
newPoint = (1,0)
generateMazeDictHelper(n, mazeDict, lastPoint, newPoint, 0)
return mazeDict
def generateMazeDictHelper(n, mazeDict, lastPoint, newPoint, index):
# check if newPoint valid
newX, newY = newPoint
if ((newX < 0) or (newX > n-1) or (newY < 0) or (newY > n-1)
or (isPointInDict(mazeDict, newPoint) == True)
or (newPoint == (0,0))):
return False
# set new point
if lastPoint in mazeDict:
mazeDict[lastPoint].append(newPoint)
else:
mazeDict[lastPoint] = [newPoint]
# check if maze complete
if (index == (n**2 - 2)):
return True
# run through moves & continue w recursion
moves = [(1,0), (0,1), (-1,0), (0,-1)]
random.shuffle(moves)
for move in moves:
dx, dy = move
nextX = newX + dx
nextY = newY + dy
nextPoint = (nextX, nextY)
if (generateMazeDictHelper(n, mazeDict, newPoint,
nextPoint, index+1) == True):
return True
# if recursion doesn't work, undo move
return generateMazeDictHelper(n, mazeDict, lastPoint, newPoint, index)
def isPointInDict(mazeDict, point):
for coordinate in mazeDict:
if point in mazeDict[coordinate]:
return True
return False
def mazeSolver(n, mazeDict, startCell, endCell):
flippedDict = flipMazeDict(mazeDict)
solution = [startCell]
lastPoint = mazeDict[startCell][0]
mazeSolverHelper(n, mazeDict, solution, lastPoint, endCell)
if (len(solution) == 1):
mazeSolverHelper(n, flippedDict, solution, lastPoint, endCell)
return flippedDict, solution
def mazeSolverInTwoParts(n, mazeDict, startCell, endCell):
# get maze dictionary, flipped maze dictionary, and solution list from UL to BR
flippedDict, solution = mazeSolver(n, mazeDict, (0,0), (n-1,n-1))
# get BL cell
intermediateCell = (n-1, n-1)
# firstSol gets from startCell to BR
firstSol = [startCell]
try:
firstLastPoint = mazeDict[startCell][0]
except:
for point in mazeDict:
if startCell in mazeDict[point]:
firstLastPoint = point
mazeSolverGivenSol(n, mazeDict, firstSol, firstLastPoint, intermediateCell, solution)
if (len(firstSol) == 1):
try:
firstLastPoint = flippedDict[startCell][0]
except:
for point in flippedDict:
if startCell in flippedDict[point]:
firstLastPoint = point
mazeSolverGivenSol(n, flippedDict, firstSol, firstLastPoint, intermediateCell, solution)
# secondSol gets from endCell to BR
secondSol = [endCell]
try:
secondLastPoint = mazeDict[endCell][0]
except:
for point in mazeDict:
if endCell in mazeDict[point]:
secondLastPoint = point
mazeSolverGivenSol(n, mazeDict, secondSol, secondLastPoint, intermediateCell, solution)
if (len(secondSol) == 1):
try:
secondLastPoint = flippedDict[endCell][0]
except:
for point in flippedDict:
if endCell in flippedDict[point]:
secondLastPoint = point
mazeSolverGivenSol(n, flippedDict, secondSol, secondLastPoint, intermediateCell, solution)
# combine firstSol and secondSol to get finalSol
finalSol = []
for i in range(len(firstSol)):
for j in range(len(secondSol)):
if (firstSol[i] == secondSol[j]):
firstHalf = firstSol[:i]
secondHalf = secondSol[:j+1]
secondHalf.reverse()
finalSol.extend(firstHalf)
finalSol.extend(secondHalf)
break
if len(finalSol) != 0:
break
# get rid of extras at end of finalSol
for i in range(len(finalSol)):
if (finalSol[i] == endCell):
if (i == len(finalSol)-1):
break
finalSol = finalSol[:i+1]
break
return finalSol
def mazeSolverHelper(n, mazeDict, solution, lastPoint, endCell):
lastX, lastY = lastPoint
# set lastPoint
solution.append(lastPoint)
# check if reached bottom right coordinate
if (lastPoint == endCell):
return True
# check if lastPoint valid
if (lastPoint not in mazeDict):
solution.pop()
return False
# recurse
for connection in mazeDict[lastPoint]:
if mazeSolverHelper(n, mazeDict, solution, connection, endCell) == True:
return True
# if recursion doesn't work
solution.pop()
return False
def mazeSolverGivenSol(n, dictionary, solution, lastPoint, endCell, givenSol):
lastX, lastY = lastPoint
# set lastPoint
solution.append(lastPoint)
# check if reached solution
for i in range(len(givenSol)):
if (lastPoint == givenSol[i]):
solution.extend(givenSol[i:])
return True
# check if lastPoint valid
if (lastPoint not in dictionary):
solution.pop()
return False
# recurse
for connection in dictionary[lastPoint]:
if mazeSolverGivenSol(n, dictionary, solution, connection, givenSol, endCell) == True:
return True
# if recursion doesn't work
solution.pop()
return False
def getMazeSolutionConnections(n, mazeDict, startCell, endCell):
solution = mazeSolverInTwoParts(n, mazeDict, startCell, endCell)
connDict = dict()
# create dictionary of all coordinates
for x in range(n):
for y in range(n):
connDict[(x,y)] = []
# map all coordinates to every point each is connected to
for key in mazeDict:
connDict[key] += mazeDict[key]
for point in mazeDict[key]:
connDict[point].append((key))
return solution, connDict
def flipMazeDict(mazeDict):
flippedDict = dict()
for key in mazeDict:
for point in mazeDict[key]:
flippedDict[point] = [key]
return flippedDict
|
b9c3b310c900b5a03a4d8c6439e4b42041fee544 | disconnect3d/python-ee-labs | /lab1/wc.py | 1,292 | 3.921875 | 4 | """Word count (wc) unix like program.
Usage:
wc <file>
wc -m | --chars <file>
wc -l | --lines <file>
Options:
-h --help Show this screen.
-m --chars Print the character counts.
-l --lines Print the newline counts.
"""
import sys
import os
from docopt import docopt
args = docopt(__doc__)
input_file = args['<file>']
count_chars = args['--chars']
count_lines = args['--lines']
if not count_chars and not count_lines:
count_chars = count_lines = True
def blocks(infile, bufsize=1024):
while True:
try:
data = infile.read(bufsize)
if data:
yield data
else:
break
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
break
if not os.path.isfile(input_file):
print "`{}` is not a file or does not exist.".format(input_file)
sys.exit()
chars_counter = 0
lines_counter = 0
with open(input_file) as fp:
for line in fp:
for c in line:
chars_counter += 1
if c == os.linesep:
lines_counter += 1
print "File: {}".format(input_file)
if count_chars:
print "Characters: {}".format(chars_counter)
if count_lines:
print "Lines: {}".format(lines_counter)
|
b390e256007cc94eef51ba9ef6d9986e156816b3 | disconnect3d/python-ee-labs | /lab2/tests/test_player_keyboard_input.py | 847 | 3.53125 | 4 | import unittest
import mock
import player_keyboard_input
PlayerKeyboardInput = player_keyboard_input.PlayerKeyboardInput
class TestPlayerKeyboardInput(unittest.TestCase):
def setUp(self):
self.player = PlayerKeyboardInput('x')
self.player._board = mock.MagicMock()
def test_make_move_proper_input(self):
player_keyboard_input.raw_input = lambda: '3'
self.assertEqual(self.player._make_move(), 3)
def test_make_move_wrong_input(self):
self.first = True
def mock_raw_input(msg=None):
if self.first:
self.first = False
return 'asd'
else:
return '4'
player_keyboard_input.raw_input = mock_raw_input
self.assertEqual(self.player._make_move(), 4)
if __name__ == '__main__':
unittest.main()
|
8df7f9a787d95033855b58f28bd082d7a363e793 | SiriShortcutboi/Clown | /ChatBot-1024.py | 1,652 | 4.21875 | 4 | # Holden Anderson
#ChatBot-1024
#10-21
# Start the Conversation
name = input("What is your name?")
print("Hi " + name + ", nice to meet you. I am Chatbot-1024.")
# ask about a favorite sport
sport = input("What is your favorite sport? ")
if (sport == "football") or (sport == "Football"):
# respond to football with a question
yards = int(input("I like football too. Can you tell me the length of a football field in yards? "))
# verify and comment on the answer
if (yards < 100):
print("No, too short.")
elif (yards > 100):
print("No, too long.")
else:
print("That's right!")
elif (sport == "baseball") or (sport == "Baseball"):
# respond to baseball with a question
strikes = int(input("I play baseball every summer. How many 'strikes' does it take to get a batter out? "))
# verify and comment on the answer
if (strikes == 3):
print("Yes, 1, 2, 3 strikes you're out...")
else:
print("Actually, 3 strikes will get a batter out.")
elif (sport == "basketball") or (sport == "Basketball"):
# respond to basketball with a question
team = input("The Harlem Globetrotters are the best. Do you know the name of the team they always beat? ")
# verify and comment on the answer (check for either version with or without capitals)
if (team == "washington generals") or (team == "Washington Generals"):
print("Yes, those Generals can never catch a break.")
else:
print("I think it's the Washington Generals.")
else:
# user entered a sport we don't recognize, so just display a standard comment
print("That sounds cool; I've never played " + sport + ".")
print("Great chatting with you.")
|
a3ceed91cd041af6743133cd050e11229d7fbc26 | deasymaharani/Grok-Learning | /C7-ITERATION/while loop.py | 456 | 4.09375 | 4 | def mul_table(num,N):
n=0
while n<N:
result = (n+1)*num
print_result = str(n+1) + " * " + str(num)+ " = "+ str(result)
n = n+1
print(print_result)
num=input("Enter the number for 'num': ")
N=input("Enter the number for 'N': ")
if not num.isdigit() or not N.isdigit() or int(num) < 0 or int(N) < 0 or int(num)==0:
print("Invalid input")
else:
num = int(num)
N = int(N)
mul_table(num,N)
|
7eafcff44500a06c7cee060805b3195c65a3c349 | deasymaharani/Grok-Learning | /C12 - FILES/sorting csv records.py | 512 | 3.609375 | 4 | import csv
def sort_records(csv_filename, new_filename):
#read from csv
fp = open(csv_filename)
data = csv.reader(fp)
header = next(data)
header_list = [header]
#extract and sort the data
data2 = list(data)
content = data2[:]
sorted_content = sorted(content)
sorted_content = header_list + sorted_content
fp.close()
#write to csv
csv_file = open(new_filename,'w')
writer = csv.writer(csv_file)
writer.writerows(sorted_content)
csv_file.close()
|
38285c6e09c248116895cff82f9bec44d891c0ed | ShashyChowdary/LearnPython2 | /Code/BigNum.py | 245 | 4.03125 | 4 | a = int(input("Enter a number : "))
b = int(input("Enter a number : "))
c = int(input("Enter a number : "))
if a>=b and a>=c :
print("big is :", a)
elif b>=c and b>=a:
print("Big number is :", b)
else :
print("Big is ", c)
|
413cd58b70651c1bdc6083ca453da78fc8cc32ae | yousef19-meet/YL1-201718 | /lab_5/lab_5.py | 851 | 3.8125 | 4 | ##########################################1
##from turtle import *
##
##class Square (Turtle):
## def __init__(self,size):
## Turtle.__init__(self)
##
## self.shapesize(size)
## self.shape("square")
##
##S1= Square(10)
##########################################2
##from turtle import *
##
##class Hexagon(Turtle):
## def __init__(self
from turtle import *
class Hexagon (Turtle):
def __init__(self,size,speed,color):
Turtle.__init__(self)
self.speed(speed)
self.color(color)
self.shapesize(size)
self.begin_poly()
for i in range(6):
self.pu()
self.rt(60)
self.fd(100)
self.end_poly()
p =self.get_poly()
register_shape("hexagon",p)
self.shape("hexagon")
H1= Hexagon(1,10,"red")
H1.fd(200)
|
724db8d86b1faae414d95ba84596a37d95f26f7d | MOON-CLJ/learning_cpp | /zju_py/1002.py | 1,434 | 3.5625 | 4 | import sys
def can_place_if(maps, x, y, count):
if maps[x][y] == 'X':
return False
# x
for x1 in range(x - 1, -1, -1) + range(x + 1, count):
if maps[x1][y] == 'M':
return False
if maps[x1][y] == 'X':
break
# y
for y1 in range(y - 1, -1, -1) + range(y + 1, count):
if maps[x][y1] == 'M':
return False
if maps[x][y1] == 'X':
break
return True
def place(maps, i, count, place_count):
if i == count ** 2:
"""
maps = [''.join(row) for row in maps]
print '\n'.join(maps)
print '** ' * 10
"""
global max_count
if place_count > max_count:
max_count = place_count
return
x, y = i / count, i % count
can_place = can_place_if(maps, x, y, count)
# place
if can_place:
current = maps[x][y]
maps[x][y] = 'M'
place(maps, i + 1, count, place_count + 1)
maps[x][y] = current
# not place
place(maps, i + 1, count, place_count)
while 1:
line = sys.stdin.readline()
count = int(line.strip())
if count == 0:
break
maps = []
for i in xrange(count):
line = sys.stdin.readline()
line = line.strip()
maps.append([char for char in line])
# process
max_count = 0
place_count = 0
place(maps, 0, count, place_count)
print max_count
|
5b479e8d4d1aff29a8009449fccd77c3044eb1b9 | RobertLeonhardt/FallingBlocks | /main.py | 1,918 | 3.765625 | 4 | """
main.py
Falling Blocks Algorithm Study
@date: 2019-11-10
@author: Robert Leonhardt <mail@4px.io>
"""
# Imports
import sys, pygame
from FallingBlocks import FallingBlocks
# Init pygame
pygame.init()
# Define window
WINDOW_HEIGHT = 600
WINDOW_WIDTH = 300
WINDOW_TITLE = "Falling Blocks Algorithm Study"
# Define colors
COLOR_MAIN_BACKGROUND = (255,255,255)
# Define screen
WINDOW = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# Set title
pygame.display.set_caption(WINDOW_TITLE)
# Set background color
WINDOW.fill(COLOR_MAIN_BACKGROUND)
# Init game
falling_blocks = FallingBlocks(WINDOW)
# Setup clock
clock = pygame.time.Clock()
# Set time elapsed
time_elapsed = 0
# Loop so the window doesnt close
while True:
# Get event
for event in pygame.event.get():
# Exit window when c button is clicked
if event.type == pygame.QUIT: sys.exit()
# Check if a key is pressed
if event.type == pygame.KEYDOWN:
# KEY UP - Rotate all movable blocks
if event.key == pygame.K_UP: falling_blocks.rotate()
# DOWN KEY - Move movable blocks down
if event.key == pygame.K_DOWN: falling_blocks.step_down()
# LEFT KEY - Move movable blocks to left
if event.key == pygame.K_LEFT: falling_blocks.step_left()
# RIGHT KEYs - Move movable blocks to right
if event.key == pygame.K_RIGHT: falling_blocks.step_right()
# S KEY - Start new game (when game is lost)
if event.key == pygame.K_s: falling_blocks.start()
# Calc time since last click
time_elapsed += clock.tick()
# If time elapsed greater than a second, update game
if time_elapsed >= 800:
# Move down
falling_blocks.step_down()
# Reset time elapsed
time_elapsed = 0
# Clean up view
pygame.display.flip()
|
4ec31a32886dbd4b465ae1716b8536e5172cf96d | pnuggz/kickstart-2020 | /b/main.py | 750 | 3.5625 | 4 | # ALWAYS NECESSARY
t = 0 # number of cases
t_i = 0 # case number
# GLOBAL ARRAY BASED ON THE CASE
n = 0 # number of houses
a = [] # house prices array
b = 0 # budget
# WORKING VARIABLES
def read_file():
# DEFINE GLOBALS HERE
# READ THE LINES FOR EACH CASE
line_1 = input()
line_2 = input()
# SPLIT LINES BY SPACE IF REQUIRED
line_1_arr = line_1.split(' ')
line_2_arr = line_2.split(' ')
# ASSIGN THE VARIABLE TO THE GLOBAL
def calculate():
# DEFINE GLOBALS HERE
global t_i
#DO CALCULATION HERE
# CHANGE THE ... TO THE ANSWER VARIABLE
print('Case #{}: {}'.format(t_i, ...))
def main():
global t
global t_i
t = int(input())
for i in range(t):
t_i = i+1
read_file()
calculate()
if __name__ == '__main__':
main() |
f81cfce6f8e5e4e01086df9ef455e9f73f047a34 | Mo-na-rh/python_homework | /hw1/8.py | 177 | 4.03125 | 4 | # functions for recursion
# numbers of Fibonacchi
n = int(input("n = "))
def fib(n):
if n in (1, 2):
return 1
return fib(n - 1) + fib(n - 2)
print(fib(n))
|
0ecb379e9f534c7774c93e31acecb41ee4d93e41 | lxndrvn/python-4th-tw-mentors-life-oop-overload_mentors_life | /mentor.py | 1,514 | 3.75 | 4 | import os
import csv
from person import Person
from student import Student
class Mentor(Person):
def __init__(self, first_name, last_name, year_of_birth, gender, energy_level, happiness_level, nickname, soft_skill_level):
super().__init__(first_name, last_name, year_of_birth, gender, energy_level, happiness_level)
self.nickname = nickname
self.soft_skill_level = int(soft_skill_level)
def teach(self, student, delta):
self.soft_skill_level += int(delta)
student.knowledge_level += int(delta)
self.soft_skill_level += int(delta)
print("Mentor {0} is teaching student {1}. Student's knowledge level is now {2}. And the mentor's soft skill level is now {3} ".format(
self.nickname, student.first_name, student.knowledge_level, self.soft_skill_level))
def grade_project(self, project, grade, delta):
project.grade = grade
self.soft_skill_level += int(delta)
print("Mentor {0} gave a {1} for project {2}. Mentor's soft skill level is now {3}.".format(
self.nickname, grade, project.name, self.soft_skill_level))
@classmethod
def create_by_csv(cls, file_name="mentors.csv"):
mentor_list = []
path = os.path.abspath("./data/%s" % file_name)
with open(path, newline='') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
new_mentor = Mentor(*row)
mentor_list.append(new_mentor)
return mentor_list |
9d9fcd5f8d6b2879a7e0e92e351eadc404aff631 | meggangreen/advent-code-2018 | /files/day-24.py | 9,883 | 3.515625 | 4 | """ Notes
side < army < group < unit, effective power
side = immune sys or infection
unit:
- hit points: amount of damage withstood -- health
- attack damage: amount of damage dealt -- damage
- attack type: eg radiation, fire, cold, slashing, etc -- weapon
- initiative: attack order and tie winner -- drive
- weaknesses: attack types
- immunities: attack types
group:
- units: [(quantity, unit)]
- effective power: sum(unit_quantity * unit_attack_damage)
- select_target(possible_targets)
- attack_target(target)
fight: 2 phases: target selection, attacking
- target selection:
in decreasing order of effective power, group targets enemy group to
which it deals most damage, after accounting for weakness and immunity
- each group has chosen up to 1 group to attack
- each group is being attacked by up to 1 group
- attacking:
"""
from queue import PriorityQueue
import re
# class Unit:
# """ information for one unit """
# def __init__(self, health, damage, weapon, weaknesses=None, immunities=None):
# self.health = health
# self.damage = damage
# self.weapon = weapon
# self.weaknesses = weaknesses
# self.immunities = immunities
# def __repr__(self):
# health = f"H:{self.health}"
# damage = f"D:{self.damage}"
# weapon = self.weapon
# # initi = f"I:{self.initiative}"
# weak = self.weaknesses
# immun = self.immunities
# return f'<Unit {health} {damage} {weapon} {weak} {immun}>'
class Group:
""" A Group is the smallest as a the trait for each unit can be extrapolated
to the group. A unit is just 1 member who lives or is lost in an attack.
"""
def __init__(self, banner, units, drive, health, damage, weapon, weaknesses=None,
immunities=None):
self.banner = banner
self.units = units
self.drive = drive # self.drive # * self.units
self.health = health
self.damage = damage
self.weapon = weapon
self.weaknesses = weaknesses if weaknesses else []
self.immunities = immunities if immunities else []
self._set_efficacy()
def __repr__(self):
return f'<G - {self.banner} - Units: {self.units} - Drive: {self.drive} - Effic: {self.efficacy} >'
def _set_efficacy(self):
self.efficacy = self.damage * self.units
def _select_target(self, targets):
""" called by Fight; returns the target """
target_q = PriorityQueue() # my new fave
impact = 0
for t in targets:
if t.banner == self.banner:
continue
impact = self._calc_impact_on(t)
target_q.put((-impact, -t.efficacy, -t.drive, t))
target = None if target_q.empty() else target_q.get()[3]
return target
def _calc_impact_on(self, target):
if self.units < 1:
impact = 0
else:
impact = self.efficacy
if self.weapon in target.immunities:
impact += -self.efficacy
elif self.weapon in target.weaknesses:
impact += self.efficacy
return impact
def _defend(self, impact):
""" updates units, drive, efficacy in an attack """
self.units += -(impact // self.health)
if self.units < 1:
self.units = 0
# print("group lost")
self._set_efficacy()
class Army:
""" Each side has an Army; each army has 1+ Groups """
def __init__(self, banner, groups=None):
self.banner = banner # immune system or infection
self.groups = groups if groups else set()
def __repr__(self):
groups = '\n '.join([g.__repr__() for g in self.groups])
return f'<Army {self.banner} with\n {groups} />'
def _exists(self):
if not self.groups:
# print(f"{self.banner} is no more.")
return False
for group in self.groups:
if group.units < 1:
self.groups.remove(group)
return True
class Fight:
""" A full turn of play. """
def __init__(self, armies):
self.armies = armies
self.face_offs = {}
def fight(self):
self._select_targets()
self._attack_targets()
return self.armies
def _select_targets(self):
# get all groups
groups = set([group for army in armies.values() for group in army.groups])
# choose selection order -- a PQ!
select_q = self._make_selection_queue(groups)
# for each Group:
while not select_q.empty():
_, _, selector = select_q.get()
# call G._select_target and pass avail targets
target = selector._select_target(groups)
if target:
# add to face_offs
self.face_offs[selector] = target
# remove selected from avail
groups.remove(target)
def _make_selection_queue(self, groups):
select_q = PriorityQueue()
for group in groups:
select_q.put((-group.efficacy, -group.drive, group))
return select_q
def _attack_targets(self):
# get attack order
attack_q = self._make_attack_queue()
# carry out attacks
while not attack_q.empty():
_, offense = attack_q.get()
defense = self.face_offs[offense]
impact = offense._calc_impact_on(defense)
# remove old defense
self.armies[defense.banner].groups.remove(defense)
# apply impact
defense._defend(impact)
# add modified defense if not lost
if defense.units > 0:
self.armies[defense.banner].groups.add(defense)
def _make_attack_queue(self):
attack_q = PriorityQueue()
for offense in self.face_offs:
attack_q.put((-offense.drive, offense))
return attack_q
class Battle:
""" A full game of Fights, with Armies. """
def __init__(self, armies):
self.armies = armies
def fight(self):
while True:
lost = []
for a, army in self.armies.items():
if army._exists() is False:
lost.append(a)
for a in lost:
self.armies.pop(a)
if len(self.armies) > 1:
self.armies = Fight(self.armies).fight()
elif len(self.armies) == 1:
army = [army for army in armies.values()][0]
units = sum([g.units for g in army.groups])
return f"Winner: {army.banner} with {units} units."
else:
return "Everyone loses in war."
def parse_input(filepath):
p_army = re.compile(r'(?<=^Army: )[\w\s]+(?=\n)')
p_units = re.compile(r'^[\d]+(?= units)')
p_health = re.compile(r'[\d]+(?= hit points)')
p_weaks = re.compile(r'(?<=weak to )[\w,\s]+(?=[;|\)])')
p_immuns = re.compile(r'(?<=immune to )[\w,\s]+(?=[;|\)])')
p_damage_weapon = re.compile(r'(?<=does )[\d]+ [\w]+(?= damage)')
p_drive = re.compile(r'(?<=initiative )[\d]+(?=\n)')
with open(filepath) as file:
lines = file.readlines()
# find armies and groups
armies = {}
for i, line in enumerate(lines):
# army?
is_army = re.search(p_army, line)
if is_army:
banner = is_army[0]
armies[banner] = Army(banner)
# group?
is_group = re.search(p_units, line)
if is_group:
units = is_group[0]
drive = re.search(p_drive, line)[0]
health = re.search(p_health, line)[0]
damage, weapon = re.search(p_damage_weapon, line)[0].split()
weaks = re.search(p_weaks, line)
if weaks:
weaks = weaks[0].split(', ')
immuns = re.search(p_immuns, line)
if immuns:
immuns = immuns[0].split(', ')
armies[banner].groups.add(Group(banner,
int(units),
int(drive),
int(health),
int(damage),
weapon,
weaks,
immuns))
return armies
def apply_boost(army, boost):
for group in army.groups:
group.damage += boost
group._set_efficacy()
return army
def find_boost_bisection():
""" found out bisection doesn't work for all inputs; certainly several
copied solutions didn't work for me.
"""
armies = parse_input('day-24.txt')
army = armies["Immune System"]
boost_low = 0
boost_upp = 0
boost = 0
winner = "Infection"
while "Infection" in winner:
if boost == 0:
boost_upp = 100
boost = boost_upp
else:
boost_low = boost_upp
boost_upp *= 10
boost = boost_upp
print(boost)
army_b = apply_boost(army, boost)
armies["Immune System"] = army_b
winner = Battle(armies).fight()
return boost_low, boost_upp
################################################################################
if __name__ == '__main__':
# testing
armies = parse_input('day-24-test.txt')
battle = Battle(armies)
assert battle.fight() == 'Winner: Infection with 5216 units.'
armies = parse_input('day-24.txt')
battle = Battle(armies)
pt1 = battle.fight()
print(f"Part 1: {pt1}")
|
2b4cb4a8810cce0e75d888f062410ef2bbda76fd | ishtiaque06/next_blue_bus | /pyScripts/csv_parser.py | 1,728 | 3.671875 | 4 | #This file parses a csv file which has multiple titles without commas followed by
#multiple lines of comma-separated values and outputs them into separate csv files
# Then writes these files into the corresponding days' CSV's.
import os.path
import csv
def parser():
current_dir = os.path.dirname(__file__)
#Open the input file as read-only
initial = open(os.path.join(current_dir,
'csv_schedules', 'bluebus_schedules.csv'),
'r')
csv_list = []
#loops through the input file
for line in initial:
#This block fixes the headings for Saturday night and Sunday.
if line == "BrynMawrtoHaverford,HaverfordtoBrynMawr\n":
line = "LeaveBrynMawr,LeaveHaverford\n"
if line == "LeavesBMC,LeavesSuburbanSquare,LeavesHCSouthLotBusStop,LeavesStokes,LeavesSuburbanSquare\n":
line = "LeaveBrynMawr,LeaveSuburbanSquare,LeaveHCSouthLotBusStop,LeaveHaverford,LeaveSuburbanSquare\n"
if ',' not in line: #If the line doesn't contain a comma, it's a title
filename = line[:-1] + '.csv' #the title is used to make the filename.csv
new_file = open((os.path.join(current_dir,
'csv_schedules/', filename)), 'w') #new file opened to write to
new_file.close() #new file is closed
csv_list.append(filename)
else: #Else, the csv line belongs to the title that was found in a previous line
new_file = open((os.path.join(current_dir,
'csv_schedules/', filename)), 'a') #appends the csv to the new file
new_file.write(line[:-1] + '\n')
new_file.close()
initial.close()
return csv_list
if __name__ == '__main__':
parser() |
a88db08f69102367f18f6b6b279db83ebd8e82a5 | mikebohdan/CGApp | /lab5/app/figure.py | 2,999 | 3.5 | 4 | from math import cos, sin
import numpy as np
class Point:
def __init__(self, x=0, y=0, z=0):
self.x = x * 10
self.y = y * 10
self.z = z * 10
def to_vector(self=None):
return np.matrix([self.x, self.y, self.z, 1])
class Line:
def __init__(self, from_p, to_p):
self.from_p = from_p
self.to_p = to_p
def __iter__(self):
return (getattr(self, attr) for attr in self.__dict__)
class Figure:
def __init__(self, figure=None):
try:
self.points = figure['points']
self.lines = [Line(self.points[f], self.points[t])
for f, t in figure['lines']]
except Exception:
self.points = []
self.lines = []
figure = Figure({
"points": [
# first rectangle
Point(1, 2, 2),
Point(1, 2, 9),
Point(6, 2, 2),
Point(6, 2, 9),
Point(1, 4, 2),
Point(1, 4, 9),
Point(6, 4, 2), # line to second rect
Point(6, 4, 9), # line to second rect
# second rectangle (num + 7)
Point(3, 4, 3),
Point(3, 4, 6),
Point(6, 4, 3), # line to first rect
Point(6, 4, 6), # line to first rect
Point(3, 5, 3), # line to third rect`
Point(3, 5, 6), # line to third rect
Point(6, 5, 3),
Point(6, 5, 6),
# third rectangle (num + 16)
Point(3, 5, 1), # line to second rect
Point(3, 5, 7), # line to second rect
Point(11, 5, 1),
Point(11, 5, 7),
Point(3, 6, 1), # line to fourth
Point(3, 6, 7), # line to fourth
Point(11, 6, 1),
Point(11, 6, 7), # line to fourth
# fourth rectangle (num + 24)
Point(3, 6, 5), # line to third
Point(3, 6, 7), # line to third
Point(5, 6, 5),
Point(5, 6, 7), # line to third
Point(3, 9, 5),
Point(3, 9, 7),
Point(5, 9, 5),
Point(5, 9, 7),
],
"lines": [
# first rectangle
[0, 4], [1, 5], [2, 6], [3, 7], # vertical
[0, 1], [1, 3], [3, 2], [2, 0], # top horizontal
[4, 5], [5, 7], [6, 4], # bottom horizontal
# second rectangle
[8, 12], [9, 13], [10, 14], [11, 15], # vertical
[8, 9], [9, 11], [10, 8], # top horizontal
[13, 15], [15, 14], [14, 12], # bottom horizontal
# third rectangle
[16, 20], [17, 21], [18, 22], [19, 23], # vertical
[17, 19], [19, 18], [18, 16], # top horizontal
[23, 22], [22, 20], # bottom horizontal
# fourth rectangle
[24, 28], [25, 29], [26, 30], [27, 31], # vertical
[27, 26], [26, 24], # top horizontal
[28, 29], [29, 31], [31, 30], [30, 28], # bottom horizontal
# connections
[6, 10], [11, 7], # first to second
[16, 12], [13, 17], # second to third
[20, 24], [23, 27] # third to fourth
]
})
|
25e208529299adf682217e85c0d03136b69958a0 | mikebohdan/CGApp | /lab3/app/curve.py | 647 | 3.515625 | 4 | from app.point import Point
class Curve:
def __init__(self, fpoint, tpoint, hpoint):
self.fpoint = fpoint
self.tpoint = tpoint
self.hpoint = hpoint
def __iter__(self):
return self._curve_iterator()
def _curve_iterator(self):
for i in range(0, 101, 5):
t = i / 100
A = (1 - t) ** 2
B = (1 - t) * t
C = t ** 2
denominator = A + B + C
yield Point((A * self.fpoint.x + B * self.hpoint.x + C * self.tpoint.x) / denominator,
(A * self.fpoint.y + B * self.hpoint.y + C * self.tpoint.y) / denominator)
|
8c7c2fe69ae3c8c279ddba7bbadee11bd04b5296 | idastambuk/shtrikaona-koda | /python/zadatak2.py | 225 | 3.890625 | 4 | """Napiši skriptu koja od korisnika traži unos tri broja i
javlja koji je od tih brojeva najveći."""
a=[]
while len (a) < 3:
x= int(raw_input("Upisi broj: "))
a.append(x)
print "najveći broj je", max(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.