blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b934bdcd25d1f38e90d97241c00a92c82a85160e | srisaipog/ICS4U-Classwork | /Learning/Algorithms/Search/Binary VS Linear/main.py | 1,211 | 3.9375 | 4 | """
Complete the provided spreadsheet by changing the values in this program
according to the spreadsheet and record the results.
"""
import timeit
from typing import List
def linear_search(target: int, data: List) -> int:
for i, num in enumerate(data):
if num == target:
return i
return -1
def binary_search(find: int, numbers: List[int]) -> int:
first = 0
last = len(numbers) - 1
mid = last + first // 2
while True:
not_found = (last - first) <= 0
if not_found:
return -1
if numbers[mid] == find:
return mid
elif numbers[mid] > find:
last = mid
mid = (last + first) // 2
elif numbers[mid] < find:
first = mid
mid = (last + first) // 2
for i in range(1, 12):
DATASET_SIZE = 10**i
NUMBER = 10
SEARCH_TARGET = DATASET_SIZE - 1
# SEARCH_TARGET = 0
# SEARCH_TARGET = DATASET_SIZE // 2
# dataset = list(range(DATASET_SIZE))
dataset = list(range(DATASET_SIZE))
result = timeit.timeit(
"binary_search(SEARCH_TARGET, dataset)",
number=NUMBER,
globals=globals())
print(result) |
6d72ca5f0317d5bef54078bc91fbc9003d05ef8a | Takkoyanagi/playground | /leetcode/reverse_linkedlist.py | 471 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
self.prev = None
self.curr = head
while (self.curr != None):
self.nextTemp = self.curr.next
self.curr.next = self.prev
self.prev = self.curr
self.curr = self.nextTemp
return self.prev
|
f69676f8c3d40905eeaac153e174f564cbc0e6a7 | JaiJun/Codewar | /7 kyu/Highest and Lowest.py | 1,043 | 4.21875 | 4 | """
In this little assignment you are given a string of space separated numbers,
and have to return the highest and lowest number.
Example:
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"
Notes:
All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space, and highest number is first.
I think best solution:
def high_and_low(numbers):
nn = [int(s) for s in numbers.split(" ")]
return "%i %i" % (max(nn),min(nn))
https://www.codewars.com/kata/554b4ac871d6813a03000035
"""
def high_and_low(numbers):
Result = []
for i in numbers.split():
Result.append(int(i))
Result = sorted(Result)
return str(Result[-1]) + " " + str(Result[0])
if __name__ == '__main__':
input = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
high_and_low(input)
|
1e24f12e4f1cc916d28f4e7f2dcbc89ab63cf2ac | irenenikk/advent-of-code-18 | /5/5.2.py | 883 | 3.671875 | 4 | import re
inputs = open("input.txt", "r").read()
# add each character to stack
# with a new character, check if reacts with the top element of stack
def react(a, b):
if a.isupper() and a.lower() == b:
return True
if b.isupper() and b.lower() == a:
return True
return False
def react_polymer(inputs):
stack = list()
for char in inputs:
if (len(stack) == 0):
stack.append(char)
continue
# peek stack
top = stack[-1]
if react(char, top):
stack.pop()
else:
stack.append(char)
return len(stack)
chars = set()
min_length = len(inputs)
[ chars.add(char.lower()) for char in inputs]
for char in chars:
cleaned_input = re.sub('['+ char + char.upper() +']', '', inputs)
min_length = min(min_length, react_polymer(cleaned_input))
print(min_length) |
958ab7b44ece1d8b84bf8daf79aec5b3e90c6af1 | mcdy143/datamining | /clustering/clustering2.py | 5,342 | 3.53125 | 4 | # k-means clustering
# Daniel Alabi and Cody Wang
import math
import random
from heapq import *
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import spline
# selects centers using the "refined cluster centers"
# algorithm which clusters a random sample of the data
# n times (n=50 in this case) and then clusters
# the resulting centers
def selcentersfancy(data, k):
allcenters = []
for i in range(50):
# grab a random sample of size,
# a 10th of the size of the original dataset
randomdata = [data[int(random.random()*(len(data)-1))] for j in range(len(data)/10)]
(sse, centers, clusters) = kmeans(randomdata, k, 1)
for j in range(len(centers)):
if centers[j] not in allcenters:
allcenters.append(centers[j])
(sse, centers, clusters) = kmeans(allcenters, k, 1)
return centers
# selects centers randomly
def selcentersrand(data, k):
minmaxattrs = [(min([row[j] for row in data]), max([row[j] for row in data])) \
for j in range(1, 5)]
return [[mini+random.random()*(maxi-mini) for (mini, maxi) in minmaxattrs] for i in range(k)]
# returns the euclidean squared distance
# between point1 and point2
def euclideansq(point1, point2):
return sum([(point1[i]-point2[i])**2 for i in range(1, 5)])
# returns (centers, clusters)
# where centers (centroids, in this case) are the final centers of the
# k-means clustering
# and clusters is a list of size k
# where clusters[i] -> cluster corresponding to centers[i]
def kmeans(data, k, method):
if method == 1:
centers = selcentersrand(data, k)
# make selected centers look like rows of data
for center in centers:
center.insert(0, "")
else:
centers = selcentersfancy(data, k)
lastclusters = None
while True:
clusters = [[] for i in range(k)]
# heap used to store the SSE for each point
pointerrors = []
# assign points to the closest center
for i in range(len(data)):
row = data[i]
closest = 0
closestdist = euclideansq(centers[closest], row)
for j in range(len(centers)):
d = euclideansq(centers[j], row)
if d < euclideansq(centers[closest], row):
closest = j
closestdist = d
clusters[closest].append(i)
# use pointerrors as a max heap to get
# the points with the most error
heappush(pointerrors, (-closestdist, i))
emptyclusterfound = False
# get indices for all empty clusters
for i in range(len(clusters)):
if len(clusters[i]) == 0:
(error, rowindex) = heappop(pointerrors)
centers[i] = data[rowindex]
clusters[i] = [rowindex]
emptyclusterfound = True
if lastclusters == clusters and not emptyclusterfound: break
lastclusters = clusters
# re-calculate the new cluster centers (centroids)
for i in range(k):
cluster = clusters[i]
centers[i] = [sum([data[rowindex][j] for rowindex in cluster])/float(len(cluster)) for j in range(1, 5)]
# make centers "look like" actual data points
centers[i].insert(0, "")
sse = sum([-x for (x, y) in pointerrors])
sse = sum([-x for (x, y) in pointerrors])
# clusters[i] corresponds to the row indices of the data
# belonging to the ith cluster
return (sse, centers, clusters)
# Calculates the Euclidean magnitude of the line
def euclidean(line):
return math.sqrt(sum([int((line[i]))**2 for i in range(1, 5)]))
if __name__=="__main__":
f = open("wp_namespace.txt")
cols = f.readline().split()
data = []
for line in f:
newline = line.strip().split('\t')
euclideansum = euclidean(newline)
newline[1] = float(newline[1])/euclideansum
newline[2] = float(newline[2])/euclideansum
newline[3] = float(newline[3])/euclideansum
newline[4] = float(newline[4])/euclideansum
data.append(newline)
# print data
k = int(raw_input("Enter the value for k: "))
print "Choose the method you wish to use to select initial cluster centers"
method = int(raw_input("Enter 1 for random, 2 for fancy (farthest from closest center): "))
(sse, finalcenters, clusters) = kmeans(data, k, method)
for i in range(len(finalcenters)):
print "=============Center============"
print finalcenters[i]
print "================================"
for j in clusters[i]:
print data[j]
print "================================"
print "total sse: "
print sse
sses = []
kvalues = range(1, 21)
for k in kvalues:
sses.append(kmeans(data, k, 2)[0])
# ============= Code to Plot kvalues against Percentage Correct ========== #
xdata = np.array(kvalues)
ydata = np.array(sses)
plt.xlabel("k-values")
plt.ylabel("SSE")
xnew = np.linspace(xdata.min(), xdata.max(), len(kvalues)*5)
ysmooth = spline(xdata, ydata, xnew)
plt.plot(xnew, ysmooth)
plt.show()
# ==================================================================#
|
0ae2d97e4a316b5f51b1b17935dc4b569376fec6 | NidhiSingh0068/Open-CV--Computer-Vision | /chapter5.py | 511 | 3.59375 | 4 | ##Size of Image
import cv2
import numpy as np
img = cv2.imread("Resources/lam.jpg")
print(img.shape) #shape of image (183, 275, 3)
imgResize = cv2.resize(img, (150, 100))
print(imgResize.shape) #resizing an image -increase or decrease
imgCropped = img[0:100,200:275] #Cropping an image - (height[starting point:Ending point],width[starting point:Ending point])
cv2.imshow("Image", img)
cv2.imshow(" Resized Image", imgResize)
cv2.imshow("Cropeed Image", imgCropped)
cv2.waitKey(0) |
55f67ed4143042d359c567d14b8592fb94131b92 | AFatWolf/cs_exercise | /9.3. Exercises/Q6.py | 122 | 3.609375 | 4 | def checkList(l):
if len(l):
return "List is not empty"
return "List is empty"
l = [1]
print(checkList(l)) |
08c76392ebcb8bf75c441d0823d3d6afa09ae8bc | kineugene/lessons-algorithms | /lesson-2/task_6.py | 1,089 | 3.5625 | 4 | import random
import sys
from time import sleep
if __name__ == '__main__':
print("У вас есть 10 попыток, чтобы угадать число от 0 до 100. "
"После каждой попытки будет подсказка, больше или меньше указанного загаданное число.")
number = random.randint(0, 100)
for i in range(10):
guess = int(input(f"У вас осталось {10 - i} попыток. Введите число:\n"))
if guess == number:
print(f"Верно! Это число {guess}. ")
break
elif i == 9:
print(f"Жаль, но попытки кончились. Загаданное число: {number}. ")
else:
print(f"Мимо) Загаданное число {'больше' if guess < number else 'меньше'} указанного.")
for i in range(6):
sleep(1)
sys.stdout.write(f"\rПрограмма завершится через {5 - i} сек.")
sys.stdout.flush()
|
941fca493d53154e40bc155aa23ba7d47c29917c | Libardo1/TemperaturePrediction | /Weather.py | 9,957 | 3.84375 | 4 | '''
Created on Feb 11, 2012
@author: Andrew Taber
'''
## Workflow:
## 1. Take filename argument and open a file, read from file
## 2. Process the data in the file (i.e. organize data by grouping by location in a list indexed by date, then aggregating into dictionary of locations)
## 3. On each location's dataset, perform linear regression to find linear trend
## 4. To the linear trend add seasonal variations as learned from data of previous years
## 5. Aggregate location data into new dictionary containing predictions
## 6. Convert the dictionary into CSV format as in input
## Assuming temperature data has both a seasonal component and a linear trend (due to climate change), the better model would take both
## into account. We further assume that while there might be a linear trend in temperatures, the average distance of temperature from the
## regression line as a function of seasonal position (where in the year a day falls) is approximately constant in the long term.
## As a result, we calculate the prediction for next year's data by first calculating where the linear regression predicts the temperature
## should be, and then taking into account seasonal factors by adding the expected distance from the regression line. The expected distance
## is calculated as an exponentially weighted
import sys
import numpy
import math
import matplotlib.pyplot as plt
def get_total_lines(filename):
"""Finds the total number of lines in a file given a filename as a parameter
Input :: String
Output :: Integer"""
csvfile=open(filename,'r')
numberOfLines=len(csvfile.readlines())
csvfile.close()
return numberOfLines
def get_location_dict(filename):
"""Converts CSV formatted file into a dictionary whose keys are column indices,
and whose values are lists of values for a given column.
Input :: CSV formatted file
Output :: Dictionary whose keys are integers and whose values are lists
TODO: Catch exceptions if dataset is not formatted correctly, is wrong size, etc."""
print "Calculating database size..."
filelength = get_total_lines(filename)
print "Dataset has %i points" %filelength
print "Beginning Calculations: \n"
csvfile=open(filename,'r')
locations={}
nextline=csvfile.readline()
current_line_number=0
current_percent_completed=0
print "Organizing dataset by location and date"
while nextline != '':
for i in range(1,len(nextline.split(','))):
if i not in locations.keys():
locations[i]=[int(nextline.split(',')[i])]
elif i != len(nextline.split(','))-1:
locations[i]+=[int(nextline.split(',')[i])]
else:
locations[i]+=[int(nextline.split(',')[i])]
#Move on to next line, update progress, log to user current percentage completed
nextline = csvfile.readline()
current_line_number+=1
log_percent(current_percent_completed,math.floor(100*current_line_number/filelength))
current_percent_completed=math.floor(100*current_line_number/filelength)
print "Dataset successfully organized! \n"
return locations
def log_percent(oldpercentage,newpercentage):
if oldpercentage == newpercentage:
pass
else:
print "Percent Completed: %i" %newpercentage
def get_linear_regression_coefficients(datelist):
"""Obtains the linear trend coefficient by a least squares method.
Takes a list of numbers as an input, and returns a tuple consisting of
the slope and intercept of the regression line.
Input :: List of integers or floats
Output :: Tuple of floats"""
x = numpy.arange(len(datelist))
y = numpy.array(datelist)
A = numpy.vstack([x,numpy.ones(len(x))]).T
m, c= numpy.linalg.lstsq(A,y)[0]
return (m,c)
def get_regression_line(datelist):
"""Uses parameters found from get_linear_regression_coefficients to
get datapoints for the regression line.
Input :: List of integers or floats
Output :: numpy array of regression line fit to data"""
x = numpy.arange(len(datelist))
m, c = get_linear_regression_coefficients(datelist)
return m*x+c
def get_previous_average_diff(datelist,date_number,width=10,weight_factor=.8):
"""Averages the values for previous years by taking **width** amounts of days
from previous years approximately centered at **date_number** and averaging the
distance between these values and the regression line at that time.
The average from previous years is exponentially weighted, so older data gets much less weight.
Input :: Datelist - list of numbers; Date_number - a number signifying the position in the year of the
date we're interested in; Width - number specifying how many days we should average over;
Weight_factor - number between 0 and 1 that changes how quickly we 'forget' about older data.
Output :: Integer or float"""
t = date_number
reg_line = get_regression_line(datelist)
difference_list = []
while t < len(datelist):
if t-width/2 < 0:
difference = reg_line[t] - numpy.average(datelist[0:t+width/2])
difference_list += [difference]
elif t+width/2 > len(datelist):
difference = reg_line[t] - numpy.average(datelist[t-width/2:])
difference_list += [difference]
else:
difference = reg_line[t] - numpy.average(datelist[t-width/2:t+width/2])
difference_list += [difference]
t+= 365 #Move on to same time next year
weight_list = []
for i in range(0,len(difference_list)):
weight_list+= [weight_factor**-(i+1)]
weight_list.reverse() #So more recent values get more weight
difference_average = numpy.average(difference_list,weights=weight_list)
return difference_average
def get_prediction(datelist,date_number):
"""Given a list of numbers and a number specifying the position of the date whose value we're interested in,
returns the prediction of the value on that date
Input :: Datelist - list of numbers; date_number - integer
Output :: Float or integer"""
reg_line = get_regression_line(datelist)
previous_average = get_previous_average_diff(datelist,date_number)
prediction = reg_line[date_number] + previous_average
return prediction
def get_next_year_data(datelist):
"""Given a list of values, predict the values for a whole year
Input :: List of numbers
Output :: List of numbers"""
new_year_values = []
for t in range(1,366):
new_year_values+= [get_prediction(datelist,t)]
return new_year_values
def predict(filename,plot=False):
"""Given a filename, retrieve the value data from file and predict the next year's values
for each location.
Input :: String; Optional Boolean
Output :: Prints to STDOUT """
prediction = {}
location_dict = get_location_dict(filename)
print "Beginning prediction algorithm: \n"
for location_number, location_data in location_dict.iteritems():
print "Calculating prediction for location number %i" %location_number
prediction[location_number] = get_next_year_data(location_data)
print "Prediction algorithm successfully terminated! \n"
if plot:
plt.plot(prediction[2])
plt.show()
to_csv_format(prediction)
def to_csv_format(location_dict):
"""Converts our dictionary formatted data into CSV format like the input file to Weather.py.
Is the inverse of get_location_dict().
Input :: Dictionary
Output :: None (Writes to STDOUT)"""
print "Writing CSV Output..."
csv_string = ""
for i in range(0,365):
Date_name= "2010-" + get_posix_date(i+1)
csv_string+= Date_name + ',' #Print date as first entry to line
csv_string+= write_csv_line(location_dict,i)
print csv_string
def write_csv_line(dictionary,index):
"""Helper function to modularize the inversion process from dictionary to CSV file"""
csv_line=''
for i in range(1,len(dictionary.keys())):
if i< len(dictionary.keys())-1:
csv_line+= str(dictionary[i][index]) + ","
else:
csv_line+= str(dictionary[i][index]) + "\n"
return csv_line
def get_posix_date(i):
"""Convert a number signifying position in the year into POSIX %M-%D format
Input :: Integer
Output :: String"""
assert(type(i)==int)
if i < 10:
i = "0%s"%i
if i <= 31:
return "01-%s"%i
elif i <= 59:
i= int(i)-31
return "02-%s"%i
elif i <= 90:
i= int(i)-59
return "03-%s"%i
elif i <= 120:
i= int(i)-90
return "04-%s"%i
elif i <= 151:
i=int(i)-120
return "05-%s"%i
elif i <= 181:
i=int(i)-151
return "06-%s"%i
elif i <= 212:
i=int(i)-181
return "07-%s"%i
elif i <= 243:
i=int(i)-212
return "08-%s"%i
elif i <= 273:
i= int(i)-243
return "09-%s"%i
elif i <= 304:
i= int(i)-273
return "10-%s"%i
elif i <= 334:
i= int(i)-304
return "11-%s"%i
else:
i= int(i)-334
return "12-%s"%i
def test():
#loc_dict=get_location_dict(sys.argv[1])
#to_csv_format(loc_dict)
#plt.plot(get_regression_line(loc_dict[1]))
#plt.plot(loc_dict[1])
#plt.show()
#print get_regression_line(loc_dict[1])
#print len(get_regression_line(loc_dict[1]))
predict(sys.argv[1],plot=True)
if __name__ == '__main__':
predict(sys.argv[1]) |
817bc4ff4d5f7a70c25ab577fad34d42e9e69399 | 0x1701/Python_intro | /analyze_mdout.py | 1,107 | 3.828125 | 4 | import os
import argparse
#to open the file for reading
# tell argparse to handle arguments
parser = argparse.ArgumentParser(description="parsers amber mdout files to extract total energy.")
#Tell argparse what argument to expect
parser.add_argument("path", help="The filepath to the file.")
#Get arguments from the user
args = parser.parse_args()
filename = args.path
f = open(filename, 'r') # r is for open the file FOR reading
# then read data in the file
data = f.readlines()
f.close()
#once you read the data, you close the file
#open a file for writing
base_filename = filename.split('.')[0]
output_filename = F'{base_filename}_Etot.txt'
f_write = open(output_filename, 'w+') # this will create a new file with name
print(F'Writing output to {output_filename}')
f_write.write('Total Energy\n')
etot = []
# loop through lines in the file
for line in data:
split_line = line.split()
# get info from line
if 'Etot' in line:
# Write info into file
etot.append(split_line[2])
etot = etot[:-2]
for energy in etot:
f_write.write(F"{energy}\n")
f_write.close()
|
9dca946da68c7d677e563459d1d47e61ff7fe645 | manhtung2111/Dictionary_Excercises | /Try_Except_Exercises.py | 207 | 3.5 | 4 | try:
print(x)
print("Hello World")
print("Em tên là Ngô Mạnh Tùng")
except:
print("sai mẹ r :))))")
else:
print("Cứ tiếp tục in :))")
finally:
print("Em chào các anh các chị") |
149605d4a282d55ea7d823da465a2cacc5d096f3 | jadenpadua/ICPC | /core/trees/deserialize-serialize-bst.py | 1,221 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Codec:
def serialize(self, root):
return self.serializeHelper(root)
def deserialize(self, data):
serialized_arr = data.split(',')
print(serialized_arr)
q = queue.Queue()
for i in range(len(serialized_arr)):
q.put(serialized_arr[i])
return self.deserializeHelper(q)
def deserializeHelper(self,q):
nodeValue = q.get()
if nodeValue == 'X':
return None
newNode = TreeNode(nodeValue)
newNode.left = self.deserializeHelper(q)
newNode.right = self.deserializeHelper(q)
return newNode
def serializeHelper(self,node):
if node is None:
return 'X'
return str(node.val) + ',' + self.serializeHelper(node.left) + ',' + self.serializeHelper(node.right)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
|
f69df9cf0ead6e28ca9d56cb181d95f893416f80 | grudus/AdventOfCode2020 | /src/main/python/day03.py | 1,002 | 3.53125 | 4 |
from operator import mul
from functools import reduce
def first_star(forest):
return traverse_forest(forest, (3, 1))
def second_star(forest):
slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
trees = [traverse_forest(forest, slope) for slope in slopes]
return reduce(mul, trees)
def traverse_forest(forest, slope):
(dx, dy) = slope
current_coord = (0, 0)
forest_size_y = len(forest)
forest_size_x = len(forest[0])
num_of_trees = 0
while current_coord[1] < (forest_size_y - dy):
next_coord = (current_coord[0] + dx, current_coord[1] + dy)
if next_coord[0] >= forest_size_x:
next_coord = (next_coord[0] - forest_size_x, next_coord[1])
if forest[next_coord[1]][next_coord[0]] == '#':
num_of_trees += 1
current_coord = next_coord
return num_of_trees
forest = open('src/main/resources/day03/input.txt', 'r').read().split("\n")
print(first_star(forest))
print(second_star(forest))
|
915c93e79e7791e5b715ae2b37cc91f974a3d7be | WangYihang/CrackMe | /templates/keygen.py | 724 | 3.5625 | 4 | #!/usr/bin/env python
# encoding:utf-8
import sys
def check_password(username, password):
v2 = 0
v7 = 0
for k in password:
v7 = v2
v3 = 0
if (k > ord("0")) and (k < ord("9")):
v3 = 1
v5 = v7
if v3 == 1:
break
v5 = ord(i) - 48
v2 = 10 * v5
print v5
def get_password(username):
password = ""
print password
def show_help():
print "Usage : \n\tpython %s [username]" % sys.argv[0]
def main():
# if len(sys.argv) != 2:
# show_help()
# exit(1)
# get_password(sys.argv[1])
check_password("admin", "123456")
if __name__ == "__main__":
main()
|
d8ce8dbb879999bd81a0e9eda8398c434b3b5501 | qmnguyenw/python_py4e | /geeksforgeeks/algorithm/easy_algo/5_15.py | 22,463 | 3.65625 | 4 | Dividing a Large file into Separate Modules in C/C++, Java and Python
If you ever wanted to write a large program or software, the most common
rookie mistake is to jump in directly and try to write all the necessary code
into a single program and later try to debug or extend later.
This kind of approach is doomed to fail and would usually require re-writing
from scratch.
So in order to tackle this scenario, we can try to divide the problem into
multiple subproblems and then try to tackle it one by one.
Doing so, not only makes our task easier but also allows us to achieve
**Abstraction** from the high-level programmer and also promotes **Re-
usability** of code.
If you check any Open-Source project from either GitHub or GitLab or any other
site of the likes, we can see how the large program is “decentralized” into
many numbers of sub-modules where each individual module contributes to a
specific critical function of the program and also various members of the Open
Source Community come together for contributing or maintaining such file(s) or
repository.
Now, the big question lies in how to “break-down” not theoretically but
**PROGRAMMATICALLY**.
We will see some various types of such divisions in popular languages such as
C/C++, Python & Java.
* ### Jump to C/C++
* ### Jump to Python
* ### Jump to Java
## C/C++
For Illustrative Purposes,
Let us assume we have all the basic **Linked List insertions** inside one
single program. Since there are many methods (functions), we cannot clutter
the program by writing all the method definitions above the obligatory main
function. But even if we did, there can arise the problem of ordering the
methods, where one method needs to be before another and so on.
So to solve this problem, we can declare all the prototypes at the beginning
of the program, followed by the main method and below it, we can define them
in any particular order:
**Program:**
## FullLinkedList.c
__
__
__
__
__
__
__
// Full Linked List Insertions
#include <stdio.h>
#include <stdlib.h>
//--------------------------------
// Declarations - START:
//--------------------------------
struct Node;
struct Node* create_node(int data);
void b_insert(struct Node** head, int data);
void n_insert(struct Node** head, int data, int pos);
void e_insert(struct Node** head, int data);
void display(struct Node* temp);
//--------------------------------
// Declarations - END:
//--------------------------------
int main()
{
struct Node* head = NULL;
int ch, data, pos;
printf("Linked List: \n");
while (1) {
printf("1.Insert at Beginning");
printf("\n2.Insert at Nth Position");
printf("\n3.Insert At Ending");
printf("\n4.Display");
printf("\n0.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch;);
switch (ch) {
case 1:
printf("Enter the data: ");
scanf("%d", &data;);
b_insert(&head;, data);
break;
case 2:
printf("Enter the data: ");
scanf("%d", &data;);
printf("Enter the Position: ");
scanf("%d", &pos;);
n_insert(&head;, data, pos);
break;
case 3:
printf("Enter the data: ");
scanf("%d", &data;);
e_insert(&head;, data);
break;
case 4:
display(head);
break;
case 0:
return 0;
default:
printf("Wrong Choice");
}
}
}
//--------------------------------
// Definitions - START:
//--------------------------------
struct Node {
int data;
struct Node* next;
};
struct Node* create_node(int data)
{
struct Node* temp
= (struct Node*)
malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
return temp;
}
void b_insert(struct Node** head, int data)
{
struct Node* new_node = create_node(data);
new_node->next = *head;
*head = new_node;
}
void n_insert(struct Node** head, int data, int pos)
{
if (*head == NULL) {
b_insert(head, data);
return;
}
struct Node* new_node = create_node(data);
struct Node* temp = *head;
for (int i = 0; i < pos - 2; ++i)
temp = temp->next;
new_node->next = temp->next;
temp->next = new_node;
}
void e_insert(struct Node** head, int data)
{
if (*head == NULL) {
b_insert(head, data);
return;
}
struct Node* temp = *head;
while (temp->next != NULL)
temp = temp->next;
struct Node* new_node = create_node(data);
temp->next = new_node;
}
void display(struct Node* temp)
{
printf("The elements are:\n");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
//--------------------------------
// Definitions - END
//--------------------------------
---
__
__
**Compiling the code:** We can compile the above program by:
gcc linkedlist.c -o linkedlist
And it works!
**Underlying problems in the above code:**
We can already see the underlying problem(s) with the program, the code is not
at all easy to work with, neither individually nor in a group.
If someone would want to work with the above program, then some of the many
problems faced by that person are:
1. **Need to go through the Full source file** to improve or enhance some functionality.
2. **Cannot easily re-use** the program as a framework for other project(s).
3. **Code is very cluttered** and not at all appealing making it Very Difficult to navigate through the code.
In case of group project or large programs, the above approach is guaranteed
to enhance the overall expenditure, energy and failure rate.
**The Correct Approach:**
We see these lines starting in every C/C++ program which starts with “#include
”.
This means to include all the functions declared under the “library” header
**(.h files)** and defined possibly in **library.c/cpp** files.
These lines are processed by pre-processor during compilation.
We can manually try to create such a library for our own purpose.
**Important things to remember:**
1. “.h” files contain only Prototype declarations (such as Functions, Structures) and global variables.
2. “.c/.cpp” files contain the real implementation (Definitions of declaration in the header files)
3. When compiling all the source files together, make sure there are no multiple definitions of a same functions, variable etc. for the same project. (VERY IMPORTANT)
4. Use **static functions** to restrict to the file where they are declared.
5. Use **extern** keyword to use variable(s) that reference external files.
6. If using C++, be careful about namespaces always use **namespace_name::function()** to avoid collision.
**Dividing the program into smaller codes:**
Looking into the above program, we can see how this large program can be
divided into suitable small parts and then easily worked on.
The above program has essentially 2 main functions:
1) Create, Insert and store data into Nodes.
2) Display the Nodes
So I can divide the program accordingly such that:
1) Main File -> Driver program, Nice Wrapper of the Insertion Modules and
where we use the additional files.
2) Insert -> The Real Implementation Lies here.
Keeping the mentioned Important Points in mind, the program is divided as:
> **linkedlist.c** -> Contains Driver Program
> **insert.c** -> Contains Code for insertion
>
> **linkedlist.h** -> Contains the necessary Node declarations
> **insert.h** -> Contains the necessary Node Insertion Declarations
In each header file, we start with:
#ifndef FILENAME_H
#define FILENAME_H
Declarations...
#endif
The reason we write our declarations in between the **#ifndef, #define and
#endif** is to prevent multiple declarations of identifiers such as data
types, variables etc. when the same header file is invoked in new file
belonging to the same project.
For this Sample Program:
**insert.h** -> Contains Node insertion’s declaration and also declaration of
Node itself.
One very important thing to remember is that compiler can see declarations in
header file but if you try to write code **INVOLVING** definition of the
declaration declared elsewhere, it will lead to error since compiler compiles
each .c file individually before the proceeding to the linking stage.
**linkedlist.h** -> A helper file that contains Node and it’s Display
declarations that is to be included for files that uses them.
**insert.c** -> Include the Node declaration via **#include “linkedlist.h”**
which contains the declaration and also all other definitions of methods
declared under insert.h.
**linkedlist.c** -> Simple Wrapper containing an infinite loop prompting user
to Insert Integer data at required position(s), and also contains the method
that displays the list.
**One final thing to keep in mind is that, mindless including files into each
other may result in multiple re-definition(s) and result in error.**
Keeping the above in mind should you carefully divide into suitable sub
programs.
## linkedlist.h
__
__
__
__
__
__
__
// linkedlist.h
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
struct Node {
int data;
struct Node* next;
};
void display(struct Node* temp);
#endif
---
__
__
## insert.h
__
__
__
__
__
__
__
// insert.h
#ifndef INSERT_H
#define INSERT_H
struct Node;
struct Node* create_node(int data);
void b_insert(struct Node** head, int data);
void n_insert(struct Node** head, int data, int pos);
void e_insert(struct Node** head, int data);
#endif
---
__
__
## insert.c
__
__
__
__
__
__
__
// insert.c
#include "linkedlist.h"
// "" to tell the preprocessor to look
// into the current directory and
// standard library files later.
#include <stdlib.h>
struct Node* create_node(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct
Node));
temp->data = data;
temp->next = NULL;
return temp;
}
void b_insert(struct Node** head, int data)
{
struct Node* new_node = create_node(data);
new_node->next = *head;
*head = new_node;
}
void n_insert(struct Node** head, int data, int pos)
{
if (*head == NULL) {
b_insert(head, data);
return;
}
struct Node* new_node = create_node(data);
struct Node* temp = *head;
for (int i = 0; i < pos - 2; ++i)
temp = temp->next;
new_node->next = temp->next;
temp->next = new_node;
}
void e_insert(struct Node** head, int data)
{
if (*head == NULL) {
b_insert(head, data);
return;
}
struct Node* temp = *head;
while (temp->next != NULL)
temp = temp->next;
struct Node* new_node = create_node(data);
temp->next = new_node;
}
---
__
__
## linkedlist.c
__
__
__
__
__
__
__
// linkedlist.c
// Driver Program
#include "insert.h"
#include "linkedlist.h"
#include <stdio.h>
void display(struct Node* temp)
{
printf("The elements are:\n");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
struct Node* head = NULL;
int ch, data, pos;
printf("Linked List: \n");
while (1) {
printf("1.Insert at Beginning");
printf("\n2.Insert at Nth Position");
printf("\n3.Insert At Ending");
printf("\n4.Display");
printf("\n0.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch;);
switch (ch) {
case 1:
printf("Enter the data: ");
scanf("%d", &data;);
b_insert(&head;, data);
break;
case 2:
printf("Enter the data: ");
scanf("%d", &data;);
printf("Enter the Position: ");
scanf("%d", &pos;);
n_insert(&head;, data, pos);
break;
case 3:
printf("Enter the data: ");
scanf("%d", &data;);
e_insert(&head;, data);
break;
case 4:
display(head);
break;
case 0:
return 0;
default:
printf("Wrong Choice");
}
}
}
---
__
__
Finally, we save all of them and compile as follows.
**gcc insert.c linkedlist.c -o linkedlist**
Voila, it compiled successfully, let’s just do a quick sanity check, just in
case:
**Output:**

It remains mostly same for C++ keeping aside usual language
feature/implementation changes.
## Python
Here it is not so difficult. Usually, the first thing to do is to create a
**virtual environment**. It is a must in order to prevent breaking of a bunch
of scripts due to various version dependencies and such. For eg, You might
want to use Version 1.0 of some module for one project, but this latest
version deprecated a feature that is available in 0.9 and you prefer to use
the old version for this new project or simply you want to upgrade libraries
without breaking old and existing projects. The solution is an isolated
environment for each separate project/script(s).
**How to instatll Virtual Env:**
Use **pip** or **pip3** to install **virtualenv** if not installed already:
**pip install virtualenv**
**Setting up Isolated Environment for each project/script:**
Next Navigate to some directory to store your projects and then:
> **virtualenv app_Name** # (Or)
> **virtualenv -p /path/to/py3(or)2.7 app_name** # For specific interpreter
> dependency
> **source app_name/bin/activate** # Start Working
> **deactivate** # To Quit
Now you can use pip to install all the desired modules and they act as
standalone to this isolated project and you don’t need to worry of system wide
script breaking. eg: With virtual env and source activated,
**pip install pip install pandas==0.22.0**
One important thing to do is to create an explicit empty file named:
**__init__.py**
This is done in order to treat the directory as containing package(s) and
access sub modules inside the directory. If you don’t create such a file,
Python will not explicitly look for sub-modules inside the project directory
and any attempt to access them gives an error.
**Importing the previously saved modules into new files:**
Now you can start importing the previously saved modules into new files in
either of the ways:
> **import module**
> **from module import submodule** # (or) from module.submodule import
> subsubmodule1, subsubmodule2
> **from module import *** # (or) from module.submodule import *
The First line allows you to access references via module.feature() or
module.variable.
The Second line allows you to access reference the mentioned specific module
directly. eg: feature()
The Third line allows you to access all references directly. eg: feature1(),
feature2() etc.
**Example of a single cluttered File:**
## Point.py
__
__
__
__
__
__
__
# point.py
class Point:
def __init__(self):
self.x = int(input ("Enter the x-coordinate: "))
self.y = int(input ("Enter the y-coordinate: "))
def distance (self, other):
return ((self.x - other.x)**2 + (self.y -
other.y)**2) ** 0.5
if __name__ == "__main__":
print("Point 1")
p1 = Point ()
print("\nPoint 2")
p2 = Point ()
print( "Distance between the 2 points is {:.4f}".format
(p1.distance(p2)))
---
__
__
The weird looking ‘ **if __name__ == “__main__”:** ‘ is used to prevent
execution of the code under it when imported in other modules.
We can simply abstract the Point Implementation to a separate file and use a
Main File to fulfill our exact requirement.
**Dividing the code into smaller parts:**
The Program can be divided such that:
1) Main File -> Driver program, Create, Manipulate and use Objects.
2) Point File -> All the methods we can define using a Point in the Cartesian
plane.
This sample program contains:
**Helper.py** -> Which consists of a Point class that contains methods such
as distance and also it consists of init method which helps auto-initialize
the required x and y variables.
**Main.py** -> Main Program that creates 2 objects and finds the distance
between them.
## Helper.py
__
__
__
__
__
__
__
# Helper.py
class Point:
def __init__(self):
self.x = int(input ("Enter the x-coordinate: "))
self.y = int(input ("Enter the y-coordinate: "))
def distance (self, other):
return ((self.x - other.x)**2 + (self.y -
other.y)**2) ** 0.5
---
__
__
## Main.py
__
__
__
__
__
__
__
# Main.py
from Helper import Point
def main ():
print("Point 1")
p1 = Point ()
print("\nPoint 2")
p2 = Point ()
print( "Distance between the 2 points is {:.4f}".format
(p1.distance(p2)))
main ()
---
__
__
**Output:**

