blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
1c64989c3d865d279c0d8bc7dbbba53dc4c4c247 | loadlj/leetcode | /Range_sum_query.py | 760 | 3.734375 | 4 | # Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
class NumArray(object):
def __init__(self, nums):
self.nums = nums
self.updatedlist = []
self.updateList()
def updateList(self):
if len(self.nums) >0:
self.updatedlist.append(self.nums[0])
for i in range(1,len(self.nums)):
self.updatedlist.append(self.updatedlist[i-1] + self.nums[i])
def sumRange(self, i, j):
sum = self.updatedlist[j]
if i >=1:
sum -= self.updatedlist[i-1]
return sum
# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.sumRange(1, 2)
|
4b784585fefbe4087acbc9747f481fc650a21f84 | D7DonKIM7E/Python | /BOJ_2588.py | 119 | 3.6875 | 4 | first = int(input())
second = input()
for digit in second[::-1] :
print(first*int(digit))
print(first*int(second))
|
a686a0f2ff0ea00d450015ed2f203ac144098c0d | luka3117/toy | /py/山内 テキスト text sample code/ohm/ch4/list4-2.py | 1,149 | 3.515625 | 4 | #-*- coding: utf-8 -*-
# List 4-2 skew、kurtosisの例
from scipy.stats import skew, kurtosis, norm, uniform, kurtosistest
import math
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
numsamples = 100000
v1 = norm.rvs(loc=0.0, scale=1.0, size=numsamples)
print('正規分布N(0,1)', 'skew=', round(skew(v1),4), 'kurtosis=', round(kurtosis(v1),4))
vt = np.array([math.sqrt(u*16/numsamples) for u in range(numsamples)]) #右上がり三角分布を作る
#print('4', 'skew=', skew(v4), 'kurtosis=', kurtosis(v4))
v = v1+(vt*3.0) # v1とvtを要素ごとに足す。正規分布要素に右上がり三角要素が足される。
print('正規+右上がり', 'skew=', round(skew(v),4), 'kurtosis=', round(kurtosis(v),4))
# 出力結果は
# 正規分布N(0,1) skew= 0.0033 kurtosis= -0.0279
# 正規+右上がり skew= -0.4748 kurtosis= -0.4724
plt.hist(v, bins=50, normed=True, color='black', alpha=0.5)
plt.grid() #グリット線を引いてくれる
plt.xlabel('x') #x軸のラベル
plt.ylabel('頻度') #y軸のラベル
plt.title('正規分布+右上がり三角分布のヒストグラム')
plt.show()
|
5e260fa16cb00b8d231a1285fe00b907654183c2 | luka3117/toy | /py/山内 テキスト text sample code/ohm/ch7/list7-7.py | 2,833 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# List 7-7 出生率と死亡率の関係
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
np.set_printoptions(precision=4)
x = np.loadtxt('shusseiritsu.csv', delimiter=",") # CSVファイルからデータを読込む
# 出典 http://www.mhlw.go.jp/toukei/saikin/hw/jinkou/suikei15/dl/2015suikei.pdf
birth1 = [u[1] for u in x if u[0]<=1975]
death1 = [u[2] for u in x if u[0]<=1975]
birth2 = [u[1] for u in x if (1976<=u[0] and u[0]<=1989)]
death2 = [u[2] for u in x if (1976<=u[0] and u[0]<=1989)]
birth3 = [u[1] for u in x if 1990<=u[0]]
death3 = [u[2] for u in x if 1990<=u[0]]
model2 = sm.OLS(death2, sm.add_constant(birth2))
results2 = model2.fit()
print(results2.summary())
b, a = results2.params
print('1976~1989年 a=', a.round(4), 'b=', b.round(4), 'p値=', results2.pvalues)
# 出力結果は
# OLS Regression Results
# ==============================================================================
# Dep. Variable: y R-squared: 0.241
# Model: OLS Adj. R-squared: 0.178
# Method: Least Squares F-statistic: 3.813
# Date: Fri, 02 Feb 2018 Prob (F-statistic): 0.0746
# Time: 14:33:04 Log-Likelihood: 9.9691
# No. Observations: 14 AIC: -15.94
# Df Residuals: 12 BIC: -14.66
# Df Model: 1
# Covariance Type: nonrobust
# ==============================================================================
# coef std err t P>|t| [0.025 0.975]
# ------------------------------------------------------------------------------
# const 6.6939 0.255 26.223 0.000 6.138 7.250
# x1 -0.0382 0.020 -1.953 0.075 -0.081 0.004
# ==============================================================================
# Omnibus: 0.867 Durbin-Watson: 1.444
# Prob(Omnibus): 0.648 Jarque-Bera (JB): 0.486
# Skew: 0.434 Prob(JB): 0.784
# Kurtosis: 2.716 Cond. No. 97.7
# ==============================================================================
#
# Warnings:
# [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
#
# 1976~1989年 a= -0.0382 b= 6.6939 p値= [ 5.7855e-12 7.4589e-02]
|
afdc0cfdf6ac796e06cc2e1cd574cfb765b67eed | j2sdk408/misc | /mooc/algorithms_II/lsd_sort.py | 2,265 | 3.625 | 4 | """
implementation for least-signficant-digit-first string sort
"""
from str_custom import StringCustom
class LsdSort(object):
"""class for LSD string sort"""
def __init__(self, str_list):
"""initialization"""
self.str_list = str_list
self.sort()
def __str__(self):
"""to string"""
return "\n".join([str(x) for x in self.str_list])
def sort(self):
"""sort string"""
# extra space for re-ordering
reorder_list = [None] * len(self.str_list)
# starts from the longest position
max_len = max([x.length for x in self.str_list])
def map_idx(x):
"""calculate map index including None"""
if x is None:
return 0
else:
return ord(x) + 1
# sort from right to left
for char_idx in xrange(max_len - 1, -1, -1):
# ascii map + None@1 + extra space@0
key_map = [0] * (128 + 1 + 1)
# count frequency
for idx in xrange(len(self.str_list)):
curr_char = self.str_list[idx][char_idx]
key_map[map_idx(curr_char) + 1] += 1
# culmulate map
for idx in xrange(1, len(key_map)):
key_map[idx] += key_map[idx - 1]
# sort by copying to reorder list
for idx in xrange(len(self.str_list)):
curr_char = self.str_list[idx][char_idx]
curr_map_idx = map_idx(curr_char)
curr_key = key_map[curr_map_idx]
key_map[curr_map_idx] += 1
reorder_list[curr_key] = self.str_list[idx]
# copy back
for idx, item in enumerate(reorder_list):
self.str_list[idx] = item
if __name__ == "__main__":
import random
max_len = 20
str_count = 30
str_list = []
# random gen
for _ in xrange(str_count):
curr_str = []
for _ in xrange(int(random.random() * max_len)):
curr_char = chr(int(random.random() * 25) + 97)
curr_str.append(curr_char)
str_list.append("".join(curr_str))
sc_list = [StringCustom.from_str(x) for x in str_list]
lsd = LsdSort(sc_list)
print lsd
|
20fadd9ad05d61ed6b884287fd0cebdd0ae916e6 | j2sdk408/misc | /mooc/algorithms_II/st_tst.py | 4,503 | 3.734375 | 4 | """
implementation for string symbol table with ternary search try
"""
class Node(object):
"""class for tri node"""
MIDDLE = 0
LEFT = 1
RIGHT = 2
def __init__(self):
"""initialization"""
self.value = None
self.char = None
# 0: middle
# 1: left
# 2: right
self.node_list = [None] * 3
class StringST(object):
"""class for string-based symbol table"""
def __init__(self):
"""initialization"""
self.root_node = None
def __str__(self):
"""to string"""
out_list = []
return "\n".join(out_list)
def put(self, key, value):
"""put key-value pair into the symbol table"""
assert key.__class__ == str
self.root_node = self.__class__.put_node(
self.root_node,
key,
value,
0
)
def get(self, key):
"""return value paired with given key"""
assert key.__class__ == str
node = self.__class__.get_node(self.root_node, key, 0)
if node is None:
return None
else:
return node.value
def delete(self, key):
"""delete key and corresponding value"""
assert key.__class__ == str
self.root_node = self.__class__.delete_node(self.root_node, key, 0)
@classmethod
def put_node(cls, curr_node, key, value, d):
"""put key value to node, currently scanning position d"""
curr_char = key[d]
if curr_node is None:
curr_node = Node()
curr_node.char = curr_char
if curr_char < curr_node.char:
curr_node.node_list[Node.LEFT] = cls.put_node(
curr_node.node_list[Node.LEFT],
key,
value,
d
)
elif curr_char > curr_node.char:
curr_node.node_list[Node.RIGHT] = cls.put_node(
curr_node.node_list[Node.RIGHT],
key,
value,
d
)
elif d < len(key) - 1:
curr_node.node_list[Node.MIDDLE] = cls.put_node(
curr_node.node_list[Node.MIDDLE],
key,
value,
d + 1
)
else:
curr_node.value = value
return curr_node
@classmethod
def get_node(cls, curr_node, key, d):
"""get key @ position d"""
curr_char = key[d]
if curr_node is None:
return None
if curr_char < curr_node.char:
return cls.get_node(
curr_node.node_list[Node.LEFT],
key,
d
)
elif curr_char > curr_node.char:
return cls.get_node(
curr_node.node_list[Node.RIGHT],
key,
d
)
elif d < len(key) - 1:
return cls.get_node(
curr_node.node_list[Node.MIDDLE],
key,
d + 1
)
else:
return curr_node
@classmethod
def delete_node(cls, curr_node, key, d):
"""delete key and corresponding value"""
curr_char = key[d]
if curr_node is None:
return None
if curr_char < curr_node.char:
curr_node.node_list[Node.LEFT] = cls.delete_node(
curr_node.node_list[Node.LEFT],
key,
d
)
elif curr_char > curr_node.char:
curr_node.node_list[Node.RIGHT] = cls.delete_node(
curr_node.node_list[Node.RIGHT],
key,
d
)
elif d < len(key) - 1:
curr_node.node_list[Node.MIDDLE] = cls.delete_node(
curr_node.node_list[Node.MIDDLE],
key,
d + 1
)
else:
curr_node.value = None
# check if any link exists in current node
for node in curr_node.node_list:
if node is not None:
return curr_node
# check if current node holds value
if curr_node.value is not None:
return curr_node
else:
return None
if __name__ == "__main__":
st = StringST()
st.put("shell", 2)
st.put("apple", 123)
print st.get("shell")
print st.get("apple")
st.delete("shell")
print st.get("shell")
|
e671953c188a7d380130aa00f48a25ccbf099ad5 | j2sdk408/misc | /mooc/algorithms_II/msd_sort.py | 2,709 | 3.546875 | 4 | """
implementation for least-signficant-digit-first string sort
"""
from str_custom import StringCustom
class MsdSort(object):
"""class for MSD string sort"""
def __init__(self, str_list):
"""initialization"""
self.str_list = str_list
self._aux_list = [None] * len(self.str_list)
self.sort(0, len(self.str_list) - 1, 0)
def __str__(self):
"""to string"""
return "\n".join([str(x) for x in self.str_list])
@staticmethod
def map_idx(x):
"""calculate map index including None"""
if x is None:
return 0
else:
return ord(x) + 1
def sort(self, idx_st, idx_end, char_idx):
"""sort string"""
# terminate whtn index overlap
if idx_st >= idx_end:
return
# ascii map + None@1 + extra space@0
key_map = [0] * (128 + 1 + 1)
key_map2 = [0] * (128 + 1 + 1)
# count frequency
char_found = False
for idx in xrange(idx_st, idx_end + 1):
curr_char = self.str_list[idx][char_idx]
if curr_char is not None:
char_found = True
key_map[self.map_idx(curr_char) + 1] += 1
key_map2[self.map_idx(curr_char) + 1] += 1
# terminate when no char to be found
if not char_found:
return
# culmulate map
for idx in xrange(1, len(key_map)):
key_map[idx] += key_map[idx - 1]
# sort by copying to reorder list
for idx in xrange(idx_st, idx_end + 1):
curr_char = self.str_list[idx][char_idx]
curr_map_idx = self.map_idx(curr_char)
curr_key = key_map[curr_map_idx]
key_map[curr_map_idx] += 1
self._aux_list[curr_key] = self.str_list[idx]
# copy back
for idx in xrange(idx_st, idx_end + 1):
self.str_list[idx] = self._aux_list[idx - idx_st]
# sort recursively toward right
next_start = 0
for count in key_map2:
if count != 0:
self.sort(
idx_st + next_start,
idx_st + next_start + count - 1,
char_idx + 1
)
next_start += count
if __name__ == "__main__":
from lsd_sort import LsdSort
sc_list = StringCustom.from_str(
"itwasbestitwasw"
).suffixes()
msd = MsdSort(sc_list)
lrs = StringCustom.from_str("")
for idx in xrange(len(sc_list) - 1):
curr_len = msd.str_list[idx].lcp(msd.str_list[idx + 1])
if curr_len > lrs.length:
lrs = msd.str_list[idx].substring(0, curr_len - 1)
print lrs
|
8829a7674ab5b9cdd3b0e5e54f28611912b206d8 | j2sdk408/misc | /mooc/algorithms_II/pathes.py | 858 | 3.734375 | 4 | """
implementation of graph algorithms
"""
class Pathes(object):
"""class for path searching"""
def __init__(self):
"""initializer"""
self.s = 0
@classmethod
def from_graph(cls, G, s):
"""find pathes in G grom source s"""
p = cls()
p.s = s
assert s < G.V()
assert s >= 0
return p
def has_path_to(self, v_in):
"""is theree a path from s to v"""
return False
def path_to(self, v_in):
"""path from s to v; null if no such path"""
return None
def print_path(self, v_count):
"""print path"""
for v in xrange(v_count):
print "%s: %s" % (v, self.path_to(v))
if __name__ == "__main__":
import sys
file_name = sys.argv[1]
G = Graph.from_file(file_name)
P = Pathes.from_graph(G, 0)
|
02307d05d584281dd61948087f1ed8fc6853dafd | chitritha/python-project | /finalProj_cnalluru_07.py | 5,965 | 3.890625 | 4 | """
Program: Commodity Data Filtering Final
Author: Nalluru Chitritha Chowdary
Description: This program is used to filter and represent data based on user inputs
Revisions:
00 - Importing CSV, datetime and plotly modules
01 - Printing announcement
02 - Import data from CSV file and change into required format
03 - Compiling list of all Commodities, dates and locations in dictionaries
04 - Asking user input on the commodities, dates and locations required
05 - Filtering out the records based on the user criteria
06 - Creating a dict with commodities and locations as key and average of the prices as values
07 - Plotting the data using plotly
"""
### Step 1 - Importing CSV, datetime and plotly modules
import csv
import itertools
import sys
from _datetime import datetime
import plotly.offline as py
import plotly.graph_objs as go
### Step 2 - Printing announcement
print('=' * 26, '\nAnalysis of Commodity Data\n', '=' * 26, '\n', sep='')
### Step 3 - Import data from CSV file and change into required format
data = []
csvfile = open('produce_csv.csv', 'r')
reader = csv.reader(csvfile)
for row in reader:
if reader.line_num == 1:
locations = row[2:]
else:
for location, value in zip(locations, row[2:]): # iterate through locations and values
row_num = len(data) # index for the data row
data.append(row[:1]) # new data row: commodity
data[row_num].append(datetime.strptime(row[1], '%m/%d/%Y')) # append date
data[row_num].append(location) # append location
data[row_num].append(float(value.replace('$', ''))) # append price value
csvfile.close()
### Step 4 - Compiling list of all Commodities, dates and locations in dictionaries
commList = dict()
for num, commodity in enumerate(sorted(set(x[0] for x in data))):
commList[num] = commodity # Creating dict with index as keys and commodity as values
dateList = dict()
for num, date in enumerate(sorted(set(x[1] for x in data))):
dateList[num] = date.strftime('%Y-%m-%d')
# Creating dict with index as keys and dates in string format as values
locList = dict()
for num, location in enumerate(sorted(locations)):
locList[num] = location
# Creating dict with index as keys and locations as values
### Step 5 - Asking user input on the commodities, dates and locations required
print("SELECT PRODUCTS BY NUMBER ...")
for i in commList:
# Printing all commodities 3 a line
if (i + 1) % 3 == 0:
print(f"<{i:2}> {commList[i]:20}")
else:
print(f"<{i:2}> {commList[i]:20}", end='')
try:
products = [commList[int(p.replace('<> ', ''))] for p in
input("\nEnter product numbers separated by spaces: ").split()]
# Taking and validation user inputs
except TypeError as t:
print("\nInvalid input. Please enter a valid number from 0 to 21.")
sys.exit()
print("\nSelected products: ", end='')
print(*products, sep=" ")
print("\nSELECT DATE RANGE BY NUMBER ...")
for i in dateList:
# Printing all dates 5 a line
if (i + 1) % 5 == 0:
print(f"<{i:2}> {dateList[i]:<10}")
else:
print(f"<{i:2}> {dateList[i]:<10}", end='\t')
print(f"\nEarliest available date is: {min(dateList.values())}"
f"\nLatest available date is: {max(dateList.values())}\n")
try:
# Validating date input
startDate, endDate = map(
int, input("Enter start/end date numbers separated by a space: ").split())
except TypeError as t:
print('Invalid input. Please try again')
sys.exit()
except ValueError as v:
print("Please enter only 2 values: Start date and End Date")
sys.exit()
if not (not (endDate < startDate) and not (endDate < 0) and not (endDate > 52) and not (startDate < 0) and not (
endDate > 52) and not (startDate == '')) or endDate == '':
raise Exception("The start date cannot be greater than end date. Please enter a valid number between 0 and 52")
print(f"\nDates from {dateList[startDate]} to {dateList[endDate]}\n")
dates = [datetime.strptime(dateList[n], '%Y-%m-%d') for n in range(startDate, endDate + 1)]
# print(dates)
print("SELECT LOCATIONS BY NUMBER ...")
for i in locList:
# Printing all locations
print(f"<{i}> {locList[i]}")
try:
selLocations = [locList[int(l)] for l in input("\nEnter location numbers separated by spaces: ").split()]
# Taking and validation user inputs
except TypeError as t:
print("Please enter a valid number between 0 and 4")
sys.exit()
print("\nSelected locations: ", end='')
print(*selLocations, sep=" ")
### Step 6 - Filtering out the records based on the user criteria
select = list(filter(lambda a: a[0] in products and a[1] in dates and a[2] in selLocations, data))
print(len(select), "records have been selected.")
### Step 7 - Creating a dict with commodities and locations as key and average of the prices as values
pltData = dict()
for x in itertools.product(products, selLocations):
priceList = [i[3] for i in select if i[0] == x[0] and i[2] == x[1]]
if len(priceList) > 0:
pltData[x] = sum(priceList) / len(priceList)
### Step 8 - Plotting the data using plotly
plt = [None] * len(selLocations)
for i, loc in enumerate(selLocations):
# Creating list of lists with the required information
plt[i] = go.Bar(
x=products,
y=[pltData[y] for y in pltData.keys() if y[1] == loc],
name=loc
)
layout = go.Layout(
barmode='group'
)
fig = go.Figure(data=plt, layout=layout)
# Adding a title to the x axis, y axis and chart
fig.update_layout(title_text=f'Produce Prices from {dateList[startDate]} through {dateList[endDate]}',
xaxis=dict(title='Product'),
yaxis=dict(title='Average Price',
tickformat="$.2f")) # formatting the y axis values
py.plot(fig, filename='final-proj.html')
|
94a97edaa66c9527fc133ec3c33386a5410968ba | biradarshiv/Python | /CorePython/24_String_Formatting.py | 1,464 | 4.46875 | 4 | """
The format() method allows you to format selected parts of a string.
Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?
To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method:
"""
print("# First example")
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
print("# Format the price to be displayed as a number with two decimals")
price = 49
txt = "The price is {:.2f} dollars"
print(txt.format(price))
print("# Multiple Values")
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
print("# EOF")
# You can use index numbers (a number inside the curly brackets {0})
# to be sure the values are placed in the correct placeholders
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
print("# Named Indexes")
# You can also use named indexes by entering a name inside the curly brackets {carname},
# but then you must use names when you pass the parameter values txt.format(carname = "Ford")
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
print("# EOF")
|
6ef55a33502d489e160f6b1109182584a17b792b | biradarshiv/Python | /CorePython/1Introduction_Comments.py | 1,466 | 4.03125 | 4 | """
Python is a programming language.
Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English language.
Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
Python uses indentation to indicate a block of code.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly brackets for this purpose.
Run below in command line
# To get to know the python version installed in our system
python --version
# Save the file containing code with an extension of .py and run it with below command
python helloworld.py
"""
# Indentation Matters
if 5 > 2:
print("Five is greater than two!")
# Even though the indentation space is different it has to be the same to consider it as a block
# Even a single space will do as a indentation. Atleast one space should be there to start a block
if 6 > 2:
print("Six is greater than two!")
print("This will also print because of same indentation")
# Variables
# In Python variables are created the moment you assign a value to it. Python has no command for declaring a variable.
x = 5
y = "Hello, World!"
print(x)
print(y)
# Single line comment is # and multiline comment is in the middle of 3 double quotes
'Single line comment'
"""
Multiple
Line
Comment
"""
|
a36c60c380517b1e6b6d146669e9b93cf797fbcd | biradarshiv/Python | /CorePython/13_ClassObject.py | 2,393 | 4.25 | 4 | """
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
"""
print("# Create a class and access a property in it")
class MyClass:
x = 5
print(MyClass)
p1 = MyClass()
print(p1.x)
print("# __init__() Function")
print("""
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties,
or other operations that are necessary to do when the object is being created:""")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
print("# Object Methods")
# Objects can also contain methods. Methods in objects are functions that belong to the object.
# Note: The self parameter is a reference to the current instance of the class,
# and is used to access variables that belong to the class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
print("# The self Parameter")
"""The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:"""
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
print("# Delete Object Properties")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1.age
# print(p1.age) # This will throw error, since this property of the object is deleted in the above line
print("# Delete Objects")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1
# print(p1) # This will throw error, since this complete object is deleted in the above line
print("# EOF")
|
3edbceaa1a25e81edc5e284886f8a74ed0b875cc | szoto1/python101 | /day03.py | 3,946 | 3.625 | 4 | # # # # # wiek = input("Ile masz lat?")
# # # # # koty = input("Ile masz kotów?")
# # # #
# # # # # wiek = 2
# # # # # koty = 5
# # # #
# # # # # zdanie = "Ala ma 2 lata i posiada 5 kotów."
# # # # # zdanie = "Ala ma " + str(wiek) + " lata i posiada " + str(koty) + " kotów."
# # # # # zdanie = f"Ala ma {wiek} lata i posiada {koty} kotów."
# # # # # zdanie = "Ala ma {} lata i posiada {} kotów.".format(wiek, koty)
# # # # # zdanie = "Ala ma {a} lata i posiada {b} kotów.".format(b=koty, a=wiek)
# # # # # print(zdanie)
# # # #
# # # # # liczba = 1.234
# # # # # print("liczba: %s" % liczba) # 1.234 (string rep.)
# # # # # print("liczba: %f" % liczba) # 1.234000 (float)
# # # # # print("liczba: %0.10f" % liczba) # 1.2340000000 (float z precyzją)
# # # # # print("liczba: %0.1f" % liczba) # 1.2 (float z precyzją/zaokrąlenie)
# # # # # print("liczba: %d" % liczba) # 1 (całkowita)
# # # #
# # # # # 012345678901
# # # # # zdanie_master = "encyklopedia"
# # # # # zdanie = zdanie_master[4] # k
# # # # # zdanie = zdanie_master[-3] # d
# # # # # zdanie = zdanie_master[2:8] # cyklop
# # # # # zdanie = zdanie_master[:7] # encyklo
# # # # # zdanie = zdanie_master[8:] # edia
# # # # # zdanie = zdanie_master[1:7:2] # nyl
# # # # # zdanie = zdanie_master[::-1] # aidepolkycne
# # # # # print(zdanie)
# # # #
# # # # # print("Start")
# # # # # zmienna_a = False
# # # # # if(zmienna_a):
# # # # # print("Prawda")
# # # # # else:
# # # # # print("Fałsz")
# # # # # print("Koniec")
# # # #
# # # # # print("Sprawdzenie parzystości liczb")
# # # # # liczba = int(input("Podaj liczbę: "))
# # # # # # liczba = 2
# # # # # if(liczba%2==0):
# # # # # print("Liczba parzysta.")
# # # # # else:
# # # # # print("Liczba nieparzysta.")
# # # # # print("Koniec.")
# # # #
# # # # # print("Sprawdzenie podzielnosci przez 3 i 5")
# # # # # liczba = int(input("Podaj liczbę: "))
# # # # # # liczba = 15
# # # # #
# # # # # if (liczba%3==0 and liczba%5==0):
# # # # # print("Liczba podzielna przez 3 i przez 5")
# # # # # elif liczba%3==0:
# # # # # print("Liczba podzielna przez 3")
# # # # # elif liczba%5==0:
# # # # # print("Liczba podzielna przez 5")
# # # # # else:
# # # # # print("Liczba niepodzielna przez 3 i 5")
# # # # # print("Koniec.")
# # # #
# # # # # # wyrazy = ("raz", "dwa", "trzy") # krotka == tuple - nie można edytować
# # # # # wyrazy = ["raz", "dwa", "trzy"] # list - lista, można edytować
# # # # # wyrazy[0] = "jeden"
# # # # # print(wyrazy)
# # # #
# # # # # liczby_parzyste = range(0,20,2)
# # # # # # if 10 in liczby_parzyste:
# # # # # # print("Prawda")
# # # # # # else:
# # # # # # print("Fałsz")
# # # # # lista_liczb_parzystych = list(liczby_parzyste)
# # # # # print((lista_liczb_parzystych))
# # # # # lista_liczb_parzystych = tuple(liczby_parzyste)
# # # # # print((lista_liczb_parzystych))
# # # #
# # # # napis = "dwa"
# # # # lista = list(napis) # ['d', 'w', 'a']
# # # # print(lista)
# # # # lista = (napis) # dwa
# # # # print(lista) # ['d', 'w', 'a']
# # #
# # # lista_zakupow = ["kiełbasa", "piwko", "chipsy", "węgiel", "kubeczki"]
# # # print(lista_zakupow)
# # # lista_zakupow.append("talerzyki")
# # # print(lista_zakupow)
# # # lista_zakupow.insert(0, "grill")
# # # print(lista_zakupow)
# # # lista_zakupow[0] = "elektryczny grill"
# # # print(lista_zakupow)
# # # lista_zakupow.remove("piwko")
# # # print(lista_zakupow)
# # # if "vodka" in lista_zakupow:
# # # lista_zakupow.remove("vodka")
# # # else: print("Brak vodki")
# # #
# # # del(lista_zakupow[1])
# # # print(lista_zakupow)
# #
# # print("Start")
# # liczba = 1
# # while liczba < 5:
# # print(liczba)
# # liczba = liczba + 1
# # print("Koniec")
# #
#
# lista_liczb = [1,2,3,4]
# for liczba in lista_liczb:
# print(liczba)
# if liczba==2:
# break
#
# for litera in "jakies zdanie":
# print(litera) |
50d9dd353abba8ec79d57f9603db650e5756fae9 | sathishkumar-smart/Sathish-kumar | /grap.py | 286 | 3.796875 | 4 | import turtle
colors = [ "red","purple","blue","green","orange","yellow","white","brown","violet"]
my_pen = turtle.Pen()
turtle.bgcolor("black")
for i in range(360):
my_pen.pencolor(colors[i % 9])
my_pen.width(i/50 + 1)
my_pen.forward(i)
my_pen.left(65) |
3446b3c1b5cb77bc60d2c5709e91d8656c3447ea | Nicholas-Swift/Data-Structures | /set.py | 5,193 | 3.859375 | 4 | # A Hash Table
from linkedlist import LinkedList
class Set(object):
def __init__(self, init_size=8):
"""Initialize this hash table with the given initial size"""
# Best: Omega(1)
# Worst: O(n) (init size)
self.buckets = [LinkedList() for i in range(init_size)]
self.entries = 0
self.load = self.entries / len(self.buckets)
self.max_load = 2/float(3)
def __repr__(self):
"""Return a string representation of this hash table"""
return 'HashTable({})'.format(self.length())
def __contains__(self, key):
"""Does it contain the item"""
# Best: Omega(1)
# Worst: O(n) (number of items in bucket)
return self.contains(key)
def __iter__(self):
"""Iterate through the hash table"""
# Best: Omega(1)
# Worst: O(1)
for bucket in self.buckets:
if bucket:
for item in bucket:
yield item
def _update_entries(self, number_added):
"""Update the number of entries and update the load, resize if needed"""
# Best: Omega(1)
# Worst: O(1)
self.entries += number_added
self.load = self.entries / float(len(self.buckets))
if self.load > self.max_load:
self._resize_up()
def _resize_up(self):
"""The load factor is greater than 0.75! Resize and Rehash! Resize and Rehash it all!"""
# Best: Omega(n)
# Worst: O(n)
new_length = len(self.buckets)*2
# Create new buckets list, recalculate load with new_length
new_buckets = [LinkedList() for i in range(new_length)]
self.load = self.entries / float(new_length)
# Iterate through current items and add to new buckets
for item in self.__iter__():
index = hash(item) % new_length
new_buckets[index].append(item)
self.buckets = new_buckets
return
def _resize_down(self):
"""Resize down! There are too many buckets and too little entries. Resize and Rehash!"""
# Best: Omega(n)
# Worst: O(n)
new_length = self.entries * 2
# Create new buckets list, recalculate load with new_length
new_buckets = [LinkedList() for i in range(new_length)]
self.load = self.entries / float(new_length)
# Iterate through current items and add to new buckets
for item in self.__iter__():
index = hash(item) % new_length
new_buckets[index].append(item)
self.buckets = new_buckets
return
def _bucket_index(self, key):
"""Return the bucket index where the given key would be stored"""
# Best: Omega(1)
# Worst: O(1)
return hash(key) % len(self.buckets)
def _bucket(self, key):
"""Return the bucket where the given key would be stored"""
# Best: Omega(1)
# Worst: O(1)
index = self._bucket_index(key)
return self.buckets[index]
def length(self):
"""Return the length of this hash table"""
# Best: Omega(1)
# Worst: O(1)
return self.entries
def contains(self, key):
"""Return True if this hash table contains the given key, or False"""
# Best: Omega(1)
# Worst: O(n) (number of items in bucket)
bucket = self._bucket(key)
for item_key, item_value in bucket:
if key == item_key:
return True
return False
def add(self, item):
"""Insert the given item to the set"""
# Best: Omega(1)
# Worst: Omega(1)
bucket = self._bucket(item)
bucket_item = bucket.find(lambda x: x == item)
if bucket_item is None:
bucket.append(item)
self._update_entries(1)
def remove(self, item):
"""Delete the given item from this hash table, or raise KeyError"""
# Best: Omega(1)
# Worst: O(n)
bucket = self._bucket(item)
bucket_item = bucket.find(lambda x: x == item)
if bucket_item is not None:
bucket.delete(item)
self._update_entries(-1)
return
else:
raise KeyError('Item is not in HashTable')
def items(self):
"""Return a list of all items in this hash table"""
# Best: Omega(n) (number of items in hash table)
# Worst: O(n)
items = []
for item in self.__iter__():
items.append(item)
return items
def shrink():
"""Let user shrink the hash table to fit"""
# Best: Omega(n)
# Worst: O(n)
self._resize_down()
return
def clear(self):
"""Empty the Linked List"""
# Best: Omega(1)
# Worst: O(n) (number of buckets)
for i, bucket in enumerate(self.buckets):
if bucket:
self.buckets[i] = LinkedList()
self.entries = 0
self.load = 0
def test_hash_table():
ht = HashTable()
ht.set('1', 1)
ht.set('2', 1)
ht.set('3', 1)
for i in ht.buckets:
print(i)
if __name__ == '__main__':
test_hash_table()
|
4ff11193a8c26d84d00ba20d3fab03525b980fa9 | Nicholas-Swift/Data-Structures | /test_deque.py | 2,267 | 3.765625 | 4 | #!python
from deque import Deque
import unittest
class QueueTest(unittest.TestCase):
def test_init(self):
q = Deque()
assert q.peekLeft() is None
assert q.peekRight() is None
assert q.length() == 0
assert q.is_empty() is True
def test_init_with_list(self):
q = Deque(['A', 'B', 'C'])
assert q.peekLeft() == 'A'
assert q.peekRight() == 'C'
assert q.length() == 3
assert q.is_empty() is False
def test_length_with_push_and_pop_right(self):
q = Deque()
assert q.length() == 0
q.pushRight('A')
assert q.length() == 1
q.pushRight('B')
assert q.length() == 2
q.popRight()
assert q.length() == 1
q.popRight()
assert q.length() == 0
def test_length_with_push_and_pop_left(self):
q = Deque()
assert q.length() == 0
q.pushLeft('A')
assert q.length() == 1
q.pushLeft('B')
assert q.length() == 2
q.popLeft()
assert q.length() == 1
q.popLeft()
assert q.length() == 0
def test_length_with_push_and_pop_left_and_right(self):
q = Deque()
assert q.length() == 0
q.pushRight('A')
assert q.length() == 1
q.pushLeft('B')
assert q.length() == 2
q.popRight()
assert q.length() == 1
q.popLeft()
assert q.length() == 0
def test_peek_left_and_right(self):
q = Deque()
assert q.peekLeft() is None
q.pushRight('A')
assert q.peekLeft() == 'A'
assert q.peekRight() == 'A'
q.pushRight('B')
assert q.peekLeft() == 'A'
assert q.peekRight() == 'B'
q.popRight()
assert q.peekRight() == 'A'
q.popRight()
assert q.peekLeft() is None
def test_push_right_and_left(self):
q = Deque()
q.pushLeft('A')
q.pushRight('B')
assert q.peekLeft() == 'A'
assert q.peekRight() == 'B'
q.pushRight('C')
assert q.peekLeft() == 'A'
assert q.peekRight() == 'C'
q.pushLeft('Z')
assert q.peekLeft() == 'Z'
assert q.peekRight() == 'C'
if __name__ == '__main__':
unittest.main()
|
0abe423a5725967d6b813d2c72571fb1d5b96773 | Junrongh/15-619-CloudComputing | /Project1_1/q5.py | 1,235 | 3.8125 | 4 | #!/usr/bin/env python3
import pandas as pd
import json
from csv import QUOTE_NONE
def main():
"""
Please search and read the following docs to understand the starter code.
pandas.read_table
1) With 'squeeze=True', pandas.read_table returns a Series instead of a
DataFrame.
2) Without 'quoting=QUOTE_NONE', the following records will be
interpreted to share the same title 'Wild_Bill_Hickok':
"Wild_Bill"_Hickok 63
Wild_Bill_Hickok 40
3) Without 'keep_default_na=False', the following records will be
interpreted to numpy.nan (Not a Number):
NaN 13
pandas.Index.tolist
to convert the indexes to a list
TODO:
* Slice the top 3 articles
* Convert the indexes as a list
* Dump the list as a JSON array
* Print the JSON array to StdOut
"""
navalues=['nan']
s = pd.read_table('output', header=None, index_col=0, squeeze=True,
quoting=QUOTE_NONE, keep_default_na=False,
na_values=navalues, encoding='utf-8')
d = pd.Index.tolist(s.sort_values(ascending = False).head(3).index)
print(json.dumps(d))
if __name__ == "__main__":
main()
|
5b23f87d82b4596860ca67e2d6232e4207f053a9 | kanosaki/picbot | /picbot/utils/__init__.py | 824 | 3.5 | 4 |
import itertools
def uniq(*iters):
"""Make unique iterator with preserving orders. """
return UniqueIterator(itertools.chain(*iters))
class UniqueIterator(object):
def __init__(self, source):
self.source = source
self._history = set()
def __iter__(self):
return self
def __next__(self):
next_candidate = next(self.source)
while next_candidate in self._history:
next_candidate = next(self.source)
self._history.add(next_candidate)
return next_candidate
class AttrAccess(dict):
def __getattr__(self, key):
try:
v = self[key]
if isinstance(v, dict):
return AttrAccess(**v)
else:
return v
except KeyError:
raise AttributeError(key)
|
8f6472d4db42afc132521b63df85977a06582164 | SociallyAwkwardTurtle/Python | /Vestluskaaslane.py | 398 | 3.96875 | 4 | print("Hello world!")
print("I am Thonny!")
print("What is your name?")
myName = input()
print("Hello, " + myName + ", it's nice to meet you!")
print("How old are you?")
input()
print("Oh, that's nice!")
from random import *
a = (randint(2, 5))
if a == 2:
a=("two")
elif a == 3:
a=("three")
elif a == 4:
a=("four")
elif a == 5:
a=("five")
print ("I am only " + a + " years old.")
|
f0d4e56573bf9b971b561a94b472facc155ebb35 | ajboxjr/CS-2-Tweet-Generator | /class7/data-structure/linkedlist.py | 7,118 | 4.21875 | 4 | class Node(object):
def __init__(self, data):
"""Initialize the node with a data and a pointer(next)"""
self.data = data
self.next = None
def __repr__(self):
"""Return a string representation of this node."""
return 'Node({!r})'.format(self.data)
"""
TO lower space time complexity added abstract len function(self.len)
"""
class LinkedList(object):
"""Initialize this linked list and append the given items, if any."""
def __init__(self, items=None):
self.head = None
self.tail = None
#Alternative way of calculating length/ rather than itteration
self.len = 0
if items is not None:
for item in items:
self.append(item)
def __str__(self):
"""Return a formatted string representation of this linked list."""
items = ['({!r})'.format(item) for item in self.items()]
return '[{}]'.format(' -> '.join(items))
def __repr__(self):
"""Return a string representation of this linked list."""
return 'LinkedList({!r})'.format(self.items())
def __iter__(self):
"""Returning the start node for the self"""
self.node = self.head
return self
def __next__(self):
"""Return the current node in instance of the linked list """ # Kaichi
# 1. set current node as variable
# update the itterator to next node(for next update)
# 2. current node
if self.node is not None:
node = self.node
self.node = self.node.next
return node
else:
raise StopIteration
def items(self):
"""Return a list (dynamic array) of all items in this linked list.
Best and worst case running time: O(n) for n items in the list (length)
because we always need to loop through all n nodes to get each item."""
items = [] # O(1) time to create empty list
# Start at head node
# Loop until node is None, which is one node too far past tail
for node in self: # Always n iterations because no early return
items.append(node.data) # O(1) time (on average) to append to list
# Skip to next node to advance forward in linked list
# Now list contains items from all nodes
return items # O(1) time to return list
def is_empty(self):
"""Return a boolean indicating whether this linked list is empty."""
return self.head is None and self.tail is None
def append(self,data):
"""Add Node with data to the end of linked list and set to tail"""
if self.is_empty():
# setting tail and head to Node
self.head = Node(data)
self.tail = self.head
self.len +=1
else:
#Use self.tail to elimitate itterating
#1. Create Node
#2. Set tail.next to Node
#3. Set tail to node
last = self.tail
node = Node(data)
last.next = node
self.tail = node
self.len += 1
print(self)
def prepend(self,data):
"""Add Node to begining of Linkelist. Set it to head"""
if self.is_empty():
self.head = Node(data)
self.tail = self.head
self.len += 1
else:
#1. Create a node
#2. Set node next to head
#3. Set head to the node
new = Node(data)
self.len += 1
new.next = self.head
self.head = new
def replace(self,item, quality):
"""Find item and set it's prev(if one) to item and item prev.next to item"""
curr = self.head
while curr:
if quality(curr.data):
curr.data = item
return True
else:
curr = curr.next
return False
def find(self, quality):
for node in self:
if quality(node.data): #Node(data)[0]
return node.data
return None
def delete(self,item):
"""Delete a node based on it's data value"""
#Delete first node
if self.is_empty():
return ValueError
else:
if self.head.data == item:
self.head = self.head.next
self.len -=1
if self.head == None:
self.tail = None
return "Deleted first node"
#The other nodes
else:
#IF item found prev.next will be set to curr.next(erasing the node)
prev = self.head
curr = prev.next
while curr is not None:
print("prev {} , cur {}".format(prev.data, curr.data))
if curr.data == item:
prev.next = curr.next
self.len -=1
if prev.next == None:
self.tail = prev
return "deleted {}".format(curr)
else:
prev = prev.next
curr = prev.next
if curr == None:
self.tail = None
else:
print("{} is not in the linkedlist".format(item))
return ValueError
def get_node(self, index):
"""(ABstract). Get element based on index."""
if self.is_empty():
return -1
else:
if index == 0:
return self.head
else:
x = 0
curr = self.head
while x < index:
if curr.next != None:
print(curr.data)
curr = curr.next
x+=1
else:
print("index out of bounds")
return -2
print(curr.data)
return curr
def length(self):
"""Return the legth of the code"""
"""
This solution is O(N)
idx = 0
for _ in self:
idx +=1
return idx
"""
return self.len
def test_linked_list():
ll = LinkedList()
print('list: {}'.format(ll))
print('\nTesting append:')
for item in ['A', 'B', 'C']:
print('append({!r})'.format(item))
ll.append(item)
print('list: {}'.format(ll))
print('head: {}'.format(ll.head))
print('tail: {}'.format(ll.tail))
print('length: {}'.format(ll.length()))
# Enable this after implementing delete method
delete_implemented = True
if delete_implemented:
print('\nTesting delete:')
for item in ['B', 'C', 'A']:
print('delete({!r})'.format(item))
ll.delete(item)
print('list: {}'.format(ll))
print('head: {}'.format(ll.head))
print('tail: {}'.format(ll.tail))
print('length: {}'.format(ll.length()))
if __name__ == '__main__':
test_linked_list()
|
d11e5c2dd401e69ba65f98f2557fb496ff1e1a47 | trivedisorabh/Triangle-Symmetries-with-Python-Turtle | /triangle_symmetry_turtle..py | 4,097 | 4.03125 | 4 | import turtle
import tkinter as tk
screen = turtle.Screen()
class Label(turtle.Turtle):
def __init__(self, coordinates=None, screen=screen):
turtle.Turtle.__init__(self)
if coordinates is None:
self.coordinates = [0, 0]
else:
self.coordinates = coordinates
self.text = ""
self.color("white")
self.coordinates = coordinates
self.hideturtle()
self.penup()
self.screen = screen
def show(self, message, alignment="center", size=18):
self.screen.tracer(0)
self.clear()
self.goto(self.coordinates)
self.write(
message,
font=("Helvetica", size),
align=alignment,
)
self.screen.tracer(1)
def show_labels(vertices):
global label1, label2, label3
label1.show(vertices[0])
label2.show(vertices[1])
label3.show(vertices[2])
def clear_labels():
global label1, label2, label3
label1.clear()
label2.clear()
label3.clear()
def reset():
global vertices
vertices = ["A", "B", "C"]
show_labels(vertices)
def rotate_clockwise():
global vertices
temp = vertices[-1]
for i in range(len(vertices) - 1, 0, -1):
vertices[i] = vertices[i - 1]
vertices[0] = temp
update_rotation("clockwise")
def rotate_anticlockwise():
global vertices
temp = vertices[0]
for i in range(len(vertices) - 1):
vertices[i] = vertices[i + 1]
vertices[-1] = temp
update_rotation("anticlockwise")
def reflect_A():
global vertices
b_pos = vertices.index("B")
c_pos = vertices.index("C")
vertices[b_pos], vertices[c_pos] = (
vertices[c_pos],
vertices[b_pos],
)
update_reflection()
def reflect_B():
global vertices
a_pos = vertices.index("A")
c_pos = vertices.index("C")
vertices[a_pos], vertices[c_pos] = (
vertices[c_pos],
vertices[a_pos],
)
update_reflection()
def reflect_C():
global vertices
a_pos = vertices.index("A")
b_pos = vertices.index("B")
vertices[a_pos], vertices[b_pos] = (
vertices[b_pos],
vertices[a_pos],
)
update_reflection()
def update_rotation(direction):
global triangle
clear_labels()
if direction == "clockwise":
triangle.right(120)
else:
triangle.left(120)
show_labels(vertices)
def update_reflection():
global triangle
clear_labels()
show_labels(vertices)
def make_button(canvas, text, command):
return tk.Button(
canvas.master,
font=("Helvetica", 12),
text=text,
background="hotpink",
foreground="white",
bd=0,
command=command,
)
def create_button(canvas, x, y, text, command):
canvas.create_window(
x, y, window=make_button(canvas, text, command)
)
if __name__ == "__main__":
screen.setup(500, 600)
screen.title("Symmetries of an Equilateral Triangle")
screen.bgcolor("blue")
canvas = screen.getcanvas()
label1 = Label([-85, -55])
label2 = Label([0, 75])
label3 = Label([85, -55])
triangle = turtle.Turtle("triangle")
triangle.shapesize(120 / 20)
triangle.color("hotpink")
triangle.right(30)
canvas = screen.getcanvas()
create_button(canvas, 0, -250, "Reset", reset)
create_button(
canvas,
0,
-150,
"Rotate 120° clockwise",
rotate_clockwise,
)
create_button(
canvas,
0,
-200,
"Rotate 120° anticlockwise",
rotate_anticlockwise,
)
create_button(
canvas,
0,
100,
"Reflect about perp. bisector of BC",
reflect_A,
)
create_button(
canvas,
0,
150,
"Reflect about perp. bisector of AC",
reflect_B,
)
create_button(
canvas,
0,
200,
"Reflect about perp. bisector of AB",
reflect_C,
)
vertices = ["A", "B", "C"]
show_labels(vertices)
turtle.done()
|
b20a049364c8648b65d06340a2cdd1613ff9c5ec | chris31513/haskell-pearls | /Python/criptoaritmos.py | 3,745 | 3.546875 | 4 | #Christian Rodrigo Garcia Gomez
#Decidí usar Python por que se me facilita mucho más pensar el código en este lenguaje.
#Especificamente para este problema es más sencillo usar Python porque resulta más claro a la hora de trabajar con listas.
import random
import sys
import gc
sys.setrecursionlimit(30000000)
def criptoaritmos(string):
return generate_valid_tuples(string)
def split_string(string):
gc.collect()
if(check_valid_string(string)):
return merge_splits(split_in_math_symbol(string), split_in_eq_symbol(string))
else:
raise Exception("La cadena '{}' no es valida".format(string))
def get_math_symbol(string):
if("+" in string):
return "+"
elif("*" in string):
return "*"
elif("-" in string):
return "-"
else:
raise Exception("La cadena '{}' no es valida".format(string))
def split_in_math_symbol(string):
gc.collect()
return string.replace(" ", "").split(get_math_symbol(string))
def split_in_eq_symbol(string):
gc.collect()
return split_in_math_symbol(string)[1].split("=")
def merge_splits(list1, list2):
gc.collect()
return list1[0:len(list1) - 1] + list2
def get_inits(string):
gc.collect()
return get_inits_aux(split_string(string), list())
def get_inits_aux(splitted_string, list_aux):
gc.collect()
if(splitted_string == []):
return list_aux
else:
list_aux.append(splitted_string[0][0])
return get_inits_aux(splitted_string[1:len(splitted_string)], list_aux)
def to_int(splitted_string, inits):
gc.collect()
return to_int_aux("".join(set("".join(splitted_string))), inits, list())
def to_int_aux(string_without_duplicates, inits, list_aux):
gc.collect()
for char in string_without_duplicates:
if(char in inits):
list_aux.append((char, random.randint(1, 9)))
else:
list_aux.append((char, random.randint(0, 9)))
return list_aux
def check_valid_string(string):
gc.collect()
return ("+" in string or "*" in string or "-" in string) and "=" in string
def build_packages(ints, string):
gc.collect()
return build_packages_aux(ints, split_string(string), list(), list())
def build_packages_aux(ints, splitted_string, list_aux1, list_aux2):
gc.collect()
for string in splitted_string:
for char in string:
list_aux2.append(str(get_int(char, ints)))
list_aux1.append("".join(list_aux2.copy()))
list_aux2.clear()
return list_aux1
def get_int(char, ints):
gc.collect()
for tup in ints:
if(char == tup[0]):
return tup[1]
def is_valid(ints, string):
gc.collect()
if("+" in string):
return int(build_packages(ints, string)[0]) + int(build_packages(ints, string)[1]) == int(build_packages(ints, string)[2])
elif('*' in string):
return int(build_packages(ints, string)[0]) * int(build_packages(ints, string)[1]) == int(build_packages(ints, string)[2])
elif('-' in string):
return int(build_packages(ints, string)[0]) - int(build_packages(ints, string)[1]) == int(build_packages(ints, string)[2])
def generate_valid_tuples(string):
gc.collect()
return generate_valid_tuples_aux(string, list())
def generate_valid_tuples_aux(string, list_aux):
gc.collect()
while(len(list_aux) != 1):
list_aux.append(to_int(split_string(string), get_inits(string)).copy())
print("\rLista analizada: %s" % (list_aux[-1]), end = '')
if(not is_valid(list_aux[len(list_aux) - 1], string)):
del list_aux[-1]
sys.stdout.write("\033[K")
print("\rLista final: %s " % (list_aux[-1]), end = '\n')
return list_aux
criptoaritmos(input("Escribe tu palabra: ")) |
2358ce9bd1a93f9692cff142908bde4f985fd4c5 | sukiskumar/sukiskumar | /ex3.py | 202 | 4.125 | 4 | ch=input("enter a char:")
if(ch=='A'or ch=='a'or ch=='E'or ch=='e'or ch=='I'or ch=='i'or ch=='O'or ch=='o'or ch=='U'or ch=='u'):
print(ch,"its a vowel letter")
else:
print(ch,"its a consonent")
|
7bd52e231d77bfe94c4277772ef77bc4f56b7f57 | Andyyesiyu/IS590 | /Assignment/A2/hw2.py | 10,993 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from ast import literal_eval as make_tuple
import math
# Edge definition:
# - p1, p2: endpoints of the segment
# - slope: slope of the segment
# - intersect: intersect of the line (extention of the segment most probably) on the y axis
class Edge:
def __init__(self, p1, p2, slope, intersect):
self.p1 = p1
self.p2 = p2
self.slope = slope
self.intersect = intersect
# The point matrix would seem like following:
# (0,0) (0,1) (0,2) ... (0,n)
# (1,0) ...
# (2,0) ...
# .
# .
# .
# (m,0) ...
# - points: A 2D array, storing `True/False` indicating whether the point is on a segment or not.
# - edges: The list storing current lines
def initPoints(m=4, n=4):
points = []
for _ in range(m):
row = []
for _ in range(n):
row.append(False)
points.append(row)
return points
def printPuzzle(points):
for i in points:
print(i)
def rollTurn():
if random.randint(1, 10) < 5:
return 0
else:
return 1
turnMap = {0: "Computer", 1: "Player"}
def checkValidEdge(points, edges, newEdge, endpoint):
# print(newEdge.p1, newEdge.p2, endpoint)
# print("Start checking edge validation...")
# Check if endpoints match
if not (-1, -1) in endpoint:
# Must start fron an endpoint
if not (newEdge.p1 in endpoint or newEdge.p2 in endpoint):
return False
# Cannot accept a line that would turn itself in to a closed shape
if newEdge.p1 in endpoint and points[newEdge.p2[1]][newEdge.p2[0]] == True:
return False
if newEdge.p2 in endpoint and points[newEdge.p1[1]][newEdge.p1[0]] == True:
return False
# Check if it's the very first input for the entire puzzle
if not edges:
# print(0)
return True
# Check intersection:
for edge in edges:
# print("slopes:", edge.slope, newEdge.slope)
if edge.slope != newEdge.slope:
# print(1)
# print(edge.intersect, newEdge.intersect)
if edge.slope == 'infinity':
intersectY = newEdge.slope*edge.p1[0] + newEdge.intersect
if newEdge.slope == 0:
if (edge.p1[0], intersectY) != newEdge.p1 and (edge.p1[0], intersectY) != newEdge.p2 and edge.p1[0] > min(newEdge.p1[0], newEdge.p2[0]) and edge.p1[0] < max(newEdge.p1[0], newEdge.p2[0]) and intersectY >= min(edge.p1[1], edge.p2[1]) and intersectY <= max(edge.p1[1], edge.p2[1]):
# print("HERE1")
return False
if intersectY > min(newEdge.p1[1], newEdge.p2[1]) and intersectY < max(newEdge.p1[1], newEdge.p2[1]):
# print("HERE2")
return False
elif newEdge.slope == 'infinity':
intersectY = edge.slope*newEdge.p1[0] + edge.intersect
if intersectY == math.floor(intersectY) and math.floor(intersectY) == edge.p1[1] or math.floor(intersectY) == edge.p2[1]:
temp = (newEdge.p1[0], intersectY)
if temp not in endpoint:
return False
if intersectY > min(newEdge.p1[1], newEdge.p2[1]) and intersectY < max(newEdge.p1[1], newEdge.p2[1]):
# print("HERE6")
return False
else:
intersectX = (edge.intersect - newEdge.intersect) / \
(newEdge.slope - edge.slope)
# print(intersectX)
if (intersectX == edge.p1[0] or intersectX == edge.p2[0]) and (edge.p1 not in endpoint and edge.p2 not in endpoint):
# print("HERE4")
return False
if (intersectX > min(newEdge.p1[0], newEdge.p2[0]) and intersectX < max(newEdge.p1[0], newEdge.p2[0])) \
and (intersectX > min(edge.p1[0], edge.p2[0]) and intersectX < max(edge.p1[0], edge.p2[0])):
# print("HERE5")
return False
else:
# print(2)
if newEdge.slope == 'infinity':
if newEdge.p1[0] != edge.p1[0]:
continue
else:
newEdgeYRange = range(min(newEdge.p1[1], newEdge.p2[1]), max(
newEdge.p1[1], newEdge.p2[1]) + 1)
edgeYRange = range(min(edge.p1[1], edge.p2[1]), max(
edge.p1[1], edge.p2[1]) + 1)
ns = set(newEdgeYRange)
inter = ns.intersection(edgeYRange)
if inter and len(inter) > 1:
return False
else:
if newEdge.intersect != edge.intersect:
continue
else:
newEdgeXRange = range(min(newEdge.p1[0], newEdge.p2[0]), max(
newEdge.p1[0], newEdge.p2[0]) + 1)
edgeXRange = range(min(edge.p1[0], edge.p2[0]), max(
edge.p1[0], edge.p2[0]) + 1)
ns = set(newEdgeXRange)
inter = ns.intersection(edgeXRange)
if inter and len(inter) > 1:
return False
return True
def moveToEdge(newMove):
# Cannot set a same point twice as a valid segment
if newMove[0] == newMove[1]:
return None, False
# Endpoints of a segement must be within the border of the puzzle
for i in newMove:
if not (i[0] in range(height) and i[1] in range(width)):
return None, False
x1 = newMove[0][1]
y1 = newMove[0][0]
x2 = newMove[1][1]
y2 = newMove[1][0]
if x1 == x2:
slope = 'infinity'
intersect = None
else:
slope = (y1 - y2)/(x1 - x2)
intersect = (x1*y2 - x2*y1)/(x1 - x2)
return Edge((x1, y1), (x2, y2), slope, intersect), True
def generateNextEdge(points, edges, endpoint):
for i in range(height):
for j in range(width):
if not points[i][j]:
if not (-1, -1) in endpoint:
for ep in endpoint:
newMove = ((i, j), (ep[1], ep[0]))
newEdge, validMove = moveToEdge(newMove)
if not validMove:
pass
else:
validEdge = checkValidEdge(
points, edges, newEdge, endpoint)
if not validEdge:
pass
else:
return newEdge
else:
newMove = ((i, j), (0, 0))
newEdge, validMove = moveToEdge(newMove)
if not validMove:
pass
else:
validEdge = checkValidEdge(
points, edges, newEdge, endpoint)
print(validEdge)
if not validEdge:
pass
else:
return newEdge
return newEdge
def getNextEdge(edges, endpoint):
validMove = False
validEdge = False
while not validEdge:
print("Please input a valid move (e.g. (0,0), (0,1)):")
newMove = input()
# Always require two points as input
# For example, ((0, 0), (1,0))
try:
newMove = make_tuple(newMove)
except:
continue
if type(newMove) != tuple or len(newMove) != 2:
continue
newEdge, validMove = moveToEdge(newMove)
# print(validMove, "validMove")
if not validMove:
print("Invalid input!")
continue
validEdge = checkValidEdge(points, edges, newEdge, endpoint)
if not validEdge:
print("Invalid input!")
continue
# print(validEdge, "validEdge")
return newEdge
def move(turn, points, edges, endpoint):
if turn == 0:
newEdge = generateNextEdge(points, edges, endpoint)
# newEdge = getNextEdge(edges, endpoint)
else:
newEdge = getNextEdge(edges, endpoint)
return newEdge
def checkIfFinished(points, edges, endpoint):
for i in range(height):
for j in range(width):
for ep in endpoint:
newMove = ((i, j), (ep[1], ep[0]))
newEdge, validMove = moveToEdge(newMove)
if validMove:
validEdge = checkValidEdge(
points, edges, newEdge, endpoint)
if validEdge:
return False
return True
def updatePuzzle(points, newEdge, endpoint):
# Update endpoint
if (-1, -1) in endpoint:
endpoint[0] = newEdge.p1
endpoint[1] = newEdge.p2
else:
for i in range(2):
if endpoint[i] == newEdge.p1:
endpoint[i] = newEdge.p2
break
elif endpoint[i] == newEdge.p2:
endpoint[i] = newEdge.p1
break
# Update points
if newEdge.slope == 'infinity':
for i in range(min(newEdge.p1[1], newEdge.p2[1]), max(newEdge.p1[1], newEdge.p2[1]) + 1):
points[i][newEdge.p1[0]] = True
else:
for i in range(min(newEdge.p1[0], newEdge.p2[0]), max(newEdge.p1[0], newEdge.p2[0]) + 1):
if math.floor(newEdge.slope*i + newEdge.intersect) == newEdge.slope*i + newEdge.intersect:
points[math.floor(newEdge.slope*i +
newEdge.intersect)][i] = True
return
if __name__ == "__main__":
print("Please input the height of the puzzle:")
height = input()
height = int(height)
print("Please input the width of the puzzle:")
width = input()
width = int(width)
points = initPoints(height, width)
edges = []
turn = rollTurn()
finished = False
endpoint = [(-1, -1), (-1, -1)]
print("Game starts!")
printPuzzle(points)
print('\n')
while not finished:
print(turnMap[turn], "'s turn!")
if width == 1 and height == 1:
print(turnMap[(turn+1) % 2], "wins!")
exit(0)
newEdge = move(turn, points, edges, endpoint)
print(turnMap[turn], "takes (", newEdge.p1[1], ",",
newEdge.p1[0], "), (", newEdge.p2[1], ",", newEdge.p2[0], ")")
edges.append(newEdge)
updatePuzzle(points, newEdge, endpoint)
printPuzzle(points)
print("endpoints are now:", "(", endpoint[0][1], ",", endpoint[0]
[0], "),", "(", endpoint[1][1], ",", endpoint[1][0], ")")
print('\n')
finished = checkIfFinished(points, edges, endpoint)
turn = (turn + 1) % 2
printPuzzle(points)
print("No more available moves!")
print(turnMap[turn], "wins!")
|
4db5286513dde4db5afc628bb1c084b187ee898a | sfaisalaliuit/dictionary | /dict_double_prog3.py | 439 | 3.90625 | 4 | faisal = {'username': 'sfaisal', 'online': True, 'students': 145, 'section':'Computer Science', 'experience in years':21}
farhan = {'username': 'farhanahmed', 'online': False, 'students': 144, 'section':'Software Engineering', 'experience in years':15}
for key, value in faisal.items():
print(key, 'is the key for the value', value)
for key, value in farhan.items():
print(key, 'is the key for the value', value)
|
f846806fe36f18555ee326609d90581c099e6ee2 | ps3296/Automated-Pun-Generator | /python files/Scripts/Scripts/homonyms_textfile_cdt/trial_generate_jokes.py | 967 | 3.765625 | 4 | def indefinite_article(w):
if w.lower().startswith("a ") or w.lower().startswith("an "): return ""
return "an " if w.lower()[0] in list('aeiou') else "a "
def camel(s):
return s[0].upper() + s[1:]
def joke_type1(d1,d2,w1):
return "What do you call " + indefinite_article(d1) + d1 + " " + d2 + "? " + \
camel(indefinite_article(w1)) + w1 + "."
def joke_type2(d1,d2,w1):
return "When is " + indefinite_article(d1) + d1 + " like " + indefinite_article(d2) + d2 + "? " + \
"When it is ."
data = open("trial_homonyms.txt","r").readlines()
for line in data:
[w1,d1,pos1,d2,pos2]=line.strip().split(",")
if pos1=='adjective' and pos2=='noun':
print (joke_type1(d1,d2,w1))
elif pos1=='noun' and pos2=='adjective':
print (joke_type1(d2,d1,w1))
elif pos1=='noun' and pos2=='noun':
print (joke_type2(d1,d2,w1))
print (joke_type2(d2,d1,w1))
|
7f27483d65ad0113c2b9159fa6ef4e15c59992b7 | TeamContagion/CTF-Write-Ups | /2022/SekaiCTF2022/crypto/SecureImageEncryption/enc.py | 1,646 | 3.6875 | 4 | from PIL import Image
def openImage():
#opens both images and loads them
img1 = Image.open("encryptedimg1.png")
img2 = Image.open("encryptedimg2.png")
pixels1 = img1.load()
pixels2 = img2.load()
width1, height1 = img1.size
width2, height2 = img2.size
list1 = []
#check for correct size
if width2 != 256 or width1 != 256:
print("not correct size")
"""
this part gets the grayscale value of at each pixel of the encrypted images
Its serves as a coordinate mapping
Index 0 will have the grayscale value stored as a tuple of the first pixel in image 1 and image 2"""
for x in range(width1):
for y in range(height1):
r1= img1.getpixel((x,y))
r2= pixels2[x, y]
list1.append((r1, r2))
return list1
def rgbToHex(rgb):
return '%02x%02x%02x' % rgb
def main():
values = openImage()
#created image object for making decrypted image.
finalImage = Image.new(mode="RGB", size=(256, 256))
#opened flag encrypted image
img3 = Image.open("encryptedFlag.png")
img = img3.convert('RGB')
pixels = img.load()
width, height = img.size
counter = 0
hexlist=""
""" It gets the value in order of the encrypted image file and puts that pixel in the coordinates indicated
by the values obtained from the grayscale"""
for i in range(256):
for j in range(256):
finalImage.putpixel((255-values[counter][0], 255-values[counter][1]), pixels[i,j])
counter += 1
finalImage.rotate(90).transpose(Image.FLIP_LEFT_RIGHT).show()
if __name__ == '__main__':
main() |
47846eb1a2b8b5db15f5f7262ae51e15973eb75b | oxfordni/python-for-everyone | /examples/lesson2/4_exercise_1.py | 372 | 4.21875 | 4 | # Determine the smallest number in an unordered list
unordered_list = [1000, 393, 304, 40594, 235, 239, 2, 4, 5, 23095, 9235, 31]
# We start by ordering the list
ordered_list = sorted(unordered_list)
# Then we retrieve the first element of the ordered list
smallest_number = ordered_list[0]
# And we print the result
print(f"The smallest number is: {smallest_number}")
|
0c4af3021580b97e5d9d244695e5a22e5e9eb136 | oxfordni/python-for-everyone | /examples/lesson2/1_data_types_tuples.py | 152 | 3.875 | 4 | # Define an initial tuple
my_tuple = (1, 2, 3)
# Print out the list
print(my_tuple)
# Print the value at the beginning of the list
print(my_tuple[0])
|
c700081a72e7cc131897478a8f02db1507044b07 | apalaciosc/python_quantum | /practica_01/ejercicio_01.py | 180 | 3.671875 | 4 | def ensure_question(palabra):
if len(palabra) == 0:
print('Cadena no válida')
else:
print(f'{palabra}?')
palabra = input('Escriba una palabra: ')
ensure_question(palabra)
|
321b6d8b4b9ccd840eef7801dccf0cffa7a571fe | apalaciosc/python_quantum | /clase_07/scrapping.py | 893 | 3.875 | 4 | from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="title story title2"><b>The Dormouse's story</b></p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.
</p>
<p class="story">...</p>
</body>
</html>
"""
contenido = BeautifulSoup(html_doc, 'html.parser')
print(contenido.prettify())
print(contenido.title)
print(contenido.title.name)
print(contenido.title.string)
print(contenido.p)
print(contenido.p['class'])
print(contenido.a)
print(contenido.find_all('a'))
print(contenido.find(id="link3"))
|
c1bbd7598c2a95628257451d744cfd3cf6bf1f98 | nawan44/Python-Basic | /iteration.py | 171 | 4.03125 | 4 | #basic iteration
Spirit = 5
for Day in range(1, Spirit+1):
print('Never Give Up')
#iteration in string
Hi = 7
for Good in range(2, Hi+7):
print(f'Morning {Good}') |
55e1d5407c28c0ea3953dedfe7bb97981a8d0455 | nawan44/Python-Basic | /arithmetic.py | 476 | 3.921875 | 4 |
#Standart Operator Arithmetic
a = 10
b = 3
#operator +
res = a + b
print(a, '+', b ,'=', res)
#operator -
res = a - b
print(a, '-', b ,'=', res)
#operator - Multiple
res = a * b
print(a, '-', b ,'=', res)
# operator / Dividen
res = a / b
print(a, '/', b ,'=', res)
# operator ^2 Eksponen
res = a ** b
print(a, '**', b ,'=', res)
# operator % Modulus
res = a % b
print(a, '%', b ,'=', res)
# operator // floor division
res = a // b
print(a, '//', b ,'=', res)
|
18ca47e10a0af9166e4366ca61b3a726bbc74454 | callmefarad/Python_For_Newbies | /sesions/stringslice.py | 756 | 4.53125 | 5 | # slicing simply means returning a range of character
# this is done by using indexing pattern
# note when dealing with range the last number is exclusive.
# i.e if we are to get the last letter of digit 10, we would have a
# range of number tending to 11 where the 11th index is exclusive
# declaring my variable
my_string = "This is my string."
# printing the whole value of the variable
print(my_string[:])
# printing the word "my" from the value
print("Am printing the word \"my\" from the variable using string slicing")
print(my_string[8:10])
# we also use negative indexing during slicing
# lets print the word "string" from the back using negative indexing
print("printing the word \"string\" using negative indexing.")
print(my_string[-7:-1]) |
f8ccced9d2f8bf8df346c5f5ff77a1fbc8d32954 | callmefarad/Python_For_Newbies | /sesions/rangetype.py | 367 | 4.125 | 4 | # showing range type representation
# declaring a variable name range_of_numbers
range_of_numbers = range(40)
# displaying the range of numbers
print("Below shows the range of numbers")
print(range_of_numbers)
# displaying python representation of the output value
print("Below show the python data type representation of the output")
print(type(range_of_numbers))
|
85b7757dd6d1e1e5a6872596d297e5a690707f86 | callmefarad/Python_For_Newbies | /sesions/sorting_item.py | 5,457 | 4.3125 | 4 | # SORT
# the sorted() function is used to sort items in ascending order by default or by user prescriptions.
# basic sorting is used without a key and mapping function
# BASIC SORT
# sorting items in a list
print('\nsorted() function shows all the items in ascending order')
items = [1, 29, 37, 97, 2, 57, 37, 58, 46, 61, 74, 9273, 54]
print(sorted(items))
# Enumerator helps us know the index of we would like to sort
print('\nEnumerator helps us to know the index number of itme we would want to sort for.')
print(list(enumerate(items)))
# we can also impose a start index value rather than the default (0)
print('Making the index to start with 1 rather than the default(0) value.')
print(list(enumerate(items, start=1)))
# KEY FUNCTION SORT
# sorting items using the keyword "sorted", "key function" and "mapping funtion".
# it takes this format: sorted(object list, key=lambda: class_name: class.name(where class.name is the property to sort))
# (sorted(list of objects, key=lambda, maping the class to the property in the argument to sort))
class Student:
# create an init function that serve as the construct of the class
def __init__(self, name, age, python_score, django_score, ml_score):
# defining the propertis contained in the class
self.name = name
self.age = age
self.python_score = python_score
self.django_score = django_score
self.ml_score = ml_score
# __repr__() function return a string containing a printable representation of an object.
def __repr__(self):
return repr((self.name, self.age, self.python_score, self.django_score, self.ml_score))
# creating instances of the Student class
nd = Student("ndidi", "45", "100", "100", "100")
ol = Student('ola', '75', '150', '200', '250')
tb = Student('tobi', '20', '200', '175', '150')
om = Student('oma', '30', '100', '100', '100')
# putting the created objects in a list
object_list = [
nd, ol, tb, om
]
# sorting the objects by age
print("\nsorting the objects by age:")
sorted_items = sorted(object_list, key=lambda Student: Student.age)
print(sorted_items, '\n')
# sorting the objects by python score
print("sorting the objects by python score:")
sorted_items = sorted(object_list, key=lambda Student: Student.python_score)
print(sorted_items, '\n')
# sorting the objects by django score
print("sorting the objects by django score:")
sorted_items = sorted(object_list, key=lambda Student: Student.django_score)
print(sorted_items, '\n')
# sorting the objects by ml score
print("sorting the objects by machine learning score:")
sorted_items = sorted(object_list, key=lambda Student: Student.ml_score)
print(sorted_items, '\n')
# we can also use the same method to sort for tupple
class_list = [
("charles", 45, "100", "100", "1"),
('hammed', 75, '150', '200', '250'),
('kingsley', 20, '200', '175', '150'),
('james', 30, '100', '100', '100'),
]
# sorting the class list by age
print('sorting the ages of students in tupple (student_list).')
sorted_list = sorted(class_list, key=lambda Student: Student[1])
print(sorted_list)
# OPERATOR MODULE FUNCTION
# The key-function patterns shown above are very common, so Python provides convenience functions to make
# accessor functions easier and faster. The operator module has itemgetter(), attrgetter(), and a
# methodcaller() function.
# itemgetter() function look at the index to find element while the attrgetter() function look at the name(string) of the name of
# the passed in the agument.
# the itemgetter() function is used for tupple while the attrgetter() function is used for list
# we must first import the itemgetter() and attrigetter() function from the operator module
from operator import itemgetter, attrgetter
print('using itemgetter() function to dislplay students age of object in Student class(tupple)')
print(sorted(class_list, key=itemgetter(1)))
print('')
print('using attrgetter() function to display students age of object in Student class (list)')
print(sorted(object_list, key=attrgetter('age')))
# DESCENDIGN SORT
# Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is used to flag descending
# sorts. For example, to get the student data in reverse age order:
# sort students in descending order
print('\nthe reverse order of student age:')
sorted_list = sorted(object_list, key=attrgetter('age'), reverse=True)
print(sorted_list)
# the min() function checks for the minimum value while the max() checks for the maximum value in a list, tuple or dictionary
print('\nDisplay the student who got the highest score in python')
maximum_no = max(object_list, key=attrgetter('python_score'))
print(maximum_no)
print('\nDisplay the student who got the highest score in django')
maximum_no = max(object_list, key=attrgetter('django_score'))
print(maximum_no)
print('\nDisplay the student who got the highest score in machine learning')
maximum_no = max(object_list, key=attrgetter('ml_score'))
print(maximum_no)
print('\nDisplay the student who got the lowest score in python')
minimum_no = min(object_list, key=attrgetter('python_score'))
print(minimum_no)
print('\nDisplay the student who got the lowest score in django')
minimum_no = min(object_list, key=attrgetter('django_score'))
print(minimum_no)
print('\nDisplay the student who got the lowest score in machine learning')
minimum_no = min(object_list, key=attrgetter('ml_score'))
print(minimum_no)
|
4a2d69fd9c1d182db95a7df2dbead89b3628f002 | callmefarad/Python_For_Newbies | /sesions/stringreplacement.py | 164 | 4.40625 | 4 | # The string replacement is used to replace a character with another
# character in that string.
my_sentence = "Ubani Friday"
print(my_sentence.replace("U", "O"))
|
b30d79e7e57f57b9b079bb566e41c6deb88425c5 | callmefarad/Python_For_Newbies | /sesions/languagetranslation.py | 708 | 4.0625 | 4 | # This progrma is called the cow translation language.
# It converts every vowel letter found in a word to "COW", thereby forming the cow language.
# defining the function
def copywrite():
print("Copywrite: Ubani U. Friday")
def translate(phrase):
word_translation = "" # an empty variable to hold each element of any work inputed
for letter in phrase:
if letter in "AEIOUaeiou":
word_translation = word_translation + "cw"
else:
word_translation = word_translation + letter
return word_translation
# main program
userinput = input("\nEnter any word or sentence you like to translate to a cow language: ")
print(translate(userinput))
copywrite()
|
b59e530c1b2e7d8275003cde9e1b8bce78d9b43f | callmefarad/Python_For_Newbies | /sesions/membershipin.py | 536 | 4.3125 | 4 | # a membership operator checks if sequence is present in an object
# "in" is on of the membership operator
# creating a variable named "
my_list = ['orange', 'bean', 'banana', 'corn']
print("List of items: ", my_list)
# creating a check variable
check = "banana"
# prints the result
print(check in my_list)
""""
# creates a conditional statement
if check in my_list:
print(check.upper(), "is present in the list.")
else:
print(check, "is not present in the list.")
print("************************************** ")
"""
|
fd0795fd1e3b86ce259b392b644d5ade274655f0 | callmefarad/Python_For_Newbies | /sesions/func.py | 1,652 | 4.15625 | 4 | # # declaring a function
# def dummy():
# print("this is a dummy print.")
#
# # callin the function
# dummy()
#
# def add():
# user1 = float(input('Enter your firstnumber: '))
# user2 = float(input('Enter your secondnumber: '))
# sum = user1 + user2
# return sum
#
# # call the function
# add()
# x = 5
# def anything():
# global x
# x = 6
# print(x * 2)
#
# anything()
# print(x)
#
# def greet(name, message):
# print(name + " " + message)
# def greet(name, message):
# return name + " " + message
#
# print(greet('ole', 'good morning'))
#
# def greet(name, message="goood morning"):
# print( name + " " + message)
#
#
# greet("osazie", "welcome")
# def fruits(*fruitslist):
# return fruitslist
#
# print(fruits('ola', 'sade', 'tolu'))
# # using a lamdda function
# square = lambda x, y: (x*x) - (y)
#
# print(square(4,4))
# root of an equation (b2 - 4ac)/(2a)
# equation_root = lambda a,b,c : -b((b*b - 4*a*c)/(2*a))
#
# a = float(input('Enter the value of a: '))
# b = float(input('Enter the value of b: '))
# c = float(input('Enter the value of c: '))
#
# # call the lamda function
# print(equation_root(a,b,c))
# a lambda function that performs the square of a number
# square = lambda x: x * y
#
# user = float(input('number: '))
# print(square(user))
root = lambda a, b, c: ((a*a) + (b) -c)
x = float(input('a: '))
y = float(input('b: '))
z = float(input('c: '))
# call the function
print(root(x,y,z))
# a default function that performs the square of a number
# def square(x):
# result = x * x
# return result
#
# u = float(input('number: '))
# print(square(u))
|
0f6be41aa20de93a0ec323b95b78b7e1b906996e | callmefarad/Python_For_Newbies | /sesions/division.py | 257 | 3.828125 | 4 | # division operator is represented with a forward slash "/"
# it is used to get a floating value after a successful divisional operation.
all_states = 30000
lagos_state = 307
total_count = all_states / lagos_state
print("The total count is: ", total_count) |
05700d145da30b014ab880e5af9be1a13d3a0a98 | callmefarad/Python_For_Newbies | /sesions/passwordChecker.py | 1,122 | 4.125 | 4 | # a program that checks if a password is too weak, weak and very strong
# defining the function
def copywrite():
print("Copywrite: Ubani U. Friday")
# main function
special_characters = ['!', '^', '@', '#', '$', '%', '&', '*', '(', ')', '_', '+']
special_numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
upper_character = ['A','B','C','D','E','F','G','H','I','J','K','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
counter_character = 0
counter_number = 0
counter_upper = 0
list_holder = []
userinput = input("Enter your password: ")
list_holder = list_holder + list(userinput)
for i in range(len(userinput)):
if list_holder[i] in special_characters:
counter_character += 1
if list_holder[i] in special_numbers:
counter_number += 1
if list_holder[i] in upper_character:
counter_upper += 1
if len(userinput)<7:
print("TOO WEAK, please include numbers and special characters")
elif len(userinput)>=7 and counter_number>0 and counter_character>0 and counter_upper >0:
print("VERY STRONG password.")
else:
print("The password is WEAK")
copywrite()
|
918bcf54bf0c511c9f3b07af080991bb0ae64965 | satvks/Djikstras-Dungeon | /P1/p1-myvers.py | 6,713 | 3.84375 | 4 | from p1_support import load_level, show_level, save_level_costs
from math import inf, sqrt
from heapq import heappop, heappush
def dijkstras_shortest_path(initial_position, destination, graph, adj):
""" Searches for a minimal cost path through a graph using Dijkstra's algorithm.
Args:
initial_position: The initial cell from which the path extends.
destination: The end location for the path.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
If a path exits, return a list containing all cells from initial_position to destination.
Otherwise, return None.
"""
visitingq = []
came_from = dict()
cost_so_far = dict()
came_from[initial_position] = None
cost_so_far[initial_position] = 0
heappush(visitingq, (cost_so_far[initial_position], initial_position))
while visitingq:
cur_cost, cur_pos = heappop(visitingq)
"""
if cur_pos == destination:
path = []
if current == destination:
while current:
path.append(current)
current = prev[current]
path.reverse()
return path
adjacent = nav(graph, current)
"""
for edge, cost in adjacent:
newCost = currentCost + cost
if edge not in dist or newCost < dist[edge]:
dist[edge] = newCost
prev[edge] = current
heappush(queue, (newCost, edge))
for edges in navigation_edges(graph, cur_pos):
## it's pretty much what's on the redblob code page
pass
def dijkstras_shortest_path_to_all(initial_position, graph, adj):
""" Calculates the minimum cost to every reachable cell in a graph from the initial_position.
Args:
initial_position: The initial cell from which the path extends.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
A dictionary, mapping destination cells to the cost of a path from the initial_position.
"""
dist = {}
dist[initial_position] = 0
queue = []
heappush(queue, (0, initial_position))
while len(queue) != 0:
currentCost, current = heappop(queue)
adjacent = adj(graph, current)
for next, cost in adjacent:
newCost = currentCost + cost
if next not in dist or newCost < dist[next]:
dist[next] = newCost
heappush(queue, (newCost, next))
return dist
def navigation_edges(level, cell):
""" Provides a list of adjacent cells and their respective costs from the given cell.
Args:
level: A loaded level, containing walls, spaces, and waypoints.
cell: A target location.
Returns:
A list of tuples containing an adjacent cell's coordinates and the cost of the edge joining it and the
originating cell.
E.g. from (0,0):
[((0,1), 1),
((1,0), 1),
((1,1), 1.4142135623730951),
... ]
"""
### The Better One -- not. The range is some whack shit ###
xs, ys = zip(*(list(level['spaces'].keys()) + list(level['walls']))) # this is getting the min n max val
x_lo, x_hi = min(xs), max(xs)
y_lo, y_hi = min(ys), max(ys)
cell_x, cell_y = cell
cell_cost = level['spaces'][cell]
check_list = [(x,y) for x in [cell_x + 1, cell_x, cell_x - 1]
for y in [cell_y + 1, cell_y, cell_y - 1]
if not (x == cell_x and y == cell_y)]
ret_list = []
for space in check_list:
space_x, space_y = space
if not (x_lo <= space_x <= x_hi) or not (y_lo <= space_y <= y_hi):
continue
if space in level['spaces']:
space_cost = level['spaces'][space]
# some math up in dis
if (abs(space_x - cell_x) == 1) and (abs(space_y - cell_y) == 1):
path_cost = (0.5) * sqrt(2) * space_cost + (0.5) * sqrt(2) * cell_cost
else:
path_cost = (0.5) * space_cost + (0.5) * cell_cost
ret_list.append((space, path_cost))
print ret_list
return ret_list
def test_route(filename, src_waypoint, dst_waypoint):
""" Loads a level, searches for a path between the given waypoints, and displays the result.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
dst_waypoint: The character associated with the destination waypoint.
"""
# Load and display the level.
level = load_level(filename)
show_level(level)
# Retrieve the source and destination coordinates from the level.
src = level['waypoints'][src_waypoint]
dst = level['waypoints'][dst_waypoint]
# Search for and display the path from src to dst.
path = dijkstras_shortest_path(src, dst, level, navigation_edges)
if path:
show_level(level, path)
else:
print("No path possible!")
def cost_to_all_cells(filename, src_waypoint, output_filename):
""" Loads a level, calculates the cost to all reachable cells from
src_waypoint, then saves the result in a csv file with name output_filename.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
output_filename: The filename for the output csv file.
"""
# Load and display the level.
level = load_level(filename)
show_level(level)
# Retrieve the source coordinates from the level.
src = level['waypoints'][src_waypoint]
# Calculate the cost to all reachable cells from src and save to a csv file.
costs_to_all_cells = dijkstras_shortest_path_to_all(src, level, navigation_edges)
save_level_costs(level, costs_to_all_cells, output_filename)
if __name__ == '__main__':
filename, src_waypoint, dst_waypoint = 'example.txt', 'a','e'
# Use this function call to find the route between two waypoints.
test_route(filename, src_waypoint, dst_waypoint)
# Use this function to calculate the cost to all reachable cells from an origin point.
cost_to_all_cells(filename, src_waypoint, 'my_costs.csv')
|
9e34742605447bc3ec4ab6da44d9b5ae5a19d32b | MetallicMonkeyu/image_encrypt | /Cube.py | 5,417 | 3.5625 | 4 | from PIL import Image
from Key import *
class Cube:
#im_path can be pefected by asking user to choose a folder
def __init__(self, img_path = [], block_size = 8):
self.image = [] #Open a new file
self.blc_size = block_size
self.img_path = img_path
def Row(self, row_index, shift_times):
"""
All operations in this function are index operation (start from 0)
"""
#Get operation vector
"""
block_nums: how many blocks in each row
blcok_nums = image.width [0] / block.size
"""
blc_nums = self.image.size[0] / self.blc_size
opt_vector = shiftBits(shift_times, blc_nums)
#Copy original image for reference
ori_image = self.image.copy()
ori_image.load()
#Execute row rolling operation
"""
each Element in vector is the Relative Coordinate of the Block in Original Image
each Index of Element is the Relative Coordinate of the Block in New Image
"""
for index, elm in enumerate(opt_vector):
#Crop a block from original image
crop_area = (self.blc_size * elm, self.blc_size * row_index, \
self.blc_size * (elm + 1), self.blc_size * (row_index + 1))
crop_blc = ori_image.crop(crop_area)
crop_blc.load()
#Paste the block to new image
paste_area = (self.blc_size * index, self.blc_size * row_index,\
self.blc_size * (index + 1), self.blc_size * (row_index + 1))
self.image.paste(crop_blc, paste_area)
def Col(self, col_index, shift_times):
"""
All operations in this function are index operation (start from 0)
"""
#Get operation vector
"""
block_nums: how many blocks in each colum
blcok_nums = image.height [1] / block.size
"""
blc_nums = self.image.size[1] / self.blc_size
opt_vector = shiftBits(shift_times, blc_nums)
#Copy original image for reference
ori_image = self.image.copy()
ori_image.load()
#Execute row rolling operation
"""
each Element in vector is the Relative Coordinate of the Block in Original Image
each Index of Element is the Relative Coordinate of the Block in New Image
"""
for index, elm in enumerate(opt_vector):
#Crop a block from original image
crop_area = (self.blc_size * col_index, self.blc_size * elm, \
self.blc_size * (col_index + 1), self.blc_size * (elm + 1))
crop_blc = ori_image.crop(crop_area)
crop_blc.load()
#Paste the block to new image
paste_area = (self.blc_size * col_index, self.blc_size * index,\
self.blc_size * (col_index + 1), self.blc_size * (index + 1))
self.image.paste(crop_blc, paste_area)
def Enc(self, auto = False, key_path = [],wd_num = 20):
#Plase Choose a file:
#
#If auto = True, generate a Key_map Automatically
key_mgr = Key()
if auto == True:
key_mgr.SetKeyPath(self.img_path + '.key')
key_mgr.GenKey(word_num = wd_num)
else:
key_mgr.SetKeyPath(key_path)
key_mgr.OpenFile()
#Operation Begin
opt_info = key_mgr.GetKeyInfo()
for rl_round in range(0,opt_info['rl_round']):
for row_index in range(0,self.image.size[0]/self.blc_size):
shift_times = key_mgr.GetEncKey()
self.Row(row_index, shift_times)
for col_index in range(0,self.image.size[1]/self.blc_size):
shift_times = key_mgr.GetEncKey()
self.Col(col_index, shift_times)
#Operation End
key_mgr.CloseFile()
self.image.save(fp = self.img_path)
def Dec(self, key_path):
#Please choose a key?
key_mgr = Key()
key_mgr.SetKeyPath(key_path)
key_mgr.OpenFile()#Here should choose the file path
opt_info = key_mgr.GetKeyInfo()
#Calculate stop_index:
used_knum = (self.image.size[0]/self.blc_size + self.image.size[1]/self.blc_size) * opt_info['rl_round']
stop_index = used_knum % opt_info['wd_num']
#Set Key Cursor:
key_mgr.SetKeyCursor(key_index = stop_index)
for rl_round in range(0,opt_info['rl_round']):
for col_index in list(reversed(range(0, self.image.size[1]/self.blc_size))):
shift_times = - key_mgr.GetDecKey()
self.Col(col_index, shift_times)
for row_index in list(reversed(range(0, self.image.size[0]/self.blc_size))):
shift_times = - key_mgr.GetDecKey()
self.Row(row_index, shift_times)
key_mgr.CloseFile()
self.image.save(fp = self.img_path)
def OpenImg(self, path):
self.image = Image.open(path)
self.img_path = path
def SetBlockSize(self, size):
self.blc_size = size
def CloseImg(self):
self.image.close()
def shiftBits(times, block_num):
#Generate Origin coordinate vector:
vector = [x for x in range(0,block_num)]
#Shift Operation:
times = times % block_num
for i in range(0,times):
vector.insert(0,vector[-1])
del vector[-1]
print (vector)
return vector
|
67c8770308f34f234d91c330da73e5aefee2a58c | Ilis/dawson | /useless_trivia.py | 585 | 4.125 | 4 | # Useless trivia
name = input("Hi! What's your name? ")
age = input("How old are you? ")
age = int(age)
weight = int(input("What is your weight? "))
print()
print("If Cammings write you a letter, he write", name.lower())
print("If mad Cammings write you a letter, he write", name.upper())
called = name * 5
print("Kid can call you like this:", called)
seconds = age * 365 * 24 * 60 * 60
print("Your age in seconds is:", seconds)
moon_weight = weight / 6
print("Your weight on the Moon is:", moon_weight)
sun_weight = weight * 27.1
print("Your weight on the Sun is:", sun_weight)
|
d05ab90c27a5d8821c19b17cb48a2dafc78f35bc | GaboUCR/Mit-Introduction-to-python | /ps1/Ps1B.py | 848 | 4.28125 | 4 | total_cost = float(input("Enter the cost of your dream house "))
annual_salary = float(input("enter your annual salary "))
portion_saved= float(input("enter the percentage to be saved "))
semi_annual_raise = float(input("Enter the percentage of your raise"))
current_savings = 0
annual_return = 0.04
total_months = 0
portion_down_payment = 0.25
months_to_get_raise = 0
while total_cost * portion_down_payment > current_savings :
months_to_get_raise += 1
current_savings += current_savings*annual_return /12
current_savings += (annual_salary / 12 ) * portion_saved
if (months_to_get_raise == 6 ):
annual_salary = annual_salary + annual_salary*semi_annual_raise
months_to_get_raise = 0
total_months += 1
print("you need to save for " , total_months , " months to be able to make a payment" )
|
9aac5e114701687f7fd97c620cdba469a6d117de | malikrafsan/Python-Language-Linter | /cyk_parser.py | 1,244 | 3.578125 | 4 | # File ini adalah CYK Parser yang digunakan
# Pada file ini, dilakukan pengecekan syntax dengan CYK
def cyk_parser(grammar, prob):
#grammar -> a dictionary of CNF
#prob -> string problem
#Set up variable
numb = len(prob)
if(numb == 0):
return True
parsetable = [[[] for i in range(numb)] for j in range(numb)]
#CYK Algorithm
#Fill first row
for i in range(numb):
terminal = prob[i]
#Get all nonterminal that produces prob[i]
terminal = [terminal]
for nonterm in grammar:
if(terminal in grammar[nonterm]):
parsetable[i][i].append(nonterm)
#Fill the rest of parsetable
for i in range(1, numb):
for j in range(numb - i):
ind = j + i
for k in range(j, ind):
for nonterm in grammar:
for prod in grammar[nonterm]:
if(len(prod) != 1):
if((prod[0] in parsetable[j][k]) and (prod[1] in parsetable[k + 1][ind]) and (nonterm not in parsetable[j][ind])):
parsetable[j][ind].append(nonterm)
if('S' in parsetable[0][numb-1]):
return True
else:
return False
|
b5e10ed6fec1e800562c5e7a381eceb00b53b6ab | aleph2c/miros-random | /set_hacking.py | 673 | 3.59375 | 4 | from itertools import combinations
def make_combo(_max, _pick):
comb = combinations(list(range(1,_max+1)), _pick)
return list(comb)
print(make_combo(3, 2))
def make_next(_max, _pick):
full_combo = [a for a in make_combo(_max, _pick)]
sub_combo = [b for b in full_combo if _max in b]
return sub_combo
top = 13
maximum_pick = []
max_length = 0
for _max in range(top):
for picks in range(top):
working_list = make_next(_max, picks)
length = len(working_list)
print(_max, picks, length, working_list)
if max_length < length:
maximum_pick = [_max, picks]
max_length = length
print(maximum_pick, max_length)
|
8111dfc4110b25b75a6d8f4e3e583aa583a54d31 | DoughyJoeyD/WorkLog2 | /task.py | 1,889 | 4.125 | 4 | from datetime import datetime
import os
import time
#handy script to clean the screen/make the program look nice
def clearscreen():
os.system('cls' if os.name == 'nt' else 'clear')
#how each task is constructed
#name
#date of task
#time taken
#extra notes
class Task():
def __init__(self):
pass
#asks the user for a task name
def get_task_name(self):
clearscreen()
name = input("Task Name: ")
if name.upper != "BACK":
self.name = name.upper()
#asks the user for a task time
def get_time(self):
clearscreen()
self.time = False
while self.time == False:
try:
time = input('How long was the task?(Only Enter Min): ')
self.time = str(int(time))
except ValueError:
print('Thats not a number!')
#asks the user for extra notes
def get_remarks(self):
clearscreen()
extra = input("Additional Notes? ").upper()
self.extra = extra
#asks the user for a date in MM/DD/YYYY Format
def get_date(self):
clearscreen()
self.date = False
while self.date == False:
try:
date = input("Please enter the date of task(MM/DD/YYYY): ")
self.date = datetime.strptime(date, '%m/%d/%Y')
except ValueError:
clearscreen()
print('Oops, Please Enter In Month(08), Day(04), Year(1990) Format!')
time.sleep(2)
#A really clean way of printing each task all at once
def taskprinter(self):
print("---------------------")
print('Task Name: ' + self.name)
print('Task Date: ' + self.date.strftime('%m/%d/%Y'))
print('Time Taken: ' + self.time + " Minutes")
print('Extra: ' + self.extra)
print("---------------------")
|
bd0e4c8d341eab303c06ea1a3ab55c1b67cce480 | uniquezhiyuan/ShipClassify | /route_revise.py | 3,550 | 3.6875 | 4 | import numpy as np
import pandas as pd
from math import sqrt
import time
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# print(data_1.describe())
# 最小二乘回归
def least_squares(x, y):
x_ = x.mean()
y_ = y.mean()
m = np.zeros(1)
n = np.zeros(1)
k = np.zeros(1)
p = np.zeros(1)
for i in np.arange(len(x)):
k = (x[i]-x_) * (y[i]-y_)
m += k
p = np.square(x[i]-x_)
n = n + p
a = m / n
b = y_ - a * x_
return a[0], b[0]
# 北纬26°上相邻经线圈相距100.053km,经线圈上相邻纬线圈相距111.600km
# 数值修正
def revise(x, y, t):
x = np.array(x)
y = np.array(y)
new_x = []
new_y = []
new_x.append(x[0])
new_x.append(x[1])
new_y.append(y[0])
new_y.append(y[1])
for i in range(len(x) - 2):
speed = sqrt(((x[i + 2] - x[i + 2 - 1]) * 100053)**2 + ((y[i + 2] - y[i + 2 - 1]) * 111600)**2) / (t[i + 2] - t[i + 1])
print('航行速度:', speed, 'm/s')
k, b = least_squares(x[0:i + 2], y[0:i + 2])
x_ = new_x[i + 2 - 1] - sqrt((speed * (t[i + 2] - t[i + 2 -1]))**2 / (k**2 + 1)) / 100053
y_ = new_y[i + 2 - 1] - sqrt((speed * (t[i + 2] - t[i + 2 -1]))**2 / (k**2 + 1)) * k / 111600
new_x.append((x_ + x[i + 2]) / 2)
new_y.append((y_ + y[i + 2]) / 2)
return new_x, new_y
def compare(x, y, new_x, new_y, title_name):
plt.plot(new_x, new_y, label='修正轨迹')
plt.plot(x, y, label='原始轨迹')
plt.legend(loc='best')
plt.xlabel('经度')
plt.ylabel('纬度')
plt.title(title_name)
plt.show()
# 残差平方和评估:数据与拟合直线残差平方和
def evaluate(x, y):
x = np.array(x)
y = np.array(y)
k, b = least_squares(x, y)
# print('k, b:', k, b)
diff_list = x * k + b - y
# print(diff_list)
sum_square = 0
for i in diff_list:
sum_square += i ** 2
return sum_square / len(x)
data_1 = pd.read_csv(open('./data/1.csv'))
lon = data_1.ix[:, '经度'] # 12,13,16,13
lat = data_1.ix[:, '纬度']
tim = data_1.ix[:, '时间'] # 2018042910515071 ,整型
tim = [int(time.mktime(time.strptime(str(t)[0:14], "%Y%m%d%H%M%S"))) for t in tim] # 时间戳
lon_1, lat_1, t_1 = lon[0:12], lat[0:12], tim[0:12]
lon_2, lat_2, t_2 = lon[12:25], lat[12:25], tim[12:25] # straight
lon_3, lat_3, t_3 = lon[25:41], lat[25:41], tim[25:41]
lon_4, lat_4, t_4 = lon[41:54], lat[41:54], tim[41:54]
new_lon_1, new_lat_1 = revise(lon_1, lat_1, t_1)
new_lon_2, new_lat_2 = revise(lon_2, lat_2, t_2)
new_lon_3, new_lat_3 = revise(lon_3, lat_3, t_3)
new_lon_4, new_lat_4 = revise(lon_4, lat_4, t_4)
compare(lon_1, lat_1, new_lon_1, new_lat_1, '信号源一原始轨迹和修正轨迹对比')
compare(lon_2, lat_2, new_lon_2, new_lat_2, '信号源二原始轨迹和修正轨迹对比')
compare(lon_3, lat_3, new_lon_3, new_lat_3, '信号源三原始轨迹和修正轨迹对比')
compare(lon_4, lat_4, new_lon_4, new_lat_4, '信号源四原始轨迹和修正轨迹对比')
evaluate(lon_1[2:], lat_1[2:]), evaluate(new_lon_1[2:], new_lat_1[2:])
evaluate(lon_2[2:], lat_2[2:]), evaluate(new_lon_2[2:], new_lat_2[2:])
evaluate(lon_3[2:], lat_3[2:]), evaluate(new_lon_3[2:], new_lat_3[2:])
evaluate(lon_4[2:], lat_4[2:]), evaluate(new_lon_4[2:], new_lat_4[2:])
|
4aed7141e11f5cabd8d860ecdac245dffe71e6df | Gutwack/pythonProjects | /basicMetacamDose.py | 235 | 3.921875 | 4 | breed = input("Is this a dog or a cat?")
weight = float(input("What is the weight?"))
if breed == "dog":
dose = weight * 0.04
print(dose)
elif breed == "cat":
dose = weight * 0.05
print(dose)
else:
print("error")
|
01886e6780ca312c23c54061942ab487f0477727 | olamileke/web-scraping | /nytimes.py | 2,209 | 3.65625 | 4 | # Python program to fetch the contents of an nytimes article
from bs4 import BeautifulSoup, Tag
from urllib.request import Request, urlopen
import re
url = input('enter the url for the nytimes articles - ')
# formatting the text in the format we want
def parse_text(soup):
article_title = soup.h1.string
article_summary = soup.find(id='article-summary')
article_picture = soup.picture.img['src']
if article_summary is None:
article_summary = article_title.parent.parent.next_sibling
if article_summary.string is None:
article_summary = ''
else:
article_summary = article_summary.string
else:
article_summary = article_summary.string
article_blocks_parent = soup.find('section', class_='meteredContent')
blocks = article_blocks_parent.find_all('div', class_='StoryBodyCompanionColumn')
article_text = ''
for block in blocks:
paragraphs = block.find_all('p')
block_text = ''
for p in paragraphs:
p_text = ''
for child in p.children:
if(isinstance(child, Tag)):
if child.string:
p_text = p_text + child.string
else:
p_text = p_text + child
block_text = block_text + p_text
article_text = article_text + block_text
print('{0}\n{1}\n{2}\n\n{3}'.format(article_title, article_summary, article_picture, article_text))
# validating if the user entered a valid link to nytimes.com
if re.match('https://(www.)*nytimes.com/.+', url) is None:
print('please enter a valid nytimes article')
elif re.match('https://(www.)*nytimes.com/live(.*)', url) is not None:
print('Sorry. I do not scrape nytimes live blogs')
elif re.match('https://(www.)*nytimes.com/interactive(.*)', url) is not None:
print('Sorry. I do not scrape nytimes interactive articles')
else:
try:
req = Request(url, headers={'User-Agent' : 'Mozilla/5.0'})
html = urlopen(req).read().decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
parse_text(soup)
except:
print('There was a problem scraping the data')
|
2035a32bf51f3e3b3134e30a2943dd7d7a66220f | Terund/tools | /代码/进程、线程、协程/多线程访问共享数据的问题.py | 889 | 3.75 | 4 | """
多线程访问共享数据的问题:
1.哪些问题
数据混乱问题
2.如何解决
用锁(互斥锁)threading.Lock
获取锁(上锁)
lock.acquire()
释放锁(解锁)
locl.release()
获取锁与释放锁的次数要对应
好处:
保护数据安全,实现数据同步,不会混乱
弊端:
效率降低
容易导致死锁
"""
import time
import threading
#模拟的总票数
tickets = 1000
lock = threading.Lock()
def sale(name):
global tickets
while tickets > 0:
if lock.acquire():
if tickets > 0:
tickets -= 1
time.sleep(0.01)
print('{}售出1张票,剩余{}张'.format(name, tickets))
lock.release()
t1 = threading.Thread(target=sale,args=('窗口1',))
t2 = threading.Thread(target=sale,args=('窗口2',))
t1.start()
t2.start() |
2ac555d1dccc370a726e52e8283c1957de19b7a5 | andrew5205/Maching_Learning | /Python/regression/linear_regression/linear_regression.py | 1,933 | 3.828125 | 4 |
# Linear
# y = b0 + b1 * x1
# y: Dependent Variable (DV)
# x: Independent Variable (IV)
# b1: Coeddicient
# b0: Constant
# sum( y - y^) ** 2
# *********************************************************************************************************************
# Simple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
# *********************************************************************************************************************
# Training the Simple Linear Regression model on the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the Test set results
y_pred = regressor.predict(X_test)
# Visualising the Training set results
f1 = plt.figure(1)
plt.scatter(X_train, y_train, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
# plt.show()
# Visualising the Test set results
f2 = plt.figure(2)
plt.scatter(X_test, y_test, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'green')
plt.title('Salary vs Experience (Test set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
# # ********************************************************************
# # To show all figure at once
# #
# f1 = plt.figure(1)
# # code for f1
# f2 = plt.figure(2)
# # code for f2
# plt.show()
# # ********************************************************************
|
4ee82efb6887d9f33e7d71fdec4fa23bb129cd57 | StrategyCode/CourseEra | /Assignment_4.6.py | 392 | 3.6875 | 4 | def computepay():
if Hr > 40:
GrossPay=((Hr-40) * 1.5 * RatePerHour + (40 * RatePerHour))
else:
GrossPay=Hr * RatePerHour
return GrossPay
Hr=input("Enter Hours Worked")
RatePerHour=input("Enter Rate per Hours")
try:
Hr=float(Hr)
RatePerHour=float(RatePerHour)
except:
print("Please enter valid entry")
exit()
print(computepay())
#print(NetGrossPay) |
ca3966a88fae4251deb78a587564f7bb82d348ec | StrategyCode/CourseEra | /Assignment_12.2.py | 617 | 3.578125 | 4 | #To read the Web Content using URL and get the sum of all numeric Values.
import urllib.request,urllib.error,urllib.parse
import re
from bs4 import BeautifulSoup
sum=0
#Reading the content of Web Page
#WebContent=urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_42.html').read()
WebContent=urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_262655.html').read()
soup=BeautifulSoup(WebContent,'html.parser')
#Extracting the content of Comment
NumContent=re.findall('class="comments">(.+?)<',soup.decode())
#Calculating the Total Sum
for num in NumContent:
sum=sum+int(num)
print(sum)
|
2062897e73bd9d494b843b2853bb63cfa3010477 | AzizIsa/python-challenge | /PyBank/main.py | 1,738 | 3.765625 | 4 | #Import necessary libriaries
import os
import csv
import sys
#Define average function
def average(list):
return int(sum(list) / len(list))
#Create a path for the file
csvpath = os.path.join('Resources', 'budget_data.csv')
# Open the csv file
with open(csvpath, newline='') as csvfile:
# read the file
csvreader = csv.reader(csvfile, delimiter = ',')
#To avoid from the 1st row (header)
csv_header = next(csvreader)
#Convert the data to list
сsv_reader = list(csvreader)
#Calculate the total number of months included in the dataset
rowcount = len(сsv_reader)
#Empty list to place data of the differences of each row.
change=[]
#Calculate the total net amount of "Profit/Losses" over the entire period
total = 0
for row in сsv_reader:
total = total + int(row[1])
change.append(int(row[1]))
#Calculate the average change in "Profit/Losses" between months over the entire period
diff = [change[i]-change[i-1] for i in range(1,len(change))]
##Using Custom average function above
totalaverage = average(diff)
greatestInc= max(diff)
greatestDec = min(diff)
#Find months of max & min values.
max_index = diff.index(greatestInc)
max_month = сsv_reader[max_index+1][0]
min_index = diff.index(greatestDec)
min_month = сsv_reader[min_index+1][0]
#Uncomment the line below to export the results into txt file.
#sys.stdout= open('output.txt', 'w')
print(f"Total Months: {rowcount}")
print(f"Total: ${total}")
print(f"Average Change: ${totalaverage}")
print(f"Greatest Increase in Profits: {max_month} (${greatestInc})")
print(f"Greatest Decrease in Profits: {min_month} (${greatestDec})")
|
48f2cb31b76fb208e71f6ffe91d372979886dd47 | harshagl2002/COVID_CLI | /Province_CovidTracker.py | 2,835 | 3.53125 | 4 | import requests
import json
import datetime
def province():
url = "https://covid-19-statistics.p.rapidapi.com/reports"
ISO = input("Enter the ISO code of the country that you would like to search for.(ISO code of India is IND. ISO code of New Zealand is NZ): ")
province = input("Enter the province you would like to search for: ")
date = input("Enter the date (yyyy-mm-dd) you would like to search for: ")
year,month,day = date.split('-')
isValidDate = True
try :
datetime.datetime(int(year),int(month),int(day))
except ValueError :
isValidDate = False
if(isValidDate) :
querystring = {"date":date,"iso":ISO,"region_province":province}
headers = {
'x-rapidapi-key': "574d25f133msh5c58c65e8a4c944p1e6b8fjsnee1da55d91cd",
'x-rapidapi-host': "covid-19-statistics.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
data = response.text
parsed = json.loads(data)
if len(parsed["data"]) == 0:
print("Data not available")
else:
data_dict = parsed["data"][0]
print()
print("NEW CASES in", province, "on", date, "is", data_dict["confirmed_diff"])
print("TOTAL number of cases in", province, "till", date, "is", data_dict["confirmed"])
print("ACTIVE number of cases in", province, "on,", date, "is", data_dict["active"])
print("Number of DEATHS recored in", province, "on", date, "is", data_dict["deaths_diff"])
print("Number of RECOVERIES recorded in", province, "on", date, "is", data_dict["recovered_diff"])
else:
print("You have entered an invalid date. Kindly enter a valid date")
date = input("Enter the date (yyyy-mm-dd) you would like to search for: ")
querystring = {"date":date,"iso":ISO,"region_province":province}
headers = {
'x-rapidapi-key': "574d25f133msh5c58c65e8a4c944p1e6b8fjsnee1da55d91cd",
'x-rapidapi-host': "covid-19-statistics.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
data = response.text
parsed = json.loads(data)
if len(parsed["data"]) == 0:
print("Data not available")
else:
data_dict = parsed["data"][0]
print()
print("NEW CASES in", province, "on", date, "is", data_dict["confirmed_diff"])
print("TOTAL number of cases in", province, "till", date, "is", data_dict["confirmed"])
print("ACTIVE number of cases in", province, "on,", date, "is", data_dict["active"])
print("Number of DEATHS recored in", province, "on", date, "is", data_dict["deaths_diff"])
print("Number of RECOVERIES recorded in", province, "on", date, "is", data_dict["recovered_diff"])
|
913d183c3e9b8d62e2637c2f4bef9748c0923f83 | LostRob/Paradise | /水仙花数.py | 196 | 3.609375 | 4 | a = int(input( 'a = '))
x = int(a//100)
y = int((a//10)%10)
z = int(a%10)
if (x ** 3 + y ** 3 + z ** 3) == x * 100 + y * 10 + z:
print('是水仙花数')
else:
print('不是水仙花数')
|
b00bc36b3d68b0ecdb14f3b8906e032593a74038 | SuryaNMenon/Python | /Functions/shapeArea.py | 699 | 4.03125 | 4 | def circArea():
radius = int(input("Enter radius"))
print("Area =", (3.14 * radius**2))
def triArea():
base = int(input("Enter base"))
height = int(input("Enter height"))
print("Area =", (0.5 * base * height))
def recArea():
length = int(input("Enter length"))
breadth = int(input("Enter breadth"))
print("Area =", length*breadth)
def squArea():
side = int(input("Enter side"))
print("Area=", (side*side))
while(1):
choice = int(input("Menu\n1)Circle Area\n2)Triangle Area\n3)Rectangle Area\n4)Square area\nEnter your choice: "))
if choice == 1: circArea()
elif choice == 2: triArea()
elif choice == 3: recArea()
elif choice == 4: squArea()
else: print("Wrong choice") |
2327acffc2344bdbc183846ef128e0337d5367c3 | SuryaNMenon/Python | /Classes/rectangleClass.py | 343 | 3.90625 | 4 | class Rectangle:
def __init__(self,length,width):
self.length = length
self.width = width
def Area(self):
print(f"Area = {self.length * self.width}")
def Perimeter(self):
print(f"Perimeter = {2*(self.length + self.width)}")
rec1 = Rectangle(5,10)
rec2 = Rectangle(20,10)
rec1.Area()
rec2.Perimeter() |
7df9906b8a9cc0b658ed28494a8598c0948625ec | SuryaNMenon/Python | /Dictionaries/mapLists.py | 295 | 4.03125 | 4 | userlist1 = []
userlist2 = []
for iter in range(int(input("Enter the number of keys"))):
userlist1.append(input("Enter key: "))
for iter in range(int(input("Enter the number of values"))):
userlist2.append(input("Enter value: "))
userdict = dict(zip(userlist1,userlist2))
print(userdict) |
ae9a97b3fb40b8285182bb65d435f836de70ada6 | SuryaNMenon/Python | /Functions/timeAndCalendar.py | 543 | 4.21875 | 4 | import calendar,time
def localTime():
localtime = time.asctime(time.localtime(time.time()))
print(f"Current local time is {localtime}")
def displayCalendar():
c = calendar.month(int(input("Enter year: ")),int(input("Enter month: ")))
print("The calendar is:\n",c)
while(1):
choice = int(input("Menu\n1)Show current local time\n2)Show calendar for a month\n3)Exit\nEnter your choice: "))
if choice ==1: localTime()
elif choice == 2: displayCalendar()
elif choice == 3: exit(1)
else: print("Wrong choice")
|
a71788020b4f3fb954314330c388705e504a56dc | SuryaNMenon/Python | /Other Programs/whileCountdown.py | 192 | 4.21875 | 4 | #Program to print a countdown using user input range and while loop
high = int(input("Please enter the upper limit of the range"))
i=high
while i>-1:
print(i)
i-=1
print("Blast off!")
|
fb5c157023bdc1099b78647dcf39010377639d26 | SuryaNMenon/Python | /Files/writeAndRead.py | 284 | 3.625 | 4 | with open("/Ghosty's Files/Programming/Python/Files/testfile4.txt","a") as file:
file.write(input("Enter data to be inserted into the file. EOL = NewLine"))
with open("/Ghosty's Files/Programming/Python/Files/testfile4.txt", "r") as file:
for line in file:
print(line) |
8c2bbc0c0175bc8883d9fe65cbca3511dbefd81e | SuryaNMenon/Python | /Other Programs/leapYear.py | 217 | 4.3125 | 4 | #Program if user input year is leap year or not
year = int(input('Enter the year'))
if(year%4==0 or year%100==0 or year%400==0):
print('Given year is a leap year')
else:
print('Given year is not a leap year')
|
6feb3063ad9b8e229f56dd16dc7c9c7a525bf1d5 | SuryaNMenon/Python | /Other Programs/factorial.py | 187 | 4.34375 | 4 | #Program to print factorial of user input number
num = int(input('Enter the number\n'))
fact = 1
for iter in range(1,num+1):
fact = fact * iter
print('Factorial of', num, 'is', fact)
|
6722bc1f4b416b80bf6211d900e3444c27abd2b9 | bigsnarfdude/d3py | /d3py/css.py | 2,020 | 3.671875 | 4 | #!/usr/bin/python
class CSS:
"""
a CSS object is a dictionary whose keys are CSS selectors and whose values
are dictionaries of CSS declarations. This object is named according to the
definition of CSS on wikipedia:
A style sheet consists of a list of rules.
Each rule or rule-set consists of one or more selectors and a
declaration block.
A declaration-block consists of a list of declarations in braces.
Each declaration itself consists of a property, a colon (:), a value.
"""
def __init__(self, css=None):
self.rules = css or {}
assert isinstance(self.rules, dict)
def __getitem__(self, selector):
"returns the dictionary of CSS declarations, given a selector"
return self.rules[selector]
def __setitem__(self, selector, declarations):
"adds a dictionary of CSS declarations to the specified selector"
assert isinstance(declarations, dict)
if selector in self.rules:
self.rules[selector].update(declarations)
else:
self.rules[selector] = declarations
def __add__(self, css):
if isinstance(css, dict):
for selector, declarations in css.iteritems():
try:
self.rules[selector].update(declarations)
except KeyError:
self.rules[selector] = declarations
return self
elif isinstance(css, CSS):
return self.__add__(css.rules)
else:
errmsg = "Unsupported addition between %s and %s"
raise Exception(errmsg % (type(self), type(css)))
def __str__(self):
css = ""
for selector, declarations in self.rules.iteritems():
css += "%s {\n" % selector
for prop, value in declarations.iteritems():
if value is None:
value = "none"
css += "\t%s: %s;\n" % (prop, value)
css += "}\n\n"
return css
|
5493d5308b986e4efd6bfed3687712872d76bc35 | hyjae/udemy-data-wrangling | /DataCleaning/audit.py | 2,698 | 4.21875 | 4 | """
Observation of types
- NoneType if the value is a string "NULL" or an empty string ""
- list, if the value starts with "{"
- int, if the value can be cast to int
- float, if the value can be cast to float, but CANNOT be cast to int.
For example, '3.23e+07' should be considered a float because it can be cast
as float but int('3.23e+07') will throw a ValueError
- 'str', for all other values
The type() function returns a type object describing the argument given to the
function. You can also use examples of objects to create type objects, e.g.
type(1.1) for a float: see the test function below for examples.
"""
import codecs
import csv
import json
import pprint
CITIES = 'cities.csv'
FIELDS = ["name", "timeZone_label", "utcOffset", "homepage", "governmentType_label",
"isPartOf_label", "areaCode", "populationTotal", "elevation",
"maximumElevation", "minimumElevation", "populationDensity",
"wgs84_pos#lat", "wgs84_pos#long", "areaLand", "areaMetro", "areaUrban"]
"""
Note: A set is unordered collection with no duplicate elements.
Curly braces or set function can be used to create sets.
"""
def check_type(value, isInt):
if isInt:
try:
int(value)
return True
except ValueError:
return False
else:
try:
float(value)
return True
except ValueError:
return False
def audit_file(filename, fields):
fieldtypes = {}
for field in fields:
fieldtypes[field] = set()
with open(filename, 'r') as f:
reader = csv.DictReader(f)
"""
for i in range(3):
l = reader.next()
"""
for i, datum in enumerate(reader):
if i == 2:
break
for datum in reader:
for key, value in datum.items():
if key in fields:
if value == 'NULL' or value == '':
fieldtypes[key].add(type(None))
elif value[0] == '{':
fieldtypes[key].add(type([]))
elif check_type(value, True):
fieldtypes[key].add(type(1))
elif check_type(value, False):
fieldtypes[key].add(type(1.1))
else:
fieldtypes[key].add(type('str'))
f.close()
return fieldtypes
def test():
fieldtypes = audit_file(CITIES, FIELDS)
pprint.pprint(fieldtypes)
assert fieldtypes["areaLand"] == set([type(1.1), type([]), type(None)])
assert fieldtypes['areaMetro'] == set([type(1.1), type(None)])
if __name__ == "__main__":
test()
|
d203e5505f5db11247c9235d678999ed345e5d61 | PrathmeshPure/fun-py-programs | /file-translator-using-googleapi.py | 4,098 | 3.734375 | 4 | '''
by: Prathmesh Pure
This program is written to translate small text or srt files from
original language to target language.
Source language is detected automatically.
This program is just passing a string and language code to google translate api
and takes response from api and displays only translated text.
Language codes are mentioned at the end of file.
'''
from urllib.request import Request, urlopen
def translate(to_translate, to_langage="auto"):
# agents are required to request, else google gives 403 error
agents = {'User-Agent': "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"}
link = "http://translate.google.com/m?hl=en&sl=auto&tl=%s&q=%s" % (to_langage, to_translate.replace(" ", "+"))
# https://translate.google.com/m?hl=en&sl=auto&tl=hi&q=ti+amo <- sample url
request = Request(link, headers=agents)
page = urlopen(request).read()
''' Translated text on html page is written between following tag
<div dir="ltr" class="t0"></div>
'''
before_trans = b'class="t0">'
n = len(before_trans)
frm = page.find(before_trans) + n
result = page[frm:]
result = result.split(b"<")[0]
# decode() is required to write text in utf-8 again
return result.decode()
def main(src, dest, ln):
srcfile = open(src, "r", encoding="utf-8-sig")
destfile = open(dest, "w", encoding="utf-8-sig")
for line in srcfile:
trans = translate(line, "hi")+"\n"
destfile.writelines(trans)
destfile.close()
srcfile.close()
if __name__ == '__main__':
srcfile = "NFO.txt"
destfile = "File2.txt"
lang = "hi" # hi = hindi, en = english likewise other also
print(main(srcfile, destfile, lang))
'''
LANGUAGES = {
'af': 'afrikaans',
'sq': 'albanian',
'am': 'amharic',
'ar': 'arabic',
'hy': 'armenian',
'az': 'azerbaijani',
'eu': 'basque',
'be': 'belarusian',
'bn': 'bengali',
'bs': 'bosnian',
'bg': 'bulgarian',
'ca': 'catalan',
'ceb': 'cebuano',
'ny': 'chichewa',
'zh-cn': 'chinese (simplified)',
'zh-tw': 'chinese (traditional)',
'co': 'corsican',
'hr': 'croatian',
'cs': 'czech',
'da': 'danish',
'nl': 'dutch',
'en': 'english',
'eo': 'esperanto',
'et': 'estonian',
'tl': 'filipino',
'fi': 'finnish',
'fr': 'french',
'fy': 'frisian',
'gl': 'galician',
'ka': 'georgian',
'de': 'german',
'el': 'greek',
'gu': 'gujarati',
'ht': 'haitian creole',
'ha': 'hausa',
'haw': 'hawaiian',
'iw': 'hebrew',
'hi': 'hindi',
'hmn': 'hmong',
'hu': 'hungarian',
'is': 'icelandic',
'ig': 'igbo',
'id': 'indonesian',
'ga': 'irish',
'it': 'italian',
'ja': 'japanese',
'jw': 'javanese',
'kn': 'kannada',
'kk': 'kazakh',
'km': 'khmer',
'ko': 'korean',
'ku': 'kurdish (kurmanji)',
'ky': 'kyrgyz',
'lo': 'lao',
'la': 'latin',
'lv': 'latvian',
'lt': 'lithuanian',
'lb': 'luxembourgish',
'mk': 'macedonian',
'mg': 'malagasy',
'ms': 'malay',
'ml': 'malayalam',
'mt': 'maltese',
'mi': 'maori',
'mr': 'marathi',
'mn': 'mongolian',
'my': 'myanmar (burmese)',
'ne': 'nepali',
'no': 'norwegian',
'ps': 'pashto',
'fa': 'persian',
'pl': 'polish',
'pt': 'portuguese',
'pa': 'punjabi',
'ro': 'romanian',
'ru': 'russian',
'sm': 'samoan',
'gd': 'scots gaelic',
'sr': 'serbian',
'st': 'sesotho',
'sn': 'shona',
'sd': 'sindhi',
'si': 'sinhala',
'sk': 'slovak',
'sl': 'slovenian',
'so': 'somali',
'es': 'spanish',
'su': 'sundanese',
'sw': 'swahili',
'sv': 'swedish',
'tg': 'tajik',
'ta': 'tamil',
'te': 'telugu',
'th': 'thai',
'tr': 'turkish',
'uk': 'ukrainian',
'ur': 'urdu',
'uz': 'uzbek',
'vi': 'vietnamese',
'cy': 'welsh',
'xh': 'xhosa',
'yi': 'yiddish',
'yo': 'yoruba',
'zu': 'zulu',
'fil': 'Filipino',
'he': 'Hebrew'
}
'''
|
4afad85b6bcbaf932ee7a4754308804db627d963 | kalyanrohan/ASSIGNMENTS | /FIBONACCI.py | 246 | 4.15625 | 4 |
#0,1,1,2,3,5,8
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
nterms = int(input("n= "))
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i))
|
1df3bc87016ad046ffc4c7a27108e943ae84da27 | kalyanrohan/ASSIGNMENTS | /level2excercise.py | 1,187 | 4.6875 | 5 | #LEVEL 2
"""
1.Using range(1,101), make a list containing only prime numbers.
"""
prime=[x for x in range(2,101) if x%2!=0 and x%3!=0 and x%5!=0 and x%7!=0]
print(prime)
"""
2.Initialize a 2D list of 3*3 matrix. E.g.-
1 2 3
4 5 6
7 8 9
Check if the matrix is symmetric or not.
"""
"""
3. Sorting refers to arranging data in a particular format. Sort a list of integers in ascending order ( without using built-in sorted function ).
One of the algorithm is selection sort. Use below explanation of selection sort to do this.
INITIAL LIST :
2 3 1 45 15
First iteration : Compare every element after first element with first element and if it is larger then swap. In first iteration, 2 is larger than 1. So, swap it.
1 3 2 45 15
Second iteration : Compare every element after second element with second element and if it is larger then swap. In second iteration, 3 is larger than 2. So, swap it.
1 2 3 45 15
Third iteration : Nothing will swap as 3 is smaller than every element after it.
1 2 3 45 15
Fourth iteration : Compare every element after fourth element with fourth element and if it is larger then swap. In fourth iteration, 45 is larger than 15. So, swap it.
1 2 3 15 45
"""
|
1ff75c4685f869eece4ada6af2fb00769e251097 | JudgeVector/Projects | /SOLUTIONS/Text/CountVowels.py | 636 | 4.1875 | 4 | """
Count Vowels - Enter a string and the program counts the number of vowels in the text.
For added complexity have it report a sum of each vowel found.
"""
vowels = ['a','e','i','o','u']
vowel_count = [0,0,0,0,0]
def count_vowels(s):
for i in range(0, len(s)):
if s[i] in vowels:
for j in range(0, len(vowels)):
if s[i] is vowels[j]:
vowel_count[j] += 1
total = 0
for v in range(0, len(vowel_count)):
total += vowel_count[v]
print(vowels[v] + ' : ' + str(vowel_count[v]))
return total
print('Total number of vowels: ' + str(count_vowels(input('Enter a word or phrase to count the vowels: ').lower())))
|
47d3b0a870d32315963196eef208d39be488c468 | lduran2/dev.array-problems.in-python | /p01B-missing-number-sorted | 5,602 | 4.25 | 4 | #!/usr/bin/env python3
r'''
./p01B-missing-number-sorted
This program finds the missing number in a list of integers. This
implementation is optimized for sorted lists through use of binary
search.
* by: Leomar Duran <https://github.com/lduran2>
* date: 2019-06-28T23:53ZQ
* for: https://dev.to/javinpaul/50-data-structure-and-algorithms-\
problems-from-coding-interviews-4lh2
'''
import random # for picking the missing number
import logging # for logging
import sys # for command line arguments
def main(
min = 1, # the minimum value in the array to generate
max = 100, # the maximum value in the array to generate
print = print # the printing function
):
r'''
Tests the find_missing function on a shuffled array from 1 to 100.
'''
# generate the list of numbers
NUMBERS = generate_missing_number_list(min, max)
# find the missing number
MISSING = find_missing(NUMBERS, min, max)
# The output:
print('The array:')
print(NUMBERS)
print()
print('The missing number is ', MISSING, '.', sep='')
def find_missing(numbers, min, max):
r'''
Finds the number missing in the array of integers @numbers whose
elements are in the interval [min, max].
{1} Calculates the rightmost index for a binary search.
{2} Uses binary search to find the number before the missing.
{3} The missing number is one more than the number found.
'''
RIGHT = ((max - min) - 1) #{1}
INDEX = binary_search(numbers, RIGHT, #{2}
missing_number_arithpredicate)
MISSING = (numbers[INDEX] + 1) #{3}
return MISSING
def missing_number_arithpredicate(subject):
r'''
This arithpredicate uses the number at $list[mid], and returns -1
if the number and the following number are as expected, 0 if only
the current number is as expected and the following are not, or
+1 if the current number is not expected.
A number $list[index] is expected if it equals $(list[0] + index).
{1} Divides up the @subject parameter.
{2} Finds the minimum, actual current element, and calculates the
expected element.
{3} Compares the actual and expected current elements.
{4} If the actual is less or equal,
{5} checks that the next elemet is still within range,
and if so, return 0, avoiding index overflow.
{6} checks whether the next element is greater than one more
than the current, and if so, return 0.
If neither {5,6}, the comparator will be negative.
If not {4}, the comparator will be positive.
{7} Returns the comparator.
'''
(index, list, off, len) = subject #{1}
#{2}
MIN = list[0]
ELEMENT = list[index]
EXPECTED = (index + MIN)
comparison = (ELEMENT - EXPECTED) #{3}
if (comparison <= 0): #{4}
if ((index + 1) == len): #{5}
return 0
NEXT = list[index + 1] #{6}
comparison = (NEXT - (ELEMENT + 2))
if (comparison > 0):
comparison = 0
return comparison #{7}
def binary_search(list, right, arithpredicate, left = 0, default = -1):
r'''
Searches the list within indices in the interval [left, right] for
an element that satisfies the given arithpredicate.
Starts with the entire list as the sublist.
{1} Loops until the sublist is empty.
{2} Calculates the midpoint of the sublist.
{3} Tests the element at the midpoint with the arithpredicate.
{4} If the element is too low, shifts the left endpoint of the
sublist to the midpoint
{5} If the element is too high, shifts the right endpoint of
the sublist to the endpoint
{6} Otherwise, returns the midpoint.
{7} If the sublist is empty, returns $default.
params:
list -- the list to search
right -- the index of the rightmost endpoint of the list
arithpredicate -- an arithpredicate with which to search the
list
left -- the index of the leftmost endpoint of the list
default -- the default index to return
returns:
the index of the element satisfying the arithpredicate, or
$default (-1 by default) if no such element is found
'''
LEN = (right + 1) # the length of the entire list
logging.debug(r'Searching through list of size: %d...', LEN)
while (left <= right): #{1}
MID = ((left + right) >> 1) #{2}
logging.debug(r' Midpoint: %d', MID)
COMPARISON = arithpredicate((MID, list, left, LEN)) #{3}
if (COMPARISON < 0): #{4}
left = (MID + 1)
elif (COMPARISON > 0): #{5}
right = (MID - 1)
else: #{6}
return MID
return default #{7}
def generate_missing_number_list(min, max):
r'''
Generates a list of shuffled numbers in the interval [min, max]
with one number missing.
{1} Chooses a random number in the interval [min, max[ to replace.
{2} Creates an list in the interval [min, max], skipping the
number to replace.
params:
min -- the minimum value in the list
max -- the maximum value in the list
'''
MISSING = random.randrange(min, max) #{1}
logging.debug(r'Missing number chosen: %d', MISSING)
numbers = [x for x in range(min, (max + 1)) if (x != MISSING)] #{2}
return numbers
if (r'__main__' == __name__):
# if '--debug' flag was given in command line arguments,
# place the logger in debug mode
if (r'--debug' in sys.argv):
logging.basicConfig(level=logging.DEBUG)
main()
|
eeb30e32b2a5b095987e5be0d0249c84328838dc | mwanchap/Oiler | /problem1.py | 561 | 3.765625 | 4 | def getSumOfMultiples(baseNum, count):
the_sum = baseNum
max_value = int(count/baseNum) + 1
for i in range(2, max_value):
the_sum += baseNum * i
return the_sum
def sumDivisibleBy(number, count):
the_max = int(count/number)
return int(number * (the_max * (the_max + 1)) /2)
count = 999
# attempt 1
count2 = getSumOfMultiples(3, count) + getSumOfMultiples(5, count) - getSumOfMultiples(15, count)
print(count2)
# attempt 2
count3 = sumDivisibleBy(3, count) + sumDivisibleBy(5, count) - sumDivisibleBy(15, count)
print(count3) |
73bb14c9e8453d5131fba8c15782a09a23860b28 | glennsvel90/Navy_Weather_Data_Analyzer | /navywDB.py | 8,544 | 3.828125 | 4 | from datetime import date, datetime, timedelta
from tkinter import messagebox
import sqlite3
import NavyWWeb
class NavyWDB():
"""
Create and manages a database that stores local cache of all weather data that's been
downloaded from the internet.
"""
def __init__(self, **kwargs):
""" open the database """
self.filename = kwargs.get('filename', 'navyw.db')
self.table = kwargs.get('table', 'weather')
#open a database, or create a new one if none is found.Store the reference to the database in the class db variable
self.db = sqlite3.connect(self.filename)
self.db.row_factory = sqlite3.Row
# if table does not exist, will create a new table with the following columns
self.db.execute("""CREATE TABLE IF NOT EXIST {} (Date TEXT, Time TEXT, Status Text, Air_Temp FLOAT,
Barometric Press FLOAT, Wind_Speed FLOAT""".format(self.table))
def get_data_for_range(self, start, end):
"""
Using the start and end dates, return a generator of dictionaries that have all weather data, such as Wind Speed,
Barometric Pressure, and Wind Speed in those dates.
"""
#This funtion is called by the NavyWApp module.
dates_to_update = []
# find pre-2007 dates and add to list of dates to be updated
# by checking if there is no data for a Jan 12 date in that given year in the database
for year in range(start.year, 2007):
if list(self._get_status_for_range(date(year,1,12), date(year,1,12))) == []:
dates_to_update.append(date(year,1,12))
# before finding post-2006 dates first find a temporary start date either on or after jan 1 2007
if (end.year > 2006) and (start >= date(2007,1,1)):
temp_start = start
elif (end.year > 2006) and (start < date(2007,1,1)):
temp_start = date(2007,1,1)
else:
temp_start = end
# obtains dates between temp_start and end for dates post 2006, then adds these dates to "dates to update" list
delta = end - temp_start
for d in range(delta.days +1):
dates_to_update.append(temp_start + timedelta(days=d))
# convert the dictionary of dictionaries that comes out from using the "get status for range" function
# into a list of dictionaries containing the key Date and its value, and the
# key Status and it's value
statuses = list(self._get_status_for_range(temp_start, end))
# for each dictionary in the above statuses list, if the key of status is 'complete', remove the datetime object from the list of dates to be updated. From the
# the reading of the database when turned the python datetime date into a string from the "get status for range" function, the statuses list created has
# a string form of the date. Convert that string form date into a datetime in order to specify the removal of the date time from "dates to update list"
for entry in statuses:
if entry['Status'] == 'COMPLETE':
dates_to_update.remove(datetime.strptime(str(entry['Date']), '%Y%m%d').date())
# if status is partial, download more data for the partial date.
elif entry['Status'] == 'PARTIAL':
try:
# downloading of data is initiated through the "update data for date" function and it's inherent calling of navywweb module's "get data for
# date" function
self._update_data_for_date(datetime.strptime(str(entry['Date']), '%Y%m%d').date(), True)
except:
raise
dates_to_update.remove(datetime.strptime(str(entry['Date']), '%Y%m%d').date())
error_dates = []
for day in dates_to_update:
try:
# download weather data for the days
self._update_data_for_date(day, False)
# for any errors that occur for the downloading of certain dates, capture the error and present it as a warning message
except ValueError as e:
error_dates.append(e)
if error_dates != []:
error_message = "There were problems accessing data for the following dates. They were not included in the results.\n"
for day in error_dates:
error_message += '\n{}'.format(day)
messagebox.showwarning(title='Warning', message=error_message)
# finally obtain the weather data from the database and create a generator object of dictionary of dictionaries
cursor = self.db.execute('''SELECT Air_Temp, Barometric_Press, Wind_Speed FROM {} WHERE Date BETWEEN {} AND {}'''.format(self.table,
start.strftime(%Y%m%d),
end.strftime(%Y%m%d)))
for row in cursor:
yield dict(row)
def get_status_for_range(self, start, end):
"""
Given a start and end date, return a generator of dicts containing the dates and their corresponding status value which
is entered as either COMPLETE or PARTIAL.
"""
# from the multiple records of different timestamps for redunant dates between the start and end date, get one date result.
# Turn the python dates datetime objects into string text form to be able to be added and be compatible with the database
cursor = self.db.execute('''SELECT DISTINCT Date, Status FROM {} WHERE Date BETWEEN {} AND {}'''.format(self.table,
start.strftime(%Y%m%d),
end.strftime(%Y%m%d)))
for row in cursor:
yield dict(row)
def _update_data_for_date(self, date, partial):
"""
Uses NavyWWeb module to download data for dates not already in the DB. If partial data exists, then it is deleted and re-downloaded
completely
"""
# if partial data exist for that date, delete what is ever in the database for that specific date to avoid duplicate data. The date was initially a datetime
# object, so turn it into a string to be read by the database to delete it.
if partial:
self.db.execute('DELETE FROM {} WHERE DATE = {}'.format(self.table, date.strftime('%Y%m%d')))
self.db.commit()
try:
#return a generator of dictionaries for the six fields in the database using the navywweb module's get_data_for_date function, set the generator
# equal to data variable
data = navywweb.get_data_for_date(date)
except
raise
for entry in data:
self.db.execute('''INSERT INTO {} (Date, Time, Status, Air_Temp, Barometric_Press, Wind_Speed) VALUES (?,?,?,?,?,?)'''.format(self.table),
(entry['Date'].replace("_", ""),
entry['Time'],
entry['Status'],
entry['Air_Temp']
entry['Barometric_Press'],
entry['Wind_Speed']))
self.db.commit()
def clear(self):
""" Clears the database by dropping the current table. """
self.db.execute('DROP TABLE IF EXISTS {}'.format(self.table))
def close(self):
"""
closes the database in a safe way and delete the filename reference to it
"""
self.db.close()
del self.filename
|
c1235b19604218e998ba053ac1549bc238a1bfe1 | git484/leetcoding | /prime no check.py | 219 | 3.890625 | 4 | y=int(input("enter a no\n"))
flag=1
for x in range(2, y, +1):
if y%x == 0:
print("Not prime")
flag=0
break
if flag==1:
print("It is prime")
|
4241f67d8f7f09470233d34d60cc3da6ae7e80e1 | avner-csumb/python-day4 | /number_game.py | 207 | 3.921875 | 4 | low = int(raw_input('Enter low number: '))
high = int(raw_input('Enter high number: '))
# i = low
# while i <= high:
# print(i)
# i += 1
my_list = range(low, high+1)
for i in my_list:
print(i)
|
ec3e44a582edfa4a939eb1b1f314302dea22c52f | zhangruochi/Book | /FluentPython/chapter2/bisect_module.py | 628 | 3.53125 | 4 | #!/usr/bin/env python3
#info
#-name : zhangruochi
#-email : [email protected]
import bisect
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
NEEDLES.reverse()
for num in NEEDLES:
position = bisect.bisect_right(HAYSTACK,num)
print(position, end=",")
print("")
#找到成绩对应的 gradrs
def grade_student(grade):
return "ABCD"[bisect.bisect_left([60,70,80,90],grade)]
print(grade_student(65))
import random
my_list = []
for i in range(10):
new_item = random.randrange(10 * 2)
bisect.insort(my_list, new_item)
print(my_list)
|
34f524b2719d445a465475d2ce564c810ac2badb | cy486/python | /cards_tools.py | 3,757 | 3.734375 | 4 | #记录所有的名片
card_list=[]
def show_menu():
"""显示菜单"""
print("*" * 50)
print("欢迎使用【名片管理系统】V1.0")
print()
print("1. 新增名片")
print("2. 显示全部")
print("3. 查询名片")
print()
print("0. 退出系统")
print("*" * 50)
def new_card():
"""增加名片"""
print("-" * 50)
print("新增名片")
#1.提示用户输入名片的详细信息
name_str = input("请输入姓名:")
phone_str = input("请输入电话:")
qq_str = input("请输入qq:")
email_str = input("请输入邮箱:")
#2.使用用户输入的信息建立一个名片字典
card_dict = {"name": name_str,
"phone": phone_str,
"qq": qq_str,
"email": email_str}
#3.将名片字典添加到列表中
card_list.append(card_dict)
print(card_list)
#4.提示用户添加成功
print("%s 的名片添加成功" %name_str)
def show_all():
"""显示所有名片"""
print("-" * 50)
print("显示所有名片")
#判断是否存在名片记录,如果没有,提示用户并返回
if len(card_list) == 0:
print("当前没有名片记录,请先添加")
return
#打印表头
for name in ["姓名","电话","qq","邮箱"]:
print(name,end="\t\t")
print("")
#打印分割线
print("=" * 50)
#遍历名片列表依次输出字典信息
for card_dict in card_list:
print("%s\t\t" *4 %(card_dict["name"],
card_dict["phone"],
card_dict["qq"],
card_dict["email"]))
def find_card():
"""搜索名片"""
print("-" * 50)
print("搜索名片")
#1.提示用户要查询的姓名
find_name = input("请输入要搜索的姓名: ")
#2.遍历名片列表,查询要搜索的姓名,如果没有,提示用户
for card_dict in card_list:
if card_dict["name"]==find_name:
print("姓名\t\t电话\t\tqq\t\t邮箱\t\t")
print("=" * 50)
print("%s\t\t" * 4 % (card_dict["name"],
card_dict["phone"],
card_dict["qq"],
card_dict["email"]))
deal_card(card_dict)
break
else:
print("抱歉,没有找到 %s" % find_name)
def deal_card(card_dict):
"""处理查找到的名片
:param card_dict: 查找到名片的字典
"""
print(card_dict)
action_str = input("请选择要执行的操作 "
"【1】修改 【2】 删除 【0】 返回上级菜单")
if action_str == "1":
card_dict["name"] = input_card_info(card_dict["name"],"姓名:")
card_dict["phone"] = input_card_info(card_dict["phone"] ,"电话:")
card_dict["qq"] = input_card_info(card_dict["qq"],"qq:")
card_dict["email"] = input_card_info(card_dict["email"],"邮箱:")
print("修改名片成功")
elif action_str == "2":
card_list.remove(card_dict)
print("删除名片成功")
elif action_str == "0":
pass
def input_card_info(dict_value,tip_message):
"""
输入名片信息
:param dict_value: 字典中原有的值
:param tip_message: 输入字典提示文字
:return: 如果用户输入值返回用户输入的值,用户没输入就返回原来的
"""
result_str = input(tip_message)
if len(result_str) > 0:
return result_str
else:
return dict_value |
f313f28359bae14970c42448354d98f346640793 | neulab/tranx-study | /analysis/submissions/638965bbb0d66a5b0eae27d1324bbf89_task1-1_1596102935/task1-1/main.py | 557 | 3.625 | 4 | import random
output = {}
# generate random chars and ints and add them to a dictionary
for i in range(100):
character = (chr(random.randint(97, 122)))
integer = random.randint(1, 20)
if character in output:
output[character].append(integer)
else:
output[character] = [integer]
# sort dictionary
for key in output:
output[key] = sorted(output[key])
letters_sorted = sorted(output.items())
for (key,list) in letters_sorted:
pair = str(key)
for num in list:
pair = pair + " " + str(num)
print(pair)
|
1526c3057de6507187e3cc2f50f9d04e1c9b6df4 | neulab/tranx-study | /analysis/submissions/34b1ef17e6625ba2350f6f1c169591a1_task2-1_1595488334/task2-1/main_patch.py | 320 | 3.609375 | 4 | # Example code, write your program here
import pandas as pd
import os
os.mkdir("output")
df = pd.read_csv('data.csv')
# If you know the name of the column skip this
first_col = df.columns[0]
last_col = df.columns[-1]
# Delete first
df = df.drop([first_col, last_col], axis=1)
df.to_csv('output/output.csv', index=False) |
68473ef8a02dcf900cb061acbc7e1c852fbea181 | neulab/tranx-study | /analysis/submissions/9dd43727b9246d7f2220b94ff43380cf_task1-1_1596138232/task1-1/main.py | 684 | 3.796875 | 4 | # Example code, write your program here
import string
import random
from collections import defaultdict
dict = defaultdict(list)
def random_char():
letter = string.ascii_lowercase
result = ''.join(random.choice(letter))
return result
for i in range (1, 100):
tempkey = random_char()
tempval = random.randint(1, 20);
dict[tempkey].append(tempval)
print (dict)
dict2 = dict.items()
sorted_dict = sorted(dict2)
for x in range(0,len(sorted_dict)):
sorted_dict[x][1].sort()
for x in range(0,len(sorted_dict)):
print (sorted_dict[x][0], end= " ")
for y in range (0, len(sorted_dict[x][1])):
print (sorted_dict[x][1][y], end = " ")
print() |
0b3d42404a595e14ccf1a8089805f1f7e28401df | neulab/tranx-study | /analysis/submissions/0ed2dff1d23b0de1cfcf9edb0ba35b1c_task7-2_1591994712/task7-2/main.py | 1,184 | 3.71875 | 4 | # Example code, write your program here
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def main():
df = pd.read_csv("StudentsPerformance.csv")
grouped = df.groupby(['gender', 'race/ethnicity'])
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(20, 6))
bar_width = 0.35
for ax, subject in zip(axes, ['math', 'reading', 'writing']):
avg_score = grouped[f"{subject} score"].mean()
for key, shift in [('male', -0.5), ('female', 0.5)]:
value = avg_score[key].to_list()
shift *= bar_width
ax.bar(np.arange(len(value)) + shift, value, width=bar_width, label=key.capitalize())
for i, v in enumerate(value):
ax.text(i + shift, v + 2, f"{v:.2f}", ha='center', va='center')
ax.set_xlabel("Race/Ethnicity")
ax.set_ylabel("Average Scores")
ax.set_xticklabels([0] + [x.split()[1] for x in avg_score['male'].index.to_list()])
ax.set_title(subject.capitalize())
ax.legend(loc="upper left")
fig.suptitle("Scores by race/ethnicity and gender")
fig.savefig("output/grouped_scores.png")
if __name__ == '__main__':
main()
|
2827ba2ce9df9c1e4174af53375b04a56f1b8981 | neulab/tranx-study | /analysis/submissions/27570bb3cfcc304aeede0cdf6c2e2762_task2-1_1600789334/task2-1/main.py | 472 | 3.640625 | 4 | # Example code, write your program here
import csv
import pandas as pd
#reader = csv.reader(open('data.csv', 'rb'))
with open("data.csv", 'r') as reader,open("output.csv", 'w') as outFile:
out = csv.writer(outFile,delimiter=',',quotechar='"')
for row in reader:
col = row.split(',')
if len(col) >=6:
outFile.write(col[1].strip()+","+col[2].strip()+","+col[3].strip()+","+col[4].strip()+","+"\n")
outFile.close()
reader.close()
|
0e4617ecbba8d6579b53c98087b96364e5dc6e83 | neulab/tranx-study | /analysis/submissions/0ed2dff1d23b0de1cfcf9edb0ba35b1c_task1-1_1591986411/task1-1/main.py | 463 | 3.640625 | 4 | # Example code, write your program here
import random
import string
from collections import defaultdict
def main():
letters = [random.choice(string.ascii_lowercase) for _ in range(100)]
numbers = [random.randint(1, 20) for _ in range(100)]
d = defaultdict(list)
for c, x in zip(letters, numbers):
d[c].append(x)
print("\n".join(f"{c} {' '.join(map(str, xs))}" for c, xs in sorted(d.items())))
if __name__ == '__main__':
main()
|
44e9c95706879ed95d2dc9f2f4206dcfff1ac3d2 | neulab/tranx-study | /analysis/submissions/10fb8132405b6c443addb06bc941f9e3_task1-1_1597089229/task1-1/main.py | 633 | 3.703125 | 4 | # Example code, write your program here
import string
import random
num = []
num_paired = []
mydict = {}
letter = string.ascii_lowercase
res = ''.join(random.choice(letter) for i in range(100))
#print(res)
for i in range(100):
num.append(random.randint(1, 20))
#print(num)
for i in range(100):
for j in range(100):
if res[i] == res[j]:
num_paired.append(num[j])
num_paired.sort()
mydict[res[i]] = num_paired
num_paired = []
sorted_dict=sorted(mydict.items())
#print(sorted_dict)
for i in sorted_dict:
print(i[0], end=" ")
for j in i[1]:
print(j, end=" ")
print()
|
6657bda6817d3be50fabbe73148becf243bee6f3 | neulab/tranx-study | /analysis/submissions/0bd31633162f7a836160dd5b6359d29b_task2-1_1601661947/task2-1/main_patch.py | 188 | 3.640625 | 4 | import pandas as pd
columns_needed = ["first_name","last_name","email","gender"]
df = pd.read_csv('data.csv', usecols = columns_needed)
df.to_csv(r'example_output/output.csv')
print(df) |
f945785dd904c59d4723a7ed0db600d45e180b54 | kju2/euler | /problem067.py | 1,013 | 3.75 | 4 | """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt, a 15K text file
containing a triangle with one-hundred rows.
NOTE: This is a much more difficult version of Problem 18. It is not possible
to try every route to solve this problem, as there are 299 altogether! If you
could check one trillion (1012) routes every second it would take over twenty
billion years to check them all. There is an efficient algorithm to solve it.
"""
from problem018 import triangle_sum
def main():
"""
>>> main()
7273
"""
with open("problem067.txt") as f:
triangle = f.read().splitlines()
triangle = [[int(n) for n in line.split(' ')] for line in triangle]
triangle.reverse()
print(reduce(triangle_sum, triangle)[0])
if __name__ == "__main__":
import doctest
doctest.testmod()
|
9b3661b407e31b15525d7caa1f956252a28a9d99 | kju2/euler | /problem047.py | 1,265 | 3.703125 | 4 | """
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 * 7
15 = 3 * 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2^2 * 7 * 23
645 = 3 * 5 * 43
646 = 2 * 17 * 19.
Find the first four consecutive integers to have four distinct primes factors.
What is the first of these numbers?
"""
from itertools import count
from prime import Primes
def main():
"""
>>> main()
134043
"""
primes = Primes(10 ** 6)
min_consecutive_valid_numbers = 4
distinct_prime_factors = 4
# next number after lower bound has to have at least distinct_prime_factors
# of odd primes as prime factors
lower_bound = (3 * 5 * 7 * 11) - 1
number = 0
consecutive_valid_numbers_count = 0
for number in count(lower_bound):
if consecutive_valid_numbers_count == min_consecutive_valid_numbers:
break
if len(set(primes.factors_of(number))) == distinct_prime_factors:
consecutive_valid_numbers_count += 1
else:
consecutive_valid_numbers_count = 0
# print first number of the consecutive numbers
print(number - distinct_prime_factors)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
15090f3167cc207f0cf64acb0b3c84e27bbf85c4 | kju2/euler | /problem304.py | 1,494 | 3.515625 | 4 | """
http://projecteuler.net/problem=304
"""
def fib(nth):
"""fib returns the nth fibonacci number."""
fib_matrix = [[1, 1], [1, 0]]
if nth == 0:
return 0
power(fib_matrix, nth - 1)
return fib_matrix[0][0]
def power(matrix, exponent):
"""power computes the power to a given matrix."""
if exponent == 0 or exponent == 1:
return
power(matrix, exponent / 2)
multiply(matrix, matrix)
if exponent % 2 != 0:
multiply(matrix, [[1, 1], [1, 0]])
def multiply(matrix_a, matrix_b):
"""
multiply multiplies two matrixes. The result is saved to matrix_a and
is given mod 1234567891011.
"""
x = matrix_a[0][0] * matrix_b[0][0] + matrix_a[0][1] * matrix_b[1][0]
y = matrix_a[0][0] * matrix_b[0][1] + matrix_a[0][1] * matrix_b[1][1]
z = matrix_a[1][0] * matrix_b[0][0] + matrix_a[1][1] * matrix_b[1][0]
w = matrix_a[1][0] * matrix_b[0][1] + matrix_a[1][1] * matrix_b[1][1]
matrix_a[0][0] = x % 1234567891011
matrix_a[0][1] = y % 1234567891011
matrix_a[1][0] = z % 1234567891011
matrix_a[1][1] = w % 1234567891011
def main():
"""
Precomupted the primes in the file "problem304.txt" to reduce the runtime.
>>> main()
283988410192
"""
limit = 100000
primes = [int(i) for i in open("problem304.txt").readline().split(' ')]
print(sum(fib(primes[n]) for n in range(limit)) % 1234567891011)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
53cf3eed32f2c405ee56e4b433e3180bc1aa1d77 | kju2/euler | /problem033.py | 1,362 | 4.15625 | 4 | """
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in
attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is
correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples of this type of fraction, less than
one in value, and containing two digits in the numerator and denominator.
If the product of these four fractions is given in its lowest common terms,
find the value of the denominator.
"""
from fractions import Fraction
from operator import mul
def main():
"""
>>> main()
100
"""
# not a curious fraction 30/50 or 77/77
curious_fractions = []
for numerator_tens in range(1, 10):
for denominator_unit in range(1, 10):
for cancler in range(1, 10):
numerator = numerator_tens * 10 + cancler
denominator = cancler * 10 + denominator_unit
fraction1 = Fraction(numerator, denominator)
fraction2 = Fraction(numerator_tens, denominator_unit)
if fraction1 == fraction2 and numerator != denominator:
curious_fractions.append(fraction1)
print(reduce(mul, curious_fractions).denominator)
if __name__ == "__main__":
import doctest
doctest.testmod()
|
b0d32f2891d07fb5f8e5ae9e803d549f68d30e51 | kju2/euler | /problem005.py | 1,244 | 4.0625 | 4 | """
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of
the numbers from 1 to 20?
"""
def main():
"""
divisible by 2 if step is 2
divisible by 3 if step is 3*2
divisible by 4 if step is 3*2**2
divisible by 5 if step is 5*3*2**2
divisible by 6 because of 2 and 3
divisible by 7 if step is 7*5*3*2**2
divisible by 8 if step is 7*5*3*2**3
divisible by 9 if step is 7*5*3*3*2**3
divisible by 10 if step is 7*5*3*3*2**4
divisible by 11 if step is 11*7*5*3*3*2**4
divisible by 11 if step is 11*7*5*3*3*2**4
divisible by 12 because of 2 and 6
divisible by 13 if step is 13*11*7*5*3*3*2**4
divisible by 12 because of 7 and 2
divisible by 15 because of 5 and 3
divisible by 16 because of 8 and 2
divisible by 17 if step is 17*13*11*7*5*3*3*2**4
divisible by 18 because of 9 and 2
divisible by 19 if step is 19*17*13*11*7*5*3*3*2**4
divisible by 20 because of 5 and 2
>>> main()
232792560
"""
print(19 * 17 * 13 * 11 * 7 * 5 * 3 * 3 * (2 ** 4))
if __name__ == "__main__":
import doctest
doctest.testmod()
|
62c31161a0a2b0b85a00071db97210d1d3892454 | HarshVikram/learning-python | /Python Syntax/if_else.py | 287 | 4.09375 | 4 | size = input('Enter the size of shirt: ')
value = int(size)
if value == 40:
print(' is S')
elif value == 42:
print(size + ' is M')
elif value == 44:
print(size + ' is L')
elif value > 44:
print('Size is not available')
else:
print('We would have to place a custom order')
|
79a2518aa79292f1ddffd39a3f3b78f0d7e07e0e | Kuomenghsin/my-learning-note | /HW2/heap_sort_ 06111306.py | 1,400 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
class Solution():
def heap_sort(self, nums):
self.nums = nums
self.heapSort(nums)
return nums
def toHeap(self,arr, n, i): #堆積size = n
bigest = i # 子樹根初始值 index = i
L = 2*i + 1 # (左子節點) = 2*i + 1 由左子數計算樹根位址i
R = 2*i + 2 # (右子節點) = 2*i + 2 由右子數計算樹根位址i
# 左子節點存在而且大於父節點
if L < n and arr[i] < arr[L]:
bigest = L
# 右子節點存在而且大於父節點
if R < n and arr[bigest] < arr[R]:
bigest = R
# 更換父節點
if bigest != i:
arr[i],arr[bigest] = arr[bigest],arr[i] # 兩兩交換
# 最後堆積樹根
self.toHeap(arr, n, bigest)
# 主程式根據串列sort
def heapSort(self,arr):
n = len(arr) #串列大小
# 建立maxheap串列(父節點永遠大於子節點)
for i in range(n, -1, -1):
self.toHeap(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # 兩兩交換
self.toHeap(arr, i, 0)
output=Solution().heap_sort([ 2, 4 ,7, 1, 21,-3, 64, 12, 11, 15, 4, 7, 8])
output
# In[ ]:
|
f334ed11c9801ead3700cc0fa687ff7a81353643 | kn0709/python | /gu_nu.py | 762 | 3.796875 | 4 | import random
def number_game(in_val):
number_range = [x for x in range(1,101)]
rand_num = random.choice(number_range)
if int(in_val) == rand_num:
print("Amazing how did this happen")
else:
diff_num = int(in_val) - rand_num
if diff_num < 0:
print("You are just {} behind".format(diff_num * -1))
print("I have choosen {}".format(rand_num))
else:
print("You are just {} ahaead".format(diff_num))
print("I have choosen {}".format(rand_num))
def main():
while True:
user_option = raw_input("Do you want to play a Game (Yes/No): ")
if user_option in ['Yes','Y','y','yes']:
user_val = raw_input("Please guess a number between 1 to 100: ")
number_game(user_val)
continue
else:
break
if __name__ == '__main__':
main()
|
a3940af34ce7d808facbdb0ac67cdbbd17d50a23 | xxrom/617_merge_two_binary_trees | /main.py | 2,534 | 4.125 | 4 | # Definition for a binary tree node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return str(self.__dict__)
class Solution:
# print all values
def printAll(self, root):
if root.val != None:
print(root.val)
if root != None and root.left != None:
self.printAll(root.left)
if root != None and root.right != None:
self.printAll(root.right)
def mergeTrees(self, node0: Node, node1: Node) -> Node:
# if one of the nodes exist
if (node0 != None and node0.val != None) or (node1 != None and node1.val != None):
# We use node0 as merged one (for answer), so init it if needed
if node0 == None:
node0 = Node(0)
# Merge (add) value from node1 (another one tree)
node0.val += node1.val if node1 != None and node1.val != None else 0
# Find out values from node1 childrens (like shortcuts)
node1Left = node1.left if node1 != None and node1.left != None else None
node1Right = node1.right if node1 != None and node1.right != None else None
# If someone in the left/right exist, then merge deeper
if node0.left != None or node1Left != None:
node0.left = self.mergeTrees(
node0.left, node1Left)
if node0.right != None or node1Right != None:
node0.right = self.mergeTrees(
node0.right, node1Right)
# merged tree - node0 (result)
return node0
tree0 = Node(1, Node(3, Node(5)), Node(2))
tree1 = Node(2, Node(1, None, Node(4)), Node(3, None, Node(7)))
my = Solution()
merged = my.mergeTrees(tree0, tree1)
my.printAll(merged)
# 3
# 4 5
# 5 4 5 7
# with additional merged tree:
# Runtime: 108 ms, faster than 5.41% of Python3 online submissions for Merge Two Binary Trees.
# Memory Usage: 14.1 MB, less than 22.86% of Python3 online submissions for Merge Two Binary Trees.
# without additional tree:
# Runtime: 104 ms, faster than 9.26% of Python3 online submissions for Merge Two Binary Trees.
# Memory Usage: 13.7 MB, less than 74.29% of Python3 online submissions for Merge Two Binary Trees.
# Runtime: 96 ms, faster than 17.71% of Python3 online submissions for Merge Two Binary Trees.
# Memory Usage: 13.8 MB, less than 68.57% of Python3 online submissions for Merge Two Binary Trees.
|
f1773013a4d82b0d140d882e87e25dd3a6205bc8 | isaaczinda/route-planner | /tools/Geometry.py | 3,274 | 3.75 | 4 | import math
import numpy as np
def DifferenceBetweenDegrees(One, Two):
Difference = abs(One - Two)
if Difference <= 180:
return Difference
else:
return abs(Difference - 360)
# always returns an angle less than pi radians
def AngleBetweenLines(LineOne, LineTwo):
LengthOne = np.linalg.norm(np.array(LineOne))
LengthTwo = np.linalg.norm(np.array(LineTwo))
# normalize the vectors
LineOne = np.array(LineOne) / LengthOne
LineTwo = np.array(LineTwo) / LengthTwo
# no need to divide by sum of lengths because these are both 1
CosTheta = np.dot(np.array(LineOne), np.array(LineTwo))
# can be one of two different things.
ThetaValues = [math.acos(CosTheta), math.pi - math.acos(CosTheta)]
# use the sum of normalized vectors to determine if the angle is less than or greater than 90
# if the angle if less than 90, we return something greater than 90
if np.linalg.norm(LineOne + LineTwo) < math.sqrt(2):
# return the larger of the two theta values
return sorted(ThetaValues)[1]
# if the angle is greater than 90, we return something less than 90
else:
# return the smaller of the two theta values
return sorted(ThetaValues)[0]
# vector points towards PointTwo
def PointsToVector(PointOne, PointTwo):
return [PointTwo[0] - PointOne[0], PointTwo[1] - PointOne[1]]
# angle in radians
def BearingToVector(Bearing, Strength=1):
# convert bearing to angle
return [math.cos(Bearing) * Strength, math.sin(Bearing) * Strength]
# returns bearing in radians
def AngleToBearing(Angle):
# add 90 degrees to the angle
AddedAngle = Angle + math.pi / 2.0
# flip the x component of the angle
RawAngle = math.atan2(math.sin(AddedAngle), -math.cos(AddedAngle))
return RawAngle % (math.pi * 2)
# takes bearing in radians returns degree in radians
def BearingToAngle(Bearing):
FlippedAngle = math.atan2(math.sin(Bearing), -math.cos(Bearing))
# add 90 degrees to the angle
AddedAngle = FlippedAngle - math.pi / 2.0
# flip the x component of the angle
return AddedAngle % (math.pi * 2)
def VectorFromSpeedBearing(Speed, Bearing):
x = math.cos(math.radians(Bearing)) * Speed
y = math.sin(math.radians(Bearing)) * Speed
return [x, y]
# all angles in degrees
# wind bearing is the direction that the wind is blowing not where it is coming from
def SolveWindTriangle(WindBearing, WindStrength, Airspeed, PlaneBearing):
# make sure that we don't allow any vectors with length 0
# if there is no wind, the airspeed is the actual speed
if WindStrength == 0:
return Airspeed
GroundVector = BearingToVector(math.radians(PlaneBearing))
WindVector = BearingToVector(math.radians(WindBearing), Strength=WindStrength)
GroundWindAngle = AngleBetweenLines(GroundVector, WindVector) # checked and good
if WindStrength > Airspeed:
raise ValueError("WindStrength must always be less than Airspeed")
# this is SSA congruence; it works because the side opposite the known angle is always larger than the other side.
AirGroundAngle = math.asin(WindStrength * math.sin(GroundWindAngle) / float(Airspeed))
# print "air ground", AirGroundAngle
AirWindAngle = math.pi - (AirGroundAngle + GroundWindAngle)
# assumed
GroundLength = (math.sin(AirWindAngle) * Airspeed) / math.sin(GroundWindAngle)
return GroundLength |
2d3924eabaa80591b15c9b3530ca10b1aa0b20d7 | adityaramkumar/LeetCode | /144.py | 416 | 3.65625 | 4 | # Runtime: 44 ms, faster than 37.20% of Python3 online submissions for Binary Tree Preorder Traversal.
# Difficulty: Medium
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) \
+ self.preorderTraversal(root.right)
|
e7b383915b973dac1dd462df936a45c53e5b8c46 | adityaramkumar/LeetCode | /125.py | 452 | 3.828125 | 4 | # Runtime: 80 ms, faster than 42.27% of Python3 online submissions for Valid Palindrome.
# Difficulty: Easy
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = self.clean_string(s)
return s == s[::-1]
def clean_string(self, s):
return ''.join([char.lower() for char in s if 48 <= ord(char) <= 57 or 65 <= ord(char) <= 90 or 97 <= ord(char) <= 122])
|
Subsets and Splits