blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
01b69c651496874f1c5897ea66ed00fa3e7e957b | rksam24/MCA | /Sem 1/oops/File Handling/Marksheet/maxMarks.py | 1,095 | 4.125 | 4 | #3. Also generate a file containing name of students scoring highest marks subject-wise.
import pickle
#function to create file conataing higest marks in each subject
def highest_marks():
marksFile= open('student_record','rb') #open the file
data=pickle.load(marksFile) # load the data
dict1={}
dict1['name']=[]
for i,j in data.items(): #loop to create dict subjects as keys and marks as value
dict1['name'].append(i)
for x,y in j.items():
if x not in dict1:
dict1[x]=[]
dict1[x].append(y)
else:
dict1[x].append(y)
file= open('maxfile.txt',"w") #create which contain highest marks of each subject
#loop fot highest marks
for sub in dict1:
if sub not in ("name","RollNo"):
maximum = max(dict1[sub])
ind = dict1[sub].index(maximum)
file.write("Max of {} is {} of {} and Rollno {}\n".format(sub,maximum,dict1["name"][ind],dict1["RollNo"][ind]))
file.close() #close the file
marksFile.close()#close the file
highest_marks() |
55f196eb218de80f92b03ca78d290774df0ce9ef | rcabral1/rcabral-SE126 | /python 2/Lab 3/Lab_3_Part_A.py | 2,479 | 3.75 | 4 | #Ryan Cabral
import csv
total_records = 0
idr = 0
counterMale = 0
counterFemale = 0
Moldnotregistered = 0
Foldnotregistered = 0
eligiblenovote = 0
votedadded = 0
processed = 0
ager = 0
genderr = 0
registeredr = 0
votedr = 0
def print_():
print("\t\tNumber of males not eligible to register {0} ".format(counterMale))
print("\n\t\tNumber of females not eligible to register {0} ".format(counterFemale))
print("\n\t\tNumber of males who are old enough to vote but have not registered {0} ".format(Moldnotregistered))
print("\n\t\tNumber of females who are old enough to vote but have not registered {0} ".format(Foldnotregistered))
print("\n\t\tNumber of individuals who are eligible to vote but did not vote {0} ".format(eligiblenovote))
print("\n\t\tNumber of individuals who did vote {0} ".format(votedadded))
print("\n\t\tNumber of records processed {0} ".format(processed))
with open("C:/Users/008003309/Downloads/voters.csv") as csvfile:
file = csv.reader(csvfile)
for rec in file:
total_records += 1
print("{0:5} \t {1:8} \t {2:3} \t {3:7} \t {4:5}".format(rec[0], rec[1], rec[2], rec[3], rec[4]))
idr = rec[0]
ager = float(rec[1])
genderr = rec[2]
registeredr = rec[3]
votedr = rec[4]
#BASE-------------------------------------------------------------
if votedr == "Y":
votedadded = votedadded + 1
if ager < 18 and registeredr == "N" and genderr == "M":
counterMale = counterMale + 1
if ager < 18 and registeredr == "N" and genderr == "F":
counterFemale = counterFemale + 1
if ager >= 18 and registeredr == "N" and genderr == "M":
Moldnotregistered = Moldnotregistered + 1
if ager >= 18 and registeredr == "N" and genderr == "F":
Foldnotregistered = Foldnotregistered + 1
if ager >= 18 and registeredr == "N" and votedr == "N":
eligiblenovote = eligiblenovote + 1
processed = processed + 1
print(total_records)
print_()
#id = print(idr)
#age = print(ager)
#age_ = int(age) - 0
#gender_ = print(genderr)
#gender_ = gender_.lower()
#if(gender_ != "m" and gender_ != "f"):
#gender_=input("Please enter [m/f] when you run again! ")
#registered = print(registeredr)
#voted = print(votedr)
#voted = voted.lower() |
d3594f8ed3c508e702f423c36dfae1482ef83f06 | itsmrajesh/python-programming-questions | /TCS/series2.py | 593 | 3.8125 | 4 | import math as m
"""1 2 3 3 5 5 7 7 7 7 11 11 13 13 13 13 17 17"""
def is_prime(n):
if n <= 1:
return False
else:
val = round(m.sqrt(n))
for i in range(2, val + 1):
if n % i == 0:
return False
return True
a=1
p=2
def get_next_prime(p):
p += 1
while True:
if is_prime(p):
return p
else:
p += 1
num=int(input())
print("1",end=" ")
for i in range(1,num//2):
next_prime=get_next_prime(p)
r=next_prime-p
for i in range(r):
print(p,end=" ")
p=next_prime
|
bc0e50fc73f45c25f0ca3b7879197d97cef6a664 | manchuran/isPointInRectangle | /isIn3.py | 1,422 | 3.765625 | 4 | def isIn3(firstCorner=(0,0), secondCorner=(0,0), point=(0,0)):
'''
Checks if point is in rectangle
Returns: True if point is in rectangle; False otherwise
'''
a1,b1=firstCorner[0], firstCorner[1]
a3,b3=secondCorner[0], secondCorner[1]
x, y = point[0], point[1]
a2, b2 = a1, b3
a4, b4 = a3, b1
ysht = -b1-b1
ylng = -b3-b3
if ysht > ylng:
ysht,ylng=ylng,ysht
xsht = -a1-a1
xlng = -a3-a3
if xsht > xlng:
xsht,xlng=xlng,xsht
#Point distances
px = -y-y
py = -x-x
if (ysht<=px<=ylng) and (xsht<=py<=xlng):
return True
return False
def header():
print('-'*20+'-'*12*3)
print('{:^20}|{:^12}|{:^12}|{:^12}'.format('rectangle','point','calculated','given'))
print('-'*20+'-'*12*3)
if __name__ == '__main__':
list_of_points = [[(1,2), (3,4), (1.5, 3.2), 'True'], [(4,3.5), (2,1), (3, 2), 'True'],
[(-1,0), (5,5), (6,0), 'False'], [(4,1), (2,4), (2.5,4.5), 'False'],
[(1,2), (3,4), (2,2), 'True'], [(4,5), (1,1.5), (4.1,4.1), 'False'], [(2,2),(4,3),(3,3), 'True'],
[(2,1),(-3,3),(1,1), 'True']]
header()
for item in list_of_points:
args = item[:3]
print('{:<20}{:^14}{:^14}{:^9}'.format(str(item[:2]),
str(item[2]),str(isIn3(*args)), item[3]))
|
95e616be536498c8c13129684b06383d7bda8fe3 | tifat58/ML_Seminar_Predicting_Sensitivity_of_Anti_Cancer_Drugs | /Code_Repository/read_file.py | 1,269 | 3.890625 | 4 | import matplotlib.pyplot as plt
def plot1(x,y, plot='plot'):
print(x,y, plot)
# plt.plot([1,2,3,4])
# plt.ylabel('some numbers')
# plt.show()
# now create a subplot which represents the top plot of a grid
# with 2 rows and 1 column. Since this subplot will overlap the
# first, the plot (and its axes) previously created, will be removed
plt.figure(1)
plt.subplot(211)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('1st Figure')
plt.plot(range(12), range(2,14), '*-')
plt.legend('first')
plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background
plt.subplot(211)
plt.ylabel('y axis modified')
plt.plot(range(12), range(5,17))
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
plt.show()
plt.figure(2)
plt.xlabel('An x axis')
plt.ylabel('An y axis')
plt.title('2nd Figure')
plt.plot(range(12), range(2,14), '*-', label='new')
plt.grid()
plt.legend(loc='center left', bbox_to_anchor=(1, 0))
plt.savefig('test.png', format='png', dpi=900, bbox_inches='tight')
open_file = open('parameters.txt', 'r', encoding='utf-8')
lines = open_file.read().splitlines()
name = lines[0].split('=')[1]
age = lines[1].split('=')[1]
print(name, age)
plot1(100,200, 'a')
with open('parameters.txt', 'r') as fp:
print(fp.read())
line = fp.read()
|
1a096378d474115a19d87afa003a49c952316166 | CQUT-Embedded-Lab/Socket_CSModel | /server.py | 1,767 | 3.53125 | 4 | from socket import *
from time import ctime
import threading
class Server:
def __init__(self):
self.BUFFSIZE = 1024
self.tcp_server_socket = socket(AF_INET, SOCK_STREAM)
self.tcp_client_socket_list = [] # 放每个客户端的socket
def create_server(self, ipaddr, port):
HOST = ipaddr
PORT = port
ADDR = (HOST, PORT)
self.tcp_server_socket.bind(ADDR)
self.tcp_server_socket.listen(5)
def handle(self, tcp_client_socket_list, BUFFSIZE):
while True:
for tcp_client_socket in tcp_client_socket_list:
try:
data = tcp_client_socket.recv(BUFFSIZE)
except Exception as e:
continue
if not data:
tcp_client_socket_list.remove(tcp_client_socket)
continue
print('[{}][{}]: {}'.format(ctime(), tcp_client_socket.getpeername(), data))
tcp_client_socket.send(bytes('[{}][{}]: {}'.format(ctime(), tcp_client_socket, data), encoding="utf-8"))
def start(self):
t = threading.Thread(target=self.handle, args=(self.tcp_client_socket_list, self.BUFFSIZE,)) # 子线程
t.start()
print(u'我在%s线程中 ' % threading.current_thread().name) # 本身是主线程
print('waiting for connecting...')
while True:
tcp_client_socket, addr = self.tcp_server_socket.accept()
print('connected from:', addr)
tcp_client_socket.setblocking(False)
self.tcp_client_socket_list.append(tcp_client_socket)
def main():
server = Server()
server.create_server('127.0.0.1', 5057)
server.start()
if __name__ == '__main__':
main()
|
44b771141a5d3a2ba9b49aba3d50af23a012f8e7 | TreyMcGarity/PythonPractice | /Python-Practice/alg-searching.py | 2,442 | 4.09375 | 4 | import time
start_time = time.time()
#initial list and target for search and sorts
data = [8, 5, 3, 2, 10, 7, 1, 6, 9, 4]
target = 8
#linear search O(n) //determined by size of list
def linear_search(data, target):
# traverse through the whole list
for i in range(len(data)):
# if current value is target, True
if data[i] == target:
return True
# if loop through whole list and no match, False
return False
# print(linear_search(data, target))
#Iterative Binary Search
def iterative_binary_search(data, target):
# low value is index 0 and high is index of end
low = 0
high = len(data) - 1
while low <= high:
# middle of list is low + high divided by two
mid = (low + high) // 2
print("\n",low, "low\n", mid, "mid\n", high, "high")
# if target is middle value, it's True
if target == data[mid]:
print("equals")
return True
# if target is less than middle value
elif target < data[mid]:
print("less than")
# set index of high to index of middle - 1
high = mid - 1
# if neither
else:
print("greater")
# set index of low to index of middle + 1
low = mid + 1
return False
"""
INDEXES:
0 low START OF LOOP
4 mid
9 high
5 low
7 mid
9 high
8 low
8 mid
9 high
9 low END OF LOOP
9 mid
9 high
10 low OUT OF LOOP
9 mid
9 high
False
"""
# print(iterative_binary_search(data, target))
#Recursive Binary Search
def recursive_binary_search(data, target, low, high):
# low value is index 0 and high is index of end
if low > high:
return False
else:
# middle of list is low + high divided by two
mid = (low + high) // 2
# if target is middle value, it's True
if target == data[mid]:
return True
elif target < data[mid]:
# go to top of function at new index values
return recursive_binary_search(data, target, low , mid - 1)
else:
# go to top of function at new index values
return recursive_binary_search(data, target, mid + 1 , high)
# print(recursive_binary_search(data, target, 0, len(data) - 1))
end_time = time.time()
# print (f"runtime: {end_time - start_time} seconds") |
ec3a325597d157c74acf1a919817cf99927779c1 | EsmaeelNabil/github-search-api | /github_search_api.py | 3,936 | 3.640625 | 4 | # Import required modules
import requests
import time
import csv
# Paste your Access token here
# To create an access token - https://github.com/settings/tokens
token = "access_token=" + "access_token_here"
# Base API Endpoint
base_api_url = 'https://api.github.com/'
# Enter multiple word queries with a '+' sign
# Ex: machine+learning to search for Machine Learning
print('Enter the Search Query to get the Data ')
query = input()
print('\n Query entered is', query, '\n')
search_final_url = base_api_url + 'search/repositories?q=' + query + '&' + token
# A CSV file containting the data would be saved with the name as the query
# Ex: machine+learning.csv
filename = query + '.csv'
# Create a CSV file or clear the existing one with the same name
with open(filename, 'w', newline='') as csvfile:
write_to_csv = csv.writer(csvfile, delimiter='|')
# GitHub returns information of only 30 repositories with every request
# The Search API Endpoint only allows upto 1000 results, hence the range has been set to 35
for page in range(1, 35):
# Building the Search API URL
search_final_url = base_api_url + 'search/repositories?q=' + \
query + '&page=' + str(page) + '&' + token
# try-except block just incase you set up the range in the above for loop beyond 35
try:
response = requests.get(search_final_url).json()
except:
print("Issue with GitHub API, Check your token")
# Parsing through the response of the search query
for item in response['items']:
# Append to the CSV file
with open(filename, 'a', newline='') as csvfile:
write_to_csv = csv.writer(csvfile, delimiter='|')
repo_name = item['name']
repo_description = item['description']
repo_stars = item['stargazers_count']
repo_watchers = item['watchers_count']
repo_forks = item['forks_count']
repo_issues_count = item['open_issues_count']
repo_main_language = item['language']
repo_license = None
# repo_score is the relevancy score of a repository to the search query
# Reference - https://developer.github.com/v3/search/#ranking-search-results
repo_score = item['score']
# Many Repositories don't have a license, this is to filter them out
if item['license']:
repo_license = item['license']['name']
else:
repo_license = "NO LICENSE"
# Just incase, you face any issue with GitHub API Rate Limiting, use the sleep function as a workaround
# Reference - https://developer.github.com/v3/search/#rate-limit
# time.sleep(10)
# Languages URL to access all the languages present in the repository
language_url = item['url'] + '/languages?' + token
language_response = requests.get(language_url).json()
repo_languages = {}
# Calculation for the percentage of all the languages present in the repository
count_value = sum([value for value in language_response.values()])
for key, value in language_response.items():
key_value = round((value / count_value) * 100, 2)
repo_languages[key] = key_value
print("Repo Name = ", repo_name, "\tDescription", repo_description, "\tStars = ", repo_stars, "\tWatchers = ", repo_watchers, "\tForks = ", repo_forks,
"\tOpen Issues = ", repo_issues_count, "\tPrimary Language = ", repo_main_language, "\tRepo Languages =", repo_languages, '\tRepo Score', repo_score)
# Write as a row to the CSV file
write_to_csv.writerow([repo_name, repo_description, repo_stars, repo_watchers, repo_forks,
repo_license, repo_issues_count, repo_score, repo_main_language, repo_languages])
print('==========') |
092615d596c0f9333ad9caccb48218ece3782a2a | nadya-p/k_means | /k_means.py | 1,896 | 3.53125 | 4 | import numpy as np
from sklearn.utils import check_random_state
def k_means(x, k, centers=None, random_state=0):
"""Distribute the data from x into k clusters
:param x: np.ndarray containing the datapoints
:param k: int is the number of clusters
:param centers: np.ndarray allows to specify the initial positions of centers
:random_state: int is the seed for the random number generator"""
if x.ndim != 2:
n_features = 1
for i in range(1, x.ndim):
n_features *= x.shape[i]
x = x.reshape(x.shape[0], n_features)
for i in range(x.ndim):
if x.shape[i] == 0:
raise ValueError("The input array should not contain any singleton dimensions")
if k > x.shape[0]:
raise ValueError("The number of clusters should not exceed the number of data points")
# We want the random state to be repeatable (for the unit tests)
random_state = check_random_state(random_state)
if centers is None:
centers = x[random_state.randint(0, high=x.shape[0], size=k)]
sum_of_distances = np.inf
while True:
previous_sum_of_distances = sum_of_distances
closest_center, sum_of_distances = _get_nearest_center(x, centers)
for i_center in range(centers.shape[0]):
centers[i_center, :] = np.mean(x[closest_center == i_center, :], axis=0)
if sum_of_distances >= previous_sum_of_distances:
return closest_center, centers
def _get_nearest_center(x, centers):
"""For each point, find the closest center"""
distance_to_center = np.zeros([x.shape[0], centers.shape[0]])
for i_center in range(centers.shape[0]):
distance_to_center[:, i_center] = np.linalg.norm(x - centers[i_center], axis=1)
closest_center = np.argmin(distance_to_center, axis=1)
j = np.sum(np.min(distance_to_center, axis=1))
return closest_center, j
|
c6e89499bd21bf97ba3eccc962de40d495296a0c | sbfordham/kuali-test | /elevators/elevator.py | 6,242 | 4.21875 | 4 | from __future__ import unicode_literals
from time import sleep
"""
Blake Fordham
Elevator features:
1. Initialize the elevator simulation with the desired number of elevators, and the desired number of floors.
Assume ground/min of 1.
2. Each elevator will report as is moves from floor to floor.
3. Each elevator will report when it opens or closes its doors.
4. An elevator cannot proceed above the top floor.
5. An elevator cannot proceed below the ground floor (assume 1 as the min).
6. An elevator request can be made at any floor, to go to any other floor.
7. When an elevator request is made, the unoccupied elevator closest to it will answer the call,
unless an occupied elevator is moving and will pass that floor on its way.
The exception is that if an unoccupied elevator is already stopped at that floor,
then it will always have the highest priority answering that call.
8. The elevator should keep track of how many trips it has made, and how many floors it has passed.
The elevator should go into maintenance mode after 100 trips, and stop functioning until serviced,
therefore not be available for elevator calls.
"""
class Elevator(object):
"""Tracks the state of the elevator, assumes the actual physical elevator interacts with this class"""
def __init__(self, id, top_floor, bottom_floor=1):
self.id = id
# floor status
self.min_floor = bottom_floor
self.max_floor = top_floor
self.floor = bottom_floor
self.direction = 'up'
self.occupied = False
self.stops = []
self.open = True
# history & maintenance
self.trips = 0
self.mileage = 0 # total number of floors passed since last maintanence
self.total_mileage = 0 # lifetime total number of floors passed
self.total_trips = 0 # number of lifetime trips
def __str__(self):
if self.open:
return 'Elevator {0} open on Floor {1}'.format(self.id, self.floor)
elif self.stops:
return 'Elevator {0} moving {2} passing Flo0r {1}'.format(self.id, self.floor, self.direction)
else:
return 'Elevator {0} waiting on Floor {1}'.format(self.id, self.floor)
@property
def is_moving(self):
return not self.open and len(self.stops) > 0
@property
def is_open(self):
return self.open
@property
def needs_maintanence(self):
return not self.occupied and self.trips >= 100
@property
def is_occupied(self):
return self.occupied
@property
def ascending(self):
return self.direction == 'up'
def can_access(self, floor):
return self.min_floor <= floor <= self.max_floor and not self.needs_maintanence
def moving_toward(self, floor):
if not self.occupied:
return False
return (self.direction == 'up' and self.floor < floor) or (self.direction == 'down' and self.floor > floor)
def distance_from(self, floor):
return abs(self.floor - floor)
def open_door(self):
if not self.open:
self.open = True
def close_door(self):
if self.open:
# TODO stuff woud go here to avoid closing the door too quickly and wait if the door is blocked
self.open = False
def add_stop(self, floor):
"""Add the requested floor to the list of stops (if not already in the list)."""
if floor < self.min_floor or floor > self.max_floor:
raise ValueError("Cannot reach floor {}".format(floor))
if floor != self.floor and floor not in self.stops:
self.stops.append(floor)
def passenger_request(self, floor):
"""passenger in the car pushed a floor button"""
self.occupied = True
self.add_stop(floor)
self.move()
def call_request(self, floor):
"""The call button on level 'floor' was pressed"""
self.add_stop(floor)
self.move()
def move_one(self):
self.floor += 1 if self.ascending else -1
self.mileage += 1
self.total_mileage += 1
if self.floor in self.stops:
self.stops.remove(self.floor)
self.open_door()
if not self.stops:
self.occupied = False
self.trips += 1
self.total_trips += 1
self.direction = 'down' if self.ascending else 'up'
def move(self):
self.close_door()
if self.direction == 'up' and max(self.stops) < self.floor:
self.direction = 'down'
elif self.direction == 'down' and min(self.stops) > self.floor:
self.direction = 'up'
self.move_one()
def maintenance_completed(self):
self.trips = 0
self.mileage = 0
class Controller(object):
def __init__(self, elevators, top_floor):
self.elevators = [Elevator(i, top_floor) for i in range(elevators)]
def call_light(self, floor):
# TODO depending on the 'real' implementation of the systems, this would have to be some sort of async call
while True:
# get a list of all elevators that are not in maitenance and can reach the floor
available = sorted([e for e in self.elevators if e.can_access(floor)], cmp=lambda x: x.distance_from(floor))
if not available:
# nothing is available, wait a second and try again
sleep(1)
continue
unoccupied =[e for e in available if not e.is_occupied]
# see if an empty elevator is already there
if unoccupied and unoccupied[0].floor == floor:
unoccupied[0].open_door()
break
# if not find closest moving toward floor
moving_to = sorted([e for e in available if e.moving_toward(floor)], lambda x: x.distance_from(floor))
if moving_to:
moving_to[0].call_request(floor)
break
# if none, find closest unoccupied
if unoccupied:
unoccupied[0].call_request(floor)
break
# otherwise all are occupied and moving away from floor, wait and try again
sleep(1)
|
054822d0059273685687429d34791c56852d51e8 | ShravanKumar-404/Python-Challenge-Code | /1-10/challenge10.py | 802 | 4.15625 | 4 | """
Write a Python program that checks if the string s contains all the letters in the alphabet (case-insensitive, so "A" should be equivalent to "a").
If it does, print True. Else, print False.
Before comparing the characters, you should convert the string to lowercase.
If the string contains spaces, ignore them before finding the result.
You may assume that the string doesn't contain any other symbols, only spaces (possibly).
Consider these letters as part of the alphabet: 'abcdefghijklmnopqrstuvwxyz'
the word must contain all the alphabets
"""
import string
word = "Shravan Kumar "
lowercases = set(word.lower())
letters = set(string.ascii_lowercase)
is_pangram = True
if " " in lowercases:
lowercases.remove(" ")
if lowercases == letters:
print(is_pangram)
else:
print(False)
|
1527cfa3ff02e3477a26a20be900789b34155a5f | brunorijsman/euler-problems-python | /euler/problem091.py | 1,222 | 3.5 | 4 | # Euler problem 091: "Right triangles with integer coordinates"
def solve(grid_size):
# Brute-force try all possible locations for P and Q
count = 0
for px in range(grid_size+1):
for py in range(grid_size+1):
for qx in range(grid_size+1):
for qy in range(grid_size+1):
if is_right_triangle(px, py, qx, qy):
count += 1
# Because of P-Q symmetry, everything was counted twice
return count // 2
def is_right_triangle(px, py, qx, qy):
# If the triangle is right-angled, it must obey the Pythagorean theorem
# Distance Origin to P (squared)
dops = px ** 2 + py ** 2
# Distance Origin to Q (squared)
doqs = qx ** 2 + qy ** 2
# Distance P to Q (squared)
dpqs = (qx - px) ** 2 + (qy - py) ** 2
# None of the distances are allowed to be zero
if (dops == 0) or (doqs == 0) or (dpqs == 0):
return False
# Right angle at 0?
if dops + doqs == dpqs:
return True
# Right angle at P?
if dops + dpqs == doqs:
return True
# Right angle at Q?
if doqs + dpqs == dops:
return True
# No right angle
return False
print(solve(50))
|
857d87ae6abd1d6ed7e932f6fa89fd8d74bf8a95 | kunalkumar37/allpython---Copy | /dates.py | 390 | 4.1875 | 4 | #a date in python is not a data type of its own but we can import a module named datetime ot work with dates as date objects
import datetime
x=datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
x=datetime.datetime(2020,5,17,12,2,56)
print(x)
#strftime() method
x=datetime.datetime(2002,1,24)
print(x.strftime("%A"))
print(x.strftime("%B"))
print(x.strftime("%a"))
|
ded032da05ee5f52af3c41a4eb6313804120ac63 | AlexVermil/Loleris | /Yl 3.py | 157 | 3.859375 | 4 | a = int(input("Esimene : "))
b = int(input("Teine : "))
if a > b:
minimum = b
else:
minimum = a
print("Miinimum on: " + str(minimum))
|
bbfae5ff008198be8af84c5fb3c95811625dc87b | aakostarev/python-lessons | /lesson-5/task-1.py | 776 | 3.9375 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные,
# вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка.
out_f = open("task-1.txt", "w")
while True:
a = input('Введите строку для записи в файл и нажмите Enter для записи. '
'Для окончания ввода введите пустую строку: ')
if not a == '':
out_f.write(a + '\n')
else:
print("Выходим из файла.")
break
out_f = open("task-1.txt", "r")
content = out_f.read()
print(content)
out_f.close() |
04ee9c05b529fa1502235949ebad26f3b4fd77d3 | sourabh-karmarkar/Practicals | /SourabhPractice/Python Training/HackerRank_Python/Company_Logo.py | 700 | 4.09375 | 4 | from collections import Counter
import collections
new_dict={}
if __name__ == '__main__':
s = input()
if(3 < len(s) <= 10000):
# get the occurence count of all the letters by using Counter
counter = Counter(s)
# sort the dicitonary according to the key
sorted_d = sorted(counter.items())
for key, value in sorted_d:
new_dict[key]=value
# convert the new dictionary to Counter object
new_dict_counter=collections.Counter(new_dict)
# get the most common used 3 elements from counter and store in a list
mc_list=new_dict_counter.most_common(3)
for x in mc_list:
print(x[0],x[1]) |
ea00b8ba9c10d8b8263d39be2c291d7870735bc9 | AhMedMubarak20/full-computer-vision-course | /session two/files/1. Automatic & random generation of vectors & matrix.py | 531 | 3.71875 | 4 |
# Vectors and Matrices from List
import numpy
num = [[1,2,3],[2,3,5]]
print(type(num))
nu = numpy.array(num)
print(type(nu))
# # Automatic Creation of Vectors and Matrices
# x = numpy.arange(0,10,1)
# a,b = numpy.mgrid[0:5,0:5]
# n = numpy.zeros(6)
# k = numpy.ones(6)
# zm = numpy.zeros((6,3))
# km = numpy.ones((6,3))
# #Random Generation and Identity Matrix
# y= numpy.linspace(0,10,25)
# r = numpy.random.rand(5,3)
# rr = numpy.random.randn(5,3)
# i = numpy.eye(5)
# rand = numpy.random.randint(1,50,20) |
18bfbc6a17483a871cccec077ca886fe6100e4c8 | pandrey76/Python-Jango-For-Beginner-By-Bruselovskiy | /1_PYTHON/Бесплатный/2_Тема 2. Строки в Python/15_Философия Python/PhilosofiyPython1.py | 840 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name: модуль1
# Purpose:
#
# Author: Prapor
#
# Created: 26.06.2017
# Copyright: (c) Prapor 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
#w = '33' + 5 #Данный код приведет к ошибке, т.к нельзя
#складывть различные типы данных друг с другом
w = int('33') + 5
print (w) #38
w = '33' + repr(5)
print (w) #'335' см. конкотенация строк
w = str('42') + '5'
print (w) #'425' см. конкотенация строк
if __name__ == '__main__':
main()
|
cbd38592a0ed847f467f7916c79b28fc14b0add5 | maelizarova/python_geekbrains | /lesson_6/task_3.py | 770 | 3.625 | 4 | class Worker():
def __init__(self, name, surname):
self._name = name
self._surname = surname
self._position = None
self._income = {'wage': None, 'bonus': None}
def set_income(self, wage, bonus):
self._income = {'wage': wage, 'bonus': bonus}
def set_position(self, position):
self._position = position
class Position(Worker):
def get_full_name(self):
return self._name, self._surname
def get_total_income(self):
return self._income
if __name__ == '__main__':
pos_1 = Position('Иван', 'Иванов')
pos_1.set_position('менеджер')
pos_1.set_income(40000, 3000)
print(pos_1.get_full_name())
print(pos_1.get_total_income())
|
e7002afb7becdc5226a9d69a9ddd3ac487050cf6 | tshiu/PETraining | /ex6.py | 1,602 | 4.28125 | 4 | #This will put the string "10" within the string x
x = "There are %d types of people." % 10
#Sets the variable binary to the string "binary"
binary = "binary"
#Sets the variable do_not to the string "don't"
do_not = "don't"
#sets the variable y by the string "binary" (variable=binary,)
#and "do not" (variable=do_not) within the string.
y = "Those who know %s and those who %s." % (binary, do_not)
#will print the first variable (x)
print x
#will print the second variable (y)
print y
#Will print the variable x (which is a string within this string)
print "I said: %r." % x
#Will print the variable y (which is a string within this string)
print "I also said: '%s'. " % y
#setting the variable hilarious to false
hilarious = False
#setting the variable joke_evaluation into a string that calls another variable
joke_evaluation = "Isn't that joke so funny?! %r"
#will print the string "Isn't that joke so funny and variable
#that is called which is hilarious which is the string false"
print joke_evaluation % hilarious
#setting these two variables as strings which will be printed one after the other
w = "This is the left side of ..."
e = "a string with a right side."
#will print out the combined string of w and e
print w + e
#SD
#1. Above
#2. joke_evaluation = "Isn't that joke so funny?! %r"
# print "I also said: '%s'. " % y
# print "I said: %r." % x
# y = "Those who know %s and those who %s." % (binary, do_not)
#3. I think so?
#4. I looked this up and it states that w + e makes a longer string becasue
#. python developers defined the + as a concatenation function.
|
8fe4bc747197b61331bbc7737396508898075245 | Zirmaxer/Python_learning | /Prometeus/test3.1.py | 1,071 | 3.78125 | 4 | import sys
a=float(sys.argv[1])
b=float(sys.argv[2])
c=float(sys.argv[3])
answer='zero'
# Проверка значений длины стороны
answer='not triangle' if a<0.001 else answer #Проверка значения a
answer='not triangle' if b<0.001 else answer #Проверка значения b
answer='not triangle' if c<0.001 else answer #Проверка значения c
# Конец проверки значений длины стороны
# Нахождение большей и меньших сторон
if answer=='zero':
bigest_side=a
midle_side1=b
midle_side2=c
if b>a:
bigest_side=b
midle_side1=a
midle_side2=c
elif c>a:
bigest_side=c
midle_side1=a
midle_side2=b
answer='triangle' if (midle_side1+midle_side2)>bigest_side else 'not triangle' #Проверка возможности сложить трехугольник
print (answer)
else:
answer='not triangle'
print (answer) |
141dce5fc5817a446ecd2c8c3f6ba379b541e939 | maleks93/Python_Problems | /prblm_17.py | 1,389 | 3.921875 | 4 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number/
# 17. Letter Combinations of a Phone Number
class Solution(object):
def __init__(self):
self.phone_pad = dict()
self.phone_pad[2] = ('a','b','c')
self.phone_pad[3] = ('d','e','f')
self.phone_pad[4] = ('g','h','i')
self.phone_pad[5] = ('j','k','l')
self.phone_pad[6] = ('m','n','o')
self.phone_pad[7] = ('p','q','r','s')
self.phone_pad[8] = ('t','u','v')
self.phone_pad[9] = ('w','x','y','z')
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits) == 0: # return [] if no digits in input
return []
if len(digits) == 1: # return all characters for a single digit input
return list(self.phone_pad[int(digits)])
result = self.letterCombinations(digits[1:]) # recursion if more than a single digit in the input
temp_result = []
for word in result: # concatenate left most key characters with all possible combination of characters from recursive output
for key in self.phone_pad[int(digits[0])]:
temp_result.append(key+word)
return temp_result # return result with all possible combination of characters
|
20e163f24dbcb2de692b367dab64aa6e46a33fb7 | PhillMue/python-programs | /operators/comparisonops.py | 246 | 3.96875 | 4 | #!/usr/bin/python3
def main():
x, y = 5, 6
print("x: ", id(x),"y: ", id(y))
print("x is y: ", x is y)
print("x is not y: ", x is not y)
# Elements with same value in different
# lists have different ids
if __name__ == "__main__":
main() |
ce0b7d22afbf1daf70678f43e801c5806ec3d6be | clareisaacson/pid-neural-network | /convert_set.py | 989 | 3.71875 | 4 | #import train_set
import numpy as np
from test_set import test_set_str
def parse(data_str):
'''
Parse given data string into observations and labels
:param data_str: string of observation, label examples in given format
:type data_str: string
:return: (X,Y) matrices where each line in X is an observation, each line in Y
is corresponding label.
'''
X = []
Y = []
sep = data_str.split('----')
for inst in sep:
inst_lst = inst.split()
if len(inst_lst) == 6:
r = [float(elem) for elem in inst_lst[:3]]
Y.append([float(elem) for elem in inst_lst[:3]])
X.append([float(elem) for elem in inst_lst[3:5]])
return (X,Y)
### SAMPLE STRING FOR TESTING ###
tester = """334.5179
3210.784148
19.962276
1.169307
0.165084
514.749897
----
1570.48172
3468.106238
48.158829
4.619207
0.41717
1174.068773
----
2270.654518
759.693063
3.842391
3.628208
0.134283
655.865276
----""" |
65e0d6162cd8189387a2305b970d9057738a9f7a | PraveshKunwar/python-calculator | /Volumes/pyramid.py | 381 | 3.953125 | 4 | def pyrmaidCalc():
print("""
Please give me base and height!
Ex: 3 5
3 would be base and 5 would be height!
""")
takeSplitInput = input().split()
if len(takeSplitInput) > 2 or len(takeSplitInput) < 2:
print("Please make sure you only give me two numbers!")
value = (1/3) * (int(takeSplitInput[0])) * (int(takeSplitInput[1]))
print(value) |
c23f458e847b1376d369e000283ba5c6d9e9e42a | sifact/Leet-Code-Problems | /leetCode/Array/Medium/Remove Duplicate from Sorted Array 2.py | 514 | 3.625 | 4 | def removeDuplicates(nums):
tail = 0
for num in nums:
if tail < 2 or num > nums[tail - 2]:
nums[tail] = num
print(nums)
tail += 1
return tail
def removeDuplicates2(nums):
tail = 0
for num in nums:
if tail < 2 or num > nums[tail - 2]:
nums[tail] = num
print(nums)
tail += 1
print(tail)
return tail
a = list(map(int, input().split()))
print(removeDuplicates2(a))
|
9d07cdb7072abf1d5f0db6029bb380158558e2b2 | ruozhengu/Leetcode | /findTheDuplicateNumber.py | 3,302 | 3.703125 | 4 | """
Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
There is only one duplicate number in nums, return this duplicate number.
Follow-ups:
How can we prove that at least one duplicate number must exist in nums?
Can you solve the problem without modifying the array nums?
Can you solve the problem using only constant, O(1) extra space?
Can you solve the problem with runtime complexity less than O(n2)?
"""
"""
Here's my understanding of the Floyd's Tortoise and Hare solution, and the analysis of its time complexity.
First of all, when traversing the array described in the problem by always using the current value as the next
index to go to, there must be a loop. Let's say C is the length of the loop, which is smaller than the size of the
array, aka C < n + 1. Before entering the loop, there are K steps to get from nums[0] to the beginning of the loop.
Apparently, K is also smaller than the size of the array, aka K < n + 1.
Now let's see what's happening during the first loop. When Tortoise/Slow first reached the beginning of the loop,
it moved K times; Meanwhile, Hare/Fast moved K times past the beginning of the loop, and is now somewhere in the loop.
We could take note of Fast's current distance from the beginning of the loop, which is (K % C). At this point,
how many moves it would take for Fast to catch up with Slow within the loop? It would surely take less than C moves.
In fact, with each move, Fast would shorten the gap of the two by one. We know Fast is (K % C) steps ahead of the
start point of the loop, so the gap between the two is (C - (K % C)). This is to say, When Fast catches Slow,
aka the first loop exits, Slow has moved (C - (K % C)) steps past the beginning of the loop.
Time complexity of the first loop: Slow moved K times before the loop, and then less than one loop to be caught up.
O(K + C) = O(n).
And then we move to the second loop. Slow's position remains the same while Fast is reset to nums[0].
Also Fast now moves at the same speed as Slow does. If Fast and Slow were to meet, they should meet at the beginning
of the loop. Now would they? Let's take a look. It would take Fast K moves to get to the beginning of the loop.
Where would Slow be after K moves? It would be (C - (K % C) + K) steps past the beginning of the loop. Where the
hell is that? Let's mod it with C: (C - (K % C) + K) % C = (C % C) - ((K % C) % C) + (K % C) = 0 - (K % C) + (K % C)
= 0. So yes, after K moves, Slow is also at the beginning of the loop. Thus, it would take exactly K moves to exit
the second loop, and we found the beginning of the loop.
Time complexity of the second loop: O(K) = O(n).
"""
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
tortoise = hare = nums[0]
# frame 1: find if there are actually loops
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
# frame 2: find beginning of cycle/loop
tortoise = nums[0]
while tortoise != hare:
tortoise = nums[tortoise]
hare = nums[hare]
return hare |
2f6572c5e778504e17d80c3fa75294d5d5287cfb | SuperMartinYang/learning_algorithm | /leetcode/medium/robTree.py | 1,030 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob1(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
stoleRoot = root.val + self.rob(root.right.left if root.right else None) + self.rob(root.right.right if root.right else None) + self.rob(root.left.left if root.left else None) + self.rob(root.left.right if root.left else None)
dontRoot = self.rob(root.right) + self.rob(root.left)
return max(stoleRoot, dontRoot)
def rob2(self, root):
# res[0] rob root, res[1] not rob root
res = self.robSub(root)
return max(res[0], res[1])
def robSub(self, root):
if not root:
return 0
left = self.robSub(root.left)
right = self.robSub(root.right)
return [root.val + left[0] + right[0], left[1] + right[1]] |
031feae0f9ac80f360e7d3378786f194dd5dd71d | kellischeuble/TwittOff | /twitoff/app.py | 1,599 | 3.578125 | 4 | """Main application and routing logic for Twitoff."""
# TO RUN THIS:
# FLASK_APP=hello.py flask run (from before when we were running the entire module)
# now we want to point to something inside of the module... the specific package
# FLASK_APP=twitoff:APP flask run
# can also make a shell to play with flask app by doing
# this is like a repl for the app
# FLASK_APP=twitoff:APP flask shell
from flask import Flask, render_template, request
from .models import DB, User
# import routes
def create_app():
"""Create and configure an instance of the Flask application."""
# make the app
# __name__ returns the name of the module that we are running the code from
app = Flask(__name__)
# three slashes make it a relatitive path
# set it up so that the app knows about the database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['ENV'] = 'debug'
# now make it so that the database knows about the app
DB.init_app(app)
# set route up and listen to the route
# here, we are writing a function that will return the information that
# will be displayed on the website.. the '/' is the homepage.
@app.route('/')
@app.route('/home')
def home():
# this will be shown when we are on the home page
users = User.query.all()
return render_template('base.html', title='Home', users=users)
@app.route('/about')
def about():
# this will be shown when we are on the about page
return 'About this app!'
return app |
5319a5b65569b56235a7ad949a43e123eb47d53c | amdadul3036/Python-Learning | /Project5.py | 214 | 4.1875 | 4 | number = int(input("Enter the number you want to check: "))
for i in range(2 , number):
if number%i == 0:
print("Not Prime")
break
else:
print("Prime")
# Here is the use of for else . |
aff705cb4e74c6069eff9e29de090848923fe4a0 | nancyzyhu/algorithm_described_by_python | /search_algorithm/bfs.py | 1,201 | 3.65625 | 4 | # -*- coding: utf8 -*-
# 实现广度优先搜索算法
import collections
# 定义一个图
graph = dict()
graph['me'] = ['hello', 'world', 'sking']
graph['hello'] = ['sk', 's4']
graph['s4'] = ['sk']
graph['sk'] = []
graph['world'] = ['s2']
graph['s2'] = []
graph['sking'] = ['s3']
graph['s3'] = []
def is_finish_search(vertex):
# 判断当前搜索顶点是否为终点
# 这里判断终点的条件可以自定义
if vertex == 's2':
return True
return False
def bsf(vertex, graph):
"""
实现广度优先搜索算法
:param vertex: 起始顶点
:param graph: 图
:return:
"""
search_vertexes = collections.deque()
search_vertexes += [vertex]
searched_path = []
while len(search_vertexes) > 0:
search_vertex = search_vertexes.popleft()
if search_vertex not in searched_path:
if is_finish_search(search_vertex):
searched_path.append(search_vertex)
break
else:
search_vertexes += graph[search_vertex]
searched_path.append(search_vertex)
print '->'.join(searched_path)
if __name__ == '__main__':
bsf('me', graph)
|
2b4c974307b811e9f0a2599981377c4a5bba461e | JWilson45/cmpt120Wilson | /personality.py | 2,001 | 3.78125 | 4 | actions = ['reward', 'punish', 'threaten', 'joke', 'quit']
emotions = ['anger', 'disgust', 'fear', 'happiness', 'sadness', 'surprise']
reactions =["I'm getting really ticked off!",'Thats just not right, somethings wrong with you',
"You're scaring me! Please stop.",'That makes me feel very happy!',"Oh... :( that makes me sad.",
"Oh my, that certinly is surprising!"]
reactionChart=[
[3,3,5,3,3,3],
[2,0,0,2,1,2],
[2,0,0,2,2,0],
[1,4,5,3,3,3]]
def text(emote,act):
print('\nYou preformed the action: {}. The AI, Bill, now has the feeling of: {}'.format(actions[act].capitalize(),emotions[emote].capitalize()))
print('Bill: ','"' + reactions[emote] + '"')
def startEmotion():
#Make random generator for the start emotion
import random
return random.randint(0,5)
def action():
#Get user input for the action
while True:
try: act = actions.index(input('\nHow will you treat me? (reward, punish, threaten, joke, or quit)\n').lower())
except:
print('Invalid command, try again.')
continue
return act
def quitCheck(act):
#check for quit input to end the loop
if act == 4:
return False
return True
def getNewEmot(act, emotion):
#get the next emotion from the grid and return the result as a number
emotion = reactionChart[act][emotion]
return emotion
def intro():
#Prompt the intro message and get the first action for the loop
emote = startEmotion()
print('Welcome, my name is Bill. My current emotion is: {}'.format(emotions[emote].capitalize()))
act = action()
return emote, act
def loop(emote, act):
#primary loop, prompt user and call funcitons
while quitCheck(act):
emote = getNewEmot(act, emote)
text(emote,act)
act = action()
def end():
#The end prompt
print("\nGoodbye.")
def main():
#Emote and act will be the current emotion and user action
emote, act = intro()
loop(emote, act)
end()
main()
|
21ddc282a56a2c230660b4c5a7cf5864d12d717b | nagask/Interview-Questions-in-Python | /Arrays/MissingNumber.py | 585 | 4 | 4 | '''
Created on Oct 15, 2015
@author: gaurav
'''
#You have an array of integers. Each integer in the array should be listed three times in the array.
#Find the integer which does not comply to that rule.
def main(num):
#Take the unique elements of the list and multiply every element by 3
#This finds what the sum should have been
n = lambda x: x*3
y = map(n, set(num))
#The difference between the ideal sum and the current sum is the missing
#element
return sum(y) - sum(num)
if __name__ == '__main__':
print(main([1,1,1,2,2,2,3,3])) |
1c0939a638b9a5c52b81b66f9f20d0949a93eebb | liquidpele/leapday | /leapday/leapday.py | 4,287 | 4.6875 | 5 | #!/usr/bin/python
from __future__ import print_function
import argparse
from collections import OrderedDict
import json
"""
Script to get the name of the day of the week of the leap day
on given years. Manually calculate due to pretend bugs in stdlib.
Example: ./leapday.py 2000 2004 -f shortname -m json
Assumptions:
1. No BCE years are supported
2. Gregorian calendar is used
"""
def is_leap_year(year):
"""Check if the given year is a leap year
Parameters:
year (int): Year to to check
Returns:
bool: True if the year is a leap year
"""
if not isinstance(year, int) or year < 0:
raise ValueError('Invalid year: {}'.format(year))
# Logic from: https://support.microsoft.com/en-us/help/214019/
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return True
return False
def leapday_day_of_week(year):
"""Return the day of week of the leap day of a given year
Parameters:
year (int): Year to calculate the day of week for leap day
Returns:
int: Day of week, sun=0. None for non-leapyear.
"""
if not isinstance(year, int) or year < 0:
raise ValueError('Invalid year: {}'.format(year))
if not is_leap_year(year):
return None
# Use Gauss' algorithm
# https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
# since we only ever want Feb 29th, simplify it a bit with jan1st algorithm
jan1_dow = (1 + 5 * ((year - 1) % 4)
+ 4 * ((year - 1) % 100)
+ 6 * ((year - 1) % 400)) % 7
return (jan1_dow + 59) % 7 # Feb 29th is 59 days from Jan 1st
def dow_to_name(dow, short=False):
"""Given a day of week integer, return the proper name
Parameters:
dow (int): Day of week as an integer, sun=0 sat=6
Returns:
string: Name of the given day
"""
if not isinstance(dow, int) or dow < 0 or dow > 6:
raise ValueError('Invalid day of week: {}'.format(dow))
name = ['Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'][dow]
return name[:3] if short else name
def main():
parser = argparse.ArgumentParser(
description="""Given a series of years, print the day of the week
for the leap day on each year.
If the year is not a leap year print blank.""")
parser.add_argument('years', metavar='Year', type=int, nargs='+',
help='Year as YYYY')
parser.add_argument('-f', dest='format', default=None,
help='Output format (Default is ints with Sun=0)',
choices=['name', 'shortname'])
parser.add_argument('-m', dest='machine', default=None,
help='Output as machine readable',
choices=['json', 'xml'])
args = parser.parse_args()
machine_dict = OrderedDict()
for year in args.years:
# first generate the output format for the year
dow = leapday_day_of_week(year)
if args.format:
if dow is None:
name = ''
else:
short = args.format == 'shortname'
name = dow_to_name(dow, short=short)
else:
name = '' if dow is None else '{}'.format(dow)
# now output or save the data
if args.machine is None:
print(name)
else:
# this will de-duplicate years, which is nice for machine readable
# but we can't do that for just stdout output
machine_dict[year] = name or None
# if doing machine readabe, process that now
if args.machine == 'json':
print(json.dumps(machine_dict, indent=4))
elif args.machine == 'xml':
# this is so simplistic, using a full xml lib is overkill
print('<?xml version="1.0" encoding="utf-8"?>')
print('<output>')
for year, name in machine_dict.items():
if name is None:
print(' <item year="{}" />'.format(year))
else:
print(' <item year="{}">{}</item>'.format(year, name))
print('</output>')
if __name__ == '__main__':
main()
|
0c076236219455bda731cba5bb1c026c3f669544 | mobbarley/python3x | /hailstone.py | 718 | 4.3125 | 4 | # Print the hailstone sequence starting at a given number and
# terminates at 1 and also returns its length.
# This code is compatible with Python v3.x
from ucb import main
def hailstone (num):
""" Print the hailstone sequence starting at a given number and
terminates at 1 and also returns its length. """
step = 0
while num != 1:
if num%2 == 0 :
num = num / 2
step = step + 1
print(int(num))
else:
num = (num * 3) + 1
step = step + 1
print(int(num))
print("Steps taken : ",step)
@main
def main():
num = int(input("Enter a number : "))
if num > 0:
hailstone(num)
else:
print("Invalid number", num)
|
a157c16c40a63d679505bac182a60da86a464cff | k8440009/Algorithm | /leetcode/215. Kth Largest Element in an Array_4.py | 264 | 3.625 | 4 | """
배열의 K번째 큰 요소
정렬을 이용한 풀이 : 입력값이 고정되어 있기 때문
"""
from typing import List
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums, reverse=True)[k - 1] |
369a90dba6db61b3da666204ffc3ca9d5928033a | QMSS-G5072-2020/cipher_duan_siyu | /cipher_sd3329/cipher_sd3329.py | 1,178 | 4.46875 | 4 | def cipher(text, shift, encrypt=True):
"""
This function is a substitution cipher in which each letter in the plaintext is shifted a certain number of places
Parameters
----------
text : str
A plaintext that you wish to encrypt or decrypt.
shift : int
The number of characters that you wish to shift the cipher alphabet.
encrypt: boolean
A boolean that controls between encryption and decryption.
Returns
-------
str
The encoded or decoded text.
Examples
--------
>>> text = 'DOG'
>>> shift = 3
>>> encrypt = True
>>> cipher(text, shift, encrypt)
'GRJ'
>>> text = 'Gdkkn'
>>> shift = -1
>>> encrypt = False
>>> cipher(text, shift, encrypt)
'Hello'
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index = index + shift if encrypt == True else index - shift
new_index %= len(alphabet)
new_text += alphabet[new_index:new_index+1]
return new_text
|
4b091fb7a909a6b15342319c8837ec19fe65f42c | manhcuongk55/chatbot | /bài6.py | 435 | 3.78125 | 4 | class Ex2:
def __init__(self, list1, list2):
self.list1= list1
self.list2= list2
self.tong=0
def sum(self):
for x in self.list1:
self.tong +=x
def append(self):
self.list2.append(self.tong)
def sum2(self):
for a in self.list2:
self.tong +=a
list1=[1,2,3]
list2=[4,5,6]
p1=Ex2(list1, list2)
p1.sum()
p1.sum2()
print (p1.tong) |
62cd659e48d27762e0e7b0981c952f5a61fc784a | mjarrett/adventofcode2015 | /day10/day10.py | 1,065 | 3.78125 | 4 | #!/usr/bin/python
#title :day10.py
#description :advent of code day 10
#author :Mike Jarrett
#date :20151228
#version :1
#usage :python day10.py
#notes :
#python_version :2.6.6
#==============================================================================
datum = '1113222113'
test = '1'
def looksay(look):
say = []
count = 1
for i,c in enumerate(look):
if i != len(look)-1 and look[i] == look[i+1]:
count += 1
# print c, str(count)
elif i != len(look)-1:
# print c, str(count)
say.append(str(count))
say.append(look[i])
count = 1
else:
# print c, str(count)
say.append(str(count))
say.append(look[i])
#say.append(count)
#say.append(c)
return "".join(say)
def recurse(n, start):
for i in range(n):
start = looksay(start)
#print start
return start
print datum
print "part 1: " + str(len(recurse(40, datum)))
print "part 2: " + str(len(recurse(50, datum)))
|
66657099e947a671c532928ff51364b8cca9d7e3 | Guiwald/PythonProjects | /pdf_decrypt2.py | 1,475 | 3.75 | 4 | # Decrypt password-protected PDF in Python.
#
# Requirements:
# pip install pikepdf
from pikepdf import Pdf
import pikepdf
import os
def decrypt_Pikepdf(input_path, output_path, password):
with Pdf.open(input_path, password=password) as pdf:
pdf.save(output_path)
if __name__ == '__main__':
# example usage:
# decrypt_Pikepdf('payslip_02_2020.pdf', 'payslip.pdf', 'GP58i714')
dirName = 'cracked'
# Create directory to store uncrypted PDF
try:
os.mkdir(dirName)
print('Directory', dirName, 'created')
except FileExistsError:
print('Directory', dirName, 'already exists')
# Getting PDF files
while True:
direc = input('Name of directory with PDF files: ')
if len(direc) < 1 : direc = '.'
if not os.path.exists(direc):
print('No directory named', direc)
continue
break
arr_pdf = [x for x in os.listdir(direc) if x.endswith('.pdf')]
print(len(arr_pdf), 'PDF files found.')
pwd = input('Please insert password: ')
if len(pwd) < 1 : pwd = 'GP58i714'
countnon = 0
countyes = 0
for file in arr_pdf:
# print(dirName+'/'+file)
try:
decrypt_Pikepdf(direc+'/'+file, dirName+'/'+file, pwd)
print(direc+'/'+file, 'decrypted in', dirName+'/'+file)
countyes = countyes + 1
except pikepdf._qpdf.PasswordError:
print(direc+'/'+file, '- Password incorrect')
countnon = countnon + 1
print(countyes, 'files decrypted and', countnon, 'files non decrypted') |
80bda964c9f6baa07a77a4f6672e3a991cd5ef29 | hamzaexe/python-coding-lessons | /main.py | 338 | 4.09375 | 4 | print("Welcome to the tip calculator")
total_bill=input("What was the total bill? $")
tip_percent=input("What percentage tip would you like to give? 15 20 30? ")
people=input("How many people to split the bill? ")
individual_bill=(int(total_bill) / int(people))*int(tip_percent)
print("Each Individual should pay $"+ str(individual_bill)) |
ce116c4e358c7efc3e8032bf245f006695751aad | yangsg/linux_training_notes | /python3/basic02_syntax/datatype_list.py.demo/using-Lists-as-queues.py | 443 | 4.125 | 4 | #// https://docs.python.org/3.6/tutorial/datastructures.html#using-lists-as-queues
#// 使用专有的 deque 比原始的 list 更高效
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
queue.popleft() # The first to arrive now leaves
queue.popleft() # The second to arrive now leaves
|
8f6de5c58e4b093ecc8f24d642c7d2c132754f70 | conormccauley1999/CompetitiveProgramming | /Kattis/taketwostones.py | 67 | 3.625 | 4 | s = int(raw_input()) % 2
if s == 0: print "Bob"
else: print "Alice" |
595555dbb440f615f316dfd3db1bf82a629c6bdd | eng-lenin/Python | /ex22.py | 488 | 3.921875 | 4 | n=str(input('Digite o seu nome completo: ')).strip()
print('Seu nome em letras maiúsculas é: {}'.format(n.upper()))
print('Seu nome em letras minúsculas é {}'.format(n.lower()))
print('Seu nome tem {} letras'.format(len(n)-n.count(' ')))
separa=n.split()
print('Seu primeiro nome é {} e tem {} letras'.format(separa[0],len(separa[0])))
#poderia ser assim também: print('Seu primeiro nome tem {} letras'.format(n.find(' ')))
#strip tira os espaços em lugares errados, começo e fim
|
c22d3ff2b7f40f6b3361a148b20e04b1458d8751 | Nishita-Bhagat/Python-snippets | /Check if string is palindrome or not.py | 276 | 4.3125 | 4 | #Approach 1 :
# 1) Find the reverse of string
# 2) Check if reverse and original are same or not
s = input("Enter a string:") #abcdefgh
revstr = (s[::-1]) #hgfedcba reverse order
if revstr == s:
print("Palindrome")
else:
print("Not palindrome")
|
5ac182e3c5a35f8908efde482b16044e09a7268f | chyjuls/Python_Practice | /Loops_2.py | 438 | 4.125 | 4 | # showing more loops with continue function:
Colours = ["Red", "Blue", "Pink", "White", "Purple", "Navy", ]
print("What are you searching for....")
NewColour = input()
for colour in Colours:
if colour == NewColour:
print("We Found" + " " + NewColour)
continue
print(colour + "....Not what we are looking for......")
# Be careful with your indentation else your code will not work as it should do!! |
e61c28055c692bcc73fcba9a0e1b626b876c273e | Pankaj1729/Python-Learning | /Exercise9.py | 439 | 3.546875 | 4 | name = input("enter your name : ")
n=len(name)
i=0
#j=0
#k=0
#while i<n:
# k=name.count(name[i])
# if k>1:
# while j<(i-1):
# if name[j]==name[i-1]:
# j+=1
# i+=1
#else:
# print(f"{name[i]} in name is {k} times")
# i +=1
temp=""
while i<n:
if name[i] not in temp:
print(f"{name[i]} in name is {name.count(name[i])} times")
temp += name[i]
i +=1
|
282a70e4b4a762c8e1dee8403eebd89492a7baae | Fabhi/Project-Euler | /1 - Multiples of 3 and 5.py | 390 | 3.703125 | 4 | # Problem 1 - Multiples of 3 and 5
# https://projecteuler.net/problem=1
def main(num):
mul3 = [i for i in range(num) if i%3 == 0]
mul5 = [i for i in range(num) if i%5 == 0]
mul3n5 = [i for i in range(num) if i%15 == 0]
# By Principle of Inclusion and Exclusion
final = sum(mul3) + sum(mul5) - sum(mul3n5)
print(final)
if __name__ == '__main__':
main(1000)
|
ac0035554e0eb2345737073a38bddecb1d615457 | SurendraGoutham/Project-Euler-in-Python | /EulerP002.py | 768 | 3.859375 | 4 | '''
Created on 26-Nov-2013
@author: 00003179
'''
'''
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
'''
def printFib():
x = 0
y = 1
z = 0
s = 0
for i in range(10):
z = x + y
x = y
y = z
if z % 2 == 0:
s = s + z
print s
def formsol():
x = y = 1
sum = 0
while (sum < 1000000):
sum += (x + y)
x, y = x + 2 * y, 2 * x + 3 * y
return sum
print formsol() |
f8a4390ef015feef0666d5e157bf7ec35095f31f | Arielcarv/Intro-Ciencia-da-Computacao-USP | /Part 1/Week 2/Dígito das dezenas.py | 137 | 3.9375 | 4 | inteiro = int(input("Digite um número inteiro: "))
aux = inteiro // 10
dezena = aux % 10
print(f"O dígito das dezenas é {dezena}")
|
a4653f11621fa35a60d7c7321cf011499c7dc631 | andavas/ProjetoIA_2020.1 | /BuscaGulosa.py | 8,223 | 3.546875 | 4 | import tkinter as tk #utilizada para os objetos da janela
from tkinter import ttk #utilizada no objeto combobox
from tkinter import font #utilizado para os objetos de fontes
import Algoritmo as busca #arquivo com algoritmo da busca gulosa
from tkinter import messagebox
# definindo coordenadas das cidades no plano cartesiano (mapa)
# ORDEM:
# indice da cidade
# nome da cidade
# posição (x, y) do ponto da cidade
# posição (x, y) do nome da cidade
#coluna: 0 1 2 3 4 5 6 7
eixoXY = [(0, 'Bogotá', 140, 161, 140, 145, 140, 128),
(1, "Quito", 95, 208, 65, 208, 65, 225),
(2, "Lima", 115, 300, 90, 298, 90, 315),
(3, "Manaus", 250, 185, 270, 170, 270, 152),
(4, "La Paz", 195, 285, 160, 277, 160, 260),
(5, "Brasília", 290, 293, 255, 295, 255, 310),
(6, "São Paulo", 387, 380, 435, 380, 435, 395),
(7, "Santiago", 178, 515, 178, 540, 178, 560),
(8, "Buenos Aires",270, 485, 333, 480, 333, 500)]
# armazena os elementos "linha" da rota encontrada
deletes = []
# armazena os elemtentos os valores das heurística da busca atual
deletesHeuristica = []
#Função para exibir a heurística
def exibirHeuristica():
if deletesHeuristica == []:
destino = combobox_destino.get()
for i in eixoXY:
if destino == i[1]:
auxDestino = i[0]
heuristicaAtual = busca.heuristica
if deletes != []:
for index, nome, eixoX, eixoY, eixoXT, eixoYT, heuristicaX, heuristicaY in eixoXY:
deletesHeuristica.append(0)
#inserindo heuristicas no mapa
deletesHeuristica[-1] = canvas_mapa.create_text(heuristicaX, heuristicaY, fill="blue",
text=heuristicaAtual[auxDestino][index],
font = font_mapa)
else:
for i in deletesHeuristica:
# se exister alguma heuristica escrita no mapa ela será deletada antes de exibir novos valores
canvas_mapa.delete(i)
deletesHeuristica.clear()
#função executada pelo botão BUSCAR
def aoClicar():
for i in deletes:
# deletando rota da busca anterior
canvas_mapa.delete(i)
for i in deletesHeuristica:
# sdeletando heurística da busca anterior
canvas_mapa.delete(i)
deletesHeuristica.clear()
origem = combobox_origem.get()
destino = combobox_destino.get()
if origem != "" and destino != "":
#buscando rota a partir da origem e destino
#buscando cidades que serão percorridas
caminho = busca.nomeToCodigo(origem, destino)
caminho = busca.buscarRota(caminho[0], caminho[1])
#calculando custo da rota
custo = busca.calculaCusto(caminho)
custo = 'Custo: '+str(custo)+' km'
text_custo.set(custo)
#convertendo o caminho (cidades) em uma lista de coordenadas geográficas
rota = []
for i in caminho:
rota.append(eixoXY[i][2]) #eixo X
rota.append(eixoXY[i][3]) #eixo Y
#rota possui mais de uma cidade
if(len(rota)>2):
for i in range(len(caminho)-1):
#fransformando em pares de coordenadas
auxrota = rota[i*2:(i*2)+4]
#adicionando rota ao mapa
deletes.append(0)
deletes[-1] = canvas_mapa.create_line(auxrota, fill="blue", width=3)
#destacando as cidades contidas na rota
deletes.append(0)
deletes[-1] = canvas_mapa.create_oval(rota[i*2]-5, rota[i*2+1]-5, rota[i*2]+5, rota[i*2+1]+5, fill="blue")
#destacando a cidade destino
deletes.append(0)
deletes[-1] = canvas_mapa.create_oval(rota[len(rota)-2]-5, rota[len(rota)-1]-5, rota[len(rota)-2]+5, rota[len(rota)-1]+5, fill="blue")
else: #destacando cidade no mapa
deletes.append(0)
deletes[-1] = canvas_mapa.create_oval(rota[0]-5, rota[1]-5, rota[0]+5, rota[1]+5, fill="blue")
else:
messagebox.showinfo("Erro", "Informe cidades de origem e destino!")
# criando o objeto "aplication" (que é uma janela)
aplication = tk.Tk()
aplication.title("Busca Gulosa") #Título exibido no topo da janela
aplication.geometry("570x761") #tamanho da janela
aplication.resizable(width=0, height=0) #o tamanho da janela não poderar ser alterado "maximizar/restaurar tamanho"
#lsita das cidades utilizadas para exibição no combobox
lista_de_cidades = ['Bogotá', 'Brasília', 'Buenos Aires','La Paz', 'Lima', 'Manaus', 'Quito', 'Santiago', 'São Paulo']
label_origem = tk.Label(aplication, text="Origem:") #label exibido como descrição do combobox
label_origem.place(x=10, y=5) #posição do label na tela
combobox_origem = ttk.Combobox(aplication, values=lista_de_cidades) #combobox com as opções de cidades de onde a busca irá iniciar
combobox_origem.place(x=10, y=30) #posição do combobox na tela
label_destino = tk.Label(aplication, text="Destino:") #label exibido como descrição do combobox
label_destino.place(x=190, y=5) #posição do label na tela
combobox_destino = ttk.Combobox(aplication, values=lista_de_cidades)#combobox com as opções de cidades de onde a busca irá finalizar
combobox_destino.place(x=190, y=30) #posição do combobox na tela
text_custo = tk.StringVar()
text_custo.set("Custo: ")
label_custo = tk.Label(aplication, textvariable=text_custo) #label exibido como descrição do custo da rota
label_custo.place(x=385, y=5)
# botão que executar a função "aoClicar()"
button_viajar = tk.Button(aplication, command=aoClicar, width=10, height=1, text="Buscar")
button_viajar.place(x=385, y=25) #posição do botão na tela
# botão que executar a função "exibirHeuristica()"
button_heuristica = tk.Button(aplication, command=exibirHeuristica, width=10, height=1, text="heurística")
button_heuristica.place(x=480, y=25) #posição do botão na tela
# elemento que contem o mapa, cidades, e rotas
canvas_mapa = tk.Canvas(width=550, height=701) #definição do tamanho do canvas
canvas_mapa.place(x=10, y=60), #posição do canvas na tela
imagem_mapa = tk.PhotoImage(file="mapa.png") # carregando a imagem do mapa
canvas_mapa.create_image(0, 0, image=imagem_mapa, anchor='nw') #adicionando a imagem do mapa ao canvas
#definindo tipo e tamanho da fonte utilizada no mapa
font_mapa = font.Font(family='Comic Sans MS', size=13, weight='bold')
#Desenhado as rotas no mapa
for index, nome, eixoX, eixoY, eixoXT, eixoYT, x, y in eixoXY: # buscando as cidades e suas coordenadas
for i in range(len(busca.aresta[index])): # matriz de aresta definida no back
if busca.aresta[index][i] != 0: # verificando quais arestas uma cidade possui
auxrota = [] # armazena iformações das arestas para desenhar as rotas
auxrota.append(eixoX)
auxrota.append(eixoY)
auxrota.append(eixoXY[i][2])
auxrota.append(eixoXY[i][3])
canvas_mapa.create_line(auxrota, fill="black", width=3) # criando desenho das rotas de uma cidade, defindo cor e tamanho
for index, nome, eixoX, eixoY, eixoXT, eixoYT, x, y in eixoXY:
canvas_mapa.create_oval(eixoX-5, eixoY-5, eixoX+5, eixoY+5, fill="white", outline='black' ) #inserindo cidade (ponto) no mapa
canvas_mapa.create_text(eixoXT, eixoYT, text=nome, font = font_mapa) #inserindo nomes das cidades no mapa
aplication.mainloop() #método que faz a janela ficar rodando até que acione o botão FECHAR
|
ef924a968ac64f5278f361b9d671040d69e9e972 | dilliwal11/PyConvexHullDemo | /Algorithms/HullAlgorithm.py | 989 | 3.90625 | 4 | class HullAlgorithm:
"""
Base class to be used for convex hull algorithms.
An algorithm must be initialized with initialize before use.
The field 'plane' contains a Plane containing the points we're working on.
The field 'markers' contains a Markers that can be used for illustrative
purposes.
"""
def initialize(self, plane, markers):
""" Basic initialization of algorithm before use. """
self.plane = plane
self.markers = markers
def execute(self):
"""
Does the actual hull-finding.
Should be implemented as a generator function, that is, it should yield
execution after each significant step in its execution, to allow for
redrawing of the display, as well as slowing down the execution for
better visual effect.
In addition, the algorithm should yield before doing anything, to allow
for initial drawing of the unsolved problem.
"""
pass
|
fe237aa3796e904ccb9fba12e13e50890a7f7097 | MarcisGailitis/py-various | /bin_search_str.py | 1,742 | 4.09375 | 4 | #!/usr/bin/python3
# comparison b/w linear and binary search operations in Python
import random
import datetime
def random_file(words_dict):
with open(words_dict) as f:
list_words = f.readlines()
random_word_pos = random.randint(0, len(list_words)-1)
return random_word_pos, list_words[random_word_pos].strip()
def linear_search(list, key):
start = datetime.datetime.now()
"""If key is in the list returns its position in the list"""
for i, item in enumerate(list):
if item == key:
return i, (datetime.datetime.now() - start)
def binary_search(list, key):
start = datetime.datetime.now()
"""If key is in the list returns nr of times list were
halfed for binary search"""
left = 0
right = len(list) - 1
nr_of_iterations = 0
while left <= right:
middle = (left + right) // 2
nr_of_iterations += 1
if list[middle] == key:
return nr_of_iterations, (datetime.datetime.now() - start)
if list[middle] > key:
right = middle - 1
if list[middle] < key:
left = middle + 1
def main():
words_dict = 'words.txt'
pos, word = random_file(words_dict)
print(f'Random word from Words.txt file: {word}')
with open(words_dict) as words_file:
words = [word.strip() for word in words_file]
linear_item, linear_time = linear_search(words, word)
binary_item, binary_time = binary_search(words, word)
binary_factor = linear_time//binary_time
print(f'Linear Search: {linear_item}, {linear_time}')
print(f'Binary Search: {binary_item}, {binary_time}')
print(f'Binary Search was : {binary_factor} times faster')
main()
|
dfc77ed18ca39c8799bfe6452b4c553ad488a7b3 | zhanglei86/python3-example | /algorithms/hanoi/test2.py | 399 | 3.828125 | 4 | #coding=utf-8
def hanoi(n,f,buffer,to):
if n==1:
print(f,'-->',to)
else:
#将前n-1个盘子从a移动到b上
hanoi(n-1,f,to,buffer)
#将最底下的最后一个盘子从a移动到c上
hanoi(1,f,buffer,to)
#将b上的n-1个盘子移动到c上
hanoi(n-1,buffer,f,to)
n=int(input('请输入汉诺塔的层数:'))
hanoi(n,'A','B','C')
|
6e422f604ca1233c6c3d3bcc395422a4704e7cfd | carlinhoshk/python | /pygame/alien_invasion/bullet.py | 1,353 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 08:45:24 2020
@author: Cassio (chmendonca)
Description: This class will have the bullets characteristics and behaviors
"""
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""This class configures the bullets shot by spaceship"""
def __init__(self, ai_settings,screen,ship):
"""Creates a bullet on the spaceship actual position"""
super(Bullet,self).__init__()
self.screen = screen
#Creates a new rectangle for the bullet in a fixed position (0,0) then
# sets the correct position on spaceship position
self.rect = pygame.Rect(0,0,ai_settings.bullet_width,
ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor
def update(self):
"""Moves the bullet to the top of the screen"""
#Updates the bullet position
self.y -= self.speed_factor
self.rect.y = self.y
def draw_bullet(self):
"""Draws the bullet on screen"""
pygame.draw.rect(self.screen, self.color,self.rect)
|
8beb0e14f2da59207b2ff3ace3931845838d9d16 | christensenst/python_sandbox | /python_sandbox/algorithms/tower_of_hanoi.py | 1,206 | 3.734375 | 4 | import sys
DEFAULT_NUMBER_OF_DISKS = 4
class HanoiTower(object):
def __init__(self, number_of_disks):
self.peg1 = []
self.peg2 = []
self.peg3 = []
for x in range(number_of_disks, 0, -1):
self.peg1.append(x)
self.print_tower()
def solve_tower(self, tower_height, start, auxillary, final):
if tower_height <= 0:
raise Exception('Length of starting peg is zero')
elif tower_height == 1:
self.move(start, final)
else:
self.solve_tower(tower_height - 1, start, final, auxillary)
self.move(start, final)
self.solve_tower(tower_height - 1, auxillary, start, final)
def move(self, from_peg, to_peg):
disk = from_peg.pop()
to_peg.append(disk)
self.print_tower()
def print_tower(self):
print '{} {} {}'.format(len(self.peg1), len(self.peg2), len(self.peg3))
if __name__ == '__main__':
try:
number_of_disks = int(sys.argv[1])
except IndexError:
number_of_disks = DEFAULT_NUMBER_OF_DISKS
tower = HanoiTower(number_of_disks)
tower.solve_tower(number_of_disks, tower.peg1, tower.peg2 ,tower.peg3)
|
92aa349d4e09916478d3e161533095f5c61e2b8e | Tevitt-Sai-Majji/fun-coding- | /stack implementation.py | 778 | 3.8125 | 4 | class Stack:
def __init__(self,size):
self.size=size
self.data=[]
self.top=-1
def display(self):
if self.top==-1:
print("stack is empty")
pass
for i in range(self.top,-1,-1):
print(self.data[i])
def push(self,value):
if self.top+1==self.size:
print("stack overflow")
else:
self.top+=1
self.data.append(value)
def pop(self):
if self.top==-1:
print("stack underflow")
else:
self.data.remove(self.data[-1])
self.top-=1
s=Stack(4)
s.display()
s.push(30)
s.push(39)
s.push(37)
s.push(2)
s.push(22)
s.display()
s.pop()
s.pop()
s.display()
s.pop()
s.pop()
s.pop()
s.display()
|
8e6c258b32abaf84a792eb038273a6e12501b516 | jarivandam/hu-v2alds-exercises | /week2/week2_opdr2.py | 1,606 | 3.796875 | 4 | '''
File name: week2_opdr2.py
Author: Jari van Dam
Studentnumber: 1677046
Group: V2C/retake
Teacher: Frits Dannenberg
'''
class mystack(list):
"""Summary
Attributes:
position (int): The first position were a new item can be placed.
stack (list): A list with all elements on the stack.
"""
def __init__(self):
"""Create a stack with an empty list and the position set to 0.
"""
self.stack = []
def push(self, item):
"""Summary
Args:
item (any type): The item that will be placed on the stack.
"""
self.stack.append(item)
def pop(self):
"""Return the last item placed on the stack. It also removes it from the stack.
IndexError when trying to pop form empty stack.
Returns:
any: Item last placed on the stack.
"""
return self.stack.pop()
def peek(self):
"""Get the last item placed on the stack, without removing it.
IndexError when trying to pop form empty stack.
Returns:
any: Item last placed on the stack.
"""
return self.stack[-1]
def isEmpty(self):
"""Check if stack is empty
Returns:
boolean: True on empty stack, False when stack is not empty.
"""
return not self.stack
customstack = mystack()
if __name__ == '__main__':
customstack.push("Q")
customstack.push("z")
print(customstack.pop())
print(customstack.peek())
customstack.pop()
customstack.peek()
print(customstack.isEmpty())
|
68bac53476f43d389f40f2800b66aca38b1baaa3 | rizkysifaul/Workshop_Shopee | /ds_project_shopee.py | 2,052 | 4.0625 | 4 | #import package
import streamlit as st
import pandas as pd
import numpy as np
from PIL import Image
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import time
#import the data
data = pd.read_csv("Data Clean.csv")
image = Image.open("house.png")
st.title("Welcome to the House Price Prediction App")
st.image(image, use_column_width=True)
#checking the data
st.write("This is an application for knowing how much range of house prices you choose using machine learning. Let's try and see!")
check_data = st.checkbox("See the simple data")
if check_data:
st.write(data.head())
st.write("Now let's find out how much the prices when we choosing some parameters.")
#input the numbers
sqft_liv = st.slider("What is your square feet of living room?",int(data.sqft_living.min()),int(data.sqft_living.max()),int(data.sqft_living.mean()) )
bath = st.slider("How many bathrooms?",int(data.bathrooms.min()),int(data.bathrooms.max()),int(data.bathrooms.mean()) )
bed = st.slider("How many bedrooms?",int(data.bedrooms.min()),int(data.bedrooms.max()),int(data.bedrooms.mean()) )
floor = st.slider("How many floor do you want?",int(data.floors.min()),int(data.floors.max()),int(data.floors.mean()) )
#splitting your data
X = data.drop('price', axis = 1)
y = data['price']
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=.2, random_state=45)
#modelling step
#import your model
model=LinearRegression()
#fitting and predict your model
model.fit(X_train, y_train)
model.predict(X_test)
errors = np.sqrt(mean_squared_error(y_test,model.predict(X_test)))
predictions = model.predict([[sqft_liv,bath,bed,floor]])[0]
#checking prediction house price
if st.button("Run me!"):
st.header("Your house prices prediction is USD {}".format(int(predictions)))
st.subheader("Your range of prediction is USD {} - USD {}".format(int(predictions-errors),int(predictions+errors) )) |
5af84f21e5d6e84da6718a99c8ec14e3f5069318 | V-Kiruthika/GuviBeginner | /numeric.py | 144 | 3.53125 | 4 | s=input()
c=0
for i in range(0,len(s)):
if (s[i].isdigit() or s[i]=='.'):
c+=1
if c==len(s):
print("Yes")
else:
print("No")
|
1c7bb861463b5bd3071a82eb919bcea045a3190f | jdprada1760/JesusPrada_MCA | /graph.py | 623 | 3.609375 | 4 | # Plots histogram for numbers in dist.data
import numpy as np
import matplotlib.pyplot as plt
# Gives the x,y of the histogram for logmasses from the given array of data
def histog( mf, nbins ):
hist, bin_edges = np.histogram(mf, bins = nbins)
# Obtains the center point for each bin
xcenter = (bin_edges[:-1] + bin_edges[1:])/2
return np.array(xcenter), np.array(hist)
# Loads the file
filename = "dist.data"
data = np.loadtxt(filename)
# Gets x,y points for the histogram with 10 bins
x,y = histog(data,8)
plt.bar(x,y,align='center',width = x[1]-x[0]) # A bar chart
#plt.show()
plt.savefig("graph.png")
|
226d926c8853ecf12d1717229bc39c49d633fa14 | mirunaen/w5-emn | /exercise10.py | 221 | 4.15625 | 4 | # Create a program that asks the user to enter a number and keeps asking until a number is introduced.
n=input("Enter a num:")
while n.isdigit() == False and "." not in n:
n=input("Write a num:")
n=float(n)
print(n**2) |
feff971b8ccdf31ebabbc91a9f64400e17499a46 | HANCAO/GeekBangLearn | /test/function/decorator_using.py | 816 | 3.765625 | 4 | # # 不带参数装饰器函数写作模版
# def out(func):
# def inner():
# print('start')
# func()
# print('stop')
# return inner
#
#
# # 带参数装饰器函数使用
# def new_tips(argv):
# def tips(func):
# def change(a, b): # 注意这里要带入被装饰函数里的参数
# print('start %s ' % (argv))
# func(a, b) # 这里也要
# print('stop')
# return change
# return tips
#
#
# @new_tips('add')
# def add(a, b):
# print((a + b))
#
#
# @new_tips('sub')
# def sub(a, b):
# print(a - b)
#
#
# print(add(1, 2))
# # start add
# # 3
# # stop
# # None
# print(sub(1, 2))
# # start sub
# # -1
# # stop
# # None
# def func():
# return 1 + 2
#
#
# print(func.__name__) # 获取指定函数的函数名
|
de54b825dd6777c8ec091b8e301e2c00de0763a7 | einar-helgason/THHBV2 | /card.py | 2,592 | 3.59375 | 4 |
'''
Created on Mar 6, 2014
@author: Tryggvi
'''
import operator
import pygame
from globals import *
from preloader import load_image
class Card(pygame.sprite.Sprite):
"""
The Card class represents a playing-card in the game.
In it, all card logic and card images are stored.
"""
suit_names = ["Diamonds", "Clubs", "Hearts", "Spades"]
rank_names = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
def __init__(self, suit, rank, front, x, y):
pygame.sprite.Sprite.__init__(self)
self.suit = suit
self.rank = rank
self.front = front
self.back = load_image('hidden_owl.png')
self.image = self.back
self.rect = self.image.get_rect()
self.rect.center = (x,y)
self.AOE = pygame.Rect(x,y, card_width, card_height/5) #Area Of Interest, til ad taka upp morg spil i einu.
self.AOE.topleft = (x-card_width/2, y-card_height/2)
self.hidden = True
self.isTop = False
def __str__(self):
return '%s of %s' % (self.rank_names[self.rank], self.suit_names[self.suit])
def __cmp__(self, other):
""" The first item of first tuple is compared to the first item of the second tuple.
If they are not equal, this is the result of the comparison, else the second item is considered.
"""
t1 = self.suit, self.rank
t2 = other.suit, other.rank
return cmp(t1,t2)
def flip(self):
self.image = self.front
self.hidden = False
def flip_back(self):
self.image = self.back
self.hidden = True
def move_center_to(self, *args):
if len(args) == 1 :
assert isinstance(args[0], tuple), 'Argument should be a tuple!'
self.rect.center = args[0]
#hax til ad setja midju AOE a rettan stad
self.AOE.center = tuple(map(operator.add, self.rect.center, (0, (-card_height/2)+(card_height/10) )))
else :
try:
self.rect.center = (args[0],args[1])
#hax til ad setja midju AOE a rettan stad
self.AOE.center = tuple(map( operator.add, self.rect.center, (0,(-card_height/2)+(card_height/10) )))
except (AttributeError, TypeError):
raise AssertionError('Input variables should be x and y coordinates')
def update(self, n):
self.rect.center = tuple(map( operator.add, pygame.mouse.get_pos(), (0,n*y_offset)))
def main():
print Card.__doc__
if __name__ == '__main__': main()
|
bb22cab10dbfc898a330104e77390781cde4eb93 | dpastoor/python-parsing-gharchive | /gh_parse/gh_parse/main.py | 1,968 | 3.59375 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
Usage: gh_parse <start> <end>
Examples:
gh_parse datetime1 datetime2
Options:
-h --help Show this screen.
-v --version Show version.
"""
from docopt import docopt
from gh_parse import __version__
from termcolor import cprint
import calendar
# def parse(start,end):
# for i, line in enumerate(lines):
def start():
version = ".".join(str(x) for x in __version__)
arguments = docopt(__doc__, version=version)
## actually should parse the start month
## parse the end month, and get the range of months between to loop over
start = arguments.get('<start>', None)
end = arguments.get('<end>', None)
BASE = "http://data.githubarchive.org/"
#set date ints
start_year = int(start[0:4])
end_year = int(end[0:4])
start_month = int(start[5:7])
end_month = int(end[5:7])
# parse the months and give range(startmonth, endmonth+1) --> range not inclusive
if (start_year!=end_year):
cprint("start and end years must match", 'red')
return
year = start_year
if(start_month>end_month):
cprint("start month must be less than end month")
return
months = range(start_month,end_month+1)
months_length = len(months)
for month_index, month in enumerate(months, start=1):
month = str(month) if month > 9 else "0" + str(month)
if (months_length == month_index):
# have range go to last day
days = int(end[8:10])
else:
# else have range to to full days in month
days = calendar.monthrange(year,int(month))[1]
for day in range(1, days+1):
day_str = str(day) if day > 9 else "0" + str(day)
for hour in range(0, 24):
cprint(str(BASE) + str(year) + "-" + month + "-" + day_str + "-" + str(hour) + ".json.gz")
# cprint(arguments.get('<start>'), 'blue')
# cprint(arguments.get('<end>'),'red')
|
a8749454ba202af6772ef7af2df16fe7ddac35e4 | ashish-bisht/parking_lot | /src/charge.py | 825 | 3.703125 | 4 | class Charge(object):
""" Payment per hour basis """
def __init__(self, two_wheeler_price, four_wheeler_price):
self._two_wheeler_price = two_wheeler_price
self._four_wheeler_price = four_wheeler_price
@property
def two_wheeler_price(self):
return self._two_wheeler_price
@property
def four_wheeler_price(self):
return self._four_wheeler_price
@two_wheeler_price.setter
def two_wheeler_price(self, two_wheeler_price):
self._two_wheeler_price = two_wheeler_price
@four_wheeler_price.setter
def four_wheeler_price(self, four_wheeler_price):
self._four_wheeler_price = four_wheeler_price
# c = Charge(100, 200)
# print(c)
# print(c.four_wheeler_price)
# print(vars(c))
# c.four_wheeler_price = 330
# print(c.four_wheeler_price)
|
5b65b2f4fc8c2192a428633de246911cdd657eb5 | springkind/CodaWonderland | /TIL/PYTHON/Assignment/190812_multiplication_table.py | 2,920 | 3.984375 | 4 | # direction : 구구단을 출력합니다.
# TODO 0 step
def test_mutiply():
assert multiply(2, 1) == '2*1=2' #fail
assert multiply(2, 2) == '2*2=4' #fail
assert multiply(2, 3) == '2*3=6' #fail
# E NameError: name 'multiply' is not defined
# TODO 1st step
def multiply():
pass
def test_mutiply():
assert multiply(2, 1) == '2*1=2' #fail
assert multiply(2, 2) == '2*2=4' #fail
assert multiply(2, 3) == '2*3=6' #fail
# E TypeError: multiply() takes 0 positional arguments but 2 were given
# TODO 2nd step
# def multiply(x, y):
# return f'{x}*{y}={x*y}'
#
# def test_mutiply():
# assert multiply(2, 1) == '2*1=2' #pass
# assert multiply(2, 2) == '2*2=4' #pass
# assert multiply(2, 3) == '2*3=6' #pass
# TODO 3rd step
# def multiply(x, y):
# return f'{x}*{y}={x*y}'
#
# def test_mutiply():
# assert multiply_table[0] == '2*1=2' #fail
# assert multiply_table[1] == '2*2=4' #fail
# assert multiply_table[2] == '2*3=6' #fail
# E NameError: name 'multiply_table' is not defined
# TODO 4th step
# def multiply(x, y):
# return f'{x}*{y}={x*y}'
#
# def multiply_table():
# pass
#
# def test_mutiply():
# assert multiply_table[0] == '2*1=2' #fail
# assert multiply_table[1] == '2*2=4' #fail
# assert multiply_table[2] == '2*3=6' #fail
# E TypeError: 'function' object is not subscriptable
# TODO 5th step
# def multiply(x, y):
# return f'{x}*{y}={x*y}'
#
# def multiply_table():
# return ['2*1=2']
#
# def test_mutiply():
# assert multiply_table()[0] == '2*1=2' #pass
# assert multiply_table()[1] == '2*2=4' #fail
# assert multiply_table()[2] == '2*3=6' #fail
# E TypeError: 'function' object is not subscriptable
# TODO 6th step
# def multiply(x, y):
# return f'{x}*{y}={x*y}'
#
# def multiply_table():
# table = []
# return table.append(multiply(2,1))
#
# def test_mutiply():
# assert multiply_table()[0] == '2*1=2' #fail
# assert multiply_table()[1] == '2*2=4' #fail
# assert multiply_table()[2] == '2*3=6' #fail
# TODO 7th step
def multiply(x, y):
return f'{x}*{y}={x*y}'
def multiply_table():
table = []
for i in range(2,9+1):
for j in range(1, 9+1) :
table.append(multiply(i, j))
return table
def test_mutiply():
assert multiply_table()[0] == '2*1=2' #pass
assert multiply_table()[1] == '2*2=4' #pass
assert multiply_table()[2] == '2*3=6' #pass
# f string
# def gugu(n):
# gugu_text = ''
# for i in range(1, 10) :
# gugu_text += f'{n}*{i}={n*i} '
# return gugu_text.strip()
#
# def test_gugu():
# assert gugu(2) == '2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18' #pass
# assert gugu(3) == '3*1=3 3*2=6 3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27' #pass
# assert gugu(4) == '4*1=4 4*2=8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36' #pass |
981c291837d202a5ea15bb5262adc0926f160b9e | codeAligned/DailyProgrammer | /easy/5.py | 511 | 3.671875 | 4 | #!/usr/bin/env python3
import getpass
class AuthenticationFailure(Exception):
pass
def get_creds():
with open('5.txt') as cred_file:
data = cred_file.readline()
data = data.strip()
return data.split(':')
if __name__ == '__main__':
u = input('Username: ')
p = getpass.getpass('Password: ')
user, password = get_creds()
if u != user or p != password:
raise AuthenticationFailure("Bad username or password")
else:
print('Authenticated!')
|
1b46c1e082a26055d02c0a053302a39836dc4009 | HarshCasper/Rotten-Scripts | /Python/PDF_Generator/pdf_generator.py | 601 | 3.515625 | 4 | import os
import img2pdf
from pdf2image import convert_from_path
# *.jpg to output_filename.pdf convertor
with open("output_filename.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir(".") if i.endswith(".jpg")]))
# file.pdf to output_images_folder_name/page_no.jpg convertor
pages = convert_from_path("input_filename.pdf", 500)
page_no = 0
for page in pages:
# output_images_folder_name = folder needs to be created manually to store all images
pages[page_no].save(
"output_images_folder_name/output_page_{}.jpg".format(page_no + 1), "JPEG"
)
page_no += 1
|
51fbfc8cda4c961241565bfdbf9b7cd912092dce | soltysh/talks | /2014/pyconpl/examples/task1.py | 1,345 | 3.703125 | 4 | from concurrent.futures import ThreadPoolExecutor
import time
class Task:
"""Task class wraps around and represents a running generator."""
def __init__(self, gen):
"""Initialize task object with generator."""
self._gen = gen
def step(self, value=None):
"""Advance the generator to the next yield, sending in a value."""
try:
fut = self._gen.send(value)
# attach callback to the produced future
fut.add_done_callback(self._wakeup)
except StopIteration as exc:
pass
def _wakeup(self, fut):
"""Callback function called in response to receiving result."""
result = fut.result()
# this little trick will allow us to run to the next yield
self.step(result)
def recursive(pool, n):
"""Recursive function, using yield statements."""
yield pool.submit(time.sleep, 0.001)
print(n)
# let's call create another object of ourselves and run it
# sort of recursion in a very weird way
Task(recursive(pool, n+1)).step()
if __name__ == '__main__':
# first we need to create pool executor
pool = ThreadPoolExecutor(8)
# now call our recursive function using the Task object
Task(recursive(pool, 0)).step()
# make sure we don't loose the input
while True:
pass
|
68a01a0735c626f66b314a553655c690e89b2e76 | fernandocostagomes/CursoDePython | /Exercicios Aula 24/Exercicio3_24.py | 308 | 4.09375 | 4 | '''
O usuario entra com o nome de uma cidade.
Analisar se o nome da cidade começa ou não com "São"
'''
nome = str(input('Digite o nome de uma cidade por favor: '))
if nome.count('São', 0, 3):
print('O nome da cidade começa com "São"!')
else:
print('O nome da cidade não começa com "São"!') |
03fb7eaeb1a24a5bcd68b17473d648915f7b50d6 | AswinGnanaprakash/code_box | /autoML/application/algo.py | 13,756 | 3.515625 | 4 | """
1. Ordinary linear regression
"""
def linear_regression(x_train, y_train, x_test, y_test):
from sklearn import linear_model
linear = linear_model.LinearRegression()
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
2. Ridge regression
"""
def linear_ridge(x_train, y_train, x_test, y_test):
from sklearn import linear_model
linear = linear_model.Ridge(alpha=.5)
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
3. Lasso regression
"""
def linear_lasso(x_train, y_train, x_test, y_test):
from sklearn import linear_model
linear = linear_model.Lasso(alpha=0.1)
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
4. LassoLars regression
"""
def linear_lassolars(x_train, y_train, x_test, y_test):
from sklearn import linear_model
linear = linear_model.LassoLars(alpha=.1)
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
5. Bayesian Regression
"""
def linear_bayesian_reidge(x_train, y_train, x_test, y_test):
from sklearn import linear_model
linear = linear_model.BayesianRidge()
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
6. RANSAC: RANdom SAmple Consensus
"""
def ransac_regressor(x_train, y_train, x_test, y_test):
from sklearn import linear_model
linear = linear_model.RANSACRegressor()
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
7. Logistic Regression
"""
def logistic_regression(x_train, y_train, x_test, y_test):
from sklearn import linear_model
linear = linear_model.LogisticRegression()
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
8. Linear Discriminant Analysis
"""
def linear_discriminant_analysis(x_train, y_train, x_test, y_test):
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
linear = LinearDiscriminantAnalysis(solver="svd", store_covariance=True)
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
9. Quadratic Discriminant Analysis
"""
def quadratic_discriminant_analysis(x_train, y_train, x_test, y_test):
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
linear = QuadraticDiscriminantAnalysis(store_covariance=True)
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
10. Normal Linear Discriminant
"""
def linear_discriminant_analysis_auto(x_train, y_train, x_test, y_test):
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
linear = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto')
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
11. Shrinkage Linear Discriminant
"""
def linear_discriminant_analysis_none(x_train, y_train, x_test, y_test):
import operator
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
linear = LinearDiscriminantAnalysis(solver='lsqr', shrinkage=None)
linear.fit(x_train, y_train)
value = linear.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
12. Classification SVM
"""
def svc(x_train, y_train, x_test, y_test):
from sklearn import svm
clf = svm.SVC()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
13. Regression SVM
"""
def svr(x_train, y_train, x_test, y_test):
from sklearn import svm
clf = svm.SVR()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
14. Linear SVM classifier
"""
def linear_svc(x_train, y_train, x_test, y_test):
from sklearn import svm
clf = svm.LinearSVC()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
15. Classification SGD
"""
def sgd_classifier(x_train, y_train, x_test, y_test):
from sklearn.linear_model import SGDClassifier
clf = SGDClassifier()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
16. Classification SGD
"""
def sdg_regressor(x_train, y_train, x_test, y_test):
from sklearn.linear_model import SGDRegressor
clf = SGDRegressor()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
17. Nearest Centroid Classifier
"""
def nearest_centroid(x_train, y_train, x_test, y_test):
from sklearn.neighbors import NearestCentroid
clf = NearestCentroid()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
18. KNeighborsClassifier
"""
def kneighbors_classifier(x_train, y_train, x_test, y_test):
from sklearn.neighbors import KNeighborsClassifier
clf = KNeighborsClassifier()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
19. Gaussian Naive Bayes
"""
def gaussian_nb(x_train, y_train, x_test, y_test):
from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
20. Bernoulli Naive Bayes
"""
def bernoulli_nb(x_train, y_train, x_test, y_test):
from sklearn.naive_bayes import BernoulliNB
clf = BernoulliNB()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
21. Multinomial Naive Bayes
"""
def multinomial_nb(x_train, y_train, x_test, y_test):
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB()
clf.fit(x_train, y_train)
value = clf.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
22. Classification decision trees
"""
def decision_tree_classifier(x_train, y_train, x_test, y_test):
from sklearn import tree
tree = tree.DecisionTreeClassifier()
tree.fit(x_train, y_train)
value = tree.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
23. Regressor decision trees
"""
def decision_tree_regressor(x_train, y_train, x_test, y_test):
from sklearn import tree
tree = tree.DecisionTreeRegressor()
tree.fit(x_train, y_train)
value = tree.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
24. Bagging meta-estimator
"""
def bagging_classifier(x_train, y_train, x_test, y_test):
from sklearn.ensemble import BaggingClassifier
ensem = BaggingClassifier()
ensem.fit(x_train, y_train)
value = ensem.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
25. Forests of randomized trees
"""
def random_forest_classifier(x_train, y_train, x_test, y_test):
from sklearn.ensemble import RandomForestClassifier
ensem = RandomForestClassifier(n_estimators=10)
ensem.fit(x_train, y_train)
value = ensem.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
26. Extremely Randomized Trees
"""
def extra_trees_classifier(x_train, y_train, x_test, y_test):
from sklearn.ensemble import ExtraTreesClassifier
ensem = ExtraTreesClassifier()
ensem.fit(x_train, y_train)
value = ensem.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
27. AdaBoost
"""
def ada_boost_classifier(x_train, y_train, x_test, y_test):
from sklearn.ensemble import AdaBoostClassifier
ensem = AdaBoostClassifier()
ensem.fit(x_train, y_train)
value = ensem.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
28. Gradient Tree Boosting Classifier
"""
def gradient_boosting_classifier(x_train, y_train, x_test, y_test):
from sklearn.ensemble import GradientBoostingClassifier
ensem = GradientBoostingClassifier(random_state=0)
ensem.fit(x_train, y_train)
value = ensem.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
29. Gradient Tree Boosting Regressor
"""
def gradient_boosting_regressor(x_train, y_train, x_test, y_test):
from sklearn.ensemble import GradientBoostingRegressor
ensem = GradientBoostingRegressor(random_state=0)
ensem.fit(x_train, y_train)
value = ensem.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
30. Histogram-Based Gradient Boosting
"""
def hist_gradient_boosting_classifier(x_train, y_train, x_test, y_test):
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGradientBoostingClassifier
ensem = HistGradientBoostingClassifier()
ensem.fit(x_train, y_train)
value = ensem.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
31. LabelSpreading
"""
def label_spreading(x_train, y_train, x_test, y_test):
from sklearn.semi_supervised import LabelSpreading
sel = LabelSpreading()
sel.fit(x_train, y_train)
value = sel.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
32. LabelPropagation
"""
def label_propagation(x_train, y_train, x_test, y_test):
from sklearn.semi_supervised import LabelPropagation
sel = LabelPropagation()
sel.fit(x_train, y_train)
value = sel.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
33. Classification neural network
"""
def mlp_classifier(x_train, y_train, x_test, y_test):
from sklearn.neural_network import MLPClassifier
nn = MLPClassifier()
nn.fit(x_train, y_train)
value = nn.score(x_test, y_test)
return "{0:.2f}".format(value)
"""
34. Regressor neural network
"""
def mlp_regressor(x_train, y_train, x_test, y_test):
from sklearn.neural_network import MLPRegressor
nn = MLPRegressor()
nn.fit(x_train, y_train)
value = nn.score(x_test, y_test)
return "{0:.2f}".format(value)
def main_function(x_train, y_train, x_test, y_test):
predictions_dict = dict()
predictions_dict['linear_regression'] = linear_regression(x_train, y_train, x_test, y_test)
predictions_dict['linear_ridge'] = linear_ridge(x_train, y_train, x_test, y_test)
predictions_dict['linear_lasso'] = linear_lasso(x_train, y_train, x_test, y_test)
predictions_dict['linear_lassolars'] = linear_lassolars(x_train, y_train, x_test, y_test)
predictions_dict['linear_bayesian_reidge'] = linear_bayesian_reidge(x_train, y_train, x_test, y_test)
predictions_dict['ransac_regressor'] = ransac_regressor(x_train, y_train, x_test, y_test)
predictions_dict['logistic_regression'] = logistic_regression(x_train, y_train, x_test, y_test)
predictions_dict['linear_discriminant_analysis'] = linear_discriminant_analysis(x_train, y_train, x_test, y_test)
predictions_dict['quadratic_discriminant_analysis'] = quadratic_discriminant_analysis(x_train, y_train, x_test, y_test)
predictions_dict['linear_discriminant_analysis_auto'] = linear_discriminant_analysis_auto(x_train, y_train, x_test, y_test)
predictions_dict['linear_discriminant_analysis_none'] = linear_discriminant_analysis_none(x_train, y_train, x_test, y_test)
predictions_dict['svc'] = svc(x_train, y_train, x_test, y_test)
predictions_dict['svr'] = svr(x_train, y_train, x_test, y_test)
predictions_dict['linear_svc'] = linear_svc(x_train, y_train, x_test, y_test)
predictions_dict['sgd_classifier'] = sgd_classifier(x_train, y_train, x_test, y_test)
predictions_dict['sdg_regressor'] = sdg_regressor(x_train, y_train, x_test, y_test)
predictions_dict['nearest_centroid'] = nearest_centroid(x_train, y_train, x_test, y_test)
predictions_dict['kneighbors_classifier'] = kneighbors_classifier(x_train, y_train, x_test, y_test)
predictions_dict['gaussian_nb'] = gaussian_nb(x_train, y_train, x_test, y_test)
predictions_dict['bernoulli_nb'] = bernoulli_nb(x_train, y_train, x_test, y_test)
predictions_dict['multinomial_nb'] = multinomial_nb(x_train, y_train, x_test, y_test)
predictions_dict['decision_tree_classifier'] = decision_tree_classifier(x_train, y_train, x_test, y_test)
predictions_dict['decision_tree_regressor'] = decision_tree_regressor(x_train, y_train, x_test, y_test)
predictions_dict['bagging_classifier'] = bagging_classifier(x_train, y_train, x_test, y_test)
predictions_dict['random_forest_classifier'] = random_forest_classifier(x_train, y_train, x_test, y_test)
predictions_dict['extra_trees_classifier'] = extra_trees_classifier(x_train, y_train, x_test, y_test)
predictions_dict['ada_boost_classifier'] = ada_boost_classifier(x_train, y_train, x_test, y_test)
predictions_dict['gradient_boosting_classifier'] = gradient_boosting_classifier(x_train, y_train, x_test, y_test)
predictions_dict['gradient_boosting_regressor'] = gradient_boosting_regressor(x_train, y_train, x_test, y_test)
predictions_dict['hist_gradient_boosting_classifier'] = hist_gradient_boosting_classifier(x_train, y_train, x_test, y_test)
predictions_dict['label_spreading'] = label_spreading(x_train, y_train, x_test, y_test)
predictions_dict['label_propagation'] = label_propagation(x_train, y_train, x_test, y_test)
predictions_dict['mlp_classifier'] = mlp_classifier(x_train, y_train, x_test, y_test)
predictions_dict['mlp_regressor'] =mlp_regressor(x_train, y_train, x_test, y_test)
return predictions_dict
def main(val):
from numpy import load
x_test = load(val[0])
x_train = load(val[1])
y_test = load(val[2])
y_train = load(val[3])
result = main_function(x_train, y_train, x_test, y_test)
return result |
c4930711d3808ee1eb9cbf750cf2d5c753a2ff96 | missasan/flask_python_tutorial | /python_tutorial/basic/base9.py | 187 | 4.03125 | 4 | # リスト
list_a = [1,2,3,4]
list_b = []
print(list_a)
print(list_a[0])
print(list_a[-2])
list_c = [1,[1,2,'apple'],3,'banana']
print(list_c[1][2])
list_c[1][2] = 'lemon'
print(list_c) |
0fa658387ac235cb19a995b2b59ddb585aa899fc | semalPatel/Algorithms | /selectionSort.py | 551 | 3.8125 | 4 |
def selectionSort(a, n):
count_1 = 0
count_2 = 0
for i in range(n, 0, -1):
x = 0;
print(i,a[i])
#print("for 1", count_1)
for k in range(1, i):
#print("for 2", count_2)
count_1 +=1
if a[k] > a[x]:
x = k
a[x], a[i-1] = a[i-1], a[x]
count_2 += 1
#print("swap" ,a)
print(a)
print("for 1: ", count_1, " for 2: ",count_2)
a = []
n = int(input("enter"))
for i in range(0, n):
a.append(int(input()))
selectionSort(a, n)
|
f969c5c43e7cb27bdb879e54d3c37c0337c3c0e6 | Tehnoves/my | /my.py | 82 | 3.71875 | 4 | str1 =b'Good'
str2 =b'Good'
if (str1 == str2):
print("ok")
else :
print ("bad") |
f78624cc81f7f66b6ecce3a48c80168ffa080740 | Deyvider/EjerciciosPython01 | /DatoCompuesto_01.py | 588 | 3.984375 | 4 | #Realiza una función separar(lista) que tome una
#lista de números enteros desordenados y devuelva
#dos listas ordenadas. La primera con los números
#pares y la segunda con los números impares.
print ("Funcion separar lista")
listaNumerica = [10, 7, 4, 5, 8, 1, 2, 11]
print("Tu lista original es: "+ str(listaNumerica))
listaNumerica.sort()
print(f"Despues de ordenar {listaNumerica}")
pares = []
impares = []
for n in listaNumerica:
if n % 2 == 0:
pares.append(n)
else:
impares.append(n)
print(f"Pares Ordenados {pares}")
print(f"Impares Ordenados {impares}")
|
4b26bdc9c7cb8cc35f6656dcc421ddd51fae6930 | KingOfRaccoon/2 | /12.py | 205 | 4.125 | 4 | string = '3' * 95
while '333' in string or '999' in string:
if '999' in string:
string = string.replace('999', '3', 1)
else:
string = string.replace('333', '9', 1)
print(string) |
5741d660f5c695b39a6767660c43c61661a0a1d4 | SergeyPresnyakov/-all- | /Урок 4 - Задание 7.py | 1,101 | 4.15625 | 4 | """Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное
значение. При вызове функции должен создаваться объект-генератор. Функция должна
вызываться следующим образом: for el in fact(n). Функция отвечает за получение факториала
числа, а в цикле необходимо выводить только первые n чисел, начиная с 1! и до n!.
Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал
четырёх 4! = 1 * 2 * 3 * 4 = 24.
"""
def fact(n):
factorial = 1
for el in range(1, n + 1):
factorial *= el
yield factorial
n = input("Введите число, факториал которого нужно посчитать: ")
for el in range(int(n) + 1):
g = fact(el)
print(f"Факториал {el} = {next(g)}")
|
beed0c5c35ee13000899a4ae449b8a36b15e85ed | ThomasMaze/dataMovieExtraction | /src/dateListGenerator.py | 1,089 | 3.625 | 4 | import calendar
import datetime as dt
from sys import exit
def dateGenerator(start_date):
stop_date = dt.date.today()
cal = calendar.Calendar(calendar.WEDNESDAY)
year = cal.yeardatescalendar(start_date.year,1)
#intializing week and month index
wIndex = 0
mIndex = start_date.month-1
while year[mIndex][0][wIndex][0] < start_date :
wIndex = wIndex + 1
#intializing the current date to the first Wednesday after start date
current_date = year[mIndex][0][wIndex][0]
dateList = []
while current_date <= stop_date :
if current_date.month == mIndex+1:
dateList = dateList + [current_date.isoformat()]
wIndex = wIndex + 1
try:
current_date = year[mIndex][0][wIndex][0]
except IndexError:
wIndex = 0
mIndex = mIndex + 1
if mIndex >= 12 :
dateList = dateList + dateGenerator(dt.date(start_date.year+1,1,1))
break
else :
current_date = year[mIndex][0][wIndex][0]
return dateList
|
23bdfaf6fbfcf0bf4c87fcd623519dd64c6f5726 | hakimkartik/CoffeeMachine | /beverage.py | 759 | 3.546875 | 4 | class Beverage:
def __init__(self, beverage_name, all_ingredients):
self.beverage_name = beverage_name
self.ingredients = dict()
for ingredient_name in all_ingredients:
ingredient_quantity = all_ingredients[ingredient_name]
self.ingredients[ingredient_name] = ingredient_quantity
def add_ingredient(self, name, quantity):
if quantity >= 0:
self.ingredients[name] = quantity
def get_ingredient_quantity(self, name):
return self.ingredients.get(name, -1)
def remove_ingredient(self, name):
del self.ingredients[name]
def get_beverage_name(self):
return self.beverage_name
def get_beverage_ingredients(self):
return self.ingredients
|
feeb6771c4da6b3892c4f41ee9d3a6ae2c979f58 | ereynolds123/introToProgramming | /creatingUserNames.py | 805 | 3.75 | 4 | #Program to create a file of usernames in batch mode
def createUserNames():
print("This program creates a file of usernames from a")
print(" file of names.")
#get the file names
infileName = input("What file are the names in?")
outfileName= input ("What file should the usernames go in?")
#open the files
infile = open(infileName, "r")
outfile = open (outfileName, "w")
#process each line of input file
for ling in infile:
#ge tthe first and last names from the line
first, last =line.split
#create username
userName = (first[0]+last[:7]).lower()
#write it to the output file
print(userName, file=outfile)
#close both files
infile.close()
outfile.close()
createUserNames() |
72e11ce0c80936e190c428064a8fe825e36212de | decy20002002/MyPythonCourse | /Ch03/find_dynamic_odds.py | 268 | 3.828125 | 4 | x = 0
counter = 0
limit = input('Please set the limit: ')
if limit == "":
limit = 4
else:
limit = int(limit)
while counter < limit:
#if (counter %2 != 0):
print(counter, end=" ")
counter+=1
# print(counter)
# print('\n', 'Finished looping')
|
2cc2787e606ac75c7ee199b52f230eed3ac0327a | KienHuynh/polygon_sweeping | /pslg.py | 4,269 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
class Node:
def __init__(self, _id, _pos):
"""
2D position of the node
:param _id:
:param _pos:
"""
self.id = _id
self.pos = _pos
self.edges = []
self.visited = False
class Edge:
def __init__(self, _from: Node, _to: Node, _type):
"""
:param _from: Node object
:param _to: Node onject
:param _type: "poly" or "vis"
"""
self.src = _from
self.to = _to
self.type = _type
class PSLG:
def __init__(self, polygon):
"""
:param polygon: Vertices of the polygon [[x1, y1], [x2, y2], ...], counter-clockwise
"""
self.nodes = {}
self.edges = {}
self.edge_set = []
n = len(polygon)
for i in range(n):
self.nodes[i] = Node(i, polygon[i])
for i in range(n):
edge = Edge(self.nodes[i], self.nodes[(i + 1) % n], "poly")
self.edges[i] = [edge]
self.edge_set.append(edge)
def add_node(self, Node):
num_node = len(self.nodes)
self.nodes[num_node] = Node
self.edges[num_node] = []
def add_edge(self, _e):
self.edge_set.append(_e)
self.edges[_e.src.id].append(_e)
def remove_edge(self, _e: Edge):
"""
Remove edge _e from the edge set and the adjacency list
:param _e:
:return:
"""
# Remove edge _e from the edge superset
self.edge_set.remove(_e)
# Remove edge _e from the adjacency list
self.edges[_e.src.id].remove(_e)
def draw_edge_set(self):
for e in self.edge_set:
c = 'k'
if e.type == 'vis':
c = 'b'
src = e.src.pos
to = e.to.pos
plt.plot([src[0], to[0]], [src[1], to[1]], color=c)
def draw_adj_list(self):
for k, es in self.edges.items():
for e in es:
c = 'k'
if e.type == 'vis':
c = 'b'
src = e.src.pos
to = e.to.pos
plt.plot([src[0], to[0]], [src[1], to[1]], color=c)
def node_exist(self, pos):
for k, v in self.nodes:
if v[0] == pos[0] and v[1] == pos[1]:
return True
return False
def get_node(self, pos):
for k, v in self.nodes.items():
if v.pos[0] == pos[0] and v.pos[1] == pos[1]:
return v
return None
def add_intersection(self, pos, edge, ray_start):
# If this is an actual new node
old_node = self.get_node(pos)
if (old_node == None):
node = Node(len(self.nodes), pos)
# Remove previous edge and add 4 new edges
self.add_node(node)
self.remove_edge(edge)
self.add_edge(Edge(edge.src, node, 'poly'))
self.add_edge(Edge(node, edge.to, 'poly'))
self.add_edge(Edge(node, self.nodes[ray_start], 'vis'))
self.add_edge(Edge(self.nodes[ray_start], node, 'vis'))
return node
else:
self.add_edge(Edge(old_node, self.nodes[ray_start], 'vis'))
self.add_edge(Edge(self.nodes[ray_start], old_node, 'vis'))
return old_node
def get_left_subpolygon(self, a, b):
"""
Get the subpolygon to the left of chord ab
Note that the PSLG is made of either edges of the original polygon, or visibility chords
This function will return the polygonal chain of the original polygon to the left of ab
:param a: node id
:param b: node id
:return: List[List[float]] - [[x1, y1], [x2, y2], ...] format of the subpolygon
"""
subpolygon = [self.nodes[a].pos, self.nodes[b].pos]
next_e = [e for e in self.edges[b] if e.type == 'poly']
next_e = next_e[0]
while True:
next_node = self.nodes[next_e.to.id]
if next_e.to.id == a:
break
subpolygon.append(next_node.pos)
next_e = [e for e in self.edges[next_node.id] if e.type == 'poly']
next_e = next_e[0]
return subpolygon
|
fe20b3ce523458df0aa3d818e610c0e7ed0a5196 | rileyshahar/csworkshops | /00-principles/050-fib-for.py | 354 | 4.21875 | 4 | """Compute the first 8 fibonacci numbers."""
# initial values at (0,1)
prev = 0
curr = 1
# repeat 8 times
for _ in range(8):
# output the next number
print(curr)
# update the numbers according to fibonacci rule: f(n) = f(n-1) + f(n-2)
# using python's simultaneous assignment notation to allow this
prev, curr = curr, prev + curr
|
9a43e3cad90c9a990df734d91a7404af7432ec0d | cjquines/compprog | /gcj/gcj-2019/r23.py | 2,371 | 3.53125 | 4 | # import sys
# sys.stdout.flush()
# sys.exit()
from fractions import Fraction as F
from math import ceil
from random import *
seed(11)
# taken from https://stackoverflow.com/questions/38140872/
def to_continued_fractions(x):
a = []
while True:
q, r = divmod(x.numerator, x.denominator)
a.append(q)
if r == 0: break
x = F(x.denominator, r)
return (a, a[:-1] + [a[-1] - 1, 1])
def combine(a, b):
i = 0
while i < len(a) and i < len(b):
if a[i] != b[i]:
return a[:i] + [min(a[i], b[i]) + 1]
i += 1
if i < len(a):
return a[:i] + [a[i] + 1]
if i < len(b):
return a[:i] + [b[i] + 1]
assert False
def from_continued_fraction(a):
x = F(a[-1])
for i in range(len(a) - 2, -1, -1):
x = a[i] + 1 / x
return x
def between(x, y):
def predicate(z):
return x < z < y or y < z < x
return predicate
def simplicity(x):
return x.numerator
def simplest_between(x, y):
return min(filter(between(x, y), (from_continued_fraction(combine(a, b))
for a in to_continued_fractions(x)
for b in to_continued_fractions(y))), key=simplicity)
for cas in range(int(input())):
n = int(input())
mol = []
for _ in range(n):
mol.append(list(map(int, input().split())))
# n = 10
# mol = [[randint(1, 10), randint(1, 10)] for i in range(n)]
# mol = [[1, 1], [2, 2], [1, 4]]
def brute():
for x in range(1, 25):
for y in range(1, 25):
if all(mol[i][0]*x + mol[i][1]*y < mol[i+1][0]*x + mol[i+1][1]*y for i in range(n-1)):
return x, y
return -1, -1
def sol():
gre = F(0,1)
les = float('inf')
for i in range(n-1):
a, b = mol[i]
c, d = mol[i+1]
if b == d:
if a >= c: les = -float('inf')
continue
rat = F(a-c, d-b)
if d-b > 0: gre = max(gre, rat)
else: les = min(les, rat)
if les <= gre:
return -1, -1
# print(gre, les)
if les != float('inf'):
rat = simplest_between(gre, les)
ansy, ansx = rat.numerator, rat.denominator
else:
ansx = 1
ansy = int(gre) + 1
return ansx, ansy
# k = brute()
j = sol()
# if k != j:
# print(mol, k, j)
if j == (-1, -1):
print("Case #" + str(cas+1) + ": IMPOSSIBLE")
else:
print("Case #" + str(cas+1) + ": " + str(j[0]) + " " + str(j[1]))
|
2e09de77fd4330737fbf24ae14368477edb45b48 | Oowalkman23/Python-3.8 | /Faction_Game.py | 3,745 | 3.578125 | 4 | from queue import Queue
import random
import sys
sys.setrecursionlimit(2000)
def test_case():
# factions of abcde, # as mountain, and '.' as land
# connected land would be dominated by faction if alone
# if there's more than one faction, counted as 'contested' area
factions_and_symbols = list('abcde#.')
# Setting maps
grid = []
for i in range(20):
grid_row = []
for j in range(20):
spot = random.choice(factions_and_symbols)
grid_row.append(spot)
grid.append(grid_row)
main(grid)
def main(grid):
# setting up variables for global use
# gridx = game board
# list_coordinate = list of visited coordinate (row, column)
# list_faction = dictionary of faction list
# v_arah = dictionary of direction vector on the game board
# list_tree = queue of coordinates, for recursion purpose
# contested = if more than one faction, marked as contested
global gridx, list_coordinate, list_faction, v_arah
gridx = grid
list_tree = Queue()
list_coordinate = []
list_faction = {}
v_arah = {'up':(-1,0), 'down':(1,0), 'left':(0,-1), 'right':(0,1)}
contested = 0
# initial search process, starts from row=0,column=0
for i in range(len(gridx)):
for j in range(len(gridx[0])):
data = gridx[i][j]
# if meets mountain #, continue to next iteration
if data == '#':
continue
# else, set up list_tree and counter (for counting contested area)
list_tree = Queue()
counter = {}
# if result of function which would be counter, > 1, contested area
if scan(i,j,list_tree, counter) > 1:
contested += 1
# print results for faction list, number of each, and contested area in the map.
for x in list_faction:
print(f'{x} {len(list_faction[x])}')
print(f'contested {contested}')
def check_spot(next_spot, coord, list_tree, counter):
# checking next spot as stated with other given parameters
if next_spot == '#':
pass
# storing visited coordinate, and enqueue it for next scan()
list_coordinate.append(coord)
list_tree.put(coord)
# if found '.' or factions, call function check_faction()
if next_spot != '.':
check_faction(next_spot, coord, counter)
return counter
def scan(i,j,list_tree,counter):
# scanning in 4 vector of direction
for v in v_arah:
# if next coordinate is out of index range, next iteration
if i+v_arah[v][0] in (-1,len(gridx)) or j+v_arah[v][1] in (-1, len(gridx[0])):
continue
next_spot = gridx[i+v_arah[v][0]][j+v_arah[v][1]]
coord = (i+v_arah[v][0], j+v_arah[v][1])
if coord in list_coordinate:
continue
if next_spot == '#':
continue
# check the next spot
counter = check_spot(next_spot, coord, list_tree, counter)
# check queue, if empty, then exit function
if list_tree.empty():
return len(counter)
# else, scan for next coordinate as queued
coord_next = list_tree.get()
scan(coord_next[0], coord_next[1], list_tree, counter)
return len(counter)
def check_faction(next_spot, coord, counter):
# check faction in dictionary, if there's new, add the list, and the counter
if next_spot not in list_faction:
list_faction[next_spot] = [coord]
counter[next_spot] = [coord]
else:
list_faction[next_spot].append([coord])
return counter
test_case()
|
47a15c29c709ccb75772129c816162ff3528ed7f | jacben13/adventofcode2020 | /day5/part2.py | 1,163 | 3.6875 | 4 | def find_seat_row(seat):
row_chars = seat[:7]
min = 0
max = 127
for char in row_chars:
delta = max - min + 1
half = delta // 2
if char == 'F':
max -= half
else:
min += half
return min
def find_seat_col(seat):
col_chars = seat[-3:]
min = 0
max = 7
for char in col_chars:
delta = max - min + 1
half = delta // 2
if char == 'L':
max -= half
else:
min += half
return min
def calc_seat_id(seat):
return find_seat_row(seat) * 8 + find_seat_col(seat)
boarding_pass_list = []
with open('input.txt') as f:
for line in f:
line = line.replace('\n', '')
boarding_pass_list.append(line)
max_seat_id = 0
seat_id_list = []
for bp in boarding_pass_list:
seat_id = calc_seat_id(bp)
seat_id_list.append(seat_id)
max_seat_id = max(max_seat_id, seat_id)
seat_id_list.sort()
prev = seat_id_list[0] - 1
for seat in seat_id_list:
delta = seat - prev
if delta > 1:
print('Missing seat id: {}'.format(prev + 1))
prev = seat |
b0fa2b47099f94477f518d4b3456c1e6ece5bd42 | chinmayk1613/Machine_Learning_with_PYTHON | /data_preprocessing_template.py | 2,113 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 13:04:43 2020
@author: Chinmay Kashikar
"""
#import library
import numpy as np #cotain maths
import matplotlib.pyplot as plt #help to plot nice chart.To plot something
import pandas as pd #to import dataset and to manage data set
#import dataset
dataset=pd.read_csv('Data.csv') #load data set
X=dataset.iloc[:,:-1].values #independnt variables
y=dataset.iloc[:, 3].values #dependent data
#taking care of missing data
from sklearn.impute import SimpleImputer #SimpleImputer class allow to take care of missing data
imputer=SimpleImputer(missing_values=np.nan,strategy='mean') # creating the object of class whihc take care of missing values providing some parameteres
imputer=imputer.fit(X[:, 1:3]) # fit the data to specific column
X[:,1:3]=imputer.transform(X[:,1:3]) #transform replcae the missing the data with mean of the column
#if we have caterical data we have to encode it from text to
#some number for machine learning models
#Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
labelencoder_X=LabelEncoder()
X[:,0]=labelencoder_X.fit_transform(X[:,0])
#here problem is that machine learning algo thinks that 0<2 meaning
# France is less than spain but this is not the case at all
#hence we use dummy column buidling three column
#meanig put 1 if that France is there for ex. and put 0 if not.
ct=ColumnTransformer([('encoder',OneHotEncoder(),[0])],remainder='passthrough')
X=np.array(ct.fit_transform(X))
labelencoder_Y=LabelEncoder()
y=labelencoder_X.fit_transform(y)
#Splitting dataset into train and test data
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)
#we should make feature scale to not let dominate one feature over the
#other
#feature scaling
from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler()
X_train=sc_X.fit_transform(X_train)
X_test=sc_X.transform(X_test)
#scalling the dummy coulmn depends interpreation of model and it is depends
|
b12701ea395a8748927cc0ea0664cdf3d8316138 | ramonfigueiredo/python_programming | /data_structures_algorithms/binary_search.py | 1,569 | 4.21875 | 4 | '''
Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
A simple approach is to do linear search. The time complexity of above algorithm is O(n).
Another approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
Begin with an interval covering the whole array. If the value of the search key is less than the item
in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.
Repeatedly check until the value is found or the interval is empty.
The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
'''
# Binary Search
# returns index of x in arr if present, else -1
def binary_search(arr, left, right, x):
# Check the base case
if right >= left:
mid = int(1 + (right + left)/2)
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only be present in left subarray
elif arr[mid] > x:
return binary_search(arr, left, mid-1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid+1, right, x)
else:
# Element is not present in the array
return -1
# Test array
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index %d", result)
else:
print("Element is no present in the array") |
7ec8a2505e06f856456aca8401b77b4597de86ee | robertspauls/DA-kurss | /python-spele.py | 3,022 | 3.734375 | 4 | list1 = ['_', '_', '_', '_', '_', '_', '_', '_', '_']
def error():
print('Neatbilstoša vērtība!')
def error2():
print('Lauciņš ir aizņemts!')
def test_input(a):
try:
a = int(a)
except:
return True
if a > 3 or a < 1:
return False
else: return True
def test_gajiens(b):
if list1[b] == '_':
return True
def uzvaretajs(e):
print('Uzvarēja spēlētājs ' + e + '!')
def test_uzvara1(c):
if list1[0] == list1[1] == list1[2] == c: return True
elif list1[3] == list1[4] == list1[5] == c: return True
elif list1[6] == list1[7] == list1[8] == c: return True
elif list1[0] == list1[3] == list1[6] == c: return True
elif list1[1] == list1[4] == list1[7] == c: return True
elif list1[2] == list1[5] == list1[8] == c: return True
elif list1[0] == list1[4] == list1[8] == c: return True
elif list1[2] == list1[4] == list1[6] == c: return True
def printet():
print(list1[0],list1[1],list1[2])
print(list1[3],list1[4],list1[5])
print(list1[6],list1[7],list1[8])
def main_funkcija():
printet()
for i in range(1,10):
print('---------------')
if i % 2 == 1:
print('Gājiens spēlētājam X')
d = 'X'
while d == 'X':
while d == 'X':
line1 = input('Ievadiet rindu (1-3):')
test_input(line1)
if test_input(line1):
break
error()
while d == 'X':
kolona1 = input('Ievadiet kolonu (1-3):')
test_input(line1)
if test_input(line1):
break
error()
gajiens = (int(line1) - 1) * 3 + int(kolona1) - 1
if test_gajiens(gajiens):
break
error2()
list1[gajiens] = d
if test_uzvara1(d):
uzvaretajs(d)
break
printet()
else:
print('Gājiens spēlētājam 0')
d = '0'
while d == '0':
while d == '0':
line1 = input('Ievadiet rindu (1-3):')
test_input(line1)
if test_input(line1):
break
error()
while d == '0':
kolona1 = input('Ievadiet kolonu (1-3):')
test_input(line1)
if test_input(line1):
break
error()
gajiens = (int(line1) - 1) * 3 + int(kolona1) - 1
if test_gajiens(gajiens):
break
error2()
list1[gajiens] = d
if test_uzvara1(d):
uzvaretajs(d)
break
printet()
if i == 9:
print('Spēle beidzās neizšķirti!')
if __name__ == '__main__':
main_funkcija()
|
0f27cc9f7c9ab16ccbc0bd5116695b5737451408 | Owaisaaa/Python_Basics | /guessTheNumber.py | 649 | 4.3125 | 4 | ################# Guess the number program/game ###################
import random
secretNumber = random.randint(1, 12)
print('The number is I am thinking of is between 1 and 12')
# Ask the player to guess in 5 turns
for guessNumber in range(1, 6):
print('Enter the guessed number')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low')
elif guess > secretNumber:
print('Your guess is too high')
else:
break # You guessed it correctly
if (guess == secretNumber):
print('You guessed the number in ' + str(guessNumber) + ' turns !!!')
else:
print('Sorry, the number I was thinking of was' + str(secretNumber))
|
c135056bed0f66848b3af330c8e0c3756d1f09e2 | Marcela20/rosalind_problems | /PERM.py | 278 | 3.53125 | 4 | from itertools import permutations
symbols = []
for i in range(1, 6 + 1):
symbols.append(i)
perm = permutations(symbols)
counter = 0
a = ''
for i in list(perm):
counter += 1
for j in i:
a += str(j)
a += " "
print(a)
a = ''
print(counter)
|
0b6bbfc27f2b8ccfe9bc9415c72f94314ddebd26 | cgm1904443271/iscgm | /PaChong/01-作业-豆瓣.py | 1,172 | 3.515625 | 4 |
# 作业1 : 分页获取豆瓣的数据(json数据), 把电影图片存入本地,且图片名取电影名
# url = "https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start="+ str(i * 20)+"&limit=20"
import json
import urllib.request
import os
path = r'/home/misaka/PycharmProjects/PaChong/day02/img'
headers = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'
}
x = 0
for i in range(1, 3):
url = "https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=" + str(i * 20) + "&limit=20"
req = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(req)
context = response.read().decode()
json_list = json.loads(context)
# print(json_list)
# print(cover_url)
for item in json_list:
cover_url = item['cover_url']
file_name = item['title']
x += 1
urllib.request.urlretrieve(cover_url,'/home/misaka/PycharmProjects/PaChong/day02/img/'+file_name+'.jpg')
print(x,'下载中')
|
8d69bb09c9f663a9b37d17774c38e1a8bbe3c34e | sujanghadi/Python-programs | /recursion.py | 554 | 3.984375 | 4 |
#iterative method
'''def fact(n):
fac=1
for i in range(n):
fac=fac*(i+1)
return fac
a=fact(4)
print(a)
#using recursive function
def fact(n):
if n==1:
return 1
else:
return n * fact(n-1)
print(fact(5))
def fib(n):
a=0
b=1
for i in range(2,n):
c=a+b
a=b
b=c
print(c,end=' ')
fib(8)'''
def fib(n):
if n==1:
return 1
elif n==2:
return 2
elif n>2:
return fib(n-1) + fib(n-2)
for i in range(1,10):
print(fib(i),end=" ")
|
02ddfc5ecfb03acc967acb7a8a8fb3f985c12dcb | rlorenzini/friday1 | /algorithms.py | 1,020 | 4 | 4 | #remove duplicates from arrays
list_one = [1,2,3,4,5,6,7,8,9,0]
list_two = [1,3,6,9,0]
list_three = []
for value in list_one:
if value in list_two:
next
else:
list_three.append(value)
print(list_three)
#find largest element in array
list1 = [1,2,3,4,5,6,7,8,9,99,99999]
max = 0
for i in list1:
if i > max:
max=i
print(max)
#find smallest element in array
list2 = [1,2,3,4,5,6,7,8,9,9,9,9,999,99,999,1234567]
min = list2[0]
for x in list2:
if x < min:
min=x
print(min)
#duplicate an array
try_to_dup = [1,2,3,4,5]
#want result {[1,2,3,4,5,1,2,3,4,5]}
for dup in range(0,len(try_to_dup),1):
try_to_dup.append(dup+1)
print(try_to_dup)
a = [1,2,3,4,5]
b = a + a
print(b)
#create tree with *
#character count 9*2-1
#stars = line number *2 -1
count = 1
lines = 9
white_space = " "
star_symbol = "*"
while count <= lines:
space = (lines - count)
stars = count * 2 - 1
print(f'{white_space*space}{star_symbol*stars}{white_space*space}')
count = count + 1
|
83184dddcfb24e092d4459e568c4f87602568ddf | skylerberg/ASTeditor | /ASTeditor/test.py | 166 | 3.640625 | 4 |
def fizzbuzz():
for i in range(1, 101):
if (i % 3):
print 'fizz',
if (i % 5):
print 'buzz',
print ''
fizzbuzz()
|
462d1960fe92acd0b8b024e264697f40a1954487 | jmg6033/encryptor | /encryptor.py | 625 | 3.640625 | 4 | from cryptography.fernet import Fernet
def getMessage():
plaintextMessage = raw_input("What is the message you would like to encrypt?")
return plaintextMessage
def generateKey():
key = Fernet.generate_key()
#print "Your symetric key is "+ key + " guard it with your life!"
return key
generateKey()
cipherSuite = Fernet(generateKey())
cipherText=cipherSuite.encrypt(getMessage())
def decrypt():
decryptedText = cipherSuite.decrypt(cipherText)
return decryptedText
print "this is your encrypted version of the message " + cipherText
print "this is the message back in plaintext" + decrypt() |
06e90d18c6866f14f0ed3ca6380ecd62425869b8 | Revold1/PJC-CS | /exercises/pc06-game-linked-list/task_3.py | 2,092 | 3.578125 | 4 | from linkedlist import LinkedList
SCORE_LIST = LinkedList()
with open("GAME.dat", 'r') as infile:
for line in infile:
player_id, score = line[:-1].split()
SCORE_LIST.add(player_id.lower(), score)
def val_rank_range(rank_range, linkedlist):
try:
lower, upper = rank_range.split('-') # check correct format ("X-Y")
except:
return False
if (lower.isdigit() and upper.isdigit()
and int(lower) > 0 and int(upper) > 0
and int(lower) < int(upper)
and int(upper) <= linkedlist.get_max_rank()):
return True
else:
return False
def display_rank(linkedlist):
if linkedlist.isEmpty():
print("- List is empty -")
return # EXIT
while True:
rank_range = input("Enter a rank range (e.g. 1-3): ")
if not val_rank_range(rank_range, linkedlist):
print("\n- Invalid input -\n")
else:
break
ranked_list = [] # list of tuples [(rank1, player1), (rank2, player2),...]
rank_count = {} # {rank1:count1, rank2:count2,...}
lower, upper = [int(i) for i in rank_range.split('-')]
current = linkedlist.head
while current is not None:
current_rank = linkedlist.get_rank(current.id)
if current_rank >= lower and current_rank <= upper:
ranked_list.append((current_rank, current.id))
rank_count[current_rank] = rank_count.get(current_rank, 0) + 1
elif current_rank > upper:
break
current = current.next
# display rank & player ID header
print("\n{0:^10}{1}{2:^15}".format("Rank", '|', "Player ID"))
print('-'*25)
# display rank & player ID
for data in ranked_list:
print("{0:^10}{1}{2:^15}".format(data[0], '|', data[1]))
print()
# display rank count header
print("{0:^25}".format("Count"))
print('-'*25)
# display rank count
for rank in range(lower, upper+1):
if rank in rank_count:
print("Rank #{0}: {1}".format(rank, rank_count[rank]))
# display_rank(SCORE_LIST)
|
9124dfacd1450ec99ec52abc140b79b7ceaaa1e2 | ajitnak/py_pgms_tree | /num_bsts.py | 1,031 | 3.8125 | 4 | def NumberOfBST(root):
# Base case
if (root == None):
return 0, INT_MIN, INT_MAX, True
# If leaf node then return from function and store
# information about the leaf node
if (root.left == None and root.right == None):
return 1, root.data, root.data, True
# Store information about the left subtree
L = NumberOfBST(root.left)
# Store information about the right subtree
R = NumberOfBST(root.right)
# Create a node that has to be returned
bst = [0]*4
# If whole tree routed under the current root
# is BST
if (L[3] and R[3] and root.data > L[1] and root.data < R[2]):
bst[2] = min(root.data, (min(L[2], R[2])))
bst[1] = max(root.data, (max(L[1], R[1])))
# Update the number of BSTs
bst[0] = 2 + L[0] + R[0]
return bst
# If the whole tree is not a BST,
# update the number of BSTs
bst[3] = False
bst[0] = 1 + L[0] + R[0]
return bst
|
08371aa6a6cd93c4bd6fd5c3c52201d127806477 | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190427/book_136.py | 594 | 3.859375 | 4 |
a = [1,2,3,4]
##result = []
##for num in a:
## result.append(num*3)
##print(result)
# 이건 위의 코드를 한줄로...
##result = (num * 3 for num in a)
##print(result)
##print(type(result))
##for i in result:
## print(i)
# 짝수인것만 만들어서 list로 만든다.,
##result = [num * 3 for num in a if num % 2 == 0]
##print(result)
##print(type(result))
##for i in result:
## print(i)
#내포로 만들어지는 리스트도 중첩으로 만들수 있음.
result = [x*y for x in range(2,10)
for y in range(1,10)]
print(result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.