## Java
It is similar to Python. Navigate to the new directory to save the project
files and in all of the sub program write:
**package app_name;**
On the starting line, and create a class as usual.
Import the module into new java program by again writing: package app_name and
simply reference that particular **module.function()** as they belong to same
package (are stored in same directory) and java implicitly adds the following
lines but if you need to import new module(s) from different package(s) then
do so by:
**import package.*;**
**import package.classname;**
**import static package.*;**
**Fully Qualified Name**
// eg: package.classname ob = new classname ();
The 1st and 2nd ways of look similar to python’s **from…import** syntax but
you have to explicitly state the class. In order to achieve such a not
recommended but pythonic way of **from…import** syntax style, you have to use
the 3rd method i.e., **import static** to achieve similar results but you have
to resort to using fully qualified name to prevent collisions and clear up
human misunderstandings anyway.
**Example of a single cluttered File:**
## Check.java
__
__
__
__
__
__
__
// Check.java
import java.util.*;
class Math {
static int check(int a, int b)
{
return a > b ? 'a' : 'b';
}
}
class Main {
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter value of a: ");
int a = s.nextInt();
System.out.print("Enter value of b: ");
int b = s.nextInt();
if (a == b)
System.out.println("Both Values are Equal");
else
System.out.printf("%c's value is Greater\n",
Math.check(a, b));
}
}
---
__
__
Once again there is scope of division and abstraction. We can create Multiple
standalone files that deal with the numerics and here for the example, We can
divide
**Dividing the code into smaller parts:**
The Program can be divided such that:
1) Main File -> Driver program, Write the Manipulative code here.
2) Math File -> All the methods regarding Mathematics (here Partially
implemented Check Function).
The Sample Program contains:
**Math.java** -> Which belongs to foo package and a Math class that consists
of method check which can only compare 2 nos. excluding inequality.
**Main.java** -> Main Program takes 2 numbers as input and prints the greater
of 2.
## Math.java
__
__
__
__
__
__
__
// Math.java
package foo;
public class Math {
public static int check(int a, int b)
{
return a > b ? 'A' : 'B';
}
}
---
__
__
## Main.java
__
__
__
__
__
__
__
// Main.java
// Driver Program
package foo;
import java.util.*;
class Main {
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter value of a: ");
int a = s.nextInt();
System.out.print("Enter value of b: ");
int b = s.nextInt();
if (a == b)
System.out.println("Both Values are Equal");
else
System.out.printf("%c's value is Greater\n",
Math.check(a, b));
}
}
---
__
__
**Compilation:**
**javac -d /path file1.java file2.java**
Sometimes you might want to set your classpath to point to somewhere, use the:
> **set classpath= path/to/location**
>
> // (or) pass the switch for both java and javac as
> **javac -cp /path/to/location file.java**
>
> // (or)
> **java -classpath /path/to/location file**
By default it points to current directory i.e., “ **.** ”
**Executing the code:**
> **java packagename.Main** // Here in the example it is: “java foo.Main”
**Output:**

Attention reader! Don’t stop learning now. Get hold of all the important DSA
concepts with the **DSA Self Paced Course** at a student-friendly price and
become industry ready. To complete your preparation from learning a language
to DS Algo and many more, please refer **Complete Interview Preparation
Course** **.**
My Personal Notes _arrow_drop_up_
Save
|
76b44ad297ee12925564f02654dc13c5f1bd26b7 | cerebrumaize/leetcode | /jump_game/1.py | 579 | 3.546875 | 4 |
#!/usr/bin/env python
'''code description'''
# pylint: disable = I0011, E0401, C0103
class Solution(object):
'''Solution description'''
def canJump(self, nums):
'''Solution func description'''
max_step = 0
for ind in xrange(0, len(nums)):
if ind > max_step:
return False
max_step = max(max_step, nums[ind] + ind)
return True
def main():
'''main function'''
_solution = Solution()
nums = [7, 2, 3]
res = _solution.canJump(nums)
print res
if __name__ == "__main__":
main()
|
d19c847e8ec592ec6021267489f6fed9f02ad622 | EojinK1m/Practice_Algorithm_Problems | /programmers/level2/짝지어_제거하기.py | 316 | 3.59375 | 4 | #https://programmers.co.kr/learn/courses/30/lessons/12973
def solution(s):
s = list(s)
stack = [s.pop()]
while s:
a = s.pop()
if not stack or not stack[-1] == a:
stack.append(a)
else:
stack.pop()
if stack:
return 0
else:
return 1 |
664e07e1052a211b7e8c9f320d18216e81b1a452 | AndreaGarofoli/Rosalind-problems | /2.RNA.py | 457 | 4.25 | 4 | """
Problem
An RNA string is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'.
Given a DNA string tt corresponding to a coding strand, its transcribed RNA string uu is formed by replacing all occurrences of 'T' in tt with 'U' in uu.
Given: A DNA string tt having length at most 1000 nt.
Return: The transcribed RNA string of tt.
"""
print("Write down the sequence you want to transcribe")
s = input()
print(s.replace("T", "U"))
|
4791cfc1780df006274f8855eeafcfb8d4dfbb29 | yuliang123456/p1804ll | /第二月/于亮_p10/aa/build/lib/工厂模式.py | 943 | 3.515625 | 4 | class CarStore(object):
def createCar(self,typeName):
pass
def order(self,typeName):
self.car = self.createCar(typeName)
self.car.move()
self.car.stop()
class XiandaiCarStore(CarStore):
def createCar(self,typeName):
self.carFactory=CarFactory()
return self.carFactory.createCar(typeName)
class YilanteCar(object):
def move(self):
print('...车在移动.......')
def stop(self):
print('..停车...')
class SuonataCar(object):
def move(self):
print('......车在移动.......')
def stop(self):
print('...停车.....')
class CarFactory(object):
def createCar(self,typeName):
self.typeName=typeName
if self.typeName =='伊兰特':
self.car=YilanteCar()
elif self.typeName =='索纳塔':
self.car= SuonataCar()
return self.car
suonata=XiandaiCarStore()
suonata.order('索纳塔')
|
c0c4ba9ebb6e47a3101d3936aafa7e985a5d77f8 | danahagist/100_Days_Of_ML_Code | /day25_weightedMean.py | 1,247 | 4.125 | 4 | # Task: Given an array, X, of N integers and an array, W, representing the respective weights of X's elements,
# calculate and print the weighted mean of X's elements.
# Your answer should be rounded to a scale of 1 decimal place (i.e.,12.3 format).
# ----------------------------- Solution -------------------------------------------------------------
# Creating weighted mean function, taking parameters x (array of values) and w (weights)
def weighted_mean(x,w):
# Initializing variables for numerator and denominator of weighted mean function
sum_weighted_values = 0
sum_weights = 0
# Iterating over values in N (length of array)
for i in range(N):
# Adding weighted values (numerator)
sum_weighted_values += x[i] * w[i]
# Adding weighted sums (denominator)
sum_weights += w[i]
# Calculating weigted mean (numerator/denominator)
return sum_weighted_values / sum_weights
# Reading input lines
N = int(input())
x = [int(value) for value in input().split()]
w = [int(value) for value in input().split()]
# Printing rounded, weighted mean
print(round(weighted_mean(x, w), 1))
# --------------------------- End Solution -----------------------------------------------------------
|
88a783206b3c4e7c453f2d3642be299b9031ef2f | danahagist/100_Days_Of_ML_Code | /day10_queuesAndStacks.py | 2,873 | 3.984375 | 4 | # Task:
# To solve this challenge, we must first take each character in s, enqueue it in a queue,
# and also push that same character onto a stack.
# Once that's done, we must dequeue the first character from the queue and pop the top character off the stack,
# then compare the two characters to see if they are the same;
# as long as the characters match, we continue dequeueing, popping,
# and comparing each character until our containers are empty (a non-match means s isn't a palindrome).
# Write the following declarations and implementations:
# 1. Two instance variables: one for your stack, and one for your queue.
# 2. A void pushCharacter(char ch) method that pushes a character onto a stack.
# 3. A void enqueueCharacter(char ch) method that enqueues a character in the queue instance variable.
# 4. A char popCharacter() method that pops and returns the character at the top of the stack instance variable.
# 5. A char dequeueCharacter() method that dequeues and returns the first character in the queue instance variable.
# ----------------------------------------------- Solution ----------------------------------------------------------
import sys
class Solution:
# Initializing with stack and queue attributes
def __init__(self):
self.stack = []
self.queue = []
# Pushing character onto stack, adding to end ("right side")
def pushCharacter(self, ch):
self.stack.append(ch)
# Popping character from stack, removing from end ("right side")
def popCharacter(self):
return self.stack.pop()
# Enqueueing character to queue, adding to beginning ("left side")
def enqueueCharacter(self, ch):
self.queue.insert(0,ch)
# Dequeueing character from queue, removing from end ("right side")
def dequeueCharacter(self):
return self.queue.pop()
# -------------------------------------------- End Solution -------------------------------------------------------
# ------------------------------------------- HackerRank Input ----------------------------------------------------
# read the string s
s=input()
#Create the Solution class object
obj=Solution()
l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
obj.pushCharacter(s[i])
obj.enqueueCharacter(s[i])
isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
for i in range(l // 2):
if obj.popCharacter()!=obj.dequeueCharacter():
isPalindrome=False
break
#finally print whether string s is palindrome or not.
if isPalindrome:
print("The word, "+s+", is a palindrome.")
else:
print("The word, "+s+", is not a palindrome.")
# ------------------------------------------------- End File -------------------------------------------------------
|
3f5ecf5fa3a0e4af7a12813d94c434d370fa8725 | louism33/dailyProblems | /day5.py | 686 | 4.25 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Jane Street.
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
Implement car and cdr.
'''
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(c): #first element
return c(first)
def first(a, b):
return a
def cdr(c): #snd element
return c(lambda a, b : b)
a = cons(3, 4)
b = car(a)
c = cdr(a)
print(b)
print(c)
|
cfb98b1a5e76de2353ab8e87f20abc550d61547e | ganavi12/python-program | /interview programs/first_second_list.py | 312 | 3.765625 | 4 | l1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
l2 = [0, 1, 1, 0, 1, 2, 2, 0, 1]
l3 = []
for i in range(len(l1)):
for j in range(len(l2)):
print(i,l2[j])
if i == l2[j]:
l3.append(l1[i])
print(l3)
# zipped_list = zip(l1 + l2)
# y = [x for _, x in sorted(zipped_list)]
# print(z) |
09f945f3047167c6c560911dd321f177cc94d5c8 | morningred88/data-structure-algorithms-in-python | /Stack-Queue/queue_with_stack_recursive.py | 635 | 3.578125 | 4 | class QueueStackRecursive:
def __init__(self) -> None:
self.stack = []
def enqueue(self, data):
self.stack.append(data)
def dequeue(self):
if len(self.stack) == 1:
return self.stack.pop()
item = self.stack.pop()
dequeued_item = self.dequeue()
self.stack.append(item)
return dequeued_item
queue = QueueStackRecursive()
queue.enqueue(10)
queue.enqueue(5)
queue.enqueue(20)
queue.enqueue(30)
queue.enqueue(40)
queue.enqueue(50)
print(queue.dequeue())
# # queue.enqueue(100)
# print(queue.dequeue())
# print(queue.dequeue())
# # print(queue.dequeue())
|
aa1cb2407e7c4911ef847eb4899bcb16af277a3d | saikatsengupta89/PracPy | /HCK_HappinessDegree.py | 469 | 3.546875 | 4 | # There is an array of length n
# There is a
from itertools import groupby
def calculate_happiness(n,m,arr, a,b):
pos=0
neg=0
for i in arr:
if i in a:
pos=pos +1
if i in b:
neg=neg +1
print(pos-neg)
if __name__=="__main__":
n, m= input().split(" ")
arr= input().split(" ")
a= set(input().split(" "))
b= set(input().split(" "))
calculate_happiness(int(n), int(m), arr, a,b)
|
b439e8a25dd631752dff480eef604411b0434ad3 | gabrieldepaiva/Exercicios-CursoEmVideo | /Python_Exercicios/ex006.py | 202 | 3.984375 | 4 | n = int(input('Digite um número: '))
print()
print('O dobro de {} vale {}.'.format(n,n*2))
print('O triplo de {} vale {}.'.format(n,n*3))
print('A raiz quadrada de {} vale {}.'.format(n,int(n**(1/2)))) |
bc405d451730f0062e9628586c25f8e625b364e9 | jessie0624/BasicAlgo | /BasicAlg/HeapSort.py | 1,236 | 4.03125 | 4 | def HeapSort(data):
##将数组构造成大根堆
def heapInsert(data, index):
while (data[index] > data[(index - 1)//2 if index - 1 > 0 else 0]):
data[index], data[(index - 1)//2] = data[(index-1)//2], data[index]
index = (index - 1)//2 if index - 1 > 0 else 0
##某个位置变化后做调整
def heapFy(data, index):
left = index * 2 + 1
while (left < len(data)):
if left + 1 < len(data):
largest = left if data[left] > data[left + 1] else left + 1
else:
largest = left
largest = index if data[index] > data[largest] else largest
if index == largest:
break
data[index], data[largest] = data[largest], data[index]
index = largest
left = index * 2 + 1
return data
##排序
if not data or len(data) < 2:
return
for i in range(len(data)):
heapInsert(data, i)
j = len(data) - 1
while j >= 0:
data[j], data[0] = data[0], data[j]
data[0:j] = heapFy(data[0:j],0) ##key point: modify unsorted data in range(0,j)
j -= 1
|
45bd7886fc480f6df1f79bc35309869b13f83e23 | lakshmi2710/LeetcodeAlgorithmsInPython | /Q2Search.py | 1,551 | 3.65625 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0:
return -1
index = self.getIndex(nums, 0, len(nums) - 1)
print index
if index == -1:
return self.binarySearch(nums, 0, len(nums) - 1, target)
elif (nums[index] == target):
return index
elif (nums[0] > target):
return self.binarySearch(nums, index + 1, len(nums) - 1, target)
else:
return self.binarySearch(nums, 0, index - 1, target)
def getIndex(self, nums, low, high):
print low, high
if low > high or low == high:
return -1
mid = (low + high) / 2
print mid, "mid"
if nums[mid] < nums[mid - 1]:
return mid - 1
if nums[mid] > nums[mid + 1]:
return mid
if nums[mid] > nums[low]:
return self.getIndex(nums, mid+1, high)
else:
return self.getIndex(nums, low, mid-1)
def binarySearch(self, nums, low, high, target):
if high < low:
return -1
mid = (low + high) / 2
if target == nums[mid]:
return mid
if target > nums[mid]:
return self.binarySearch(nums, (mid + 1), high, target)
else:
return self.binarySearch(nums, low, (mid - 1), target);
nums = [3,4,5,6,1,2]
print nums
target = 2
sol = Solution()
print sol.search(nums, target) |
e48d0691c1e3ac9eb15b0352e7f92eb194a83ca9 | HooFaya/test | /剑指第二轮重刷/两个链表的第一个公共结点.py | 585 | 3.609375 | 4 | # -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if not pHead2 or not pHead1:
return
cur=pHead1
stack1=[]
while(cur):
stack1.append(cur)
cur=cur.next
cur=pHead2
stack2=[]
while(cur):
stack2.append(cur)
while(stack2 and stack2 and stack1[-1] is stack2[-1]):
cur=stack1.pop()
stack2.pop()
return cur
|
3c4d47c1ae93a4190adf2e4479ed18f71c5e7ff4 | GitPistachio/Competitive-programming | /HackerRank/collections.Counter()/collections.Counter().py | 682 | 3.65625 | 4 | # Project name : HackerRank: collections.Counter()
# Link : https://www.hackerrank.com/challenges/collections-counter/problem
# Try it on :
# Author : Wojciech Raszka
# E-mail : contact@gitpistachio.com
# Date created : 2020-10-03
# Description :
# Status : Accepted (182396975)
# Tags : python
# Comment :
from collections import Counter
no_of_shoes = int(input())
shoes_by_size = Counter(map(int, input().split()))
no_of_customers = int(input())
earned_money = 0
for _ in range(no_of_customers):
size, price = map(int, input().split())
if shoes_by_size[size] > 0:
earned_money += price
shoes_by_size[size] -= 1
print(earned_money)
|
ffd6d7460ceec0c04cd8f0f631d4a31b876ebf12 | akalya23/gkj | /15.py | 127 | 3.5625 | 4 | r,b=input().split()
r=int(r)+1
b=int(b)
for num in range(r,b):
if num % 2 == 0:
print(num, end = " ")
|
53ca1c1e96ea41ce0b57ad786743f34a1cc3eb33 | paulzfm/LustreAST | /ast2lustre/src/lex_rep.py | 867 | 3.609375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
file = 'c.txt'
f = open(file).read()
for each in f.splitlines():
lis = each.split('|')
def rep(string):
string = string.replace('$', 'SSS')
string = string.replace('+', 'ADD')
string = string.replace('-', 'MINUS')
string = string.replace('*', 'MUL')
string = string.replace('/', 'DIVDIV')
string = string.replace('=', 'EQ')
string = string.replace('⟨⟩', 'MID')
string = string.replace('>', 'GRE')
string = string.replace('>=', 'GREEQ')
string = string.replace('<', 'LES')
string = string.replace('<=', 'LESEQ')
string = string.replace('$', 'SSS')
string = string.replace('$', 'SSS')
string = string.replace('$', 'SSS')
return string
for each in f.splitlines():
lis = each.split('|')
for eve in lis:
print '\t|'+ ' \"'+eve.strip()+'\"' + "\t" + "{ " + rep(eve.strip().upper()) +" }" |
b8dd7dcbd57af41138ef95680edd60166a3b5390 | gauresh29/gitfirstpro | /pract5.py | 830 | 4.09375 | 4 | #author gauresh
# date 26-10-2021//practical 5
#perpose=practical code with harry 5th pract
#function for printing next pallendron
def nextpallendrom(num):
#print(mylist)
if num >10:
while not ispallendrom(num) :
num += 1
return num
else:
return num
#This function define number is palllendrom or not
def ispallendrom(num):
return str(num) == str(num)[::-1]
#print("already ")
if __name__ == "__main__":
num=int(input("How many numbers you want to enter"))
mylist=[]
newlist=[]
for i in range(num):
pnum=int(input("enetr number\n"))
mylist.append(pnum)
for i in range(num):
#print(f" {mylist[i]} {nextpallendrom(mylist[i])}")
p=nextpallendrom(mylist[i])
newlist.append(p)
print(mylist)
print(newlist) |
4a58c4e4e5db0923233f25fb7e263eed9a3fafac | CornellDataScience/Insights-Databowl | /modeling/nn_regression.py | 3,568 | 3.578125 | 4 | # %% [markdown]
# # Applying deep learning models to Databowl
# Here I use tensorflow to build a feedforward neural net to predict yards
# gained on each rushing play.
# %%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_docs as tfdocs
np.set_printoptions(1)
# %% [markdown]
# The feature engineering notebok does a pretty good job of cleaning up the
# data, but leaves behind just a couple NA entries. We drop those rows, mostly
# for convenience.
# %%
data = pd.read_csv("data/fe_data.csv", index_col=[0,1])
data.dropna(inplace=True)
# %% [markdown]
# For this iteration, we're using only one line of data for each play--the data
# entry for the rusher. Because `IsRusher` and `IsOffense` are redundant as a
# result, we'll drop those columns from the the dataset. Then we can normalize
# all values so that they are well-interpreted by the model.
# %%
plays = data.loc[data.IsRusher]
plays = plays.astype(np.float32)
target = plays.pop("Yards")
plays.drop(["IsRusher","IsOffense"], axis=1, inplace=True)
plays_stats = plays.describe().transpose()
def norm(x):
return (x - plays_stats['mean']) / plays_stats['std']
norm_data = norm(plays)
# %%
x = norm_data.values.astype(np.float32)
y = target.values.astype(np.float32)
dataset = tf.data.Dataset.from_tensor_slices((x, y))
# %% [markdown]
# We can verify that the data arrived in the `tf.data` API all in one piece.
# %%
for f,t in dataset.take(5):
print(f"Features:\n{f}")
print(f"Target: {t}")
print()
# %% [markdown]
# Now we can segment this into a training dataset using the API.
# %%
train_data = dataset.shuffle(len(norm_data)).batch(100)
# %%
def compile_model():
model = tf.keras.Sequential([
tf.keras.layers.InputLayer(x.shape[1], name='input'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(10, activation='relu'),
#tf.keras.layers.Dropout(0.2),
#tf.keras.layers.Dense(16, activation='relu', name='hidden'),
#tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(1, activation='linear', name='output')
])
rms = tf.keras.optimizers.RMSprop(0.001)
sgd = tf.keras.optimizers.SGD()
adam = tf.keras.optimizers.Adam()
model.compile(optimizer=rms, loss='mse', metrics=['mse','mae'])
return model
EPOCHS = 50
model = compile_model()
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
history = model.fit(x,y,
validation_split=0.2,
epochs=EPOCHS,
callbacks=[early_stop],
verbose=0
)
hist = pd.DataFrame(history.history)
hist['epoch'] = history.epoch
plt.plot(hist.loss, label='Training MSE')
plt.plot(hist.val_loss, label='Validation MSE')
plt.legend()
plt.show()
# %% [markdown]
# It's pretty clear that this model is immediately overfitting. We'll need to
# look into ways to fundamentally improve it or to drastically improve our
# feature engineering.
# %% [markdown]
# We can compare this to a baseline model that just predicts the mean value of
# yards for any inputs.
# %%
mse_data = ((y-y.mean())**2).mean()
mae_data = (np.abs(y-y.mean())).mean()
print("MSE of Yards against their mean:", mse_data)
print("MAE of Yards against their mean:", mae_data)
# %% [markdown]
# The MSE of this baseline model is 33.1 yds^2, about the same as our model,
# which indicates that our model has very little predictive power.
# %%
y_pred = model.predict(x)
plt.scatter(y, y_pred, alpha=0.05)
plt.xlabel("Actual Yards")
plt.ylabel("Predicted Yards")
plt.show()
|
a8f3d747b21760cb458476e61340abb2134e41ef | tt-n-walters/saturday-python | /timer_decorator.py | 628 | 3.5 | 4 |
from time import perf_counter
def timer_decorator(func): # Define out decorator
def wrapper(*args): # Define the higher-order wrapper function
start_time = perf_counter() # It accepts *args, meaning any amount of arguments
output = func(*args) # Run the first-class function, save the returned value to a variable
end_time = perf_counter()
# print(f"Function took {end_time - start_time}s")
difference = end_time - start_time
return output, difference
return wrapper
|
6e6ab0304f094729a16b57fe1d5e4f2a70bec19a | Preethikoneti/pychallenges | /readlines.py | 462 | 3.859375 | 4 | def main():
#read file
file = open ( "/Users/kbeattie/Desktop/yesno.txt", "r" )
lines = file.readlines()
file.close()
#look for patterns
countYES = 0
countNO = 0
for line in lines:
line = line.strip().upper()
# print ( line )
if line.find("YES")!= -1 and len(line)==3:
countYES = countYES + 1
if line.find("NO") != -1 and len(line)==2:
countNO = countNO + 1
# display result
print( "Yes: ", countYES)
print( "No: ", countNO)
main() |
e364f9174e6135d7c898871fee67522d8e117bbc | MeerKat98/Morse-Code | /Morse.py | 469 | 3.5625 | 4 | #MeerKat
#Variables
arrAlpha = []
arrMorse = []
word = ''
#Main
alphaFile = open("Alphabet.txt")
morseFile = open("Morse.txt")
for line in alphaFile:
arrAlpha.append(line)
for line in morseFile:
arrMorse.append(line)
alphaFile.close()
morseFile.close()
word = raw_input("Enter word to convert to morse code: ")
for a in range(0,len(word)):
for b in range(0,len(arrAlpha)):
if word[a] == arrAlpha[b][0]:
print(arrMorse[b])
|
d40ab8362f5d957ac8596a48e658cff0f5020687 | ThibautBlomme/Informatica5 | /05 - EenvoudigeFuncties/Pythagoras.py | 396 | 3.734375 | 4 | #variabelen
a = float(input('Geef de lengte van de eerste rechthoekszijde: '))
b = float(input('Geef de lengte van de tweede rechthoekszijde: '))
from math import sqrt
c = sqrt(pow(a, 2) + pow(b, 2))
#formule
print(str('In een rechthoekige driekhoek met rechthoekzijden a = ' + str('{:.2f}'.format(a)) + ' en b = ' + str('{:.2f}'.format(b))) + ' is de schuine zijde ' + str('{:.2f}'.format(c))) |
fb0ce579bb1a84d4f311e451c21bfbecdc72f38d | Harinarayan14/p97 | /p97.py | 882 | 4.1875 | 4 | # import random for finding a random number
import random;
# Random Number
number = random.randint(1,100);
# Text
print("Number Guessing Game");
print("Guess from 1 to 100");
print("You have 10 chances.");
#Chances
chances =0;
# While Loop
while chances < 10:
# Input
guess = int(input("Enter your guess "))
# Game win
if (guess == number):
print("Congratulation YOU WON!!!")
print("Chances Taken: ")
print(chances)
break
# Game Continue
elif (guess < number):
print("Your guess was low: Guess a number higher than", guess)
else:
print("Your guess was high: Guess a number lower than", guess)
chances += 1
# Score
print("Chances Taken: ")
print(chances)
print("Chances Left: ")
print(10-chances)
# Game Over
if chances >= 10:
print("YOU LOSE!!! The number is", number) |
c0a6b34e674c5317726375178463e51bc0e8efb2 | linkeshkanna/ProblemSolving | /HackerRank.30.Days/splitStringOddEven.py | 565 | 3.8125 | 4 | # HackerRank
# https://www.hackerrank.com/challenges/30-review-loop/problem
if __name__ == '__main__':
n = int(input())
inputs = []
for i in range(n):
inputs.append(input())
print(inputs)
oddList, evenList = "", ""
for i in range(n):
print(i)
print(inputs[i])
counter = 1
for j in inputs[i]:
if counter % 2 == 0:
evenList += j
else:
oddList += j
counter += 1
print(evenList, oddList)
oddList, evenList = "", ""
|
f2246f02e7c6e964986c60844facbe994307d702 | ho-kyle/python_portfolio | /040.py | 332 | 3.796875 | 4 | a = []
for i in range(3):
e = eval(input('Please enter the first lenght of the triangle: '))
a.append(e)
b = max(a)
c = min(a)
d = sum(a) - b - c
if b == c:
print('It is an equilateral triangle.')
elif c**2 + d**2 == b**2:
print('It is an isosceles triangle.')
else:
print('The triangle is scalene.') |
761a2d0ba24cd4ca9f417d3144d4d976c349039a | NickolayTernovoy/python-algorithms | /02/tests.py | 1,893 | 3.6875 | 4 | import unittest
from LinkedList.Node import Node
from LinkedList.List import List
class NodeCase(unittest.TestCase):
def test_node_can_have_previous_element(self):
n1 = Node(1)
n2 = Node(2)
n2.prev = n1
self.assertIs(n2.prev, n1)
def test_node_can_have_next_element(self):
n1 = Node(1)
n2 = Node(2)
n1.next = n2
self.assertIs(n1.next, n2)
class ListCase(unittest.TestCase):
def test_list_can_delete_one_node_by_value(self):
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
linked_list = List();
linked_list.add_in_tail(n1)
linked_list.add_in_tail(n2)
linked_list.add_in_tail(n3)
linked_list.add_in_tail(n4)
linked_list.delete_first_by_value(3)
self.assertIsNone(n3.prev)
self.assertIsNone(n3.next)
self.assertIsNone(n1.prev)
self.assertIs(n1.next, n2)
self.assertIs(n2.prev, n1)
self.assertIs(n2.next, n4)
self.assertIs(n4.prev, n2)
self.assertIsNone(n4.next)
def test_list_can_append_node_after_item(self):
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
linked_list = List();
linked_list.add_in_tail(n1)
linked_list.add_in_tail(n2)
linked_list.add_in_tail(n4)
linked_list.append_after(node=n3, after=n2)
self.assertIsNone(n1.prev)
self.assertIs(n1.next, n2)
self.assertIs(n2.prev, n1)
self.assertIs(n2.next, n3)
self.assertIs(n3.prev, n2)
self.assertIs(n3.next, n4)
self.assertIs(n4.prev, n3)
self.assertIsNone(n4.next)
def test_list_can_append_node_in_head(self):
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
linked_list = List();
linked_list.add_in_tail(n2)
linked_list.add_in_tail(n3)
linked_list.add_in_tail(n4)
linked_list.append_in_head(n1)
self.assertIs(linked_list.head, n1)
self.assertIsNone(n1.prev)
self.assertIs(n1.next, n2)
self.assertIs(n2.prev, n1)
if __name__ == '__main__':
unittest.main(verbosity=2) |
6ed3bb7ff0b08af087087df5b67b992ef62becf1 | HunterJohnson/Interviews | /epip/rectangle_intersection.py | 741 | 4.0625 | 4 | # write a program that tests if 2 rectangles have a non-empty intersection
# if intersection is nonempty, return the rect. formed by their intersection
Rectangle = collections.namedtuple('Rectangle', ('x', 'y', 'width', 'height')) # x, y = left lower point
def intersect_rectangle(R1, R2):
def is_intersect(R1, R2):
return (R1.x <= R2.x + R2.width and R1.x + R1.width >= R2.x
and R1.y <= R2.y + R2.height and R1.y + R1.height >= R2.y)
if not is_intersect(R1,R2):
return Rectangle(0,0,-1,-1) # No intersection
return Rectangle(
max(R1.x, R2.x), max(R1.y, R2.y)
min(R1.x + R1.width, R2.x + R2.width) - max(R1.x, R2.x)
min(R1.y + R1.height, R2.y + R2.height) - max(R1.y, R2.y))
# time complexity O(1)
|
1c9800e153d11397a355d0e3be4d87cdc7cd725e | viniciusmartins1/python-exercises | /ex075.py | 558 | 4.09375 | 4 | num = ( int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite o último número: ')))
print(f'Você digitou os valores {num}')
print(f'O número 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'O valor 3 apareceu pela primeira vez na posicao {num.index(3)+1}')
else:
print('O valor 3 não aparece em neunhuma posição.')
print('Os valores PARES digitados foram ', end='')
for n in num:
if n % 2 == 0:
print(n, end=' ')
|
c08d1fa6320866bbec71eb546e88983a98d316bb | umutcaltinsoy/Data-Structures | /Dictionary/dictionary.py | 5,655 | 4.65625 | 5 | # Dictionaries :
'''
Dictionary in python is an ordered collection of data values, used to store
data values like a map, which, unlike other Data Types that hold only a
single value as an element, Dictionary holds key:value pair. Key-value is
provided in the dictionary to make it more optimized.
Key in a dictionary don't allow Polymorphism.
'''
# Creating a dictionary with integer keys
Dict = {1: 'Python', 2: 'For', 3: 'Coding'}
print(Dict)
print(type(Dict))
# Creating a dictionary with mixed keys
Dict_1 = {'Name': 'Umut', 1: [1, 2, 3, 4]}
print(Dict_1)
# Dictionary can also be created by the built-in function dict().
# An emoty dict. can be created by just placing to cury braces-{}
# Creating an empty Dictionary
d = {}
print("Empty Dictionary : ", d)
# Creating a dictionary with dict() method
dc = dict({1: 'Python', 2: 'Programming', 3: 'Umut'})
print("Dictionary with the use of dict(): ", dc)
# Nested Dictionary
# Creating a Nested Dictionary
dicts = {1: 'Umut', 2: 'Python', 3:{'A': 'Welcome', 'B': 'To', 'C': 'Programming'}}
print(dicts)
print(type(dicts))
# Adding Elements to a Dictionary
'''
One value at a time can be added to a Dictionary by defining value along
with the key e.g. Dict[Key] = 'Value'. Updating an existing value in a
Dictionary can be done by using the built-in update() method. Nested key
values can also be added to an existing Dictionary.
While adding a value, if the key value already exists, the value gets
updated otherwise a new Key with the value is added to the Dictionary.
'''
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary : ", Dict)
# Adding elements one at a time
Dict[0] = 'Umut'
Dict[2] = 'Cagri'
Dict[3] = 'Altinsoy'
Dict[4] = 1
print("Dictionary after adding 4 elements : ", Dict)
# Adding set of values to a single key
Dict['Value_set'] = 2, 3, 4
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("Updated key value : ", Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1': 'Life', '2' : 'Hard'}}
print("Adding a Nested Key : ", Dict)
# Accessing elements from a Dictionary
# In order to access the items of a dictionary refer to its key name.
# Key can be used inside square brackets.
Dict = {1: 'Python', 'name': 'Umut', 3: 'Developer'}
#accessing a element using key
print(Dict['name'])
print(Dict[1])
# There is also a method called get() that will also help in accessing the
# element from a dictionary
Dict = {1: 'Umut', 2: 'Cagri', 'Surname' : 'Altinsoy'}
# accessing an element using get()
print("Accessing an element using get : ", Dict.get('Surname'))
# Accessing element of a nested dictionary
Dict = {'Dict1': {1: 'Umut'}, 'Dict2': {'Name' : 'Cagri'}}
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
# Removing Elements from Dictionary
'''
Using del keyword : In python dictionary, deletion of keys can be done by
using the del keyword. Using del keyword, specific values from a dictionary
as well as whole dictionary can be deleted. Items in a Nested dictionary
can also be deleted by using del keyword and providing specific nested key
and particular key to be deleted from that nested dictionary.
del Dict will delete the entire dictionary and hence printing it after
deletion will raise an Error.
'''
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Programming',
'A' : {1 : 'Umut', 2 : 'Cagri', 3 : 'Altinsoy'},
'B' : {1 : 'Zed', 2 : 'Shadow'} }
print("Inıtial Dictionary : ", Dict)
# Deleting a Key value
del Dict[6]
print("Deleting a specific key : ", Dict)
# Deleting a Key from Nested Dictionary
del Dict['A'][2]
print("Deleting a key from Nested Dictionary : ", Dict)
# Using pop() method
# Pop() method is used to return and delete the value of the key specified.
Dict = {1 : 'Zed', 2 : 'Akali', 'Skill' : 'Shuriken'}
# Deleting a key using pop() method
pop_ele = Dict.pop(2)
print("Dictionary after deletion : " + str(Dict))
print('Value associated to poped key is : ' + str(pop_ele))
# Using popitem() method
# The popitem() returns and removes an arbitrary element(key, value) pair
# from the dictionary
Dict = {1 : 'Zed', 2 : 'Akali', 'Skill' : 'Shuriken'}
#Deleting an arbitrary key using popitem() function
pop_ele = Dict.popitem()
print("Dictionary after deletion : ", str(Dict))
print("The arbitrary pair returned is : " + str(pop_ele))
# Using clear() method
# All the items from a dictionary can be deleted at once by using this method
Dict = {1 : 'Zed', 2 : 'Akali', 'Skill' : 'Shuriken'}
# Deleting entire Dictionary
Dict.clear()
print("Deleting Entire Dictionary : ", Dict)
# copy() : They copy() method returns a shallow copy of the dictionary.
# clear() : The clear() method removes all items from the dictionary.
# pop() : Removes and returns an element from a dictionary having the given key.
# popitem() : Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
# get() : It is a conventional method to access a value for a key.
# dictionary_name.values() : returns a list of all the values available in a given dictionary.
# str() : Produces a printable string representation of a dictionary.
# update() : Adds dictionary dict2’s key-values pairs to dict.
# setdefault() : Set dict[key]=default if key is not already in dict.
# keys() : Returns list of dictionary dict’s keys.
# items() : Returns a list of dict’s (key, value) tuple pairs.
# has_key() : Returns true if key in dictionary dict, false otherwise.
# fromkeys() : Create a new dictionary with keys from seq and values set to value.
# type() : Returns the type of the passed variable.
# cmp() : Compares elements of both dict.
|
709b3814ad355bc74a160ca03e03ac0ecfcd50c5 | arnoqlk/icourse163-Python | /1/MoneyTrans.py | 191 | 3.5625 | 4 | Money = input()
if Money[0:3] in ['RMB']:
U = eval(Money[3:])/6.78
print("USD{:.2f}".format(U))
elif Money[0:3] in ['USD']:
R = eval(Money[3:])*6.78
print("RMB{:.2f}".format(R)) |
9edd5899c5f2d83b3c8d236fd215cd5341165df7 | andrej-sch/learning-from-images | /lfi-01/13-features.py | 1,117 | 3.8125 | 4 | # 1. read each frame from the camera (if necessary resize the image)
# and extract the SIFT features using OpenCV methods
# Note: use the gray image - so you need to convert the image
# 2. draw the keypoints using cv2.drawKeypoints
# There are several flags for visualization - e.g. DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
# close the window and application by pressing a key
import cv2 as cv
cap = cv.VideoCapture(0)
cv.namedWindow('Learning from images: SIFT feature visualization', cv.WINDOW_NORMAL)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
sift = cv.xfeatures2d.SIFT_create()
kp = sift.detect(frame, None)
flag = cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
frame = cv.drawKeypoints(frame, kp, frame, flags=flag)
cv.imshow('Learning from images: SIFT feature visualization', frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# when everything done, release the capture
cap.release()
cv.destroyAllWindows()
# inspired by
# https://docs.opencv.org/3.1.0/da/df5/tutorial_py_sift_intro.html |
8a4f2a09fb14391a76a9d25bd03ac341da4931df | maryamkh/MyPractices | /Merge_Intervals_Solution2.py | 1,659 | 3.84375 | 4 | #Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals,
#and return an array of the non-overlapping intervals that cover all the intervals in the input.
#Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
#Output: [[1,6],[8,10],[15,18]]
#Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
starts = []
ends = []
for i in range(len(intervals)):
starts.append(intervals[i][0])
ends.append(intervals[i][-1])
starts.sort()
ends.sort()
start_p = 0
end_p = 0
merged = list()
print(starts)
print(ends)
arr = [starts[0], ends[0]]
while(end_p < len(starts)):
print(f'start_p, end_p {start_p}, {end_p}')
print(f'{starts[start_p]}, {ends[end_p]}')
if starts[start_p] <= arr[1]:
ending = ends[end_p]
print(f'ending: {ending}')
arr = [arr[0], ending]
print(f'arr: {arr}')
print(f'merged: {merged}')
start_p += 1
end_p += 1
else:
print("else:")
merged.append(arr)
print(f'else merged: {merged}')
arr = [starts[start_p], ends[end_p]]
print(f'else: arr: {arr}')
print(f'else: arr: {arr}')
merged.append(arr)
print(merged)
return(merged)
|
515480233345c7050c261f367ca2a2c90e7d8a6d | Ta-SeenJunaid/Data-Structures-and-Algorithm | /Graph/dfs1.py | 682 | 4.03125 | 4 | class Node(object):
def __init__(self, name):
self.name = name
self.adjancencyList = []
self.visited = False
class DepthFirstSearch(object):
def dfs(self, node):
print(node.name)
node.visited = True
for n in node.adjancencyList:
if not n.visited:
self.dfs(n)
node1 = Node("A")
node2 = Node("B")
node3 = Node("C")
node4 = Node("D")
node5 = Node("E")
node6 = Node("F")
node1.adjancencyList.append(node2)
node1.adjancencyList.append(node3)
node2.adjancencyList.append(node4)
node2.adjancencyList.append(node5)
node3.adjancencyList.append(node6)
result = DepthFirstSearch()
result.dfs(node1) |
06257a7ca16187f01947ef227fbbc035084f30cc | jakeh524/terminal_hangman | /terminal_hangman.py | 4,443 | 3.875 | 4 | #!/usr/bin python3
# Author: Jake Herron
# Email: jakeh524@gmail.com
import random, os
def display(wrong_count):
os.system('clear')
print("------------------------------")
if(wrong_count == 0):
print(" _________ ")
print(" | | ")
print(" | ")
print(" | ")
print(" | ")
print(" | ")
print(" | ")
print(" ---")
elif(wrong_count == 1):
print(" _________ ")
print(" | | ")
print(" | O ")
print(" | ")
print(" | ")
print(" | ")
print(" | ")
print(" ---")
elif(wrong_count == 2):
print(" _________ ")
print(" | | ")
print(" | O ")
print(" | | ")
print(" | ")
print(" | ")
print(" | ")
print(" ---")
elif(wrong_count == 3):
print(" _________ ")
print(" | | ")
print(" | O ")
print(" | \\| ")
print(" | ")
print(" | ")
print(" | ")
print(" ---")
elif(wrong_count == 4):
print(" _________ ")
print(" | | ")
print(" | O ")
print(" | \\|/ ")
print(" | ")
print(" | ")
print(" | ")
print(" ---")
elif(wrong_count == 5):
print(" _________ ")
print(" | | ")
print(" | O ")
print(" | \\|/ ")
print(" | | ")
print(" | ")
print(" | ")
print(" ---")
elif(wrong_count == 6):
print(" _________ ")
print(" | | ")
print(" | O ")
print(" | \\|/ ")
print(" | | ")
print(" | / ")
print(" | ")
print(" ---")
elif(wrong_count == 7):
print(" _________ ")
print(" | | ")
print(" | O ")
print(" | \\|/ ")
print(" | | ")
print(" | / \\ ")
print(" | ")
print(" ---")
def play_game(word):
#init display
wrong_count = 0
display(wrong_count)
#init word data
word_len = len(word)
blank_word = []
for i in range(0, word_len):
blank_word += ['_']
print("Word:", ''.join(blank_word))
wrong_letters = []
print("Wrong Letters:", ', '.join(wrong_letters))
print("------------------------------")
#repeatedly take in and process letters
end_flag = False
while(end_flag == False):
#get a letter from user
valid_input = False
while(valid_input == False):
letter = input("Guess a letter: ")
letter = letter.lower()
valid_input = True
if(len(letter) != 1):
print("Please only enter a single letter. Try again.")
valid_input = False
if(letter < 'a' or letter > 'z'):
print("Please enter a letter. Try again.")
valid_input = False
if(letter in wrong_letters or letter in blank_word):
print("You already guessed that letter. Try again.")
valid_input = False
#letter is correct
letter_found = False
for i in range(0, word_len):
if(word[i] == letter):
blank_word[i] = letter
letter_found = True
#letter is wrong
if(letter_found == False):
wrong_count += 1
wrong_letters.append(letter)
#display
display(wrong_count)
print("Word:", ''.join(blank_word))
print("Wrong Letters:", ', '.join(wrong_letters))
print("------------------------------")
#you win!
if('_' not in blank_word):
end_flag = True
print("Congrats! You won Hangman!")
return
#you lose :/
if(wrong_count == 7):
end_flag = True
print("Too bad... you lost Hangman.")
return
def main():
print("Welcome to Hangman!")
#read in possible words from file
with open("words.txt") as f:
words_list = f.read().splitlines()
#play the game loop
continue_playing_flag = True
while(continue_playing_flag == True):
chosen_word = random.choice(words_list)
play_game(chosen_word)
answer = input("Would you like to play again? Enter 'yes' or 'no': ")
if(answer == 'yes'):
continue
elif(answer == 'no'):
continue_playing_flag = False
print("Goodbye! See you next time! :)")
exit(0)
if __name__ == "__main__":
main()
|
157200f1482306f44b9bc93a74a6280614dfd8ed | ToucanToco/toucan-data-sdk | /toucan_data_sdk/utils/postprocess/sort.py | 1,783 | 3.875 | 4 | from typing import TYPE_CHECKING, List, Union
if TYPE_CHECKING:
import pandas as pd
def sort(
df: "pd.DataFrame", columns: Union[str, List[str]], order: Union[str, List[str]] = "asc"
) -> "pd.DataFrame":
"""
Sort the data by the value in specified columns
---
### Parameters
*mandatory :*
- `columns` (*str* or *list(str)*): list of columns to order
*optional :*
- `order` (*str* or *list(str)*): the ordering condition ('asc' for
ascending or 'desc' for descending). If not specified, 'asc' by default.
If a list of columns has been specified for the `columns` parameter,
the `order` parameter, if explicitly specified, must be a list of same
length as the `columns` list (if a string is specified, it will be
replicated in a list of same length of the `columns` list)
---
### Example
**Input**
| variable | value |
|:--------:|:-----:|
| A | 220 |
| B | 200 |
| C | 300 |
| D | 100 |
```cson
sort:
columns: 'value'
```
**Output**
| variable | value |
|:--------:|:-----:|
| D | 100 |
| B | 200 |
| A | 220 |
| C | 300 |
"""
if isinstance(columns, str):
columns = [columns]
if isinstance(order, str):
assert order in ["asc", "desc"]
orders = [order == "asc"] * len(columns)
else:
assert len(order) == len(columns), "'columns' and 'order' lists must be of same length"
orders = []
for ord in order:
assert ord in ["asc", "desc"], f"Got order value: {order}. Expected 'asc' or 'desc'"
orders.append(ord == "asc")
return df.sort_values(columns, ascending=orders)
|
45a2f1d7d127c00a1be59cdc9cb2fd08aab6c8b7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/dlmlor002/question3.py | 255 | 4.1875 | 4 | import math
num=2
den=0
pi=2
count=1
while(den<2):
den=math.sqrt(2 + den)
term=num/den
pi*=term
count+=1
print("Approximation of pi:",round(pi,3))
radius=eval(input("Enter the radius:\n"))
area=pi*(radius**2)
print("Area:",round(area,3)) |
214fb8dcc69343e5278aeabb4adf7893f44c786d | wisesky/LeetCode-Practice | /utils/solution.py | 691 | 3.625 | 4 | import sys
import importlib
import argparse
def main(argv):
#print(argv)
# s1 cmd argv parser
#moduleName = argv[1] 必须事先指定参数类型,无法对所有Solution统一
#parser = argparse.ArgumentParser(description='Solution Time ')
#parser.add_argument('p1', type=int)
# s2 input
moduleName = input('Type in the module Name : ')
if moduleName.endswith('.py'):
moduleName = moduleName[ :-3]
so = importlib.import_module(moduleName).Solution()
func = getattr(so, moduleName)
#p1 = input('params1 = ')
#p2 = input('params2 = ')
#r = func(p1, p2)
print(func())
return
if __name__ == "__main__":
main(sys.argv)
|
f22a5f5e3532d8e334c7efbae8ecc56b71268cca | brycereynolds/practice | /algorithms/sorting/ComparatorSorting.py | 934 | 3.8125 | 4 | # See: https://www.hackerrank.com/challenges/ctci-comparator-sorting
from functools import cmp_to_key
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return repr(self.name, self.score)
def comparator(a, b):
if a.score > b.score:
return -1
elif a.score == b.score:
if a.name < b.name:
return - 1
else:
return 1
else:
return 1
# Another way to solve it that is super slick...
from functools import cmp_to_key
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def comparator(a, b):
# See https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types
return -1 if (a.score, b.name) > (b.score, a.name) else 1
|
7c6f71ef75bfb22655359f4f42bbbd9d53b574cb | dsinnovated/Workshops | /10-11-19 Intro_ML/load_data.py | 1,823 | 3.90625 | 4 | #import packages
import pandas as pd # The as keyword lets you shorten the name of the import package
original = pd.read_csv("simple_retail.csv") # Load the .csv file - It is important to note that you have to include the extension as well.
# If you do not specify a path, Python will assume the file is in the same directory as the code file you a running.
# Documentation for pandas.readcsv() https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
print(original) # Prints the dataframe we just created. If we view the variable explorer we can also see the dataframe.
#From here we can see that the dataframe consists of 541909 entries with these attributes: 0) Index 1)InvoiceNo 2) Description 3) Quantity 4) Invoice Date 5) UnitPrice 6) ConstomerID 7)Country
# Right now the data is sorted by InvoiceNo and Index. Let's try sorting by UnitPrice
# We can follow this documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html to sort
sort_by_price = original.sort_values(by=['UnitPrice'])
print("\n Sorted list by UnitPrice \n")
print(sort_by_price) # Unfortunately you won't see prices on the console unless you meddle with the settings a bit, but you can see that the dataset has clearly been changed. (you can open this in variable explorer to confirm)
# Let's say we want to export this new dataframe and store it.
# Again documentation if you need can be found here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html
sort_by_price.to_csv("simple_retail_sorted.csv")
|
72b7fdd295099cfa9aaf3ecd6b0a4e1574229231 | Merovizian/Aula22 | /Desafio109/teste.py | 1,052 | 3.75 | 4 | from leiaint import leiaint
from Desafio109 import moeda
print(f"\033[;1m{'Desafio 107 - Algumas funcoes matematicas':*^70}\033[m")
numero = 0
# loop para um menu facil
while True:
escolha = leiaint('''
1 - Criar/alterar numero
2 - Seu Dobro
3 - Sua Metade
4 - Aumentar
5 - Diminuir
0 - Sair
Escolha: ''',0,5)
if escolha == 0:
break
if escolha == 1:
numero = leiaint('Informe um numero: ')
if escolha == 2:
print(f"O dobro de {moeda.moeda(numero)} é {(moeda.dobro(numero,True))}")
if escolha == 4:
fator = leiaint('Informe o fator de aumento em %: ',0)
print(f"Aumentar {fator}% de {moeda.moeda(numero)} resulta em {(moeda.aumentar(numero,fator,True))}")
if escolha == 5:
fator = leiaint('Informe o fator de diminuição em %',0)
print(f"Diminuir {fator}% de {moeda.moeda(numero)} resulta em {(moeda.diminuir(numero,fator,True))}")
if escolha == 3:
print(f"A metade de {moeda.moeda(numero)} é {(moeda.metade(numero,True))}")
|
45f91ab175bb97124ced9bd90e2b35806cd80049 | 004sharmag/Python-practice | /board.py | 4,367 | 4.21875 | 4 | # a list for the game board
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# states the game is on going. Will break later on
game_on_going = True
winner = None
# first move
current_player = "X"
# function that prints out the board
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
# function beginning the game
def play():
# calls the function for printing the board
display_board()
# loop with functions that assigns the turn to either X or O, check if the game is won or tied, and changes
# players via turns
while game_on_going:
turn(current_player)
game_status()
change_player()
# prints the letter of the winner based on the functions below
if winner == "X" or winner == "O":
print(winner + " won.")
elif winner == None:
print("Tie")
# the player turn function that is called on 27, input position of board
def turn(player):
print(player + "'s turn")
position = input('Pick a spot between 1-9: ')
# if player inputs anything other than numbers 1-9 then this will loop requesting a valid input
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input('Invalid choice, please try again: ')
# indexes start at 0, so -1 equals the index the player chooses.
position = int(position) - 1
# ensures players cannot overwrite a position 1-9 that is already taken
if board[position] == "-":
valid = True
else:
print('You cannot go there, try again')
board[position] = player
display_board()
# game_status function is called on line 29. This determines a win or tie, with 2 function calls being defined below
def game_status():
check_win()
check_tie()
# called under game_status function. 3 function calls for the 3 ways too win: across, diagonal, up and down.
def check_win():
global winner
row_winner = check_rows()
column_winner = check_columns()
# returns the letter in any of those indexes for victory
diag_winner = check_diag()
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diag_winner:
winner = diag_winner
else:
winner = None
return
def check_rows():
global game_on_going
row_1 = board[0] == board[1] == board[2] != "-"
row_2 = board[3] == board[4] == board[5] != "-"
row_3 = board[6] == board[7] == board[8] != "-"
if row_1 or row_2 or row_3:
game_on_going = False
if row_1:
return board[0]
if row_2:
return board[3]
if row_3:
return board[6]
return
# checks the columns for victory
def check_columns():
global game_on_going
col_1 = board[0] == board[3] == board[6] != "-"
col_2 = board[1] == board[4] == board[7] != "-"
col_3 = board[2] == board[5] == board[8] != "-"
# returns the letter in any of those indexes for victory
if col_1 or col_2 or col_3:
game_on_going = False
if col_1:
return board[0]
if col_2:
return board[1]
if col_3:
return board[2]
return
# function checks diagonal victory
def check_diag():
global game_on_going
diag_1 = board[0] == board[4] == board[8] != "-"
diag_2 = board[2] == board[4] == board[6] != "-"
# returns the letter in any of those indexes for victory
if diag_1 or diag_2:
game_on_going = False
if diag_1:
return board[0]
if diag_2:
return board[2]
return
# checking for tie
def check_tie():
global game_on_going
if "-" not in board:
game_on_going = False
return
def change_player():
# Global variables we need
global current_player
# If the current player was X, make it O
# setting a value is = aka assignment operator
# == is for comparison of two variables, checking if they are equal
if current_player == "X":
current_player = "O"
# Or if the current player was O, make it X
elif current_player == "O":
current_player = "X"
return
# calls the play function to kick off the program!
play()
|
d0e166362951aa61daf12fafba5d7ab2b6900e9d | meghamohan/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 128 | 3.5 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
uniqList = set(my_list)
sumTheList = sum(uniqList)
return (sumTheList)
|
a78a44092bae2e9e1746d9a638dad069611f1f82 | glimmercn/Euler-Project | /src/solution/p65.py | 272 | 3.609375 | 4 | '''
Created on 2011-7-14
@author: huangkan
'''
from fractions import Fraction
from Mytools import contif2frac
e=[2]
for i in range(1,34):
e.append(1)
e.append(i*2)
e.append(1)
print(len(e))
a=contif2frac(e)
print(sum([int(i)for i in list(str(a.numerator))])) |
728ec706cb0543595e1168fcc7cd483231f61b1e | yamaton/codeforces | /problemSet/510A-Fox_And_Snake.py | 573 | 3.578125 | 4 | #!/usr/bin/env python3
"""
Codeforces
510 A. Fox and Snake
@author yamaton
@date 2015-07-30
"""
def solve(n, m):
grid = [['.'] * m for _ in range(n)]
for i in range(0, n, 2):
grid[i] = '#' * m
for i in range(1, n, 2):
if i % 4 == 1:
grid[i][-1] = '#'
elif i % 4 == 3:
grid[i][0] = '#'
return '\n'.join(''.join(xs) for xs in grid)
def main():
[n, m] = [int(i) for i in input().strip().split()]
assert n % 2 == 1
result = solve(n, m)
print(result)
if __name__ == '__main__':
main()
|
1573936f6403a401828c92a08b23c90774fb3359 | elenaborisova/Python-Basics | /13. Exam Prep Questions/04. SoftUni Past Exams/02. Repainting.py | 636 | 3.765625 | 4 | paper_amount_needed_sq_m = int(input())
paint_amount_needed_liters = int(input())
water_amount_needed_liters = int(input())
labor_hours_needed = int(input())
paint_amount_needed_liters += paint_amount_needed_liters * 0.1
paint_price = paint_amount_needed_liters * 14.50
paper_amount_needed_sq_m += 2
paper_price = paper_amount_needed_sq_m * 1.50
water_price = water_amount_needed_liters * 5
materials_total_price = paper_price + paint_price + water_price + 0.40
labor_price = (0.3 * materials_total_price) * labor_hours_needed
total_expenses = materials_total_price + labor_price
print(f"Total expenses: {total_expenses:.2f} lv.")
|
565fc6b25994e25e201f76f1bc9f1bc27b9499ae | bufordsharkley/advent_of_code | /2015/day12.py | 738 | 3.703125 | 4 | import json
def get_total_num(data, ignore_red=False):
if isinstance(data, basestring):
return 0
elif isinstance(data, int):
return data
elif isinstance(data, list):
return sum(get_total_num(item, ignore_red=ignore_red) for item in data)
elif isinstance(data, dict):
if ignore_red and ('red' in data or 'red' in data.values()):
return 0
return sum(get_total_num(v, ignore_red=ignore_red)
for v in data.values())
else:
raise NotImplementedError(data)
def main():
data = json.loads(open('input/input12.txt').read())
print get_total_num(data)
print get_total_num(data, ignore_red=True)
if __name__ == "__main__":
main()
|
0c109d910af292b8d6351c5dad3f3203bebd2b1f | akash1601/algorithms_leetcode_solution | /solutions/3sumCloset.py | 427 | 3.65625 | 4 | def threeSumCloset(nums,target):
#3sumCloset
nums.sort()
result = nums[0] + nums[1] + nums[2]
for i in range(len(nums)-2):
j, k = i+1, len(nums) -1
sum = nums[i] + nums[j] + nums[k]
while j < k:
if sum == target:
return sum
if abs(sum - target) < abs(result - target):
result = sum
if sum < target:
j += 1
elif sum > target:
k -= 1
print(result)
threeSumCloset([-1,2,0,5,6,1,-4],8)
|
0f465862031ff320422374243b97134f2eab58fa | liliarc96/Aula-Python | /Exercicios_2/adolescentes.py | 393 | 4.03125 | 4 | '''
• Faça um programa que lê a idade de várias pessoas
(enquanto o úsuario digitar valores positivos). Em
seguida, o algoritmo deverá apresentar a quantidade
de adolescentes (de 12 a 17 anos).
'''
adolescentes = 0
idade = 1
while idade > 0:
idade = int(input("Digite a idade: "))
if idade >=12 and idade <=17:
adolescentes += 1
print("O total de adolescente é de",adolescentes)
|
242b0e3c99716154607c7d33fcffc61e387f3922 | mayankchutani/warmup | /dynamic_programming/fibonacci.py | 423 | 3.796875 | 4 | __author__ = 'mayank'
def fib(n):
"""
Finds the fibonacci value of n
:return: integer value
"""
if n == 0:
return 0
if n == 1 or n == 2:
return 2
fibList = [None for i in range(n)]
fibList[0] = 0
fibList[1] = fibList[2] = 1
for i in range(2, n):
fibList[i] = fibList[i-1] + fibList[i-2]
return fibList[n-1]
if __name__ == '__main__':
print fib(10) |
41159614db05f9c25ea06121e0bd37912d0be17c | parkjmjohn/Computer_Graphics | /Project4/parser.py | 2,639 | 4.1875 | 4 | from display import *
from matrix import *
from draw import *
"""
Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
Every command is a single character that takes up a line
Any command that requires nextuments must have those nextuments in the second line.
The commands are as follows:
line: add a line to the edge matrix -
takes 6 nextuemnts (x0, y0, z0, x1, y1, z1)
ident: set the transform matrix to the identity matrix -
scale: create a scale matrix,
then multiply the transform matrix by the scale matrix -
takes 3 nextuments (sx, sy, sz)
move: create a translation matrix,
then multiply the transform matrix by the translation matrix -
takes 3 nextuments (tx, ty, tz)
rotate: create a rotation matrix,
then multiply the transform matrix by the rotation matrix -
takes 2 nextuments (axis, theta) axis should be x, y or z
apply: apply the current transformation matrix to the
edge matrix
display: draw the lines of the edge matrix to the screen
display the screen
save: draw the lines of the edge matrix to the screen
save the screen to a file -
takes 1 nextument (file name)
quit: end parsing
See the file script for an example of the file format
"""
def parse_file( fname, points, transform, screen, color ):
with open(fname) as f:
lines=f.readlines()
lines=[x.strip() for x in lines]
i=0;
while(i<len(lines)):
command=lines[i]
next=lines[i+1]
if(command=="line"):
points=next.split(" ")
add_edge(points,int(points[0]),int(points[1]),int(points[2]),int(points[3]),int(points[4]),int(points[5]))
i+=2
if(command=="ident"):
ident(transform)
i+=1
if(command=="scale"):
points=next.split(" ")
ret=make_scale(int(points[0]),int(points[1]),int(points[2]))
matrix_mult(ret,transform)
i+=2
if(command=="move"):
points=next.split(" ")
ret=make_translate(int(points[0]),int(points[1]),int(points[2]))
matrix_mult(ret,transform)
i+=2
if(command=="rotate"):
points=next.split(" ")
if(points[0]=="z"):
ret=make_rotZ(int(points[1]))
if(points[0]=="y"):
ret=make_rotY(int(points[1]))
if(points[0]=="x"):
ret=make_rotX(int(points[1]))
matrix_mult(ret,transform)
i+=2
if(command=="apply"):
matrix_mult(transform,points)
i+=1
if(command=="display"):
draw_lines(points,screen,color)
display(screen)
sleep(.5)
clear_screen(screen)
i+=1
if(command=="save"):
save_extension(screen,next)
clear_screen(screen)
i+=2
print_matrix(points)
f.close()
|
9b1078a82e55647db9a2a140f062f574832d5070 | harverywxu/algorithm_python | /01_string/03动荡子序列/978. 最长动荡子数组.py | 2,280 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
978. Longest Turbulent Subarray
A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:
For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.
That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.
Return the length of a maximum size turbulent subarray of A.
Example 1:
Input: [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])
Example 2:
Input: [4,8,12,16]
Output: 2
Example 3:
Input: [100]
Output: 1
"""
class Solution(object):
def maxTurbulenceSize0(self, A):
"""
:type A: List[int]
:rtype: int
"""
"""
keep state of each pair =>
increase: True,
decrease: False,
equal/init: None
state_change: True->False, False->True, +1
state not change: True->True, False->False, =2
equal: =1, contine
"""
if not A:
return 0
result = 1
sub_sum = 1
pre_state = None
for i in range(1, len(A)):
if A[i] > A[i-1]:
state = True
elif A[i] < A[i-1]:
state = False
else:
sub_sum = 1
state = None
continue
if state != pre_state:
sub_sum += 1
else:
sub_sum = 2
pre_state = state
if sub_sum > result:
result = sub_sum
return result
# Solution2
def maxTurbulenceSize1(self, A):
pre = 0
cur = 0
result = 1
sub_len = 1
for i in range(1, len(A)):
cur = cmp(A[i], A[i-1])
# (+/-), (-/+) 抖动,与之前状态不同,满足条件,+1
if pre*cur < 0:
sub_len += 1
# 当前状态为0,重新开始,sub_len = 0
elif cur == 0:
sub_len = 1
# (++,--,0+,0-) 当前状态不为0,且前后状态之积不为-1
else:
sub_len = 2
cur = pre
result = max(result, sub_len)
return result
|
87c2e287ea700db0fba71022785ae6fd41f0e15f | vicioussyndicate/JSmulligan | /matchingdbfid.py | 615 | 3.828125 | 4 | ##This function is to match the returned dbfIDs of each card, and then return the name
## of the string so that the cards a readable. Also we want to be able to write this function
## so we can organize the decklists that people are matching
import json
def matchdbfid(dbfid):
"""
Takes in the dbfid, and the dictionary of cards that was generated by parsing
through the hearthsims API which has a list of all the json files of each card
"""
with open("finalmatched.json", "r") as fin:
data = json.loads(fin.read())
d = dict(data)
name = d[dbfid]
return name
|
37e49590a3ba92b1cc782f95ae92f7531be72edf | IvaAndreeva/Anagrams | /anagrams-processor/task.py | 2,552 | 3.609375 | 4 | #!/usr/bin/env python
import sys
backup_words = ["ail", "tennis", "nails", "desk", "aliens", "table", "engine", "sail", "tail","sailq","aliensd", "taile", "pail", "pile", "lipea", "in", "sin", "sina"]
alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
def read_words():
try:
with open("words.txt") as f:
content = f.read()
f.close()
except IOError:
return backup_words
return content.split("\n")
def hash_word(word):
multi = 1
for letter in list(word):
multi *= hash_letter(word, letter)
return multi
def hash_letter(word, letter):
return ord(letter) * 7 + word.count(letter) * 23
def find_longest_of_initial_word(word, dict):
final_der = find_longest_derivation(word, dict, [])
final_der.append(word)
final_der.sort(key = lambda s: len(s))
return final_der
def find_longest_derivation(word, dict, der_list):
derivations = find_derivations(word, dict)
for derivation in derivations:
inner_list = []
inner_list.append(derivation)
longest = find_longest_derivation(derivation, dict, inner_list)
inner_list.extend(longest)
if len(inner_list)>len(der_list):
der_list=inner_list
return list(set(der_list))
def find_derivations(of_word, dict):
if not dict.has_key(len(of_word)+1):
return []
result = []
length = len(of_word) + 1
for letter in alpha:
new_hash = hash_word(of_word + letter)
if dict[length].has_key(new_hash):
result.append(dict[length][new_hash])
return result
def index_words(words):
dict = {}
for word in words:
hash = hash_word(word)
length = len(word)
if length < 3:
continue
if not dict.has_key(length):
dict[length] = {}
if not dict[length].has_key(hash):
dict[length][hash] = ""
dict[length][hash] = word
return dict
def words_with_length(dict, length):
words = []
if not dict.has_key(length):
return words
for hash in dict[length].keys():
words.append(dict[length][hash])
return words
if __name__ == "__main__":
print "Reading words ..."
words = read_words()
print "Indexing dictionary ..."
dict = index_words(words)
ders = []
for word in words_with_length(dict, 3):
print "Looking for derivations of ", word, "..."
final_der = find_longest_of_initial_word(word, dict)
ders.append(final_der)
print "Longest path of derivation of ", word, ": ", final_der
print "Longest path of derivation of all the three letter words is: ", max(ders, key=len) |
85acc6b0c2ef4e5bf4ec74b5f867d1ad7cd433ad | KaneLindsay/KNN-Digit-Recognition | /KNN/myKNN.py | 5,801 | 3.921875 | 4 | from sklearn import datasets
from sklearn.model_selection import train_test_split
import numpy as np
def main(k_neighbors, dataset, test_data_percent):
"""
Predict a class for every test image and find the accuracy of the algorithm using k neighbours.
Parameters
----------
k_neighbors : int
The number of neighbors to compare test images against
dataset : array_like
The dataset to work with
test_data_percent:
The percentage of data to use as test images
"""
# Reduce 1*64 images to feature vectors.
dataset.images = dataset.images.reshape(dataset.images.shape[0], dataset.images.shape[1] * dataset.images.shape[2])
# Split dataset into training images and labels - (x_train, y_train) and testing images and labels (x_test, y_test)
x_train, x_test, y_train, y_test = train_test_split(dataset.images, dataset.target, test_size=test_data_percent/100)
train_data = input("Train dataset with incremental growth? (Y/N):")
if train_data == "Y":
x_train, y_train = increment_grow(k_neighbors, x_train, y_train)
elif train_data == "N":
pass
else:
print("Input was neither Y or N. Data will not be pruned.")
print("----------------------\nCLASSIFYING TEST DIGITS...")
total_correct = 0
errors = []
i = 0
for test_image in x_test:
prediction = predict(k_neighbors, x_train, y_train, test_image)
if prediction == y_test[i]:
total_correct += 1
else:
errors.append(
{'Actual': y_test[i], 'Prediction': prediction})
i += 1
print("Correct classifications:", total_correct)
print("Incorrect classifications:", len(x_test) - total_correct)
print(errors)
accuracy = round((total_correct / i) * 100, 2)
print("Accuracy of "+str(k_neighbors)+" nearest neighbors is: "+str(accuracy)+"%\n With", 100-test_data_percent,
"% training data and", test_data_percent, "% testing data.")
return accuracy
# Euclidean distance finder
def euclidean_distance(img_a, img_b):
"""
Finds the distance between 2 images: img_a, img_b
Parameters
----------
img_a : array_like
First feature vector to compare
img_b : array_like
Second feature vector to compare
Returns
---------
float
The euclidean distance between images a and b
"""
return sum((img_a - img_b) ** 2)
def find_best_fit(labels):
"""
Find the total number of each label and returns the most frequent
Parameters
----------
labels : array_like
The set of k-closest labels
Returns
-------
int
The predicted class given using the most often occurring label
"""
counts = np.zeros(10, dtype=int)
best = 0
# Count the labels
for i in range(len(labels)):
counts[labels[i]] += 1
# Find the most often occurring label from the counts
for i in range(len(counts)):
if counts[i] > best:
best = i
return best
def predict(k, train_images, train_labels, test_image):
"""
Predict the class of a test image based on training images and labels.
Parameters
----------
k : int
The number of neighbors to compare the test image to
train_images : array_like
The array of training feature vectors
train_labels : array_like
The array of correct labels corresponding to training feature vectors
test_image : array_like
The feature vector to be classified
Returns
-------
int
The predicted label for the test image
"""
distances = []
k_closest_labels = []
for image in range(len(train_images)):
distances.append(
{'label': train_labels[image], 'distance': euclidean_distance(train_images[image], test_image)})
# Sort the images by their euclidean distance from the test image.
sorted_distances = sorted(distances, key=lambda k: k['distance'])
# Append the closest images' labels to the list of closest labels
for i in range(k):
k_closest_labels.append(sorted_distances[i].get("label"))
return find_best_fit(k_closest_labels)
def increment_grow(k, train_images, train_labels):
"""
Reduce the size of the training data by using incremental growth, which is output to a text file.
Parameters
----------
k : int
The number of neighbors to compare
train_images : array_like
The set of feature vectors to train on
train_labels : array_like
The set of corresponding labels for the feature vectors
Returns
-------
array_like
The training dataset reached through incremental growth
"""
print("----------------------\nINCREMENTALLY GROWING LABELS...")
# Edited instance-based learning: Incremental Growth
pruned_images = [train_images[0]]
pruned_labels = [train_labels[0]]
possible_neighbors: int
for i in range(len(train_labels)):
if len(pruned_labels) < k:
possible_neighbors = len(pruned_labels)
else:
possible_neighbors = k
prune_result = predict(possible_neighbors, pruned_images, pruned_labels, train_images[i])
if prune_result != train_labels[i]:
pruned_images.append(train_images[i])
pruned_labels.append(train_labels[i])
zipped_items = str(list(map(list, zip(pruned_images, pruned_labels))))
# Write pruned labels to a text file
text_file = open("F3Model.txt", "w")
text_file.write(zipped_items)
text_file.close()
print("Training elements before pruning: ", len(train_labels))
print("Training elements after pruning: ", len(pruned_labels))
return pruned_images, pruned_labels
|
64caa5b22addf183a7845fa308f5686d808a4024 | nguyenngochuy91/companyQuestions | /google/lexiSmallestEquiString.py | 2,096 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 17:57:10 2019
@author: huyn
"""
#1061. Lexicographically Smallest Equivalent String
#Given strings A and B of the same length, we say A[i] and B[i] are equivalent characters.
#For example, if A = "abc" and B = "cde", then we have 'a' == 'c', 'b' == 'd', 'c' == 'e'.
#
#Equivalent characters follow the usual rules of any equivalence relation:
#
#Reflexivity: 'a' == 'a'
#Symmetry: 'a' == 'b' implies 'b' == 'a'
#Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'
#For example, given the equivalency information from A and B above, S = "eed", "acd", and "aab"
#are equivalent strings, and "aab" is the lexicographically smallest equivalent string of S.
#
#Return the lexicographically smallest equivalent string of S by using the equivalency information from A and B.
class Solution:
def smallestEquivalentString(self, A: str, B: str, S: str) -> str:
graph = {}
for i in range(len(A)):
a = A[i]
b = B[i]
if a not in graph:
graph[a] = set()
if b not in graph:
graph[b] = set()
graph[a].add(b)
graph[b].add(a)
cc = []
visited = set()
for letter in graph:
if letter not in visited:
queue = [letter]
visited.add(letter)
current = [letter]
while queue:
node = queue.pop()
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
current.append(neighbor)
queue.append(neighbor)
cc.append(current)
graph = {}
for current in cc:
m = min (current)
for letter in current:
graph[letter] = m
output = ""
for letter in S:
if letter not in graph:
output+=letter
else:
output+=graph[letter]
return output |
d764d30574e70de77ef9ae854e1d6cdfb4ba603f | ynbstyj/MachineLearning | /KNN/02/knn_iris.py | 463 | 3.609375 | 4 | import pandas
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
dataset = (pandas.DataFrame(pandas.read_csv("iris.csv"))).values
X = dataset[:, 0:3]
y = dataset[:, 4]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
classifier = KNeighborsClassifier(n_neighbors = 3)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
print(y_test == y_pred)
|
db5cc553c851c669ac68fe9f0675415625054c42 | Srinithyee/AI-Lab | /EX 5/166_ai_work.py | 2,495 | 3.546875 | 4 | import math
import random
class point:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def dist(self, p2) -> int:
dx = self.x - p2.x
dy = self.y - p2.y
return math.sqrt(math.pow(dx,2) + math.pow(dy, 2))
@staticmethod
def genrand(limx: tuple, limy: tuple):
limx1, limx2 = limx
limy1, limy2 = limy
x = random.randint(limx1, limx2)
y = random.randint(limy1, limy2)
return point(x, y)
class polygon:
def __init__(self, points):
self.points = points
def inside(self, x: int, y: int) -> bool:
vals = []
for i in range(len(points) - 1):
x1, y1 = self.points[i].x, self.points[i].y
x2, y2 = self.points[i+1].x, self.points[i+1].y
A = -(y2-y1)
B = x2 - x1
C = -(A*x1 + B*y1)
vals.append(A*x + B*y + C)
x1, y1 = self.points[len(points) - 1].x, self.points[len(points) - 1].y
x2, y2 = self.points[0].x, self.points[0].y
A = -(y2-y1)
B = x2 - x1
C = -(A*x1 + B*y1)
vals.append(A*x + B*y + C)
t1 = all(d>=0 for d in vals)
t2 = all(d<=0 for d in vals)
return t1 or t2
class grid:
def __init__(self, m: int, n: int, polygons, start: point, goal: point):
self.actions = ["u", "d", "l", "r"]
self.m = m
self.n = n
self.polygons = polygons
self.current = start
self.goal = goal
def isGoal(self) -> bool:
return self.start == self.goal
def get_actions(self):
admissable_actions = []
for action in self.actions:
x, y = self.current
admissable = True
if action == "u":
y += 1
if action == "d":
y -= 1
if action == "l":
x -= 1
if action == "r":
x += 1
if(x < 0 or x >= self.n or y < 0 or y >= self.m):
continue
for polygon in self.polygons:
if polygon.inside(x, y) == True:
admissable = False
break
print(x, y, admissable)
if admissable:
admissable_actions.append(action)
return admissable_actions
|
7d60d1b4e1af63911fd83d883d06f83e64b02fca | Love-yadav/LibraryManagment | /video_101_Mini_project_library_harry_version.py | 2,311 | 4.25 | 4 | #create a library class
#display book
# lend book - who owns the book if book is not present
# add book
#return book
# harry library=Library(listofbooks ,libraryname)
# dirctionary=(books-nameoftheowner)
# create main function and run an infinte while loop asking
# user for their input
class Library:
def __init__(self,list,name):
self.listofbooks=list
self.name=name
self.lendDict={}
def DisplayBook(self):
for book in self.listofbooks:
print(book)
def lendbook(self,user,book):
if book not in self.lendDict.keys():
self.lendDict.update({book:user})
# self.listofbooks.remove(book)
print("Dictionary Database is updated successfully")
else:
print(f"Book is already being used {self.lendDict[book]}")
def addbook(self,book):
self.listofbooks.append(book)
print("BOok is added successfully")
def returnbook(self,book):
self.lendDict.pop(book)
if __name__ == '__main__':
love=Library(['hindi',"english","mathes","chemistry","social"],"Nobal")
while(True):
print(f"Welcome to the {love.name} library")
print("Choose the option from below")
print("1.DisplayBook")
print("2.lendBook")
print("3.addbook")
print("4.return book")
option=int(input("enter your choice:"))
if option == 1:
love.DisplayBook()
elif option == 2:
user=input("Enter your name")
book=input("enter the book name|which you want to lend")
love.lendbook(user,book)
elif option== 3:
book=input("enter the bookname you want to add")
love.addbook(book)
elif option == 4:
book=input("Enter the book name you want to return")
love.returnbook(book)
else:
print("please Choose the valid options form above")
print("press q to quit and press c to continue")
option1=''
while(option1!='c' and option1!='q'):
option1=input()
if option1 == "q":
exit()
elif option1 =="c":
continue
|
606e1b4bb6d9b52a752a624c62f16f919bb219be | Wecros/aoc-2020 | /day5/part1.py | 1,195 | 3.890625 | 4 | #!/usr/bin/env python
import fileinput
def compute_row(line):
"""Compute the row of the seat."""
low: int = 0
high: int = 127
for char in line[:7]:
diff: int = high - low
if char == 'F':
# lower half
high -= int(diff / 2 + 0.5)
elif char == 'B':
# upper half
low += int(diff / 2 + 0.5)
return high
def compute_col(line):
"""Compute the column of the seat."""
low: int = 0
high: int = 7
for char in line[7:]:
diff: int = high - low
if char == 'L':
# lower half
high -= int(diff / 2 + 0.5)
elif char == 'R':
# upper half
low += int(diff / 2 + 0.5)
return high
def main():
highest_seatID = 0
for line in fileinput.input():
line = line.strip()
# invalid input if the line isn't 7+3 characters long
if len(line) != 10:
continue
row = compute_row(line)
col = compute_col(line)
seatID = row * 8 + col
if seatID > highest_seatID:
highest_seatID = seatID
print(highest_seatID)
if __name__ == '__main__':
main()
|
1034ed2df456a96fa2e782c0d56200c3a1762a0f | greymatterrobotics/simple-movement-example | /robot.py | 472 | 3.515625 | 4 | from sr import *
import time
R = Robot()
#Move forward
R.motors[0].target = 100
R.motors[1].target = 100
print "Moving forward"
time.sleep(2)
#Turn around
R.motors[0].target = 50
R.motors[1].target = -50
print "Turning"
time.sleep(2) #Just change this line until the amount it turns is about 180 degrees
#Come back
R.motors[0].target = 100
R.motors[1].target = 100
print "Moving back"
time.sleep(2)
#Stop
R.motors[0].target = 0
R.motors[1].target = 0
print "Stopping" |
3de83a2d105982888743371cf7bb889c3daf9e55 | fucilazo/Dragunov | /机器学习/数据科学/sample5.1_图论.py | 1,578 | 3.53125 | 4 | import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph() # 定义一个图对象
plt.subplot(221)
G.add_edge(1, 2) # 在两个节点之间添加边(图本身不带节点,它会自动创建)
nx.draw_networkx(G) # 图的位置(节点)自动生成
# nx.draw_networkx(G, node_color='g', node_shape='*', edge_color='b')
plt.subplot(222)
# 增加节点
G.add_nodes_from([3, 4])
# 增加另外的边
G.add_edge(3, 4)
G.add_edges_from([(2, 3), (4, 1)])
nx.draw_networkx(G)
# 获得节点和边的集合
print(G.nodes())
print(G.edges())
# 列出每个节点的邻接节点-->邻接表
print(nx.to_dict_of_lists(G))
# 列出每条边
print(nx.to_edgelist(G)) # 每个元组的第三个因素是边的属性
# 将图描述为NumPy矩阵(矩阵(i,j)位置的值为1,则表示节点i,j相连通)
print(nx.to_numpy_matrix(G))
# 对于稀疏矩阵
print(nx.to_scipy_sparse_matrix(G))
plt.subplot(223)
# 添加一条新的边
G.add_edge(1, 3)
nx.draw_networkx(G)
# 计算各节点的度
print(nx.degree(G))
# 对于大规模的图,常常利用节点度的直方图来近似其分布
# 建立一个具有10000个节点,链接概率为1%的随机网络,提取并显示该网络图节点度的直方图
# plt.hist(nx.fast_gnp_random_graph(10000, 0.01).degree())
# plt.show()
plt.subplot(224)
# degree_list = []
# for i in nx.fast_gnp_random_graph(10000, 0.01).degree():
# degree_list.append(i[1])
degree_list = [i[1] for i in nx.fast_gnp_random_graph(10000, 0.01).degree()]
print(degree_list)
plt.hist(degree_list)
plt.show() |
97374fc9176a37d4c97b83bf68feed57363a9fe2 | jacosta18/Raindrops_project | /formal_code.py | 600 | 4.5 | 4 | # Stage 1: Identifying the sounds and factors
# - The following part of the code demonstrates the factors 3, 5, 7 being assigned sounds:
sound_factors = {
3: "Pling",
5: "Plang",
7: "Plong",
}
# Return the sound effects assigned to factors.
def raindrops(number):
return [sounds for a, sounds in sound_factors.items() if number % a == 0]
# .items() method returns all dictionary keys with values.
def convert(number):
return "".join(raindrops(number)) or str(number)
# " ".join(raindrops(number)) is a form of concatenation with the elements of a iterable.
|
61b82ab899c2d77e842f75ba49b592d279230f77 | KennyTzeng/LeetCode | /905/main.py | 502 | 3.65625 | 4 | class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
i, j = 0, len(A)-1
while i < j:
# to find the next odd number
while not A[i] % 2 and i < len(A)-1:
i += 1
# to find the next even number
while A[j] % 2 and j > 0:
j -= 1
# swap
if i < j:
A[i], A[j] = A[j], A[i]
return A |
4026d3956f96d1e304c5dd20c10fd37bcc47d53b | devankit01/jumblewordapp | /Tkinter/Jumbleinpy/main.py | 1,472 | 3.59375 | 4 | # App
from tkinter import *
from tkinter import messagebox
import random
ans=['python','lucknow','italy','engineer','maths','automata','india','laptop','phone']
jmb=['yponth','ckluonw','altit','gieneren','tsham','mautota','idani','ptlapo','openh']
sc=['1','2','3','4','5','6','7','8','9']
logic = random.randrange(0,10,1)
def fun():
global ans,jmb,logic,sc
lb1.config(text=jmb[logic])
def checkans():
global ans,jmb,logic,sc
var = e1.get()
counter=-1
if(var == ans[logic]):
messagebox.showinfo('Good','Right Answer Dude')
reset()
else:
messagebox.showerror('oops','Wrong Answer')
e1.delete(0,END)
def reset():
global ans,jmb,logic,sc
logic=random.randrange(0,10,1)
lb1.config(text=jmb[logic])
e1.delete(0,END)
root=Tk()
root.geometry('300x400')
root.title('Jumbled Word App')
lb1=Label(
root,
text='Play Game',
font=('Verdana',18),
)
lb1.pack(pady=30)
# collect
# userans = StringVar()
e1 = Entry(
root,
font=('Verdana',15),
# textvariable = userans
)
e1.pack(pady=30)
btnchk=Button(
root,
text='Check',
font = ('Cursive',12),
width='14',
bg='Blue',
fg='White',
relief=GROOVE,
command=checkans
)
btnchk.pack(pady=20)
btnrst=Button(
root,
text='Reset',
font = ('Cursive',12),
width='14',
bg='Red',
fg='White',
relief=GROOVE,
command=reset
)
btnrst.pack()
# calling function
fun()
root.mainloop() |
723b16c126dce4dee2143dac5bf66dfe117050c4 | SriYUTHA/PSIT | /Examination/Donut.py | 490 | 3.84375 | 4 | """Donut"""
def main():
"""Donut"""
cost = int(input())
num_buy = int(input())
num_free = int(input())
num_want = int(input())
pack = num_want//(num_buy+num_free)
remain = num_want%(num_buy+num_free)
get_donut = 0
cost_all = 0
if remain >= num_buy:
pack += 1
else:
get_donut += remain
cost_all += cost*remain
cost_all += pack*num_buy*cost
get_donut += pack*(num_free+num_buy)
print(cost_all, get_donut)
main()
|
8af55c40874e837e7de3956330d793261c8ca578 | Cammr94/Spring2019_Python1_Data119 | /Week6/reading_homework_5a_reverse_string.py | 983 | 4.5625 | 5 | # -*- coding: utf-8 -*-
"""
Cameron Reading
Data 119 Python 1
3/7/2019
Homework 5 A Outputing String and Reverse from user
"""
#Getting String from User, and store it and find its length
user_string = input("Please type a sentence out and I'll reverse it!: ")
string_length = len(user_string)
#Setting word "Accumaltor" to a blank string
reversed_string = ''
#Repeats till it gets to the begining of the string, using determined length
for letter_num in range(string_length, 0, -1):
#Adds character to empty string useing letter_num from for loop
#as the position to what letter to take from the user, and assign it
#onto the end of the empty reverse string.
#And repeats, until all of the string's character are added tp new string
reversed_string = reversed_string + user_string[letter_num - 1]
#Prints out the new reversed string and outputs the character length of string
print(reversed_string)
print("Character Length of String:", string_length)
|
24a972ac0f8c428e245100f69cb0992e234c1b11 | kevin-goulding/AdventOfCode | /2019day6.py | 1,517 | 3.578125 | 4 | filename = "...\\2019day6.txt"
infile = open(filename, 'r')
orbits = []
for line in infile:
orbits.append(line)
infile.close()
#orbitDict is a dictionary where key:value = (orbiter): (planet that orbiter orbits)
orbitDict = {}
for orbit in orbits:
twoOrbitList = orbit.split(")")
orbitDict[twoOrbitList[1][0:3]]=twoOrbitList[0][0:3]
def pursueorbit(key, orbitCount):
orbitCount+=1
if orbitDict[key]=='COM':
return(orbitCount)
else:
return(pursueorbit(orbitDict[key], orbitCount))
def numToPlanets(orbiter, orbitDict):
posDict = {}
position = 1
orbited = orbitDict[orbiter]
while orbited != 'COM':
posDict[orbited] = position
position += 1
orbiter = orbited
orbited = orbitDict[orbiter]
return (posDict)
def part1(orbitDict):
totalOrbits=0
for key in orbitDict.keys():
totalOrbits += pursueorbit(key, 0)
print(totalOrbits)
def part2(orbitDict):
santa = numToPlanets('SAN', orbitDict)
you = numToPlanets('YOU', orbitDict)
common = []
for key in santa.keys():
if key in you.keys():
totalDist = santa[key]+you[key]
common.append(totalDist)
print(min(common)-2) #Subtract 2 to account for the fact that we're looking at the distance between planets that SAN and YOU orbit. Without subtracting 2, it includes a move from SAN to its planet, and YOU to its planet
part1(orbitDict)
part2(orbitDict) |
58a9e1f70ea4273cddc29adc6893dd16a1c84371 | ChoiKangM/buildUpPython | /Week_4/function.py | 141 | 3.515625 | 4 | def func1():
a = 10
print("func1에서 a의 값: %d" % a)
def func2():
print("func2에서 a의 값: %d" % a)
a = 20
func1()
func2() |
86a775aaec8325e8fffe23b26c66c8db9ae5d6e7 | caique-santana/CursoEmVideo-Curso_Python3 | /PythonExercicios/ex024 - Verificando as Primeiras Letras de um Texto.py | 363 | 4.15625 | 4 | #Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO".
# Meu
cidade = input('Qual o nome da sua cidade: ')
print('O nome da cidade começa com "Santo" ? \033[1;36m{}\033[m.'.format('SANTO' in cidade.upper().split()[0]))
# Gustavo Guanabara
cid = str(input('Em que cidade você nasceu? ')).strip()
print(cid[:5].upper() == 'SANTO') |
5ac5c991451eba2c198a63d69170e980cca112d0 | git874997967/codingbat_solutions | /lone_sum.py | 190 | 3.625 | 4 | def lone_sum(a, b, c):
sum = a + b + c
if a == b and a == c :
return 0
if a == b:
return c
elif a == c:
return b
elif c == b:
return a
return sum
|
713e0acbbd51ec5cf88525441b19291be7507e09 | Kallil12/anotacoes-cursos-online | /Datacamp - Python - Statistical Thinking/1 - statistical thinking pt 1/lecture-1.py | 2,653 | 3.859375 | 4 | # exercise 1
# Import plotting modules
import matplotlib.pyplot as plt
import seaborn as sns
# Set default Seaborn style
sns.set()
# Plot histogram of versicolor petal lengths
plt.hist(versicolor_petal_length)
# Show histogram
plt.show()
# ----//---- ----//---- ----//---- ----//---- ----//---- ----//----
# exercise 2
# Plot histogram of versicolor petal lengths
_ = plt.hist(versicolor_petal_length)
# Label axes
_ = plt.xlabel("petal length (cm")
_ = plt.ylabel("count")
# Show histogram
plt.show()
# ----//---- ----//---- ----//---- ----//---- ----//---- ----//----
# exercise 3
# Import numpy
import numpy as np
# Compute number of data points: n_data
n_data = len(versicolor_petal_length)
# Number of bins is the square root of number of data points: n_bins
n_bins = np.sqrt(n_data)
# Convert number of bins to integer: n_bins
n_bins = int(n_bins)
# Plot the histogram
plt.hist(versicolor_petal_length, bins=n_bins)
# Label axes
_ = plt.xlabel('petal length (cm)')
_ = plt.ylabel('count')
# Show histogram
plt.show()
# ----//---- ----//---- ----//---- ----//---- ----//---- ----//----
# exercise 4
# Create bee swarm plot with Seaborn's default settings
sns.swarmplot(x="species",y="petal length (cm)",data=df)
# Label the axes
_ = plt.xlabel("Species")
_ = plt.ylabel("Petal Length")
# Show the plot
plt.show()
# ----//---- ----//---- ----//---- ----//---- ----//---- ----//----
# exercise 5
def ecdf(data):
"""Compute ECDF for a one-dimensional array of measurements."""
# Number of data points: n
n = len(data)
# x-data for the ECDF: x
x = np.sort(data)
# y-data for the ECDF: y
y = np.arange(1,n+1) / n
return x, y
# ----//---- ----//---- ----//---- ----//---- ----//---- ----//----
# exercise 6
# Compute ECDF for versicolor data: x_vers, y_vers
x_vers, y_vers = ecdf(versicolor_petal_length)
# Generate plot
plt.plot(x_vers,y_vers, marker='.', linestyle='none')
# Label the axes
_ = plt.xlabel("length")
_ = plt.ylabel("ECDF")
# Display the plot
plt.show()
# ----//---- ----//---- ----//---- ----//---- ----//---- ----//----
# exercise 7
# Compute ECDFs
x_set,y_set= ecdf(setosa_petal_length)
x_vers,y_vers= ecdf(versicolor_petal_length)
x_virg,y_virg= ecdf(virginica_petal_length)
# Plot all ECDFs on the same plot
_ = plt.plot(x_set,y_set, marker='.', linestyle='none')
_ = plt.plot(x_vers,y_vers, marker='.', linestyle='none')
_ = plt.plot(x_virg,y_virg, marker='.', linestyle='none')
# Annotate the plot
plt.legend(('setosa', 'versicolor', 'virginica'), loc='lower right')
_ = plt.xlabel('petal length (cm)')
_ = plt.ylabel('ECDF')
# Display the plot
plt.show()
|
bef2e9d79c8639b289fcd0ea06fc5279159d15b2 | kkoutoup/Kickstart-Github-Project | /Dependencies/select_language.py | 768 | 4 | 4 | # What language will you be scripting in?
def select_language():
print("\n=> Select language")
languages = ["Python", "Ruby", "Javascript", "HTML"]
for index, language in enumerate(languages, start = 1):
print(f'{index}: {language}')
user_input = int(input("What language will you be scripting in? Select index ").strip())
if user_input <= len(languages):
print(f"You selected {languages[user_input - 1]}")
return languages[user_input - 1]
else:
print(f"Your list doesn\'t contain as many languages (max = {len(languages)})")
return select_language()
def set_language_extension():
language = select_language()
return {
'Python': '.py',
'Javascript': '.js',
'Ruby': '.rb',
'HTML': '.html'
}[language] |
12c204fc1a5bd4877ef53f36683d2dc83c3c5de8 | TesztLokhajtasosmokus/velox-syllabus | /week-04/4-recursion/hints/fractal.py | 332 | 3.84375 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width=600, height=600)
canvas.pack()
def fractal(x, y, size):
canvas.create_oval(x, y, x+size, y+size, fill="yellow")
if size < 10:
pass
else:
fractal(x, y, size/2)
fractal(x+size/2, y+size/2, size/2)
fractal(5, 5, 590)
root.mainloop()
|
cefe8c8678beca7b5fb691ef8b2c552ccef70d3b | zzinsane/algos | /Equili.py | 423 | 3.578125 | 4 |
# you can write to stdout for debugging purposes, e.g.
# print "this is a debug message"
def solution(A):
# write your code in Python 2.7
total = sum(A)
current = 0
result = []
for idx,ele in enumerate(A):
if total - ele - current == current:
result.append(idx)
current += ele
return result[0] if len(result) > 0 else -1
print solution([-1, 3, -4, 5, 1, -6, 2, 1])
print solution([-1])
print solution([])
|
2c9074eab6f28c40f707f512fffe7f4ef903bc6e | CezOni/MTEC2280 | /Oniszczuk_Calculator2.py | 500 | 4.0625 | 4 | import sys
calc = 0
number = input("Enter first number: ")
sign = input("Enter symbol you need (+,-,*,/): ")
number2 = input("Enter second number: ")
if(sign == '+'):
calc = int(number) + int(number2)
print(number + '+' + number2)
if(sign == '-'):
calc = int(number) - int(number2)
print(number + '-' + number2)
if(sign == '*'):
calc = int(number) * int(number2)
print(number + '*' + number2)
if(sign == '/'):
calc = int(number) / int(number2)
print(number + '/' + number2)
print(calc) |
79eb13b1119ee706cd9fd004b99b2b392ad0a9f7 | TMenezesO/Python-UERJ | /Aula5/ex1.py | 289 | 3.609375 | 4 | list_values=[10,20,30]
def listoperations(lista):
print (max(lista))
print (min(lista))
print (sum(lista))
def listmultiply(lista):
res = 1
for x in lista:
res = res*x
print (res)
return res
listoperations(list_values)
listmultiply(list_values)
|
7f85b1c86e44a38b5248019ed1c42c5d6848e355 | alabavery/Email_Distribution_Tool | /file_management.py | 2,279 | 3.578125 | 4 | import os
import glob
import json
import file_io
def prompt_user_to_save_csv(data_dir_path):
# no return
csv_file_list = []
while True:
csv_file_list = glob.glob(data_dir_path + '/*.csv')
if len(csv_file_list) > 0:
break
print()
print("..........................................................")
print("CSV data file not found at " + data_dir_path + "/")
print("Please save file as a '.csv' to " + data_dir_path + "/ before continuing.")
input("Press ENTER when you have saved the file...")
def get_csv_file_path(data_dir_path):
# must be sure that this will not be run before success of prompt_user_to_save_csv()
return glob.glob(data_dir_path + '/*.csv')[0]
def copy_csv_to_all_addresses_json_file(data_dir_path, all_addresses_file_path):
csv_file_path = get_csv_file_path(data_dir_path)
csv_addresses = file_io.get_csv_addresses(csv_file_path)
all_addresses = {'used': {'both_fields': [], 'one_field_only': []}, 'unused': csv_addresses}
file_io.write_json_data(all_addresses_file_path, all_addresses)
def fill_data_dir(data_dir_path, all_addresses_file_path, seen_email_file_path, client_secret_file_path, client_secret):
prompt_user_to_save_csv(data_dir_path)
copy_csv_to_all_addresses_json_file(data_dir_path, all_addresses_file_path)
file_io.write_json_data(seen_email_file_path, []) # make seen email file containing only empty list json
file_io.write_json_data(client_secret_file_path, client_secret)
def ensure_data_exists(data_dir_path, all_addresses_file_path, seen_email_file_path, client_secret_file_path, client_secret):
"""
Takes string, no return
More on logic -> 3rd answer at https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist
"""
try:
os.makedirs(data_dir_path)
print("Created folder at " + data_dir_path)
fill_data_dir(data_dir_path, all_addresses_file_path, seen_email_file_path, client_secret_file_path, client_secret)
except OSError: # will get OSError if the dir exists, if you don't have permissions, or other cases
if not os.path.isdir(data_dir_path): # only pay attention to the error if it is NOT due to the dir existing already
raise # make sure you know what happens if you don't have permissions so you can troubleshoot if that comes up
|
65945db4d3716494bba09d5f8b63cf501c5ea028 | hrssurt/lintcode | /lintcode/1281 Top K Frequent Elements.py | 983 | 3.765625 | 4 | """*************************** TITLE ****************************"""
"""1281 Top K Frequent Elements.py"""
"""*************************** DESCRIPTION ****************************"""
"""
Given a non-empty array of integers, return the k most frequent elements.
"""
"""*************************** EXAMPLES ****************************"""
"""
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
"""
"""*************************** CODE ****************************"""
class Solution:
"""
@param nums: the given array
@param k: the given k
@return: the k most frequent elements
"""
def topKFrequent(self, nums, k):
if not nums:
return []
if k >= len(nums):
return list(set(nums))
d = {}
for n in nums:
d[n] = d.get(n, 0) + 1
vk_pairs = sorted([(v,k) for k,v in d.items()], reverse = True)[:k]
return [p[1] for p in vk_pairs]
|
e68df0f29fd26bdbbb084600edfe39ce4ce2f201 | Jason003/interview | /Reverse Linked List.py | 565 | 3.828125 | 4 | class Solution:
def reverseList(self, head: ListNode) -> ListNode:
dummy = ListNode()
dummy.next = head
curr = head
while curr and curr.next:
nxt = curr.next
curr.next = nxt.next
nxt.next = dummy.next
dummy.next = nxt
return dummy.next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
res = self.reverseList(head.next)
head.next.next = head
head.next = None
return res |
8fc9517babab7411219386ba6d28821ee6f711ed | josephJJ1020/rockpaperscissors_CLS | /rockpaperscissors.py | 4,365 | 3.96875 | 4 | import random
import time
class Player:
def __init__(self):
self.score = 0
self.pick = None
class Game:
def __init__(self):
self.choices = ["rock", "paper", "scissors"]
self.options = ["Y", "N"]
self.running = True
def run(self):
if self.running is False:
exit()
else:
print("Rock paper scissors game\nRace to 5\n1 = rock; 2 = paper; 3 = scissors")
def close():
play_again = input("Would you like to play again? (Y/N)").upper()
if play_again not in self.options:
print("Invalid input!")
close()
if play_again == self.options[0]:
computer.score = 0
player.score = 0
play()
if play_again == self.options[1]:
print("Thank you for playing!")
self.running = False
self.run()
def play():
if player.score == 5:
print("You win!")
close()
elif computer.score == 5:
print("You lose!")
close()
else:
time.sleep(1)
player_input = int(input("Place your pick!"))
if player_input > 3 or player_input < 1:
print("Invalid input!")
play()
player.pick = self.choices[player_input-1]
computer.pick = random.choice(self.choices)
if computer.pick == player.pick:
print(f"\n\n\n\n\nYou both picked {computer.pick}! Try again!")
print(f"Player {player.score} - {computer.score} Computer\n\n\n\n")
play()
if computer.pick == self.choices[0]:
print(f"\n\n\n\n\nComputer picked {computer.pick}!")
time.sleep(1)
if player.pick == self.choices[1]:
print("You win!")
player.score += 1
print(f"Player {player.score} - {computer.score} Computer\n\n\n\n")
play()
if player.pick == self.choices[2]:
print("You lose!")
computer.score += 1
print(f"Player {player.score} - {computer.score} Computer\n\n\n\n")
play()
if computer.pick == self.choices[1]:
print(f"\n\n\n\n\nComputer picked {computer.pick}!")
time.sleep(1)
if player.pick == self.choices[0]:
print("You lose!")
computer.score += 1
print(f"Player {player.score} - {computer.score} Computer\n\n\n\n")
play()
if player.pick == self.choices[2]:
print("You win!")
player.score += 1
print(f"Player {player.score} - {computer.score} Computer\n\n\n\n")
play()
if computer.pick == self.choices[2]:
print(f"\n\n\n\n\nComputer picked {computer.pick}!")
time.sleep(1)
if player.pick == self.choices[0]:
print("You win!")
player.score += 1
print(f"Player {player.score} - {computer.score} Computer\n\n\n\n")
play()
if player.pick == self.choices[1]:
print("You lose!")
computer.score += 1
print(f"Player {player.score} - {computer.score} Computer\n\n\n\n")
play()
play()
player = Player()
game = Game()
computer = Player()
if __name__ == "__main__":
game.run()
|
e4b918492414a6fa4f03097b311aba74d43c7a2f | ysmirnova/PythonCourse | /utils/Fibo.py | 321 | 4.3125 | 4 | def generatefibonacci(length):
if length == 0:
return 0
else:
a, b = 0, 1
for i in range(2, length + 1):
a, b = b, a + b
return b
if __name__ == "__main__":
print("Input number for number in Fibonacci sequence: ")
n = int(input())
print(generatefibonacci(n))
|
90d0c67a147c853476bddb62210947414df7ccf8 | Rishu-aery/python_learning | /pallavi_practice.py | 1,015 | 4 | 4 | # Input : test_str = ‘Gfg is best’
# Output : {‘Gfg’: 1, ‘is’: 1, ‘best’: 1}
#
# Input : test_str = ‘Gfg Gfg Gfg’
# Output : {‘Gfg’: 3}
# str = " pallavi is the good girl"
# a = {i:str.count(i) for i in str.split()}
# print(a)
# Python – Convert Snake case to Pascal case
# Input : geeks_for_geeks
# Output : GeeksforGeeks
#
# Input : left_index
# Output : leftIndex
# str = "geeks_for_geeks"
# a = "".join([ i for i in str.title().split("_")])
# print(a)
# str = "geeks_for_geeks"
# print(str.title().replace("_",""))
'''Python program to print even length words in a string'''
# Input: s = "This is a python language"
# Output: This
# is
# python
# language
#
# Input: s = "i am muskan"
# Output: am
# muskan
str = "This is a python language"
a = str.split(" ")
newlist = [] # sade kol i ch pya hoya this te asi otho na this di len find kr liye?hmmm
for i in a:
n = len(i)
if n%2 == 0 :
newlist.append(i)
print(newlist)
|
9508afbd284b963958a63c15830e3629f24aac23 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/3135.py | 692 | 3.5 | 4 | #!/usr/bin/env python
from sys import stdin
cases = int(stdin.readline())
for i in range(1, cases + 1):
row = int(stdin.readline())
for k in range(1, 5):
line = stdin.readline()
if k == row:
nums = set(line.split())
row = int(stdin.readline())
for k in range(1, 5):
line = stdin.readline()
if k == row:
nums2 = set(line.split())
same = nums.intersection(nums2)
if len(same) == 1:
(element,) = same
print("Case #" + str(i) + ": " + str(element))
elif len(same) > 1:
print("Case #" + str(i) + ": Bad magician!")
else:
print("Case #" + str(i) + ": Volunteer cheated!")
|
6d67a44123c2175c79b4a7105fb923554b71b01e | MuYi0420/newstudy | /python/function-2.py | 482 | 3.921875 | 4 | def discounts(price, rate):
final_price=price*rate
# print (old_price) 结果为全局变量,可以访问,不可修改
old_price = 50
print ('修改后的old_price的值是1:',old_price) #新建一个old_price的局部变量,与全局变量无关
return final_price
old_price = float(input('请输入原价: '))
rate = float(input("请输入折扣率: "))
new_price=discounts(old_price, rate)
print ('修改后的old_price的值是2:',old_price)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.