blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
63c28b4a1bc9dfe225ab54e40f643734b8754bd6 | Pankaj-GoSu/Python-Tutorials | /Advanced/Qu3.py | 87 | 3.703125 | 4 | num =int(input("Enter a number"))
table = [num*(i+1) for i in range(10) ]
print(table) |
9941a5bfbf8964a592e973efbb49fd18742d8f5b | truongductri01/Hackerrank_problems_solutions | /Problem_Solving/Medium/3D_Surface_Area/3D_Surface_Area.py | 2,442 | 3.828125 | 4 | # Link: https://www.hackerrank.com/challenges/3d-surface-area/problem
# first create an array which consists of the following things
# for even indexed element represent the common side of two adjacent block in a row
# for the odd indexed element represent the common side of two adjacent block in each column of two continuous row
def difArray(A):
result = []
if len(A) == 1:
if len(A[0]) == 1:
return 0
else:
for i in range(len(A[0]) - 1):
result.append(min(A[0][i], A[0][i + 1]))
return sum(result)
else:
for i in range(len(A) - 1):
r = []
c = []
if len(A[i]) == 1:
r.append(0)
else:
for j in range(len(A[i]) - 1):
r.append(min(A[i][j], A[i][j + 1]))
for j in range(len(A[i])):
c.append(min(A[i][j], A[i + 1][j]))
result.append(r)
result.append(c)
if len(A[-1]) == 1:
result.append([
0]) # as later we do sum for each small array in the big result array, so we need array typr for every element
else:
arr = []
for i in range(len(A[-1]) - 1):
arr.append(min(A[-1][i], A[-1][i + 1]))
result.append(arr)
# calculate sum of result
s = 0
for i in result:
s += sum(i)
# print(result)
return s
def surfaceArea(A):
s = 0
for i in A:
for j in i:
s += 6 * j - (j - 1) * 2
# print(s)
return s - difArray(A) * 2
if __name__ == "__main__":
f = open("Input")
arr = f.readline().rstrip().split()
H = int(arr[0])
W = int(arr[1])
A = []
for _ in range(H):
A.append(list(map(int, f.readline().rstrip().split())))
# print(H,W)
# print(A)
print(surfaceArea(A))
# print(difArray(A))
# difArray(A)
f.close()
'''
What I have learned:
1. Be careful with sum.
If I use code:
arr=[[1,2], 2]
for i in arr:
print(sum(i))
then there will be an error as the last element is not array.
So I have to use:
arr=[[1,2], [2]]
2. Be aware of return statement in function, especially with if and esle condition.
If return appear in a if branch, it has to appear in the elif and else branch to, vice versa.
''' |
e636bb6eab41001f7fc108e259762b440cd390d1 | unlimitediw/CheckCode | /0.算法/147_InsertionSortList.py | 2,850 | 3.96875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = result = ListNode(0)
while head:
if result and result.val > head.val:
result = dummy
while result.next and result.next.val < head.val: # 不用全刷新 如果head大于上一次的值 那就从上一次那个位置开始刷新,很小的一个优化但是在这道题比较有用
result = result.next
temp = result.next
h_temp = head.next
result.next = head
result.next.next = temp
head = h_temp
# !!! ,, = ,, 完美解决temp问题
# result.next, result.next.next, head = head, result.next, head.next
return dummy.next
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head:
result = ListNode(head.val)
while head.next:
head = head.next
result_repre = result
if head.val < result.val:
temp = result
result = ListNode(head.val)
result.next = temp
else:
while True:
if not result_repre.next:
result_repre.next = ListNode(head.val)
break
if head.val < result_repre.next.val:
temp = result_repre.next
result_repre.next = ListNode(head.val)
result_repre.next.next = temp
break
result_repre = result_repre.next
return result
else:
return
def insertionSortList2(self, head):
if head:
result = [head.val]
while head.next:
head = head.next
for i in range(len(result) - 1, -1, -1):
if head.val > result[i]:
result.insert(i + 1, head.val)
break
elif i == 0:
result.insert(0, head.val)
result_node = ListNode(result[0])
result_node_repre = result_node
for n in result[1:]:
result_node_repre.next = ListNode(n)
result_node_repre = result_node_repre.next
return result_node
a = Solution()
k = ListNode(4)
k.next = ListNode(2)
k.next.next = ListNode(3)
k.next.next.next = ListNode(1)
print(a.insertionSortList(k).val)
|
f490e6054c9d90343cab89c810ca2c649d8138fe | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/mergeIntervals.py | 1,167 | 4.125 | 4 | """
Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
"""
Time: O(nlogn)
Space: O(n)
"""
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
start, end, result = [], [], []
for interval in intervals:
st, en = interval.start, interval.end
start.append(st)
end.append(en)
start.sort()
end.sort()
i = 0
while i < len(intervals):
st = start[i]
while i < len(intervals) - 1 and start[i + 1] <= end[i]:
i += 1
en = end[i]
result.append([st, en])
i += 1
return result
|
95e783903edc5da26d88e2f6243b5c8f5492aa03 | cafaray/atco.de-fights | /newNumeralSystem2.py | 226 | 3.53125 | 4 | def newNumeralSystem(number):
res = []
n = ord(number) - 65
for x in range(0,26):
for y in range(0,26):
if x+y ==n and x<=y:
res+=[chr(65+x) + ' + ' + chr(65+y)]
return res
|
a95a89372a4d22d820b80273034c4915913968cc | crjake/snake | /snake.py | 3,034 | 3.5625 | 4 | import pygame
import random
class Snake:
color = (0, 255, 0)
def __init__(self, x, y):
self.cells = [Cell(x, y)]
self.direction = 'LEFT'
def draw(self, screen):
for cell in self.cells:
cell.draw(screen)
def grow(self, x, y):
self.cells.insert(0, Cell(x,y))
def eat(self, food):
head = self.cells[0]
if food != None and head.x == food.x and head.y == food.y:
self.grow(food.x, food.y)
return True
return False
def outofbounds(self, x1, x2, y1, y2):
head = self.cells[0]
return head.x < x1 or head.x > x2 or head.y < y1 or head.y > y2
def collides(self, x, y, include_head):
for cell in self.cells:
if (not include_head) and (cell == self.cells[0]):
continue
if cell.x == x and cell.y == y:
return True
return False
def collidesintoitself(self):
head = self.cells[0]
return self.collides(head.x, head.y, False)
def move(self, new_direction):
if new_direction == 'UP' and self.direction != 'DOWN':
self.direction = 'UP'
if new_direction == 'DOWN' and self.direction != 'UP':
self.direction = 'DOWN'
if new_direction == 'LEFT' and self.direction != 'RIGHT':
self.direction = 'LEFT'
if new_direction == 'RIGHT' and self.direction != 'LEFT':
self.direction = 'RIGHT'
head = self.cells[0]
previousX = head.x
previousY = head.y
if self.direction == 'UP':
head.y -= Cell.height
elif self.direction == 'LEFT':
head.x -= Cell.width
elif self.direction == 'RIGHT':
head.x += Cell.width
elif self.direction == 'DOWN':
head.y += Cell.height
for cell in self.cells:
if cell == head:
continue
tempX = cell.x
tempY = cell.y
cell.x = previousX
cell.y = previousY
previousX = tempX
previousY = tempY
def printSnake(self):
for cell in self.cells:
print("(" + str(cell.x) + ", " + str(cell.y) + ")", end='')
print("")
class Cell:
width = 20
height = 20
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self, screen):
pygame.draw.rect(screen, Snake.color, (self.x, self.y, Cell.width, Cell.height), 0)
class Food:
color = (255, 0, 0)
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self, screen):
pygame.draw.rect(screen, Food.color, (self.x, self.y, Cell.width, Cell.height), 0)
@classmethod
def generateFood(cls, snake):
while True:
foodX = round(random.randint(20, 780) / 20) * 20
foodY = round(random.randint(20, 580) / 20) * 20
if(not snake.collides(foodX, foodY, True)):
break
return Food(foodX, foodY)
|
25f8f808dbd7aed6caaa304fff17bb4d3b7c9a19 | sotossotos/SinglyLinkedList | /singly_linked_list.py | 1,890 | 3.734375 | 4 | class Node:
def __init__(self,value=None,nextNode=None):
self.value=value
self.nextNode=nextNode
class SinlgeLinkedList:
def __init__(self,node=None):
self.list=node
self.size=0
def addNodeTop(self,value):
newNode=Node(value)
newNode.nextNode=self.list
self.list=newNode
self.size+=1
def addNodeBottom(self,value):
newNode=Node(value)
if self.list==None:
self.addNodeTop(value)
return
head=self.list
while head:
previous=head
head=head.nextNode
previous.nextNode=newNode
self.size+=1
return
def printListValues(self):
head=self.list
print(f"This is a List of size {self.size}")
while head:
print(f"the value is {head.value}")
head=head.nextNode
return
def search (self,value):
head=self.list
while head:
if head.value==value:
return head
else:
head=head.nextNode
return Node()
def reverseList(self):
head=self.list
previous=None
while head:
temp_head=head
head=head.nextNode
temp_head.nextNode=previous
previous=temp_head
self.list=previous
def delete(self,value):
head=self.list
previous=None
while head:
if head.value==value:
if previous is None:
self.list=head.nextNode
else:
previous.nextNode=head.nextNode
return
else:
previous=head
head=head.nextNode
def replaceNodeValue(self,newValue,value):
node=self.search(value)
node.value=newValue
|
0d8dceba50028a3b1b74f099db6232e5dd3e563e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2354/48721/321243.py | 214 | 3.5625 | 4 | s = input()
s1 = input()
if(s1 == ".#."):
print(20)
elif(s1 == "###")|(s1=="..."):
print(1)
elif s1==".....#.........":
print(301811921)
elif s1=="##..#":
print(403241370)
else:
print(436845322) |
26751f3aebccc136fcca17fb4d5469c729d2644e | dgaikwad/python_codes | /opencv/image_rotation.py | 426 | 3.578125 | 4 | #!/usr/bin/python3
import cv2
import numpy as np
pic = cv2.imread("my_image.jpg")
rows = pic.shape[1]
cols = pic.shape[0]
print(rows, cols)
center = (cols/2, rows/2)
#if angle is positive then it will rotate image anticlock wise else closckwise
angle = 90
M = cv2.getRotationMatrix2D(center, angle, 1)
rotate = cv2.warpAffine(pic, M, (cols, rows))
cv2.imshow("Image rotation", rotate)
cv2.waitKey(0)
cv2.destroyAllWindows() |
c2a0eec11ce71dc3595b8662ffa2573c141828f5 | volodiny71299/Right-Angled-Triangle | /03.5_rad_degv2.py | 428 | 4.25 | 4 |
# https://www.geeksforgeeks.org/degrees-and-radians-in-python/
# Python code to demonstrate
# working of degrees()
# for degrees()
import math
# Printing degrees equivalents.
print("pi / 180 Radians is equal to Degrees : ", end ="")
print (math.degrees(math.pi / 180))
print("180 Radians is equal to Degrees : ", end ="")
print (math.degrees(180))
print("1 Radians is equal to Degrees : ", end ="")
print (math.degrees(1))
|
2f3e457365a3a6c7e3f516fa09b4c33cce39a1dd | panzhh/python_course | /lesson_2.py | 4,300 | 4.15625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
#### SET: unordered, unique (no duplicates) and must be immutable (cannot be changed).
def my_set_test():
# Different types of sets in Python # set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
# set cannot have duplicates # Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list # Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
# set cannot have mutable items # here [3, 4] is a mutable list # this will cause an error.
#my_set = {1, 2, [3, 4]}
# Distinguish set and dictionary while creating empty set
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# initialize a with set()
a = set()
# check data type of a
print(type(a))
# initialize my_set
my_set = {1, 3}
print(my_set)
# set is unordered, can not use indexing and slicing.
# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)
### remove() and discrad().
''''
The only difference between the two is that the discard() function leaves a
set unchanged if the element is not present in the set.On the other hand, the
remove() function will raise an error in such a condition( if element is not present in the
set).
'''
# Difference between discard() and remove()
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element # Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element # Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element # not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element # not present in my_set # you will get an error.
# Output: KeyError
#my_set.remove(2)
### pop(): is unordered, so totoally random results.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
# set operation.
# union,
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
print(A.union(B))
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
print (A.intersection(B))
# in operator
my_set = {"apple", "book", 'milk'}
my_set2 = {"boy", "book", 'man'}
for x in my_set:
if x in my_set2:
print(x)
'''
Built - in functions like:
all(), any(), enumerate(), len(), max(), min(), sorted(), sum()
etc.are commonly used with sets to perform different tasks.
'''
# enumerate function
l1 = ["eat", "sleep", "repeat"]
s1 = "geek"
# creating enumerate objects
obj1 = enumerate(l1)
obj2 = enumerate(s1)
print("Return type:", type(obj1))
print(list(enumerate(l1)))
# changing start index to 2 from 0
print(list(enumerate(s1, 2)))
### exercise: remove dupicated elements from a list
def remove_duplicates_from_list(l):
return l
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
my_set_test()
|
e2b5179ddb0401d559bf6db96567d05c3d587fab | elmehdiabdi/flw | /part2/_Programming Language Research Project (1).py | 10,859 | 3.5625 | 4 |
# coding: utf-8
# ##########################################################
# # CST8333 2018 Final Project #
# # #
# # Created by Jay Italia #
# # November 22 ,2018 #
# # #
# ##########################################################
#
# ## import statements
#
# In[78]:
# import statements
import csv
import json as json
import threading
from io import StringIO
from tabulate import tabulate
import pandas as pd
# ## To Show all rows and coloumn in Output without truncating used this from (https://stackoverflow.com/a/37347783/8101986)
#
# In[79]:
# To Show all rows and coloumn in Output without truncating used this from (https://stackoverflow.com/a/37347783/8101986)
pd.set_option('display.max_columns', None) # or 1000
pd.set_option('display.max_rows', None) # or 1000
pd.set_option('display.max_colwidth', -1) # or 199
pd.set_option('max_colwidth', 800)
# Input File Read
df = pd.read_csv("32100054.csv", sep = ",")
# df.rename(columns={'REF_DATE':'DATE', 'Food categories':'Food_categories'}, inplace=True) # rename one or more columns
# # Examine the df data
# In[80]:
def DataExamination(): # Examining the dataframe(df ) data
print("\n Author is Jay Italia \n ")
# print(df.head(5)) # Display data After Renaming
# print(df) # print the first 30 and last 30 rows
print(type(df) ) # DataFrame
print(df.tail()) # print the last 5 rows
print(df.index) # “the index” (aka “the labels”)
print(df.columns) # column names (which is “an index”)
print(df.dtypes) # data types of each column
print(df.shape) # number of rows and columns
print(df.values) # underlying numpy array — df are stored as numpy arrays for effeciencies.
print("Shape(Row) Of Data Frame is ",df.shape[0]) # display only the number of rows of the ‘df’ DataFrame
print("Shape(column) Of Data Frame is ",df.shape[1])# display only the number of column of the ‘df’ DataFrame
# # Displaying data in pandas dataframe
# In[81]:
def showAllbyPd(): # Displaying data in pandas dataframe
print("\n Author is Jay Italia \n ")
print(pd.DataFrame(df).head())
class DataReader(): # Created a class to read csv file and place into list
# DatabaseReader constructor
def __init__(self, fname):
self.fname = fname;
def rowList(self):
with open(self.fname, newline='') as csvfile: # CSV File reading
reader = csv.reader(csvfile)
dlist = list(reader)
return dlist
# function to show all the rows from dataset
def showData(dlist):
print("\n Author is Jay Italia \n ")
#Looping Structures
for row in dlist:
print(row) # prints all the rows in console
# function to count the total number of rows.
def showNumRows(dlist):
print("\n Author is Jay Italia \n ")
return len(dlist) - 1
# function to show specfic row that user wants.
def showRow(dlist, row):
print("\n Author is Jay Italia \n ")
print(dlist[row])
def showCommodiytOnUOM():
print("\n Author is Jay Italia \n ")
print(df[df["UOM_ID"] == 205])
# # To select rows whose column value equals a scalar, some_value, use ==:
# In[82]:
# To select rows whose column value equals a scalar, some_value, use ==:
def showOnCommodityName():
print("\n Author is Jay Italia \n ")
commodity_input = input("Enter Commodity Name for which you want to search same commodity values :\n")# Variable assignment
print(df.loc[df['Commodity'] == commodity_input])# print all rows in which this specific commodity exist
print("Total Count of data having ", commodity_input, "Commodity name is : ")
print(df.loc[df.Commodity == commodity_input, 'Commodity'].count()) # find total count
# # To select rows whose column value equals a scalar, some_value
# In[83]:
def show_on_UOM(): # To select rows whose column value equals a scalar, some_value, use ==:
print("\n Author is Jay Italia \n ")
# Variable assignment
uom_input = input("\n Enter UOM Name which you want to search\n ")
# print all rows in which this specific UOM exist
print((df.loc[df['UOM'] == uom_input]))
print("\n Total Count of data having ",uom_input,"UOM is : \n ")
# print(df.loc[df.UOM == uom_input, 'UOM'].count()) # find total count
# In[84]:
def total_ref_date():
print("\n Author is Jay Italia \n ")
# Variable assignment
ref_date_input = input("Enter Ref date for which you want to search \n")
print("Total Count of Ref Year ", ref_date_input, " is : ")
# print(df.loc[df.DATE == ref_date_input, 'DATE'].count()) # find total count
# # Function to convert a pandas data frame into a JSON object
# In[85]:
# Function to convert a pandas data frame into a JSON object
def df_to_json(df, filename=''):
print("\n Author is Jay Italia \n ")
# json = df1.to_json(orient="values") # Writing out Data in JSON Formating
y = df.to_json(orient="values")
# Decision Structures
if filename:
# File Writing as Filename = ' ' given from input
with open(filename, 'w+') as f: f.write(json.dumps(y))
return y
# # print all rows in which this specific Food categories exist
# In[86]:
def show_on_Food_categories():
print("\n Author is Jay Italia \n ")
food_categories = input("\n Enter Food categories Name which you want to search\n ")
# print all rows in which this specific Food categories exist
print((df.loc[df['Food categories'] == food_categories]))
# # Sorting
# In[102]:
def sorting_OnValue():
print("\n Author is Jay Italia \n ")
# sorting algorithms is used to sort rows in ascending on VALUE 's values # Variables: declaration
val = df.sort_values(['VALUE'], ascending=True)
df1 = val[['Food categories','Commodity','VALUE']]
# pandas df max function used to get max value in VALUE coloumn
max_values = df1[df1['VALUE'] == df1['VALUE'].max()]
# pandas df min function used to get min value in VALUE coloumn
min_values = df1[df1['VALUE'] == df1['VALUE'].min()]
print(df1.head(10))
print("\n Max values row is : \n", max_values)
print("\n Min values row is : \n", min_values)
print("\n Memory usage information in accurate number :\n")
# we'll set the memory_usage parameter to 'deep' to get an accurate number.
print(df1.info(memory_usage='deep'))
# Pandas to JSON converting Function Call
df_to_json(df1,'Ouput_In_Json_format.txt')
print("\n Output in JSON format \n")
# print(json)
# In[88]:
def sortingOn_UOM_ID():
print("\n Author is Jay Italia \n ")
var = df.sort_values(['UOM_ID'],ascending=True) # sorting algorithms is used to sort rows in ascending on VALUE 's values # Variables: declaration
df2 = var[['Food categories', 'Commodity','UOM_ID']] # new dataframe declaration
print(df2.head(10))
print("\n Memory usage information in accurate number :\n")
print(df2.info(memory_usage='deep')) # we'll set the memory_usage parameter to 'deep' to get an accurate number.
# In[89]:
def StatOperetions():
print("\n Author is Jay Italia \n ")
print(df.groupby('VALUE').mean()) # Mean
print(df.groupby('VECTOR').describe()) # Summary Statistics in python pandas by describe
print(" And Operations")
print(df[(df.VALUE >60) & (df.REF_DATE==1960)])# ampersand for AND condition # boolean filtering with multiple conditions; indexes are in square brackets, conditions are in parens
# # List Comprehensions
# In[90]:
# List Comprehensions
def List_iterator():
print("\n Author is Jay Italia \n ")
squared_values = []
# print(df.loc[:,"VALUE"])
for x in (df.loc[:,"VALUE"]>0):
print(squared_values.append(x**2))
print(squared_values)
# In[91]:
def main():
# input_data = DataReader('32100054.csv') # reads the .csv file
#
# dList = input_data.rowList() # Function for Showing the data
# showData(dList)
# showCommodiytOnUOM() # Function for Showing all rows Commodity based on UOM
# showAllbyPd()
# showOnCommodityName() #Function for Showing all rows having specific commodity name
# total_ref_date()
# show_on_Food_categories() #function for showing all rows having specific food category
#
# show_on_UOM()
# sorting_OnValue() # function for sorting Values in ascending or descending order
#
# sortingOn_UOM_ID()# function for sorting Values in ascending or descending order
#
# Multithreading to execute two given process
# t1 = threading.Thread(target=sorting_OnValue)
# t2 = threading.Thread(target=sortingOn_UOM_ID)
# t1.start()# starting thread 1
# t2.start() # starting thread 2
# t1.join()# wait u ntil thread 1 is completely executed
# t2.join() # wait until thread 2 is completely executed
#
StatOperetions()
# List_iterator() # Iterator Function for List
# DataExamination() # Function for input data explorations
# this block of code allows running this program from the command line,
# taken from Python's official PyUnit documentation.
# Python Software Foundation. (2015). 26.4.1. Basic example. [Webpage].
# Retrieved from https://docs.python.org/3/library/unittest.html#basic-example.
if __name__ == "__main__":
# executes if run as main program.
main()
# # Multithreading to execute two given process
#
# In[92]:
# Multithreading to execute two given process
t1 = threading.Thread(target=sorting_OnValue)
t2 = threading.Thread(target=sortingOn_UOM_ID)
t1.start()# starting thread 1
t2.start() # starting thread 2
t1.join()# wait u ntil thread 1 is completely executed
t2.join() # wait until thread
# # function for sorting Values in ascending or descending order
#
# In[93]:
sortingOn_UOM_ID()
# # function for sorting Values in ascending or descending order
# In[103]:
sorting_OnValue()
# In[95]:
show_on_UOM()
# In[96]:
show_on_Food_categories() #function for showing all rows having specific food category
# In[97]:
input_data = DataReader('32100054.csv') # reads the .csv file
dList = input_data.rowList() # Function for Showing the data
showData(dList)
# In[98]:
total_ref_date()
# In[99]:
showOnCommodityName()
# In[100]:
showAllbyPd()
# In[101]:
showCommodiytOnUOM()
# In[104]:
DataExamination()
|
2eb0ce2192d8bc51b9a513f7829443c9c471b4ca | tks18/python-projects | /Day 23/Final Project - Turtle Cross Game/car_manager.py | 1,004 | 3.765625 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
class CarManager():
def __init__(self):
self.allCars = []
self.increment = 3
self.startingDistance = 5
self.chance = 5
def create_car(self):
randomint = random.randint(1, self.chance);
if(randomint == 1):
new_car = Turtle("square")
new_car.shapesize(1, 2)
new_car.pu()
new_car.color(random.choice(COLORS))
new_car.seth(180)
new_car.goto(300, random.randint(-250, 250))
self.allCars.append(new_car)
def move_cars(self):
for cars in self.allCars:
cars.forward(self.startingDistance)
def checkCollision(self, turtleboy):
for car in self.allCars:
if(car.distance(turtleboy) < 20):
return True;
def incrementit(self):
self.chance -= 1
self.startingDistance += self.increment
|
7da6c355a52664e1d15b4a6b902b6eda4cb7ed99 | 953250587/leetcode-python | /MirrorReflection_MID_858.py | 1,372 | 3.796875 | 4 | """
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.
Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.)
Example 1:
Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
Note:
1 <= p <= 1000
0 <= q <= p
"""
class Solution(object):
def mirrorReflection(self, p, q):
"""
:type p: int
:type q: int
:rtype: int
31 ms
"""
def gcd(p, q):
if q == 0:
return p
else:
return gcd(q, p % q)
a = gcd(p, q)
t1 = q / a # p的个数
t2 = p / a # q的个数
print(t1, t2)
if t1 % 2 == 0:
return 0
else:
if t2 % 2 == 1:
return 1
else:
return 2
print(Solution().mirrorReflection(p = 2, q = 1))
print(Solution().mirrorReflection(p = 3, q = 2))
print(Solution().mirrorReflection(3, 1))
print(Solution().mirrorReflection(5, 3)) |
1659d3a1550c283707b4be6ddd9b8ba6b7f7d6ec | Poonam-Patnaik/basic_programming_practice | /python_programs/product_not_available_in_cities.py | 421 | 4.21875 | 4 | cities_friend_lived = list(input('enter 10 city name where your friend lived').split(','))
product_available_in_city = list(input('enter 5 city name where product is available ').split(','))
product_not_available_in_cities = []
for city in cities_friend_lived:
if city in product_available_in_city:
continue
else:
product_not_available_in_cities.append(city)
print(product_not_available_in_cities) |
8fdc30e3050a8698df528dd33f56237a280f0a52 | TheJacksonOfGreen/LearningPython | /PythonClassFolder/112.py | 210 | 4.1875 | 4 | #!/usr/bin/python
#112
#How to Break a loop
#Introduction: break
while True:
ask = input("What should I say? Say 'Stop' if you want me to stop asking you. >")
if ask == "Stop":
break
else:
print(ask)
|
121bcff99789c9bcef2223ba590807a1c7134b1b | KirutoChan/Leonhard | /leo4.py | 681 | 4.1875 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def is_polindrome(n):
n_list = []
p_list = []
for i in str(n):
n_list.append(i)
for i in range(len(n_list) - 1, -1, -1):
p_list.append(n_list[i])
if n_list == p_list:
return True
return False
def polindrome_numbers():
polindromes = []
for i in range(999, 99, -1):
for j in range(999, 99, -1):
s = i * j
if is_polindrome(i * j):
polindromes.append(s)
return max(polindromes)
print (is_polindrome(33))
print (polindrome_numbers())
|
76ea8bb763cb6fd400af2e493e5d398d2cdc1254 | Azim-Kurani/16-642-Manipulation-Estimation-and-Control | /Problem Set 1/code.py | 7,743 | 3.9375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import time
# Question 4
# This code will show each transformation in sequence from a) -> f) and will output the original coordinates of each
# of the 5 points on the rigid body followed by their new coordinates after the transformation. The plot that displays
# this transformation is also set up to display each step from a) -> f) for 2 seconds before moving onto the next...
# IN ORDER TO DISABLE THIS AND HAVE TO MANUALLY CLOSE THE PLOT BEFORE MOVING ON TO THE NEXT:
# replace plt.show(block = False) with plt.show(block = True) everywhere you see !!!!!!!!!!! notation
points = np.array([[-1.0,1.0], [0.0,1.0], [1.0,0.0], [0.0,-1.0], [-1.0,-1.0]])
plt.plot(points[:,0], points[:,1], 'bX') #Blue Xs represent beginning
# The Z-coordinate must be 1 in order to preserve the displacement when doing a transformation
rigidShape = [np.matrix([[-1.0],[1.0],[1.0]]),
np.matrix([[0.0],[1.0],[1.0]]),
np.matrix([[1.0],[0.0],[1.0]]),
np.matrix([[0.0],[-1.0],[1.0]]),
np.matrix([[-1.0],[-1.0],[1.0]])]
a = np.matrix([[1.0, 0.0, 4.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0]])
b = np.matrix([[0.866, 0.5, 0.0],
[-0.5,0.866,0.0],
[0.0, 0.0, 1.0]])
# a)
print ("4. a)_________________________________")
XList1 = []
YList1 = []
count = 1
for i in rigidShape:
print ("Point" + str(count))
ai = a*i
print("Original:")
print (i)
print("Transformation")
print (a*i)
#Append these to be used later to shade-in the shape demarcated by the coordinates
XList1.append(ai[0,0])
YList1.append(ai[1,0])
print ("")
plt.plot(ai[0,0],ai[1,0], 'ro') #Red circles on points
count = count + 1
# Fill up the space between the points in the transformed coordinate system
plt.fill(XList1,YList1)
axis = plt.gca()
axis.set_xlim([-2,6])
axis.set_ylim([-3,3])
plt.show(block = False) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
time.sleep(2) # Show this diagram for 2 seconds
plt.close()
#==============================================================================================================
# b)
print ("4. b)_________________________________")
# Replot the points
plt.plot(points[:,0], points[:,1], 'bX')
XList1[:] = []
YList1[:] = []
count = 1
for i in rigidShape:
print ("Point" + str(count))
abi =a*b*i
print("Original:")
print (i)
print("Transformation")
print (abi)
XList1.append(abi[0,0])
YList1.append(abi[1,0])
print ("")
plt.plot(abi[0,0],abi[1,0], 'ro')
count = count + 1
# Fill up the space between the points in the transformed coordinate system
plt.fill(XList1,YList1)
axis = plt.gca()
axis.set_xlim([-2,6])
axis.set_ylim([-3,3])
plt.fill(XList1,YList1)
plt.show(block = False) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
time.sleep(2)
plt.close()
#==============================================================================================================
# c)
print ("4. c)_________________________________")
# Replot the points
plt.plot(points[:,0], points[:,1], 'bX')
XList1[:] = []
YList1[:] = []
count = 1
for i in rigidShape:
print ("Point" + str(count))
bai =b*a*i
print("Original:")
print (i)
print("Transformation")
print (bai)
XList1.append(bai[0,0])
YList1.append(bai[1,0])
print ("")
plt.plot(bai[0,0],bai[1,0], 'ro')
count = count + 1
# Fill up the space between the points in the transformed coordinate system
plt.fill(XList1,YList1)
axis = plt.gca()
axis.set_xlim([-2,6])
axis.set_ylim([-3,3])
plt.fill(XList1,YList1)
plt.show(block = False) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
time.sleep(2)
plt.close()
#==============================================================================================================
# d)
print ("4. d)_________________________________")
# Replot the points
plt.plot(points[:,0], points[:,1], 'bX')
XList1[:] = []
YList1[:] = []
count = 1
for i in rigidShape:
print ("Point" + str(count))
bi = b*i
print("Original:")
print (i)
print("Transformation")
print (bi)
#Append these to be used later to shade-in the shape demarcated by the coordinates
XList1.append(bi[0,0])
YList1.append(bi[1,0])
print ("")
plt.plot(bi[0,0],bi[1,0], 'ro') #Red circles on points
count = count + 1
# Fill up the space between the points in the transformed coordinate system
plt.fill(XList1,YList1)
axis = plt.gca()
axis.set_xlim([-2,6])
axis.set_ylim([-3,3])
plt.show(block = False) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
time.sleep(2) # Show this diagram for 2 seconds
plt.close()
#==============================================================================================================
# e)
print ("4. e)_________________________________")
# Replot the points
plt.plot(points[:,0], points[:,1], 'bX')
XList1[:] = []
YList1[:] = []
count = 1
for i in rigidShape:
print ("Point" + str(count))
abi =a*b*i
print("Original:")
print (i)
print("Transformation")
print (abi)
XList1.append(abi[0,0])
YList1.append(abi[1,0])
print ("")
plt.plot(abi[0,0],abi[1,0], 'ro')
count = count + 1
# Fill up the space between the points in the transformed coordinate system
plt.fill(XList1,YList1)
axis = plt.gca()
axis.set_xlim([-2,6])
axis.set_ylim([-3,3])
plt.fill(XList1,YList1)
plt.show(block = False) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
time.sleep(2)
plt.close()
#==============================================================================================================
# f)
print ("4. f)_________________________________")
# Replot the points
plt.plot(points[:,0], points[:,1], 'bX')
XList1[:] = []
YList1[:] = []
count = 1
for i in rigidShape:
print ("Point" + str(count))
bai =b*a*i
print("Original:")
print (i)
print("Transformation")
print (bai)
XList1.append(bai[0,0])
YList1.append(bai[1,0])
print ("")
plt.plot(bai[0,0],bai[1,0], 'ro')
count = count + 1
# Fill up the space between the points in the transformed coordinate system
plt.fill(XList1,YList1)
axis = plt.gca()
axis.set_xlim([-2,6])
axis.set_ylim([-3,3])
plt.fill(XList1,YList1)
plt.show(block = False) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
time.sleep(2)
plt.close()
# This section below was used in order to compute the homogenous transformation matrix from Pittsburgh to GreenWhich
'''
from numpy.linalg import inv
GreenwhichInclination = np.matrix([[np.cos(-51*np.pi/180), 0, np.sin(-51*np.pi/180), 0],
[0, 1, 0, 0],
[-np.sin(-51*np.pi/180), 0, np.cos(-51*np.pi/180), 0],
[0, 0, 0, 1]])
extension2Surface = np.matrix([[1, 0, 0, 0],
[0, 1 , 0, 0],
[0, 0, 1, -6000],
[0, 0, 0, 1]])
extension2Core = np.matrix([[1, 0, 0, 0],
[0, 1 , 0, 0],
[0, 0, 1, 6000],
[0, 0, 0, 1]])
pitInclination = np.matrix([[np.cos(40.5*np.pi/180), 0, np.sin(40.5*np.pi/180), 0],
[0, 1 , 0, 0],
[-np.sin(40.5*np.pi/180), 0, np.cos(40.5*np.pi/180), 0],
[0, 0, 0, 1]])
pitMeridian = np.matrix([[1, 0, 0, 0],
[0, np.cos(80*np.pi/180) , -np.sin(80*np.pi/180), 0],
[0, np.sin(80*np.pi/180), np.cos(80*np.pi/180), 0],
[0, 0, 0, 1]])
H = extension2Core * pitInclination * pitMeridian * GreenwhichInclination * extension2Surface
print (H)
'''
|
f6c8ed4dd7b02893989e872f2d0a5f8235467a3c | plmon/python-CookBook | /chapter 1/1.14-sort-objects-not-support-comparison.py | 868 | 3.625 | 4 | # 1.14 对不原生支持比较操作的对象排序
# 目的:对不能进行比较操作的同一个类的实例进行排序
# 方法:利用sorted()和operator.attrgetter()结合进行排序
# 该方法同时可用于max()和min()函数
# attrgetter()相当于创建了一个函数,然后将函数作用于对象上
# 用处:创建同一个类的许多实例,想要对它们之间进行排序操作时
from operator import attrgetter
class Users:
def __init__(self, user_id):
self.user_id = user_id
# 格式化类输出信息
def __repr__(self):
return 'User({})'.format(self.user_id)
users = [Users(23), Users(3), Users(99)]
a = sorted(users, key=attrgetter('user_id'))
print(a) # [User(3), User(23), User(99)]
# 也可以使用lambda表达式,但是性能不好
b = sorted(users, key=lambda k: k.user_id)
|
cc7171bbc70bce5e96c74cd1a211b07cf05a7477 | pmaywad/DataStructure-Algo | /Hash-Tables/open_adressing.py | 1,432 | 3.859375 | 4 | """
Implementation of Open Addressing in Hashing in Python
"""
class HashTable:
def __init__(self, size):
self.size = size
self.hash_table = [None]*self.size
def hash_function(self, key):
return key%self.size
def insert(self, key):
idx = self.hash_function(key)
while idx < self.size:
if self.hash_table[idx] in (None, 'DELETED'):
self.hash_table[idx] = key
return
idx += 1
print("Hash Table is full")
def display(self):
print(self.hash_table)
def remove(self, key):
idx = self.hash_function(key)
while idx < self.size:
if self.hash_table[idx] == key:
self.hash_table[idx] = 'DELETED'
return
idx += 1
def search(self, key):
idx = self.hash_function(key)
while idx < self.size:
if self.hash_table[idx] == key:
return idx
idx += 1
return -1
if __name__=='__main__':
hash_table = HashTable(7)
hash_table.insert(15)
hash_table.insert(11)
hash_table.insert(27)
hash_table.insert(8)
hash_table.insert(12)
hash_table.display()
hash_table.remove(12)
hash_table.display()
idx = hash_table.search(8)
if idx == -1:
print("key not found in hash table")
else:
print("key found at location", idx)
|
83075f5166b00949d359abcc58c39253d0dfa688 | EmpressBelless/python-day3-exercise | /circle.py | 191 | 4.34375 | 4 | def mycircle():
Pi = 3.14
r = float(input("enter the radius of a circle, the output will be the circumference of a circle: "))
Area = Pi * r * r
return Area
print(mycircle()) |
c8e0a758c751b8da995af338be9e9416b4901e53 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 7/Assignment7_2.py | 1,638 | 4.375 | 4 | #2. Write a program which contains one class named as BankAccount.
#BankAccount class contains two instance variables as Name & Amount.
#That class contains one class variable as ROI which is initialise to 10.5.
#Inside init method initialise all name and amount variables by accepting the values from user.
#There are Four instance methods inside class as Display(), Deposit(), Withdraw(),
#CalculateIntrest().
#Deposit() method will accept the amount from user and add that value in class instance variable
#Amount.
#Withdraw() method will accept amount to be withdrawn from user and subtract that amount
#from class instance variable Amount.
#CalculateIntrest() method calculate the interest based on Amount by considering rate of interest
#which is Class variable as ROI.
#And Display() method will display value of all the instance variables as Name and Amount.
#After designing the above class call all instance methods by creating multiple objects.
class BankAccount:
ROI = 10.5;
def __init__(self,Name,Amount):
self.Name = Name;
self.Amount = float(Amount);
def Deposit(self):
self.Amount += float(input("Enter the amount :"));
def Withdraw(self):
amt_withdraw = float(input("Enter the amount :"));
if(self.Amount > amt_withdraw):
self.Amount -= amt_withdraw;
def CalculateInterest(self):
return (BankAccount.ROI * self.Amount)/100;
def Display(self):
print("Name :" ,self.Name);
print("Amount :" ,self.Amount);
print("Interest :" ,self.CalculateInterest());
obj = BankAccount("harshal",1000);
obj.Deposit();
obj.Withdraw();
obj.Display();
|
99b6515f3f42696fdf3998812f69542a86dc6fe5 | Romulo2013137/Python-Codes | /TAREFA004.py | 546 | 3.921875 | 4 | n = input('Digite algo')
print('O tipo primitivo do que foi digitado é ', type(n))
print('O que foi digitado é um espaço(s)?', n.isspace())
print('O que foi digitado contem apenas números?', n.isnumeric())
print('O que foi digitado contem apenas letras?', n.isalpha())
print('O que foi digitado contem letras e números?', n.isalnum())
print('O que foi digitado está apenas em maiúsculo(a)(s)?', n.isupper())
print('O que foi digitado está apenas em minúsculo(a)(s)?', n.islower())
print('O que foi digitado é um título?', n.istitle())
|
8d18d62cde219b45c9160bd43d019b7afa8a32a3 | nikel4610/sparta_coding | /알고리즘공부/week3/selection.py | 388 | 3.546875 | 4 | input = [4, 6, 2, 9, 1]
def selection_sort(array):
# 이 부분을 채워보세요!
n = len(array)
for i in range (1,n):
for j in range(i):
if array[i-j-1] > array[i-j]:
array[i-j-1], array[i-j] = array[i-j], array[i-j-1]
else:
break #시간복잡도 줄이기
return
selection_sort(input)
print(input)
|
82ce094048e1d7b486edf1c18995ca11ecf9f75d | joaoFelix/learn-python | /challenges/CarGame.py | 837 | 4.09375 | 4 | # Commands:
# help: shows every command that can be executed
# start: starts the car
# stop: stops the car
# quit: exit the game
command = ""
car_is_started = False
while True:
command = input("> ").lower()
if command == "help":
help_msg = '''start: starts the car
stop: stops the car
quit: exit the game'''
print(help_msg)
elif command == "quit":
break
elif command == "start":
if car_is_started:
print("Car already started")
else:
car_is_started = True
print("Car started... Ready to go!")
elif command == "stop":
if car_is_started:
print("Car stopped.")
car_is_started = False
else:
print("Car already stopped")
else:
print("I don't understand that")
|
62035ef273014e44d647db00778467e6b87c579a | GoogolDKhan/Roommates-Gym-Management-System | /main.py | 1,745 | 4 | 4 | # Creating dictonaries for roommates use
roommates = {1: "Sarfaraz", 2: "Sashant", 3: "Prabhjot"}
log = {1: "Exercise", 2: "Diet"}
# log current date and time
def getdate():
import datetime
return datetime.datetime.now()
try:
# Input the selected roommate and his option to log or retrieve
print("Select your name:")
for key, value in roommates.items():
print(f"Press {key} for {value}")
roommate = int(input())
print(f"\nSelected roommate is {roommates[roommate]}")
print("Press 1 for Log")
print("Press 2 for Retrieve")
num = int(input())
# If he wants to log a new diet or exercise in his file
if num == 1:
for key, value in log.items():
print(f"Press {key} to log {value}")
log_num = int(input())
print(f"Selected Job : {log[log_num]}")
f = open(roommates[roommate] + "_" + log[log_num] + ".txt", "a")
add_more = "y"
while add_more != "n":
print(f"Enter {log[log_num]}")
mytext = input()
f.write("[ " + str(getdate()) + " ] : " + mytext + "\n")
add_more = input("ADD MORE ? y/n:")
continue
f.close()
# If he wants to retrieve his logged diet or exercise file
elif num == 2:
for key, value in log.items():
print(f"Press {key} to retrieve {value}")
log_num = int(input())
print(f"{roommates[roommate]}-{log[log_num]} Report :")
f = open(roommates[roommate] + "_" + log[log_num] + ".txt")
content = f.readlines()
for line in content:
print(line, end="")
f.close()
else:
print("Invalid Input !!!")
except Exception as e:
print("Wrong Input !!!")
|
bae13204418cc2d3c5e9baebf3459fe56f0218a2 | dmlc/gluon-cv | /docs/tutorials/classification/transfer_learning_minc.py | 10,387 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""4. Transfer Learning with Your Own Image Dataset
=======================================================
Dataset size is a big factor in the performance of deep learning models.
``ImageNet`` has over one million labeled images, but
we often don't have so much labeled data in other domains.
Training a deep learning models on small datasets may lead to severe overfitting.
Transfer learning is a technique that addresses this problem.
The idea is simple: we can start training with a pre-trained model,
instead of starting from scratch.
As Isaac Newton said, "If I have seen further it is by standing on the
shoulders of Giants".
In this tutorial, we will explain the basics of transfer
learning, and apply it to the ``MINC-2500`` dataset.
Data Preparation
----------------
`MINC <http://opensurfaces.cs.cornell.edu/publications/minc/>`__ is
short for Materials in Context Database, provided by Cornell.
``MINC-2500`` is a resized subset of ``MINC`` with 23 classes, and 2500
images in each class. It is well labeled and has a moderate size thus is
perfect to be our example.
|image-minc|
To start, we first download ``MINC-2500`` from
`here <http://opensurfaces.cs.cornell.edu/publications/minc/>`__.
Suppose we have the data downloaded to ``~/data/`` and
extracted to ``~/data/minc-2500``.
After extraction, it occupies around 2.6GB disk space with the following
structure:
::
minc-2500
├── README.txt
├── categories.txt
├── images
└── labels
The ``images`` folder has 23 sub-folders for 23 classes, and ``labels``
folder contains five different splits for training, validation, and test.
We have written a script to prepare the data for you:
:download:`Download prepare_minc.py<../../../scripts/classification/finetune/prepare_minc.py>`
Run it with
::
python prepare_minc.py --data ~/data/minc-2500 --split 1
Now we have the following structure:
::
minc-2500
├── categories.txt
├── images
├── labels
├── README.txt
├── test
├── train
└── val
In order to go through this tutorial within a reasonable amount of time,
we have prepared a small subset of the ``MINC-2500`` dataset,
but you should substitute it with the original dataset for your experiments.
We can download and extract it with:
"""
import zipfile, os
from gluoncv.utils import download
file_url = 'https://raw.githubusercontent.com/dmlc/web-data/master/gluoncv/classification/minc-2500-tiny.zip'
zip_file = download(file_url, path='./')
with zipfile.ZipFile(zip_file, 'r') as zin:
zin.extractall(os.path.expanduser('./'))
################################################################################
# Hyperparameters
# ----------
#
# First, let's import all other necessary libraries.
import mxnet as mx
import numpy as np
import os, time, shutil
from mxnet import gluon, image, init, nd
from mxnet import autograd as ag
from mxnet.gluon import nn
from mxnet.gluon.data.vision import transforms
from gluoncv.utils import makedirs
from gluoncv.model_zoo import get_model
################################################################################
# We set the hyperparameters as following:
classes = 23
epochs = 5
lr = 0.001
per_device_batch_size = 1
momentum = 0.9
wd = 0.0001
lr_factor = 0.75
lr_steps = [10, 20, 30, np.inf]
num_gpus = 1
num_workers = 8
ctx = [mx.gpu(i) for i in range(num_gpus)] if num_gpus > 0 else [mx.cpu()]
batch_size = per_device_batch_size * max(num_gpus, 1)
################################################################################
# Things to keep in mind:
#
# 1. ``epochs = 5`` is just for this tutorial with the tiny dataset. please change it to a larger number in your experiments, for instance 40.
# 2. ``per_device_batch_size`` is also set to a small number. In your experiments you can try larger number like 64.
# 3. remember to tune ``num_gpus`` and ``num_workers`` according to your machine.
# 4. A pre-trained model is already in a pretty good status. So we can start with a small ``lr``.
#
# Data Augmentation
# -----------------
#
# In transfer learning, data augmentation can also help.
# We use the following augmentation in training:
#
# 2. Randomly crop the image and resize it to 224x224
# 3. Randomly flip the image horizontally
# 4. Randomly jitter color and add noise
# 5. Transpose the data from height*width*num_channels to num_channels*height*width, and map values from [0, 255] to [0, 1]
# 6. Normalize with the mean and standard deviation from the ImageNet dataset.
#
jitter_param = 0.4
lighting_param = 0.1
transform_train = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomFlipLeftRight(),
transforms.RandomColorJitter(brightness=jitter_param, contrast=jitter_param,
saturation=jitter_param),
transforms.RandomLighting(lighting_param),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
transform_test = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
################################################################################
# With the data augmentation functions, we can define our data loaders:
path = './minc-2500-tiny'
train_path = os.path.join(path, 'train')
val_path = os.path.join(path, 'val')
test_path = os.path.join(path, 'test')
train_data = gluon.data.DataLoader(
gluon.data.vision.ImageFolderDataset(train_path).transform_first(transform_train),
batch_size=batch_size, shuffle=True, num_workers=num_workers)
val_data = gluon.data.DataLoader(
gluon.data.vision.ImageFolderDataset(val_path).transform_first(transform_test),
batch_size=batch_size, shuffle=False, num_workers = num_workers)
test_data = gluon.data.DataLoader(
gluon.data.vision.ImageFolderDataset(test_path).transform_first(transform_test),
batch_size=batch_size, shuffle=False, num_workers = num_workers)
################################################################################
#
# Note that only ``train_data`` uses ``transform_train``, while
# ``val_data`` and ``test_data`` use ``transform_test`` to produce deterministic
# results for evaluation.
#
# Model and Trainer
# -----------------
#
# We use a pre-trained ``ResNet50_v2`` model, which has balanced accuracy and
# computation cost.
model_name = 'ResNet50_v2'
finetune_net = get_model(model_name, pretrained=True)
with finetune_net.name_scope():
finetune_net.output = nn.Dense(classes)
finetune_net.output.initialize(init.Xavier(), ctx = ctx)
finetune_net.collect_params().reset_ctx(ctx)
finetune_net.hybridize()
trainer = gluon.Trainer(finetune_net.collect_params(), 'sgd', {
'learning_rate': lr, 'momentum': momentum, 'wd': wd})
metric = mx.metric.Accuracy()
L = gluon.loss.SoftmaxCrossEntropyLoss()
################################################################################
# Here's an illustration of the pre-trained model
# and our newly defined model:
#
# |image-model|
#
# Specifically, we define the new model by::
#
# 1. load the pre-trained model
# 2. re-define the output layer for the new task
# 3. train the network
#
# This is called "fine-tuning", i.e. we have a model trained on another task,
# and we would like to tune it for the dataset we have in hand.
#
# We define a evaluation function for validation and testing.
def test(net, val_data, ctx):
metric = mx.metric.Accuracy()
for i, batch in enumerate(val_data):
data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0, even_split=False)
label = gluon.utils.split_and_load(batch[1], ctx_list=ctx, batch_axis=0, even_split=False)
outputs = [net(X) for X in data]
metric.update(label, outputs)
return metric.get()
################################################################################
# Training Loop
# -------------
#
# Following is the main training loop. It is the same as the loop in
# `CIFAR10 <dive_deep_cifar10.html>`__
# and ImageNet.
#
# .. note::
#
# Once again, in order to go through the tutorial faster, we are training on a small
# subset of the original ``MINC-2500`` dataset, and for only 5 epochs. By training on the
# full dataset with 40 epochs, it is expected to get accuracy around 80% on test data.
lr_counter = 0
num_batch = len(train_data)
for epoch in range(epochs):
if epoch == lr_steps[lr_counter]:
trainer.set_learning_rate(trainer.learning_rate*lr_factor)
lr_counter += 1
tic = time.time()
train_loss = 0
metric.reset()
for i, batch in enumerate(train_data):
data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0, even_split=False)
label = gluon.utils.split_and_load(batch[1], ctx_list=ctx, batch_axis=0, even_split=False)
with ag.record():
outputs = [finetune_net(X) for X in data]
loss = [L(yhat, y) for yhat, y in zip(outputs, label)]
for l in loss:
l.backward()
trainer.step(batch_size)
train_loss += sum([l.mean().asscalar() for l in loss]) / len(loss)
metric.update(label, outputs)
_, train_acc = metric.get()
train_loss /= num_batch
_, val_acc = test(finetune_net, val_data, ctx)
print('[Epoch %d] Train-acc: %.3f, loss: %.3f | Val-acc: %.3f | time: %.1f' %
(epoch, train_acc, train_loss, val_acc, time.time() - tic))
_, test_acc = test(finetune_net, test_data, ctx)
print('[Finished] Test-acc: %.3f' % (test_acc))
################################################################################
#
# Next
# ----
#
# Now that you have learned to muster the power of transfer
# learning, to learn more about training a model on
# ImageNet, please read `this tutorial <dive_deep_imagenet.html>`__.
#
# The idea of transfer learning is the basis of
# `object detection <../examples_detection/index.html>`_ and
# `semantic segmentation <../examples_segmentation/index.html>`_,
# the next two chapters of our tutorial.
#
# .. |image-minc| image:: https://raw.githubusercontent.com/dmlc/web-data/master/gluoncv/datasets/MINC-2500.png
# .. |image-model| image:: https://zh.gluon.ai/_images/fine-tuning.svg
|
3f207ab7299b3136d4b76bb92bcbec042b5a36d5 | weed478/asd1 | /exam/1/zad1.py | 1,202 | 3.796875 | 4 | """
Jakub Karbowski
Do każdego elementu dołączamy jego orginalny indeks; element to krotka (value; original index).
Puszczamy zwykły insertion sort (dobry do k-chaotycznych tablic).
Insertion sort będzie sobie przekładał elementy aż skończy.
Na końcu sprawdzamy o ile każdy element się przesunął i liczymy największe przesunięcie, które jest naszym k.
Złożoność:
Zwykły insertion sort O(n^2) ale mamy tablicę k-chaotyczną.
Dlatego złożoność wynosi O(nk); wewnętrzna pętla sorta wykona się max k razy.
Pamięciowo zajmujemy dodatkowo O(n).
---
Myślałem czy coś może nie heap ale ponieważ nie znamy k, trzebaby na początku wszystko do niego wrzucić,
co by potem zrobiło O(nlogn) zamiast O(nlogk).
"""
from zad1testy import runtests
def insertion_sort(A, p, r):
for i in range(p + 1, r):
for j in range(i, p, -1):
if A[j - 1][0] > A[j][0]:
A[j - 1], A[j] = A[j], A[j - 1]
else:
break
def chaos_index(T):
n = len(T)
A = [(T[i], i) for i in range(n)]
insertion_sort(A, 0, n)
k = 0
for i in range(n):
k = max(k, abs(A[i][1] - i))
return k
runtests(chaos_index)
|
571ecc65e0d19494138b861d348eb434d434740f | park-seonju/Algorithm | /2일차/1번.py | 374 | 3.5625 | 4 | list1=[(90,80),(85,75),(90,100)]
a=list1[0]
b=list1[1]
c=list1[2]
print("1번 학생의 총점은 {}점이고, 평균은 {:.1f}입니다.".format(sum(a),sum(a)/len(a)))
print("2번 학생의 총점은 {}점이고, 평균은 {:.1f}입니다.".format(sum(b),sum(b)/len(b)))
print("3번 학생의 총점은 {}점이고, 평균은 {:.1f}입니다.".format(sum(c),sum(c)/len(c))) |
ece5eeb9ae0ec6bbff35d0c7f9448e81532ae8c2 | Alarical/LeetCode | /solution/98ValidateBinarySearchTree.py | 685 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def dfs(root, Min ,Max):
if root == None:
return True
if root.val <= Min or root.val >= Max :
return False
return dfs(root.left , Min , root.val) and dfs(root.right , root.val , Max)
import sys
Max = sys.maxsize
Min = -sys.maxsize-1
return dfs(root,Min,Max)
|
212917d8632ff3d9d03628bcebd888fe356b6df4 | Indrasena8/Python-Programs | /GeometricProgression.py | 232 | 3.9375 | 4 | def printGP(a, r, n):
for i in range(0, n):
curr_term = a * pow(r, i)
print(curr_term, end =" ")
a = 2 # starting number
r = 3 # Common ratio
n = 5 # N th term to be find
printGP(a, r, n) |
890c8709e8610cdf59f300da43e306138fe132ae | nishadhperera/ml | /data_preprocessing/missing_data.py | 1,797 | 3.5625 | 4 | # Data Preprocessing
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Taking care of missing data
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
# Import Dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
# Create a new Imputer object
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
# Fit second and third columns with Imputer
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
# Dealing with categorical variables
labelencoder_x = LabelEncoder()
X[:, 0] = labelencoder_x.fit_transform(X[:, 0])
print(X)
# View encoded classes
print((labelencoder_x.classes_))
# Get the encoded values for a given set pf labels
print(labelencoder_x.transform(['France', 'Germany', 'France', 'Germany', 'Spain']))
# Convert the labels encoded to dummy variables to train ML models
onehotencoder = OneHotEncoder(handle_unknown='ignore')
enc = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough')
X = np.array(enc.fit_transform(X), dtype=np.int)
print(X)
# Encoding the y values -> these are categories, so no need to do OneHotEncoding
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
print(y)
# Split the dataset to train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
print(X_train)
print(X_test)
print(y_train)
print(y_test)
# Feature scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
print(X_train)
print(X_test)
|
79501bf7bbd2b186dc52549c1b711967a1734d23 | fredrikj31/DDD-2020 | /Romertal/romertal.py | 736 | 4 | 4 | """
ROMER TAL:
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
"""
def insertSymbol(OrderNR, Number):
if (OrderNR == 1):
if Number == '1':
return "I"
elif Number == '2':
return "II"
elif Number == '3':
return "III"
elif Number == '4':
return "IIII"
elif Number == '5':
return "V"
elif Number == '6':
return "VI"
elif Number == '7':
return "VII"
elif Number == '8':
return "VIII"
elif Number == '9':
return "VIIII"
def main():
inputTal = input()
splitNumber = list(inputTal)
splitNumber.reverse()
print(splitNumber[0])
if len(splitNumber) == 1:
print(insertSymbol(1, splitNumber[0]))
else:
print("The number contains more digit")
if __name__ == "__main__":
main() |
a7317a4d6f874cb7df22b1ebe27d144c4365a323 | pinggit/leetcode | /python/002_Add_Two_Numbers.py | 3,957 | 3.90625 | 4 | """
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single
digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the
number 0 itself.
"""
##https://medium.com/@kojinoshiba/data-structures-in-python-series-1-linked-lists-d9f848537b4d
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def traverse(self):
node = self # start from the head node
while node != None:
print "%s->" % node.val, # access the node value
node = node.next # move on to the next node
class Solution(object):
# def addTwoNumbers(self, l1, l2):
# """
# :type l1: ListNode
# :type l2: ListNode
# :rtype: ListNode
# """
# last = 0
# head = prev = None
# while True:
# if l2 is None and l1 is None and last == 0:
# break
# val = last
# if l2 is not None:
# val += l2.val
# l2 = l2.next
# if l1 is not None:
# val += l1.val
# l1 = l1.next
# if val >= 10:
# val = val % 10
# last = 1
# else:
# last = 0
# current = ListNode(val)
# if prev is None:
# head = current
# else:
# prev.next = current
# prev = current
# return head
"""
create dummy node as head of the result linked list.
if any linked list is not iterated to the end, repeat:
take carry as the init val
if any linked list is not iterated to the end yet:
add its value into val
move (pointer) to the next node
use the remainder of val as a new node in result,
append (save) it to result linked list
move (pointer) to the new node, so next time
the pointer to new result node can be added to it
get the carry of current value, which will be the init value when doing
addition on the next iteration
once both linked list is iterated, if there is a carry in the last step
use it as a new node and append to the result linked list
return the result linked list using the pointer saved in the dummy head node
"""
def addTwoNumbers(self, l1, l2):
carry = 0
# dummy head
##to save the linked table
head = curr = ListNode(0)
##repeat as long as any linked list is not iterated to the end:
while l1 or l2:
##take the carry as init value
val = carry
##if any linked list is not iterated to the end, work on it
if l1:
##add its value and mv to the next
val += l1.val
l1 = l1.next
if l2:
val += l2.val
l2 = l2.next
##take the remainder as a new node in the result
curr.next = ListNode(val % 10)
curr = curr.next
##check the possible carry
carry = val / 10
if carry > 0:
curr.next = ListNode(carry)
return head.next
if __name__ == '__main__':
s = Solution()
##create 2 linked list for 2 nums
##num1=243: 3->4->2
node_1, node_2, node_3=ListNode(2), ListNode(4), ListNode(3)
node_3.next,node_2.next=node_2,node_1
##num2=564: 4->6->5
node_a, node_b, node_c=ListNode(5), ListNode(6), ListNode(4)
node_c.next,node_b.next=node_b,node_a
##show each linked list and the result
print node_3.traverse()
print '+'
print node_c.traverse()
print '='
print s.addTwoNumbers(node_3, node_c).traverse()
|
53290565833ace542e19121943f6f42aa9c82bff | ayrtondenner/ARP-2017-1 | /Lista 1 - Regressão/Respostas - Ayrton Denner/exercicio_quatro.py | 2,448 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# Método para desenhar a grid e deixar ela atrás dos pontos e das retas
def prepara_grid():
figure = plt.figure()
axis = figure.gca()
axis.set_axisbelow(True)
plt.grid(linestyle = ":")
return
# Método para colocar os labels do gráfico
def seta_labels(title, xlabel, ylabel):
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend()
return
# Método para retornar os coeficientes da reta
def calcula_coeficientes(matriz_x, matriz_y):
# y = b0 + b1 * x1 + b2 * x2 + b3 * x3
return (matriz_x.T * matriz_x).I * np.transpose(matriz_x) * matriz_y
# Método para calcular e desenhar a reta de acordo com os coeficientes
def calcula_novo_item(novo_x, lista_coeficientes):
# Y = b0 + b1 * x1 + b2 * x2 + b3 * x3 ...
calculo = lista_coeficientes.item(0, 0) + novo_x[0] * lista_coeficientes.item(1, 0) + novo_x[1] * lista_coeficientes.item(2, 0) + novo_x[2] * lista_coeficientes.item(3, 0)
return calculo
prepara_grid()
array_tamanho = np.array([87, 86, 105, 100, 88, 100, 136, 86, 84, 94, 100, 86, 78, 84, 78, 93, 104, 71, 86, 101, 83, 77, 78, 98, 98, 84, 89, 107, 138, 83, 96, 94, 104,
100, 100, 94, 111, 104, 103, 103])
array_idade = np.array([9, 10, 8, 11, 8, 9, 9, 10, 11, 6, 14, 13, 10, 8, 6, 4, 11, 15, 5, 9, 10, 10, 13, 11, 11, 8, 12, 7, 9, 11, 8, 10, 12, 14, 7, 14, 7, 6, 9, 9])
array_andar = np.array([9, 1, 12, 7, 13, 8, 6, 8, 9, 6, 4, 14, 3, 6, 11, 3, 4, 8, 8, 9, 6, 9, 6, 11, 3, 15, 4, 2, 12, 5, 14, 17, 11, 8, 6, 2, 7, 8, 10, 4])
array_preco = np.array([814364, 837887, 1094109, 727129, 784800, 1158339, 1080046, 839743, 920737, 713176, 859764, 982291, 733894, 915152, 980419, 1061956, 981657,
711479, 830290, 965093, 849199, 640924, 688660, 821829, 982912, 1020831, 710888, 801885, 1307216, 671028, 918318, 843974, 923510, 836419, 967390,
601516, 1297396, 918891, 1279741, 860217])
array_vazio = [1] * len(array_preco)
matriz_x = np.matrix([array_vazio, array_tamanho, array_idade, array_andar]).T
matriz_y = np.matrix([array_preco]).T
lista_coeficientes = calcula_coeficientes(matriz_x, matriz_y)
# Qual é o preço previsto de um imóvel com 80m2, 10 anos e que está no 9º andar?
novo_item = np.array([80, 10, 9,])
resultado_novo_item = calcula_novo_item(novo_item, lista_coeficientes)
print(resultado_novo_item) |
1a1f7576a38a4b86fa19379c3ae07fb379e82581 | BronyPhysicist/BaseballSim | /calendar/calendar.py | 1,738 | 3.875 | 4 | from date import Day
from date import Month
from date import Date
start_date = Date(Day.WED, Month.APR, 1, 2006)
#Consider moving to calendar_window?
def fill_rows_cols(start_date, builder):
start_row = int(start_date.numday / 7) + 1
start_col = start_date.day.num()
cur_date = start_date
for row in range(1, 7):
for col in range(1, 8):
if (row <= start_row and col < start_col) or start_date.month != cur_date.month:
builder.get_object('Date' + str(row) + str(col)).set_text('\n\n')
else:
builder.get_object('Date' + str(row) + str(col)).set_text(str(cur_date.numday) + '\n\n')
cur_date = cur_date.next_date()
#Returns the first day of the month preceding the month of the argument
def prev_month(start_date):
cur_date = start_date
while cur_date.numday > 7:
cur_date = Date(cur_date.day, cur_date.month, cur_date.numday - 7, cur_date.year)
while start_date.month == cur_date.month:
cur_date = cur_date.prev_date()
backwards_days = (cur_date.numday % 7) - 1
if backwards_days == -1: backwards_days = 6
count_day = cur_date.day
for count in range(0, backwards_days):
count_day = Day.prev_day(count_day)
return Date(count_day, cur_date.month, 1, cur_date.year)
#Returns the first day of the month following the month of the argument
def next_month(start_date):
cur_date = start_date
while cur_date.month.num_days() - cur_date.numday > 7: cur_date = Date(cur_date.day, cur_date.month, cur_date.numday + 7, cur_date.year)
while cur_date.month == start_date.month: cur_date = cur_date.next_date()
return cur_date
def render_calendar(start_date, builder):
builder.get_object('month').set_text(str(start_date.month.name()) + ' ' + str(start_date.year))
fill_rows_cols(start_date, builder)
|
74ce65dff5716b7df8b187055d792bbf7c14679b | jakehoare/leetcode | /python_1_to_1000/747_Largest_Number_At_Least_Twice_of_Others.py | 1,065 | 3.6875 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/largest-number-at-least-twice-of-others/
# In a given integer array nums, there is always exactly one largest element.
# Find whether the largest element in the array is at least twice as much as every other number in the array.
# If it is, return the index of the largest element, otherwise return -1.
# Iterate over nums, tracking the index of the largest num seen and the second largest num seen.
# Time - O(n)
# Space - O(1)
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first_i = 0 # index of largest num
second = 0 # second largest num
for i, num in enumerate(nums[1:], 1):
if num >= nums[first_i]:
first_i, second = i, nums[first_i] # update first_i and second
elif num > second:
second = num
return first_i if nums[first_i] >= 2 * second else -1 # check if first is at least twice second |
2c424524c7a6d59d74c97960079fb71e9c592761 | JWiryo/HackerRank | /Algorithms/Implementations/StudentGrading.py | 672 | 3.640625 | 4 | #!/bin/python
import sys
import math
def solve(grades):
# Complete this function
newScores = []
for score in grades:
if score < 38:
newScores.append(score);
elif (roundToNearest5(score) - score) < 3:
newScores.append(roundToNearest5(score));
else:
newScores.append(score);
return newScores;
def roundToNearest5(scoreToRound):
return int(5 * math.ceil((float(scoreToRound))/5));
n = int(raw_input().strip())
grades = []
grades_i = 0
for grades_i in xrange(n):
grades_t = int(raw_input().strip())
grades.append(grades_t)
result = solve(grades)
print "\n".join(map(str, result))
|
48643696961cc2d9e849e341a06dbecf1e0e1410 | AljosaZ/Simple-calculator | /simple_calculator.py | 1,677 | 4.125 | 4 | print("Welcome to my simple calculator! \n")
count = 0
while True:
if count == 6:
print("\nWas that really that hard?")
quit()
else:
try:
x = float(input("Please enter the first number: "))
break
except ValueError:
print("Please choose a number!")
count += 1
while True:
if count == 6:
print("\nWas that really that hard?")
quit()
else:
try:
y = float(input("Please enter the second number: "))
break
except ValueError:
print("Please choose a number!")
count += 1
print("""
For addition choose: +
For substraction choose: -
For multiplication choose: *
For division choose: /
""")
count2 = 0
while True:
if count2 ==6:
print("\nWas that really that hard?")
quit()
else:
try:
action = input("Please insert operator (+, - ,*, /): ")
if action == "+":
print(f"{x} + {y} = {x+y}")
break
elif action == "-":
print(f"{x} - {y} = {x-y}")
break
elif action == "*":
print(f"{x} * {y} = {x*y}")
break
elif action == "/":
if y == 0:
print("The denominator cannot equal 0!")
break
else:
print(f"{x} / {y} = {round(x/y, 2)}")
break
else:
raise ValueError
except ValueError:
print("Please choose between availabe operators!")
count2 += 1
print("\nWe did it!") |
93e0634760c414fca94f20fe364aac9d0dae59e7 | ridersw/RedditProblems | /toggleButtonProblem.py | 1,795 | 4.375 | 4 | #The problem is:
#A light bulb is connected to n switches in such a way that it lights up only when all the switches are closed. Each switch is controlled by a push button; pressing the button toggles the switch, but there is no way to know the state of the switch. Design an algorithm to turn on the light bulb with the minimum number of button pushes needed in the worst case.
import random # to get random number
def toggleButton(array, count): #function (array- array of switches, count- number of toggles)
#print("array: ", array)
length = len(array) #to get length of an array so we can get random element from array
temp = random.randint(0, length-1) #getting random element
#to toggle the switch
if array[temp] == 0:
array[temp] = 1
else:
array[temp] = 0
#incrementing the toggle count
count += 1
if 1 in array: #to check if any switch is ON (value = 1). Here i have considered 1 = ON/ Opened and 0 = OFF/ Closed
toggleButton(array, count) #recursively call function
else:
print("array: ", array) #printing array just to confirm if all switches are closed
print("The Number of Toggles: ", count) #printing number of toggles
num = int(input("Enter the number of Switches: ")) #input number of switches from user
array = [] #declaration of blank array for storing switch value (open or closed)
count = 0 #number of toggles
for i in range(num):
array.append(random.randint(0,1)) #randomly assigning value open/Closed to switches
toggleButton(array, count) #call the func
#if you want to get the maxmimum number of toggles for worst case, put the call func (line 33) in for loop and call the func multiple times to get different values of toggles. This way the time complexity would be high but so will the accuracy
|
87e8598519dd354173a1350a41b87b48113f8653 | ishankkm/pythonProgs | /leetcode/addBinary.py | 1,005 | 3.765625 | 4 | '''
Created on May 5, 2018
@author: ishank
Given two binary strings, return their sum (also a binary string).
'''
def addBinary(a, b):
carry = 0
lenA, lenB = len(a), len(b)
result = ""
padding = ""
for i in range(abs(lenA - lenB)):
padding += "0"
if lenA > lenB:
b = padding + b
elif lenB > lenA:
a = padding + a
for i in range(len(a)):
res = int(a[-(i+1)]) + int(b[-(i+1)]) + carry
if res == 3:
result += "1"
carry = 1
elif res == 2:
result += "0"
carry = 1
else:
result += str(res)
carry = 0
if carry == 1:
result += "1"
return result[::-1]
def addBinaryDirect(a, b):
return "{0:b}".format(int(a, 2) + int(b, 2))
return str(bin(int(a, 2) + int(b, 2)))[2:]
A = "11101101"
B = "10101010"
print(addBinaryDirect(A, B))
print(addBinary(A, B))
|
7e125ab8f853ebea819f1fffcb62ca6d2ba698b8 | vdesire2641/Python-list-operations | /pyt6.py | 224 | 3.875 | 4 | # write a function that takes a sentence as a parameter and returns the number of words in the sentence.
# 4.5
def take(sentence):
s = str(sentence)
print(s.split())
print(len(s.split()))
take("jerry likes to eat")
|
5b16f728a580819924bcab19688bfd92ec1b3de6 | frankShih/LeetCodePractice | /234-palindromLinkedList/solution.py | 1,493 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
'''
# using list 45%, time: O(N) space: O(N)
tempList = []
while head:
tempList.append(head.val)
head = head.next
length, left, right = len(tempList), -1, -1
left = length//2-1
if length%2:
right = length//2+1
else:
right = length//2
while left>=0 and right<length:
if tempList[left]!=tempList[right]:
return False
left-=1
right+=1
return True
'''
# reverse linkedList 67%, time: O(N), space: O(1)
length=0
curr = head
while curr:
curr = curr.next
length+=1
if length<2:
return True
breakLen = length//2-1
left = head
right = left.next
while breakLen:
temp = right
right = right.next
temp.next = left
left=temp
breakLen-=1
if length%2:
right = right.next
while left and right:
if left.val!=right.val:
return False
left = left.next
right = right.next
return True |
f0fc579a31e5cb4f90a8f0602ef805574b600c95 | elitwilliams/project-euler | /15.py | 284 | 3.609375 | 4 | # Simple combinatorics problem of 2n choose n paths
from math import factorial
sides = raw_input("Enter side length of square lattice:")
def square_lattice_paths(n):
return factorial(2*n)/(factorial(n)**2)
print square_lattice_paths(int(sides))
# Solution = 137846528820
|
03d0ba8c88437608748e182e227bb9d0e832948d | jadeli1720/Sprint-Challenge--Intro-Python | /src/comp/comp.py | 2,747 | 4.46875 | 4 | # The following list comprehension exercises will make use of the
# defined Human class.
class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"<Human: {self.name}, {self.age}>"
humans = [
Human("Alice", 29),
Human("Bob", 32),
Human("Charlie", 37),
Human("Daphne", 30),
Human("Eve", 26),
Human("Frank", 18),
Human("Glenn", 42),
Human("Harrison", 12),
Human("Igon", 41),
Human("David", 31),
]
# Write a list comprehension that creates a list of names of everyone
# whose name starts with 'D':
print("Starts with D:")
a = [letter.name for letter in humans if letter.name[0] == 'D']
print(a)
# Write a list comprehension that creates a list of names of everyone
# whose name ends in "e".
print("Ends with e:")
b = [letter.name for letter in humans if letter.name[-1] == 'e']
print(b)
# Write a list comprehension that creates a list of names of everyone
# whose name starts with any letter between 'C' and 'G' inclusive.
# name STARTS BETWEEN C & G
includes = ['C', 'D', 'E', 'F', 'F', 'G']
print("Starts between C and G, inclusive:")
c = [letter.name for letter in humans if letter.name[0] in includes]
print(c)
# Write a list comprehension that creates a list of all the ages plus 10.
# output = age + 10
print("Ages plus 10:")
d = [number.age + 10 for number in humans]
print(d)
# Write a list comprehension that creates a list of strings which are the name
# joined to the age with a hyphen, for example "David-31", for all humans.
# person.name - person.number --> string
print("Name hyphen age:")
e = [f"{person.name}-{person.age}" for person in humans]
print(e)
# Write a list comprehension that creates a list of tuples containing name and
# age, for example ("David", 31), for everyone between the ages of 27 and 32,
# inclusive.
print("Names and ages between 27 and 32:")
f = [(person.name, person.age) for person in humans if person.age <= 32 and person.age >= 27 ]
print(f)
# Write a list comprehension that creates a list of new Humans like the old
# list, except with all the names uppercase and the ages with 5 added to them.
# The "humans" list should be unmodified.
print("All names uppercase:")
# person.name.upper() person.age + 5
# g = [f"{person.name.upper()}, {person.age + 5}" for person in humans] # --> Wrong answer: need to read the problem better and look at the test to see what they are asking for. IT'S ALL RIGHT THERE!!!
g = [Human(f"{person.name.upper()}", (person.age + 5)) for person in humans]
print(g)
# Write a list comprehension that contains the square root of all the ages.
print("Square root of ages:")
import math
h = [math.sqrt(person.age) for person in humans]
print(h)
|
260ebb8b9120ae446ec0a4c9a9562b1df32876c5 | silastsui/interview-practice | /euler/1.py | 132 | 4.1875 | 4 | def find_sum_of_multiples(num):
return sum([x for x in range(num) if x%3 == 0 or x%5 == 0])
print(find_sum_of_multiples(1000))
|
7876ae01680c2a9b613c961926a75a2e4652125b | yuansun86/leetcode | /Code/216. Combination Sum III.py | 508 | 3.515625 | 4 | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
results = []
self.backtracking(0, k, n, [], results)
return results
def backtracking(self, index, k, n, path, results):
if k == 0:
if n == 0:
results.append(path[:])
return
for i in range(index + 1, 10):
path.append(i)
self.backtracking(i, k - 1, n - i, path, results)
path.pop() |
886010fde60a99179a2b35ad35545992e5118212 | KrishnaPrasath/CODEKATA_G | /Strings/wonderful.py | 380 | 4 | 4 | # check if a string us wonderful or not
# a string is wonderful if it is made up of only 3 chars
# done
try:
s = input()
except EOFError as e:
print(-1)
dic = {}
temp = 0
for each in s:
if each in dic:
temp = dic[each]
dic[each] = temp+1
else:
temp = 0
dic[each] = temp+1
if len(dic) == 3:
print('Wonder')
else:
print(-1)
|
b8eec6ba35081819b6f122cad301f8e7e37c49ba | cothuyanninh/Python_Code | /fsoft/Week 1/B1/bai6.py | 404 | 3.90625 | 4 | """C1"""
string_word = "Fresher Academy"
for i in range(len(string_word)):
if string_word[i] == "a":
# print("hihi")
string_word = string_word.replace(string_word[i], "@")
elif string_word[i] == "e":
string_word = string_word.replace(string_word[i], "3")
print(string_word)
"""C2"""
string_word = "Fresher Academy"
string_word = string_word.replace("a", "@").replace("e", "3")
print(string_word) |
a57d2db2469b743437316d898d106d1f6c305e4e | Zerobitss/Python-101-ejercicios-proyectos | /proyecto_agenda/practice.py | 140 | 4.03125 | 4 | nombre = str(input("Escribe tu nombre: "))
print (f"Hola {nombre.upper}")
print("Su nombre tiene una cantidad de letras de: ", len(nombre))
|
868dcf3acfd587a3c99bd35d65b2c70081f885b5 | nrb/jp-cli-flashcards | /table_builder.py | 2,853 | 3.5625 | 4 | from collections import defaultdict
from lxml import html
from pprint import pprint
import requests
def parse_table(japanese_rows, character_map, insert_key, basic_class):
"""Insert the information in the HTML table into the character dict.
Romaji will be keys, values are a dictionary of either hirigana or
katakana characters.
The `insert_key` argument is the specifier for hirigana vs katakana.
The `basic_class` argument specifies what kind of sound class the kanamoji
belongs to.
"""
max_len = len(japanese_rows)
row = 0
while row < max_len:
ascii_row = row + 1
japanese_cells = japanese_rows[row].getchildren()
ascii_cells = japanese_rows[ascii_row].getchildren()
# First column is sound files
japanese_cells.pop(0)
ascii_cells.pop(0)
for japanese, ascii in zip(japanese_cells, ascii_cells):
if ascii.text == '-':
continue
character_map[ascii.text][insert_key] = japanese.text
character_map[ascii.text]['romaji'] = ascii.text
character_map[ascii.text]['class'] = basic_class
# skip to the next japanese row
row += 2
return character_map
def trim_dakuon_tables(dakuontable):
rows = dakuontable.getchildren()
rows.pop(12)
rows.pop(7)
rows.pop(0)
return rows
URL = 'https://www.coscom.co.jp/hiragana-katakana/kanatable.html'
response = requests.get(URL)
tree = html.fromstring(response.content)
# These are the basic kana symbols
# 0 is hirigana, 2 is katakana SeiOn basic characters
# 1 and 3 are YoOn compound forms.
seiontables = tree.cssselect('table.kanatable')
hirigana_table = seiontables[0]
katakana_table = seiontables[2]
# The voiced consonant tables
# 0 is the g, z, d, b, and p sounds for hirigana
# 1 is hte same but for katakana
# rows 0, 7, 12 are a single td with large images. they need to be cut out.
# this applies to both.
dakuontables = tree.cssselect('table.kanatableright1')
hirigana_dakuon_table = dakuontables[0]
katakana_dakuon_table = dakuontables[1]
character_map = defaultdict(dict)
hirigana_seion_rows = hirigana_table.getchildren()
character_map = parse_table(hirigana_seion_rows, character_map,
'hirigana', 'seion')
hirigana_dakuon_rows = trim_dakuon_tables(hirigana_dakuon_table)
character_map = parse_table(hirigana_dakuon_rows, character_map,
'hirigana', 'dakuon')
katakana_seion_rows = katakana_table.getchildren()
character_map = parse_table(katakana_seion_rows, character_map,
'katakana', 'seion')
katakana_dakuon_rows = trim_dakuon_tables(katakana_dakuon_table)
character_map = parse_table(katakana_dakuon_rows, character_map,
'katakana', 'dakuon')
pprint(dict(character_map))
|
928192655b19164fc98228d3c4196d69b2eece7e | CircularWorld/Python_exercise | /month_02/teacher/day16/select_server.py | 1,312 | 3.9375 | 4 | """
基于select 的IO多路复用并发模型
重点代码 !
"""
from socket import *
from select import select
# 全局变量
HOST = "0.0.0.0"
PORT = 8889
ADDR = (HOST,PORT)
# 创建tcp套接字
tcp_socket = socket()
tcp_socket.bind(ADDR)
tcp_socket.listen(5)
# 设置为非阻塞
tcp_socket.setblocking(False)
# IO对象监控列表
rlist = [tcp_socket] # 初始监听对象
wlist = []
xlist = []
# 循环监听
while True:
# 对关注的IO进行监控
rs,ws,xs = select(rlist,wlist,xlist)
# 对返回值rs 分情况讨论 监听套接字 客户端连接套接字
for r in rs:
if r is tcp_socket:
# 处理客户端连接
connfd, addr = r.accept()
print("Connect from", addr)
connfd.setblocking(False) # 设置非阻塞
rlist.append(connfd) # 添加到监控列表
else:
# 收消息
data = r.recv(1024)
if not data:
# 客户端退出
rlist.remove(r) # 移除关注
r.close()
continue
print(data.decode())
# r.send(b'OK')
wlist.append(r) # 放入写列表
for w in ws:
w.send(b"OK") # 发送消息
wlist.remove(w) # 如果不移除会不断的写
|
950da3803d15ad4c5634e90f56c99276faddcad8 | yusufcankann/Introduction-To-Algorithms | /Final/question5.py | 1,845 | 4.0625 | 4 | #Yusuf Can Kan
#for map function.
#this doubles the ight part of the array
def double(n):
return n*2
#mergesort.
def countInverseWithMergeSort(my_arr):
inversionCount=0
if len(my_arr)<=1:
return 0
middle=len(my_arr)//2
left=my_arr[:middle] #left part
right=my_arr[middle:] #right part
inversionCount+=countInverseWithMergeSort(left) #recursive calls
inversionCount+=countInverseWithMergeSort(right)
#THIS PART MEGES THE LEFT AND RIGHT PART
s1=len(left) #size of left and right sub arrays.
s2=len(right)
i=0
j=0
x=0
while i<s1 and j<s2:
if left[i]<right[j]:
my_arr[x]=left[i]
i=i+1
else:
my_arr[x]=right[j]
j=j+1
x=x+1
while i<s1:
my_arr[x]=left[i]
i=i+1
x=x+1
while j<s2:
my_arr[x]=right[j]
j=j+1
x=x+1
# this part takes the double of second array and calculates the
# incersion count for this subarray.
i=0
j=0
x=0
doubleRight= list(map(double, right))
while i<s1 and j<s2:
if left[i]<=doubleRight[j]:
i=i+1
else:
inversionCount+=(len(left[i:]))
j=j+1
x=x+1
return inversionCount
def printResult(input,result):
print("")
print("The input is:",input)
print("The inverse count is:",result)
print("")
def calculateInverse(input):
inputCopy=input[:]
result=countInverseWithMergeSort(input)
printResult(inputCopy,result)
if __name__ == '__main__':
arr1 = [12, 11, 13, 5, 6, 7]
calculateInverse(arr1)
arr2 = [16,17,14,16,12,2]
calculateInverse(arr2)
arr3 = [100,49,25,6,5,1]
calculateInverse(arr3)
arr4 = [10,5,2,8,100,2,50,60,20,30,1]
calculateInverse(arr4)
|
f180916af608781beecc94f98beed2134bac54d1 | noorul90/Python_Learnings | /TupleTest.py | 334 | 4.25 | 4 | #list is mutable but tuple is not mutable means once you create the tuple you can't change value in tuples
numsTuple = (12,15,14,52,44) #12,15,14,52,44
nums = 14,52,55,25
print(type(nums), nums)
print(numsTuple)
print(numsTuple[1])
#immutable nature
#numsTuple[1]=15 #gives error beacause we can't change the value
#print(numsTuple) |
1f1eed0f8bede71d14c1cbd274932e6ff0b9dc20 | jayhebe/w3resource_exercises | /Basic - Part1/ex133.py | 373 | 3.5 | 4 | # import datetime
#
#
# start_time = datetime.datetime.now()
#
# for _ in range(100000):
# pass
#
# end_time = datetime.datetime.now()
# print(end_time - start_time)
from timeit import default_timer
def timer(n):
start = default_timer()
# some code here
for row in range(0, n):
print(row)
print(default_timer() - start)
timer(5)
timer(15)
|
b933450da19e624724a2df4d52df77cfeea8f1cf | Loptt/mph-programming-101 | /Clase3/EjercicioEx4.py | 906 | 4.03125 | 4 | numero = int(input("por favor ingrese un numero: "))
if numero > 0:
#positivo
if numero % 2 == 0:
#par
if numero < 100:
#menor a 100
print("es un numero positivo, par y menor a 100")
elif numero > 100:
#mayor a 100
print("es un numero positivo, par y mayor a 100")
else:
print("es un numero positivo, par y es 100")
else:
#impar
if numero < 100:
#menor a 100
print("es un numero positivo, impar y menor a 100")
else:
#mayor a 100
print("es un numero positivo, impar y mayor a 100")
elif numero < 0:
#negativo
if numero % 2 == 0:
#par
print("es un numero negativo, par y menor a 100")
else:
#impar
print("es un numero negativo, impar y menor a 100")
else:
print("el numero es 0") |
a2772aa84854ad6d6e50f0874fcd0f33b2f4636d | sametdlsk/python_Basics | /basicDataTypes.py | 7,923 | 3.84375 | 4 | # -*- coding:utf-8 -*-
"""
Bu kodlar Python ile Pycharm editörü kullanılarak yazılmıştır.
Bu kod basit sorular topluluğudur. Sorular Türkçedir.
These codes are written using the Pycharm editor in Python.
This code it contains simple questions in Turkish,
used random.
"""
import random
def againAndAgain():
print(
"Kim Python veri tipi ister yarışmamıza hoş geldiniz !(Binary veri tipleri kullanılmamıştır) 11 soruya kadar cevap verebilirsiniz. Kaç Soruya Cevap Vermek İstersiniz ? :")
numberofproblems = input()
numberofproblems = int(numberofproblems)
if numberofproblems > 11:
print("Özür dileriz ancak 11 soruya cevap verebilirsiniz !")
againAndAgain()
if numberofproblems <= 0:
print("Oynamadığınız için teşekkürler")
exit(0)
else:
for problemswanted in range(numberofproblems):
question1 = 1
question2 = 2
question3 = 3
question4 = 4
question5 = 5
question6 = 6
question7 = 7
question8 = 8
question9 = 9
question10 = 10
question11 = 11
questionNumber = random.randint(1, 11)
if questionNumber == 1:
question1Answer = input("Pythonda metinsel ifadeleri tutan veri tipi nedir ?: ")
if question1Answer == "string" \
or question1Answer == "String" \
or question1Answer == "str":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap String veri tipidir !")
if questionNumber == 2:
question2Answer = input("Pythonda haritalama(mapping) yapabilen veri tipi nedir ?: ")
if question2Answer == "dict" \
or question2Answer == "DİCT" \
or question2Answer == "Dict" \
or question2Answer == "DICT" \
or question2Answer == "dict.":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Dict veri tipidir !")
if questionNumber == 3:
question3Answer = input("Pythonda ondalıklı sayı türünü tutan veri tipi nedir ?: ")
if question3Answer == "Float" \
or question3Answer == "float" \
or question3Answer == "FLOAT":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Float veri tipidir !")
if questionNumber == 4:
question4Answer = input("Python'da tamsayı veri tipi nedir ?: ")
if question4Answer == "int" \
or question4Answer == "İNT" \
or question4Answer == "INT" \
or question4Answer == "İnt" \
or question4Answer == "integer" \
or question4Answer == "INTEGER" \
or question4Answer == "Integer":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap int yada integer veri tipidir !")
if questionNumber == 5:
question5Answer = input(
"Python'da ileri düzey matematiksel işlemlerde kullanılan sayısal veri tipi nedir ?: ")
if question5Answer == "Complex" \
or question5Answer == "COMPLEX" \
or question5Answer == "complex":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Complex veri tipidir !")
if questionNumber == 6:
question6Answer = input("Python'da değeri sadece true yada false olabilecek veri tipi nedir ?: ")
if question6Answer == "Bool" \
or question6Answer == "Boolean" \
or question6Answer == "BOOL" \
or question6Answer == "BOOLEAN" \
or question6Answer == "bool" \
or question6Answer == "boolean":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Bool yada Boolean veri tipidir !")
if questionNumber == 7:
question7Answer = input(
"Herhangi bir sayıda diğer objeleri içinde bulunduran bir sandık vazifesi görebilen" + "\n" + "ve bir listede birden fazla tip öğenin yanyana bulunabildiği veri tipi nedir ?: ")
if question7Answer == "list" \
or question7Answer == "LİST" \
or question7Answer == "List" \
or question7Answer == "LIST":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap List veri tipidir !")
if questionNumber == 8:
question8Answer = input(
"Sıralı ve değiştirilemez bir koleksiyon çeşidi olan, ( ) parantezler kullanılarak" + "\n" + "yazılan ve list veri tipindeki bazı metotları içermeyen veri tipi nedir ?: ")
if question8Answer == "Tuple" \
or question8Answer == "TUPLE" \
or question8Answer == "tuple":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Tuple veri tipidir !")
if questionNumber == 9:
question9Answer = input(
"Python'da belirli aralıkta bulunan sayıları göstermek için kullanılan veri tipi nedir ?: ")
if question9Answer == "range" \
or question9Answer == "RANGE" \
or question9Answer == "Range":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Range veri tipidir !")
if questionNumber == 10:
question10Answer = input(
"Python'da küme görevi gören ve Liste, Tuple ve Dict gibi veri tiplerini barındırabilen," + "\n" + "değiştirilebilir bir veri yapısı nedir ?: ")
if question10Answer == "set" \
or question10Answer == "SET" \
or question10Answer == "Set":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Set veri tipidir !")
if questionNumber == 11:
question11Answer = input(
"Python'da Set veri türünün kısıtlanmış halidir. Bu veri türüne ekleme," + "\n" + "silme, değiştirme yapılamaz immutable(değiştirilemez) veri tipidir. Bu veri tipi nedir ?: ")
if question11Answer == "frozenset" \
or question11Answer == "FROZENSET" \
or question11Answer == "Frozenset" \
or question11Answer == "FrozenSet":
print("Doğru Cevap Tebrikler !")
else:
print("Malesef cevabınız doğru değil, doğru cevap Frozenset veri tipidir !")
againAndAgain()
|
7dfb15c020febdc9ef00584fe800332abc75d8e7 | johnthomasjtk/Codeforces-solved-programs | /watermelon.py | 70 | 3.734375 | 4 | s = input()
if s % 2 == 0 and s > 2 :
print "YES"
else :
print "NO"
|
c44a37f819b3705b6832603ed4ac385e3750c0cc | storbukas/university | /INF237/set_1/sheep.py | 1,609 | 3.671875 | 4 | def adjacent(x,y,data):
neighbours = []
if(valid(x+1,y,data) and data[x+1][y] == "#"):
neighbours.append((x+1,y))
if(valid(x-1,y,data) and data[x-1][y] == "#"):
neighbours.append((x-1,y))
if(valid(x,y+1,data) and data[x][y+1] == "#"):
neighbours.append((x,y+1))
if(valid(x,y-1,data) and data[x][y-1] == "#"):
neighbours.append((x,y-1))
return neighbours
def valid(x,y,data):
return ((x >= 0 and x < len(data)) and (y >= 0 and y < len(data[x])))
def dfs(data,stack):
while(not stack==set()):
element = stack.pop()
data[element[0]][element[1]] = "."
for i in adjacent(element[0],element[1],data):
stack.add(i)
def sheep():
dimensions = map(int, raw_input().split())
data = list(range(dimensions[0]))
counter = 0
for i in range(len(data)):
data[i] = list(raw_input())
liste = {}
stack = set()
for x in range(len(data)):
for y in range(len(data[x])):
if(data[x][y]=="#"):
data[x][y]="."
liste[(x,y)]=adjacent(x,y,data)
for i in liste:
stack.add(i)
counter += 1
if(len(liste[(x,y)]) == 0):
continue
else:
dfs(data,stack)
#print(counter)
return counter
def main():
testcases = int(raw_input())
liste = []
for i in range(testcases):
liste.append(sheep())
for i in liste:
print(i)
if __name__ == "__main__":
main()
|
aab2b13ca01dd80ff2622a768b81a05c525042eb | Jsonghh/leetcode | /200113/Unique_Binary_Search_Trees_II.py | 855 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if not n:
return []
return self.helper(1, n)
def helper(self, start, end):
if start > end:
return [None]
res = []
for rootval in range(start, end + 1):
left_trees = self.helper(start, rootval - 1)
right_trees = self.helper(rootval + 1, end)
for i in left_trees:
for j in right_trees:
root = TreeNode(rootval)
root.left = i
root.right = j
res.append(root)
return res
|
f2762711152cf6617f935de4e69cf285c44bc08f | LRS4/mit-6.00.1x | /recursion.py | 764 | 3.9375 | 4 | def fact(x):
"""
Find the factorial of any number
"""
if x == 1:
return 1
else:
return x * fact(x - 1)
print("Factorial of 4 is " + str(fact(4)))
def fib(x):
"""
Find the Fibonacci of x
"""
if x == 0 or x == 1:
return 1
else:
return fib(x - 1) + fib(x - 2)
for i in range(15):
print(fib(i))
sentence = "Able was I, ere I saw Elba"
def isPalandrome(sentence):
"""
Determine if a sentence is a palandrome
"""
sentence = sentence.lower().replace(" ", "").replace(",", "")
if len(sentence) <= 1:
return True
else:
return sentence[0] == sentence[-1] and isPalandrome(sentence[1:-1])
print(isPalandrome(sentence)) |
4155aeca9cee9c1f911a2828d0548527e738c782 | SpCrazy/crazy | /code/SpiderDay1_Thread/ticket_lock/ticket_lock.py | 717 | 3.515625 | 4 | import time
from threading import Thread, currentThread, Lock
#买票问题
class TicketThread(Thread):
ticket = 5 #所有窗口共享5张票(类属性)
lock = Lock()
def __init__(self,thread_name):
super().__init__(name=thread_name)
def run(self):
for i in range(100):
TicketThread.lock.acquire()
if TicketThread.ticket > 0:
time.sleep(2)
TicketThread.ticket -= 1
print(currentThread().name+"卖了一张票,剩余票数为:", TicketThread.ticket)
TicketThread.lock.release()
if __name__ == '__main__':
for i in range(1,10):
t = TicketThread("窗口"+str(i))
t.start() |
d238c2d9308eeb137b15d9c320464a5cc970a4bd | MartinMa28/Algorithms_review | /union_find/0684_redundant_connection.py | 1,885 | 3.609375 | 4 | class DisjointSet:
class Node:
def __init__(self, x):
self.parent = self
self.rank = 0
self.val = x
def __init__(self):
self.num_to_node = {}
def make_set_by_edges(self, edges):
for e in edges:
if e[0] not in self.num_to_node:
self.num_to_node[e[0]] = DisjointSet.Node(e[0])
if e[1] not in self.num_to_node:
self.num_to_node[e[1]] = DisjointSet.Node(e[1])
def _find(self, node: 'DisjointSet.Node') -> 'DisjointSet.Node':
if node == node.parent:
return node
node.parent = self._find(node.parent)
return node.parent
def find(self, x: int) -> int:
return self._find(self.num_to_node[x]).val
def union(self, x: int, y: int):
n_x = self.num_to_node[x]
n_y = self.num_to_node[y]
root_x = self._find(n_x)
root_y = self._find(n_y)
if root_x is root_y:
# In the same set.
return
else:
if root_x.rank == root_y.rank:
root_x.rank += 1
root_y.parent = root_x
elif root_x.rank > root_y.rank:
root_y.parent = root_x
else:
root_x.parent = root_y
class Solution:
def findRedundantConnection(self, edges: list) -> list:
uf = DisjointSet()
uf.make_set_by_edges(edges)
for e in edges:
root_1 = uf.find(e[0])
root_2 = uf.find(e[1])
if root_1 == root_2:
return e
uf.union(e[0], e[1])
if __name__ == "__main__":
solu = Solution()
print(solu.findRedundantConnection([[1,2],[1,3],[2,3]])) |
f9c3c32eb310fa3072cac3d53475fbdfbbec800a | tarunluthra123/Competitive-Programming | /Leetcode/Pascal's Triangle.py | 449 | 3.609375 | 4 | from math import factorial as f
class Solution(object):
def generate(self, n):
"""
:type numRows: int
:rtype: List[List[int]]
"""
def nCr(n, r):
num = f(n)
den = f(r)*f(n-r)
return num//den
res = []
for i in range(n):
row = []
for j in range(i+1):
row += [nCr(i, j)]
res += [row]
return res
|
7b8afaab4569cc450927d80b2389901c91ad2790 | fedeisas/advent_of_code_python | /2a/keyboard.py | 1,017 | 3.515625 | 4 | class Keyboard():
def __init__(self):
self.keyboard = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
self.position = (1, 1)
self.code = []
self.movements = {
'U': (-1, 0),
'R': (0, 1),
'D': (1, 0),
'L': (0, -1),
}
def apply_steps(self, steps):
for step in steps:
self.apply_step(step)
def clamp(self, n):
return max(
0,
min(
len(self.keyboard) - 1,
n
)
)
def apply_step(self, step):
for move in list(step):
x, y = self.position
movement = self.movements[move]
self.position = (
self.clamp(x + movement[0]),
self.clamp(y + movement[1])
)
self.code.append(self.keyboard[self.position[0]][self.position[1]])
def get_code(self):
return ''.join(map(str, self.code)) |
277427fb348c23c1d9542dcfaacfc88bb0dcb7d9 | robdale110/PythonCourse | /WritingToFiles.py | 330 | 3.8125 | 4 | # Creates and writes to empty file, doesn't add to existing file
file = open("example1.txt", "w")
file.write("Line 1")
file.close()
file = open("example1.txt", "w")
file.write("Line 2")
file.close()
line = ["Line 1", "Line 2", "Line 3"]
file = open("example1.txt", "w")
for item in line:
file.write(item + "\n")
file.close()
|
2bcc8ded46d5d8d492fdad93c63321fd75274caa | jayadevgithub/BCR | /AsyncProject/copy_test.py | 177 | 3.71875 | 4 | import copy
# a = {"a":1,"b":2}
# b = copy.copy(a)
# b["c"] = 3;
# a["c"] = 4;
a = [1,2,3]
b = copy.copy(a)
a.append(4)
print("a "+str(a))
print("b "+str(b))
alp |
c900a585490971101e9d88dc7b2fc1790b79c034 | TheDarkKnight1939/FirstYearPython | /Greater.py | 152 | 3.640625 | 4 | j=0
for j in range(0,7):
a[j]=int(input("Input 6 numbers")
for i in range(0,6):
if a[i]>10:
print(a[i])
|
9320acada498bf5640240d37f664450cef8e97a4 | superbeckgit/cypherpuzzle | /cypher.py | 4,154 | 3.6875 | 4 | #!/usr/bin/python
from itertools import permutations
import pdb
import sys
def build_cypher_list(cylen=4):
"""
Build a list of cyphers using cylen characters each. List is all permuations.
Parameters
----------
cylen - num - number of characters per cypher
Returns
-------
cylist - [] - list of all permutations for that number of characters
Examples
--------
>>> from cypher import *
>>> ['AB', 'BA'] == build_cypher_list(2)
True
"""
# get letters AB... for cylen
letters = [chr(ord('A')+ix) for ix in range(cylen)]
letters = ''.join(letters)
cyphertups = list(permutations(letters))
cyphers = [''.join(tup) for tup in cyphertups]
return cyphers
def smash_cyphers(cylist):
"""
Combine list of strings by overlapping characters of adjacent list items.
Parameters
----------
cylist - [] - list of cyphers to smash together
Returns
-------
cystr - str - one big string of all cyphers overlapping
Examples
--------
>>> from cypher import *
>>> cylist = ['ABC', 'BCA', 'ACB']
>>> 'ABCACB' == smash_cyphers(cylist)
True
"""
if not cylist:
return ''
cystr = cylist[0]
for cypher in cylist[1:]:
overlap = get_overlap(cystr, cypher)
cystr = cystr + cypher[overlap:]
return cystr
def get_overlap(first, second):
"""
Determine how many character from the beginning of second match the ending characters
of first.
Parameters
----------
first - str - a string of characters
second - str - another string of characters
Returns
-------
overlap - num - number of characters at the end of first also found at the beginning
of second
Examples
--------
>>> from cypher import *
>>> 3 == get_overlap('ABCD', 'BCDA')
True
>>> 0 == get_overlap('ABCD', 'EFG')
True
"""
overlap = 0
for cap in range(len(second), 0, -1):
# grab chunks of second cypher in decreasing size
subcy = second[:cap]
if first.endswith(subcy):
overlap = cap
break
return overlap
def best_next(cystr, cylist):
"""
Return the item from cylist whose beginning characters most overlap with the ending
characters of cystr.
Parameters
----------
cystr - str - string of characters
cylist - [] - list of strings
Returns
-------
best - str - item from cylist with most overlap with end of cystr
Examples
--------
>>> from cypher import *
>>> best = best_next('CAB', ['BAC', 'ABC', 'ABD'])
>>> best in ['ABC', 'ABD']
True
"""
overlaps = [get_overlap(cystr, cy) for cy in cylist]
bestix = overlaps.index(max(overlaps))
best = cylist[bestix]
return best
def break_not_ones(nums):
r"""
Parameters
----------
nums - [] - list of numbers
Returns
-------
output - str - numbers joined as string, \n after each num != 1
Examples
--------
>>> from cypher import *
>>> out = break_not_ones([1, 1, 4, 1, 1, 1, 5, 1, 1])
>>> out == '114\n1115\n11'
True
"""
numset = set(nums)
numstr = ''.join(map(str, nums))
numset.remove(1)
for num in numset:
numstr = numstr.replace(str(num), '%d\n'%num)
return numstr
if __name__ == '__main__':
if len(sys.argv) == 1:
import doctest
doctest.testmod()
if len(sys.argv) == 2:
cylen = int(sys.argv[1])
cylist = build_cypher_list(cylen)
cystr = cylist.pop(0)
print('\nBuilding the sequence:')
print(cystr)
overlaps = []
for ix in range(len(cylist)):
oldlen = len(cystr)
best = best_next(cystr, cylist)
print(' + %s' % best)
cylist.remove(best)
cystr = smash_cyphers([cystr, best])
newlen = len(cystr)
overlaps.append(newlen-oldlen)
print('\nSequence growth analysis:')
print(break_not_ones(overlaps))
print('\nEfficient sequence, length')
print(cystr, len(cystr))
|
0ebc2b4598a9c0a6b1f06dd62ec2daf115fc652c | zhuhaoyue/test7 | /777.py | 623 | 3.859375 | 4 |
import random
counts = 3
answer = random.randint(1,10)
while counts > 0:
temp = input("不妨猜一下小七宝现在心里想的是哪一个数字:")
guess = int(temp)
if guess ==answer:
print("你是小七宝心里的蛔虫嘛? !")
print("哼,你猜中了也没奖励 !")
break
else:
if guess < answer:
print("小啦")
else:
print("大啦")
if counts > 1:
print("再给你一次机会!")
else:
print("机会用光咯")
counts = counts-1
print("游戏结束,不玩啦~~")
|
41c0884ceb495da58a16a74c4b299276ea90009c | karenlorhana/decisao_e_repeticaoPython | /exerciciosDecisao/questao04.py | 299 | 4 | 4 | #calcular média aluno dizendo sua média
nota1 = float(input("digite a primeira nota: "))
nota2 = float(input("digite a segunda nota: "))
media = (nota1 + nota2)/2
if(media >= 6):
print("o aluno foi aprovado com a média ", media)
else:
print("o aluno foi reprovado com a média ", media)
|
e978af14aa4eb719c0935aecd1768fe07df1be22 | fcdennis/CS50 | /problems_set/pset7/houses/import.py | 705 | 3.875 | 4 | import csv
from cs50 import SQL
from sys import argv, exit
if len(argv) != 2:
print("Usage: python import.py characters.csv")
exit(1)
db = SQL("sqlite:///students.db")
def main():
with open(argv[1]) as csv_file:
data = csv.DictReader(csv_file)
for row in data:
names = partitionFullName(row["name"])
db.execute("INSERT INTO students(first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)",
names[0], names[1], names[2], row["house"], row["birth"]
)
def partitionFullName(fullName):
names = fullName.split()
if(len(names) >= 3):
return names
else:
return [names[0], None, names[1]]
main() |
b5f9ebd0ed618e63098274b75b12063fc545437d | c940606/leetcode | /Word Pattern.py | 1,240 | 3.6875 | 4 | class Solution(object):
def wordPattern2(self, pattern, str):
"""
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式
---
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
----
思路:
通过模式把字典造出来,
:type pattern: str
:type str: str
:rtype: bool
"""
str = str.split(" ")
pattern_dict = {}
str_dict = {}
for index,key in enumerate(pattern):
if key in pattern_dict:
pattern_dict[key].append(index)
else:
pattern_dict[key] = [index]
for index,key in enumerate(str):
if key in str_dict:
str_dict[key].append(index)
else:
str_dict[key] = [index]
return sorted(pattern_dict.values()) == sorted(str_dict.values())
def wordPattern1(self, pattern, str):
str = str.split(" ")
if len(set(pattern)) != len(set(str)):
return False
if len(set(pattern)) == len(set(str)) == len(set(zip(pattern,str))):
return True
else:
return False
def wordPattern(self, pattern, s):
a = Solution()
print(a.wordPattern1("abba","dog cat cat dog"))
|
0cffd304b5bd2b9e19d68282be4949f7e77a8fb7 | sjullieb/HackerRank_Python | /6_5 Queues and Stacks.py | 3,909 | 3.859375 | 4 | class Stack:
def __init__(self, size):
self.items = []
self.size = int(size)
for i in range(self.size):
self.items.append('')
self.isfull = False
self.current = 0
def isEmpty(self):
return self.isempty
def push(self, item):
if self.isfull:
raise 'Stack is FULL'
self.items[self.current] = item
if self.current + 1 == self.size:
self.isfull = True
else:
self.current += 1
def pop(self):
if self.current == 0:
raise 'Stack is EMPTY'
if self.isfull:
item = self.items[self.current]
self.isfull = False
else:
item = self.items[self.current - 1]
self.current -= 1
return item
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
class Queue:
def __init__(self, size):
self.items = []
self.size = int(size)
for i in range(self.size):
self.items.append('')
self.isempty = True
self.current = 0
self.next = 0
def isEmpty(self):
return self.isempty
def enqueue(self, item):
if self.next == self.current and self.isempty == False:
raise 'Queue is FULL'
self.items[self.next] = item
self.isempty = False
self.next = (self.next + 1) % self.size
def dequeue(self):
if self.isempty :
raise 'Queue is EMPTY'
item = self.items[self.current]
self.current = (self.current + 1) % self.size
if self.current == self.next:
self.isempty = True
return item
def size(self):
return len(self.items)
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
class QueueOnList:
def __init__(self):
self.first = None
self.last = None
def enqueue(self, value):
item = ListNode(value)
if self.first == None:
self.first = item
self.last = item
else:
self.last.next = item
self.last = item
def dequeue(self):
if self.first == None:
raise 'Queue is Empty'
item = self.first
self.first = self.first.next
return item.value
def printQueue(self):
item = self.first
arr = []
while item != None:
arr.append(item.value)
item = item.next
print arr
class StackOnList:
def __init__(self):
self.first = None
def push(self, value):
item = ListNode(value)
item.next = self.first
self.first = item
def pop(self):
if self.first == None:
raise 'Stack is EMPTY'
item = self.first
self.first = self.first.next
return item.value
def printStack(self):
item = self.first
arr = []
while item != None:
arr.append(item.value)
item = item.next
print arr
class Solution:
# Write your code here
def __init__(self):
self.stack = StackOnList()
self.queue = QueueOnList()
def pushCharacter(self, ch):
self.stack.push(ch)
def popCharacter(self):
return self.stack.pop()
def enqueueCharacter(self, ch):
self.queue.enqueue(ch)
def dequeueCharacter(self) :
return self.queue.dequeue()
|
c9a6708eaf8e4deb40eebee4cfcfb2db934fab33 | jwu424/Leetcode | /ShortestUnsortedContinuousSubarray.py | 1,442 | 3.8125 | 4 | # Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
# You need to find the shortest such subarray and output its length.
# 1. sort the nums and compare the sorted nums with nums from beginning and end.
# Time complexity: o(NlogN)
# 2. Start from left, try to find the maximum. If nums[i] < max, then left part of i need to be sorted.
# Start from right, try to find the minimum. If nums[i] > min, then the right part of i need to be sorted.
# Time complexity: O(N)
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
sorted_num = sorted(nums)
l1, l2 = 0, len(nums)-1
while l1 <= l2 and nums[l1] == sorted_num[l1]:
l1 += 1
while l1 <= l2 and nums[l2] == sorted_num[l2]:
l2 -= 1
return l2 - l1 + 1
def findUnsortedSubarray2(self, nums: List[int]) -> int:
l_max = nums[0]
l = 0
for i in range(len(nums)):
if nums[i] > l_max:
l_max = nums[i]
elif nums[i] < l_max:
l = i
r_min = nums[-1]
r = 0
for i in range(len(nums)-1, -1, -1):
if nums[i] < r_min:
r_min = nums[i]
elif nums[i] > r_min:
r = i
if r >= l:
return 0
return l - r + 1 |
ff0f9a6cfc46b69e441b2e4d111409e388b387cf | nekapoor7/Python-and-Django | /GREEKSFORGREEKS/List/duplicate_element.py | 270 | 4.09375 | 4 | #Python | Program to print duplicates from a list of integers
list1 = list(map(int,input().split()))
new_list = sorted(set(list1))
dup_list = []
for i in range(len(new_list)):
if list1.count(new_list[i]) > 1:
dup_list.append(new_list[i])
print(dup_list)
|
80b850c10e359eaf319a11b2e735bcc37fbdbcac | igorsantos314/PythonForLife | /Person.py | 1,173 | 4.25 | 4 | class Person:
name = ''
age = 0
height = 0
weight = 0
#constructor
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
#gets
def getName(self):
return self.name
def getAge(self):
return self.age
def getHeight(self):
return self.height
def getWeight(self):
return self.weight
#sets
def setName(self, name):
self.name = name
def setAge(self, age):
self.age = age
def setHeight(self, height):
self.height = height
def setWeight(self, weight):
self.weight = weight
#data of Person
def printData(self):
print(' --> Name: ',self.name)
print(' --> Age: ',self.age)
print(' --> Height: ',self.height)
print(' --> Weight: ',self.weight)
#create persons Mary and John
mary = Person('Mary', 19, 1.75, 75)
john = Person('John', 25, 1.80, 95)
#change data of mary
mary.setWeight(90)
mary.setWeight(20)
#change data of john
john.setHeight(1.85)
john.setAge(26)
mary.printData()
john.printData()
|
3391af853761c080256c594278d0925b25b7ac14 | sota1235/AOJ-Answers | /answers/0027.py | 300 | 3.78125 | 4 | #!/usr/bin/python
# AOJ
# 0027
import datetime
days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
]
while True:
m, d = map(int, input().split(' '))
if m == 0: break
print(days[datetime.date(2004, m, d).weekday()])
|
bc1957e532b65b02e885675ccd571da4d2f0c7a2 | danilodesouzapereira/ProjetoSimuladorManobras | /Commwspython/server/graphModule.py | 11,456 | 3.765625 | 4 | # Python program for Kruskal's algorithm to find
# Minimum Spanning Tree of a given connected,
# undirected and weighted graph
# from collections import defaultdict
import random
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
'''
Class to represent a graph
'''
class Graph:
def __init__(self, vertices):
self.V = vertices # Number of vertices
self.graph = [] # Default dictionary to store graph
self.edgesKRST = [] # Store edges after KruskalRST procedure
'''
Function to add an edge to graph
'''
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
'''
Utility function to find set of an element i
(uses path compression technique)
'''
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
'''
Function to plot graph
'''
def plot_graph(self):
g = nx.Graph()
nodes_list = set([])
for edge in self.edgesKRST:
nodes_list.add(edge[0])
nodes_list.add(edge[1])
g.add_nodes_from(nodes_list)
for edge in self.edgesKRST:
g.add_edge(edge[0], edge[1])
nx.draw(g, with_labels=True)
plt.draw()
plt.show()
'''
Method to return vertices which are disconnected to vertice 0
'''
def isolated_vertices(self):
# Assess initially isolated vertices. There is no edge connecting them.
isol_vertices_1 = set(range(self.V))
for edge in self.graph:
if edge[0] in isol_vertices_1:
isol_vertices_1.remove(edge[0])
if edge[1] in isol_vertices_1:
isol_vertices_1.remove(edge[1])
# Assess initially connected vertices.
edges_list = self.graph.copy()
repeat = True
find_vertice_set = {0}
while repeat:
repeat = False
for i in reversed(range(len(edges_list))):
edge = edges_list[i]
if edge[0] in find_vertice_set or edge[1] in find_vertice_set:
find_vertice_set.add(edge[0])
find_vertice_set.add(edge[1])
edges_list.remove(edge)
repeat = True
# fill list of isolated vertices based on remaining edges
isol_vertices_2 = set()
if len(edges_list) > 0:
for edge in edges_list:
isol_vertices_2.add(edge[0])
isol_vertices_2.add(edge[1])
# determine the list of all isolated vertices
list_isolated_vertices = list(isol_vertices_1.union(isol_vertices_2))
return list_isolated_vertices
'''
Function that does union of two sets of x and y (uses union by rank)
'''
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
# Attach smaller rank tree under root of
# high rank tree (Union by Rank)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
# If ranks are same, then make one as root
# and increment its rank by one
else :
parent[yroot] = xroot
rank[xroot] += 1
'''
The main function to construct MST using Kruskal's algorithm
'''
def KruskalMST(self):
result =[] #This will store the resultant MST
i = 0 # An index variable, used for sorted edges
e = 0 # An index variable, used for result[]
# Step 1: Sort all the edges in non-decreasing
# order of their
# weight. If we are not allowed to change the
# given graph, we can create a copy of graph
self.graph = sorted(self.graph,key=lambda item: item[2])
parent = [] ; rank = []
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
# Number of edges to be taken is equal to V-1
while e < self.V -1 :
# Step 2: Pick the smallest edge and increment
# the index for next iteration
u,v,w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent ,v)
# If including this edge does't cause cycle,
# include it in result and increment the index
# of result for next edge
if x != y:
e = e + 1
result.append([u,v,w])
self.union(parent, rank, x, y)
# Else discard the edge
# print the contents of result[] to display the built MST
#print("Following are the edges in the constructed MST")
#for u,v,weight in result:
#print str(u) + " -- " + str(v) + " == " + str(weight)
#print ("%d -- %d == %d" % (u,v,weight))
# Crossover operator. It takes two parent individuals and generates
# offspring which contains characteristics from both parents.
#def crossover(self, parent_edges_1, parent_edges_2):
# if parent_edges_1 == None or parent_edges_2 == None:
# return None
#
# # Gathers edges from both parents
# union_edges = list(set(parent_edges_1) | set(parent_edges_2))
'''
Mutation operator. It deletes a random edge and inserts a new one.
To guarantee radiality, it verifies if newly added edge creates mesh.
'''
def mutation(self):
if len(self.edgesKRST) == 0:
return
# determines edge to be removed
i_remove = random.randint(0, len(self.edgesKRST)-1)
removed_edge = self.edgesKRST[i_remove]
self.edgesKRST.remove(removed_edge)
# adds edge at random, provided that it does not create mesh
new_edge = self.pick_radial_edge(removed_edge)
if new_edge != None:
self.edgesKRST.append(new_edge)
else:
self.edgesKRST.append(removed_edge)
'''
Method to determine if current graph topology is radial
'''
def is_radial(self):
parent = []; rank = []
for node in range(self.V): parent.append(node); rank.append(0)
for edge in self.edgesKRST:
x = self.find(parent, edge[0]); y = self.find(parent, edge[1])
self.union(parent, rank, x, y)
if x == y: return False
return True
'''
Method to determine if closing edge causes mesh
'''
def creates_mesh(self, candidate_edge):
parent = [] ; rank = []
for node in range(self.V):
parent.append(node) ; rank.append(0)
for edge in self.edgesKRST:
x = self.find(parent, edge[0]) ; y = self.find(parent, edge[1])
self.union(parent, rank, x, y)
# tries to insert candidate edge
x = self.find(parent, candidate_edge[0]); y = self.find(parent, candidate_edge[1])
# returns if candidate edge creates mesh
return x == y
'''
Method to pick a switch/edge to open in order to restore
graph radiality
'''
def edge_to_open_mesh(self, list_switches_to_open):
# verifications
if list_switches_to_open is None: return None
if len(list_switches_to_open) == 0: return None
str_conn_edges = ""
for edge in self.edgesKRST:
str_conn_edges += str(edge) + " "
str_sw_to_open = ""
for edge in list_switches_to_open:
str_sw_to_open += str(edge) + " "
# print("connected edges: " + str_conn_edges + " switches to open: " + str_sw_to_open)
# Among the edges that need to be opened, picks an edge
# to be opened in order to restore radiality
for edge_to_be_opened in list_switches_to_open:
# edge_list = list(edge) ; edge_to_be_opened = [edge_list[0], edge_list[1], 1]
# tries to remove edge_to_be_opened from graph
edge_to_be_opened_1 = [edge_to_be_opened[0], edge_to_be_opened[1], 1]
edge_to_be_opened_2 = [edge_to_be_opened[1], edge_to_be_opened[0], 1]
if edge_to_be_opened_1 in self.edgesKRST:
edge_to_be_opened = edge_to_be_opened_1
elif edge_to_be_opened_2 in self.edgesKRST:
edge_to_be_opened = edge_to_be_opened_2
# print("edge_to_be_opened: " + str(edge_to_be_opened))
self.edgesKRST.remove(edge_to_be_opened)
# if resulting graph is radial, returns.
if self.is_radial(): return edge_to_be_opened
else: self.edgesKRST.append(edge_to_be_opened)
return None
'''
Method to pick edge that does not cause mesh
'''
def pick_radial_edge(self, removed_edge):
parent = [] ; rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
for edge in self.edgesKRST:
u = edge[0]; v = edge[1]
x = self.find(parent, u); y = self.find(parent, v)
self.union(parent, rank, x, y)
# gets all candidate edges
candidate_edges = []
for edge in self.graph:
if edge in self.edgesKRST or edge == removed_edge:
continue
candidate_edges.append(edge)
#print("total candidates: %d" % (len(candidate_edges)))
#for edge in candidate_edges:
# print("candidate: %d -- %d" % (edge[0], edge[1]))
# Picks an edge at random. If it does not create cycle, returns the edge.
random_index = -1
for i in range(len(candidate_edges)):
random_index = random.randint(0, len(candidate_edges)-1)
edge = candidate_edges[random_index]
u = edge[0] ; v = edge[1]
x = self.find(parent, u); y = self.find(parent, v)
if x != y:
return edge
return None
'''
Function to print graph
'''
def print_graph(self):
# print the contents of result[] to display the built MST
for edge in self.edgesKRST:
print ("%d -- %d" % (edge[0],edge[1]))
'''
Variation of original method "KruskalRST". This one considers edges biased, in such a way that initially closed
edges are more likely to be picked.
'''
def KruskalRST_biased(self, initial_edges, bias_prob):
result = [] # This will store the resultant RST
i = 0 # An index variable, used for sorted edges
e = 0 # An index variable, used for result[]
# randomly rearrange the graph
random.shuffle(self.graph)
# arrange graph in such a way that initially closed edges appear first
for ini_edge in initial_edges:
if np.random.randint(0, 100) > bias_prob:
continue
index = self.graph.index(ini_edge)
item = self.graph.pop(index)
self.graph.insert(0, item)
parent = []; rank = []
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
# Number of edges to be taken is equal to V-1
while e < self.V - 1:
# Step 2: Pick the smallest edge and increment
# the index for next iteration
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
# If including this edge does't cause cycle,
# include it in result and increment the index
# of result for next edge
if x != y:
e = e + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
self.edgesKRST.append([u, v, w]) # saves spanning tree generated randomly
# Else discard the edge
'''
The main function to construct RST using Kruskal's algorithm
'''
def KruskalRST(self):
result = [] # This will store the resultant RST
i = 0 # An index variable, used for sorted edges
e = 0 # An index variable, used for result[]
# Step 1: Sort all the edges in non-decreasing
# order of their
# weight. If we are not allowed to change the
# given graph, we can create a copy of graph
#self.graph = sorted(self.graph,key=lambda item: item[2])
# randomly rearrange the graph
random.shuffle(self.graph)
parent = [] ; rank = []
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
# Number of edges to be taken is equal to V-1
while e < self.V -1 :
# Step 2: Pick the smallest edge and increment
# the index for next iteration
u,v,w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent ,v)
# If including this edge does't cause cycle,
# include it in result and increment the index
# of result for next edge
if x != y:
e = e + 1
result.append([u,v,w])
self.union(parent, rank, x, y)
self.edgesKRST.append([u,v,w]) # saves spanning tree generated randomly
# Else discard the edge |
cd4096109ba176676c09385b59e0488c477db6b3 | peteryin21/py-graph | /pagerank.py | 806 | 3.6875 | 4 | """PageRank Algorithm"""
def pagerank(graph, iterations=10, d=0.85):
""" Calculate PageRank of vertices in a graph
Paramters
----------
graph : Graph
Graph object on which to perform PageRank analysis
iterations : int
Number of iterations in PageRank calculation
d : float
Dampening factor in PageRank algorithm
Returns
-------
pagerank: dictionary
Dictionary of vertices with PageRank values
"""
num_v = graph.number_of_vertices()
# Initialize ranks to 1/N
ranks = dict.fromkeys(graph.graph_dict, 1.0/float(num_v))
for _ in range(iterations):
for vertex, edges in graph.graph_dict.items():
incoming = graph.incoming_vertices(vertex)
weighted_ranks = [ranks[v]/len(graph.graph_dict[v]) for v in incoming]
ranks[vertex] = (1-d) + d*sum(weighted_ranks)
return ranks
|
40c7ece9d67c165442fa671ced70ac2c174b526b | srinathreddy-1206/sheets | /sheets/columns.py | 2,966 | 3.921875 | 4 | from __future__ import print_function
"""
Compatible with: 3.x,
"""
class Column(object):
"""
An Individual Column within a CSV file.This serves as a base for attributes and
methods that are common to all types of columns. Subclass of Column will define behavior
for more specific data types.
"""
#This will be updated for each column's that's instantiated.
counter = 0
def __init__(self, title = None, required = True):
self.title = title
self.required = required
self.counter = Column.counter
Column.counter += 1
def attach_to_class(self, cls, name, dialect):
self.cls = cls
self.name = name
self.dialect = dialect
if self.title is None:
# Check for None so that an empty string will skip this header
self.title = name.replace('_', ' ')
dialect.add_column(self)
def to_python(self, value):
"""
Convert the given string to a native python object.
"""
return value
def to_string(self, value):
"""
Convert the given python object to a string
"""
return value
class StringColumn(Column):
"""
A Column that contains data formatted as generic strings.
"""
pass
class IntegerColumn(Column):
"""
A Column that contains data in the form of numeric integers.
"""
def to_python(self, value):
return int(value)
class FloatColumn(Column):
"""
A Column that contains data in the form of floating point numbers.
"""
def to_python(self, value):
return float(value)
import decimal
class DecimalColumn(Column):
"""
A Column that contains data in the form of decimal values, represented
in python by decimal.Decimal
"""
def to_python(self, value):
try:
return decimal.Decimal(value)
except decimal.InvalidOperation as e:
raise ValueError(str(e))
import datetime
class DateColumn(Column):
"""
A Column that contains data in the form of dates,
represented in python by datetime.date
format
A strptime() - style format string.
See http://docs.python.org/library/datetime.html for details
"""
def __init__(self, *args, **kwargs):
if 'format' in kwargs:
self.format = kwargs.pop('format')
else:
self.format = '%Y-%m-%d'
super(DateColumn, self).__init__(*args, **kwargs)
def to_python(self, value):
"""
Parse a string value according to self.format
and return only the date portion
"""
if isinstance(value, datetime.date):
return value
return datetime.datetime.strptime(value, self.format).date()
def to_string(self, value):
"""
Format a date according to self.format and return that string.
"""
return value.strftime(self.format)
|
5ee3e2049745cf516923c0aa465527f6535783ff | tanmoyee04/codes | /EncriptionDecription.py | 2,404 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 3 19:22:07 2020
@author: Tanmoyee
"""
from tkinter import *
def show_entry_field():
print("Enter your massage:%s\n Your encrypted message is:%s\n Enter your message:%s\n Your decrypted message is:%s\n"%(e1.get(),e2.get(),e3.get(),e4.get()))
def __init__(self, master):
self.master = master
master.title("Calculator")
self.total = 0
self.entered_number = 0
self.total_label_text = IntVar()
master=Tk()
Label(master,text="Enter your message:").grid(row=0)
Label(master,text="Your encrypted message is:").grid(row=3)
Label(master,text="Enter your message:").grid(row=5)
Label(master,text="Your decrypted message is:").grid(row=7)
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = 4
var1 = StringVar()
var2 = StringVar()
var3 = StringVar()
var4 = StringVar()
e1=Entry(textvariable=var1)
e2=Entry(textvariable=var2)
e3=Entry(textvariable=var3)
e4=Entry(textvariable=var4)
e1.grid(row=0,column=1)
e2.grid(row=3,column=1)
e3.grid(row=5,column=1)
e4.grid(row=7,column=1)
#vcmd = master.register(self.validate)
#self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
def encrypt():
newmessage = ''
mystring = var1.get()
for character in mystring:
if character in alphabet:
position = alphabet.find(character)
newposition = (position + int(key)) % 26
newcharacter = alphabet[newposition]
newmessage += newcharacter
else:
newmessage += character
var2.set(newmessage)
return
def decrypt():
newmessage = ''
mystring = var3.get()
for character in mystring:
if character in alphabet:
position = alphabet.find(character)
newposition = (position - int(key)) % 26
newcharacter = alphabet[newposition]
newmessage += newcharacter
else:
newmessage += character
var4.set(newmessage)
return
b1=Button(master,text="Encrypt",command=encrypt).grid(row=1,column=1)
b2=Button(master,text="Decrypt",command=decrypt).grid(row=6,column=1)
Button(master,text="Close",command=master.quit).grid(row=9,column=1)
mainloop() |
3cba1ad851b15aec772ebf331ddc0c0cdc9f6611 | ChemelAA/scientific_python | /scientific_python/a_intro/x_exceptions.py | 3,370 | 4.40625 | 4 | #!/usr/bin/env python3
from __future__ import print_function
# # Catch exceptions
# An exception is an error that throws from some point of the code. You can
# catch exception in `try`-`except` block:
try:
1 / 0
except ZeroDivisionError:
print('ZeroDivisionError was caught')
# `ZeroDivisionError was caught`
# An exception is represented as a special object of built-in class
# `Exception` (or its inheritor, see details below). Such an object can be
# get using `except ... as` syntax:
try:
1 + '0'
except TypeError as e:
assert str(e).startswith('unsupported operand type(s) for +:')
# ## `assert`
# By the way, the only thing that `assert` does is throwing `AssertionError`
# exception:
try:
assert False, 'Always fails' # the second argument is an error message
except AssertionError as e:
assert str(e) == 'Always fails'
# If exception isn't caught the entire Python program fails. That's why
# `assert` is used in the code examples of this book, the code is tested to
# not fail, so while reading you can always assume that statement after
# `assert` is true or `AssertionError` is caught as shown above.
# ## Catch exceptions of different types
# You can enumerate different exceptions in one `except` block
d = {'zero': 0}
exceptions = set()
for key in ['zero', 'unity']:
try:
d[key] = 1 / d[key]
except (ZeroDivisionError, KeyError) as e:
exceptions.add(type(e))
# Exceptions of both types were caught:
assert not exceptions.difference((ZeroDivisionError, KeyError))
# NB bool(set()) is False
# Multiple `except` blocks can be used if different behaviour should be
# implemented for different exceptions.
a = [[1], ['x', 3]]
count_value_errors = 0
count_type_errors = 0
for pair in a:
try:
x, y = pair # ValueError if pair is not a two-element collection
z = x + y # TypeError if variables cannot be added
except ValueError as e:
count_value_errors += 1
except TypeError as e:
count_type_errors += 1
assert count_value_errors == 1
assert count_type_errors == 1
# ## Exception inheritance hierarchy
# As it was mentioned above all exception classes inherit `BaseException`
# built-in class. The main inheritor of this class is `Exception`, which is
# the base of almost all built-in exceptions and should be used to create
# user-defined exceptions. See the full hierarchy of built-in exceptions on
# https://docs.python.org/3/library/exceptions.html#exception-hierarchy
assert issubclass(Exception, BaseException)
assert issubclass(ValueError, Exception)
# Multiple `except` statements work like `if` with one or more `elif`
# statements: only first matched exception is used, not all of them.
# In the next example `LookupError` and its inheritors `IndexError` and
# `KeyError` will be used.
assert issubclass(IndexError, LookupError)
a = []
try:
x = a[0]
except LookupError as e:
count_lookup_error = 1
except IndexError as e:
assert False # we cannot be here
assert count_lookup_error == 1
try:
x = a[0]
except KeyError as e:
assert False # not a KeyError
except IndexError as e:
count_index_error = 1
except LookupError as e:
assert False
assert count_index_error == 1
# ## Catch them all
# It could be desired to catch all types of exceptions at once. It is
# possible, but be aware to use it all the time.
|
920887cd31c459340231ffee09f261917a1ee044 | malavikasrinivasan/D08 | /mimsmind1.py | 3,191 | 4 | 4 | # Imports
import sys
from random import randint
# Body
def generate_random(n):
""" Generates an n-digit random integer
TODO : Zero currently not included when n = 1
"""
lower_bound = 10**(n-1)
upper_bound = (10**n)-1
return randint(lower_bound, upper_bound)
def get_bulls_and_cows(magic_number_split, guess_split):
""" Takes the magic number and user guess split into a list of digits
and calculates bulls and cows
Bull - The number of values that are equal in a given position on both the lists
Cows - All the values in the guess list present in the magic number list, minus the bulls
TODO : Ask about how it plays out when the guess is something like 444 and the magic number is 423
"""
bulls = len([i for i, j in zip(magic_number_split, guess_split) if i == j]) # zip returns a tuple of the i-th element in the lists
cows = len([i for i in guess_split if i in magic_number_split]) - bulls
return bulls, cows
def play_game(n):
""" Gets user input and checks against magic number until the user
correctly guesses the magic number or exhausts tries.
"""
max_tries = (n*n) + n # Equation for max number of tries
tries = 0
magic_number = generate_random(n)
magic_number_split = list(str(magic_number))
# Welcome message
print("Let's play the mimsmind1 game. You have {} guesses".format(max_tries))
# Get and validate user's first guess
while True:
try:
guess = int(input("Guess a {}-digit number: ".format(n)))
break
except:
print("Invalid input. Try again: ")
# Returns number of cows and bulls till tries are exhausted
while tries < max_tries:
guess_split = list(str(guess))
# Winning condition
if magic_number == guess:
tries += 1
print("Congratulations. You guessed the correct number in {} tries.".format(tries))
break
# Constraint 1 - If number of digits in guess and magic number are not the same, try again
if len(magic_number_split) != len(guess_split):
try:
guess = int(input("Invalid input, try again: "))
except:
continue # Continue till users enters valid integer input, guess still retains old value when exception occurs, so this works
# Get cows and bulls for a valid n digit input
else:
tries += 1
bulls, cows = get_bulls_and_cows(magic_number_split, guess_split)
try:
guess = int(input("{} bull(s), {} cow(s). Try again: ".format(bulls, cows)))
except:
guess = int(input("Invalid input, try again: "))
# When the user exhausts all the tries without guessing correctly
else:
print("Sorry. You did not guess the number in {} tries. The correct number is {}.".format(max_tries, magic_number))
def main():
try:
n = int(sys.argv[1]) # Number of digits in the random no.- uses command line input if valid, else defaults to 1
play_game(n)
except:
play_game(3)
if __name__ == "__main__":
main()
|
dc868301ec33b1907cbebeb72cb5328030961599 | qed11/OEC2021-Swift | /helpers/group.py | 3,038 | 3.59375 | 4 | class LunchGroup:
def __init__(self, members):
'''
:param members: list of student ids with lunch group
'''
self.members = members
class Classroom:
def __init__(self, lastPeriod, currentPeriod, baseEnvRate=0):
'''
Location class used to represent classrooms and extracurricular locations
:param lastPeriod: list of student ids within this classroom in the last period
:param currentPeriod: list of student ids within this classroom for the current period
:param baseEnvRate: infection rate of classroom due to inhabitation of infectious individuals
'''
self.lastPeriod = lastPeriod
self.currentPeriod = currentPeriod
self.baseEnvRate = baseEnvRate
self.infectedList = []
self.lastInfected = []
def resetEnvRate(classrooms):
'''
Reset environment infection rate of all classrooms
:param classrooms: dictionary of classroom objects with keys corresponding to names
'''
for class_name in classrooms.keys():
classrooms[class_name].baseEnvRate = 0
def updateClassrooms(classrooms, info_dict, period):
'''
Method for updating classroom information based on data
:param classrooms: dictionary of classroom objects with keys corresponding to names
:param info_dict: dictionary of Person objects from data with keys corresponding to student ids
:param period: current period in simulation
'''
class_names = ['Physics', 'Biology', 'Functions', 'Calculus', 'Philosophy', 'Art', 'Drama', 'Computer Science',
'Computer Engineering', 'Humanities']
if classrooms == None:
classrooms = {}
for name in class_names:
for letter in ['A', 'B']:
in_class = []
classroom_name = name+' '+letter
classrooms[classroom_name] = Classroom(None, [], 0)
# No last period for the first period
for student_id in info_dict.keys():
classrooms[info_dict[student_id].p1].currentPeriod.append(student_id)
if info_dict[student_id].infected:
classrooms[info_dict[student_id].p1].infectedList.append(student_id)
else:
for name in classrooms.keys():
classrooms[name].currentPeriod = []
classrooms[name].lastPeriod = []
classrooms[name].infectedList = []
for student_id in info_dict.keys():
student_periods = [info_dict[student_id].p1, info_dict[student_id].p2, info_dict[student_id].p3,
info_dict[student_id].p4]
classrooms[student_periods[period-1]].currentPeriod.append(student_id)
classrooms[student_periods[period-2]].lastPeriod.append(student_id)
if info_dict[student_id].infected:
classrooms[student_periods[period-1]].infectedList.append(student_id)
classrooms[student_periods[period-2]].infectedList.append(student_id)
return classrooms
|
bbe5319f3fa535300c4354aba4596b10c46082ec | renjieliu/leetcode | /0001_0599/277.py | 1,806 | 3.625 | 4 | # The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:
class Solution:
def findCelebrity(self, n: int) -> int: #O(N2 | N)
arr = [0] * n # to record how many people knows current person
people = [0] * n # to record how many people current person knows
for i in range(n):
for j in range(n):
if i != j:
t = knows(i, j)
arr[j] += t #add know to arr
people[i] += t #add know to current people
for i, a in enumerate(arr):
if a == n-1 and people[i] == 0:
return i
# print(arr, people)
return -1
# previous solution
# # The knows API is already defined for you.
# # return a bool, whether a knows b
# # def knows(a: int, b: int) -> bool:
# class Solution:
# def findCelebrity(self, n: int) -> int:
# cele = set()
# for i in range(n):
# if knows(0, i) == 1: # possible celebrity
# cele.add(i)
# for i in range(1, n):
# for c in cele:
# if knows(i,c) == 0: #if other people does not know him/her, curr is not a celebrity
# cele.remove(c)
# break
# if cele == set():
# return -1
# else:
# output = []
# for c in cele: # check how many people the celebrity know
# cnt = 0
# for i in range(n):
# if knows(c, i) == 1:
# cnt +=1
# if cnt == 1 :
# output.append(c)
# if len(output) == 1:
# return output[0]
# else:
# return -1
|
f990cfe9ea2935ff452573b1a18e21ea980fa272 | Sirivasv/ProgrammingChallenges | /COJ/div6.py | 112 | 3.640625 | 4 | N = int(input())
for i in range(N):
aux = int(input())
if (aux % 6) == 0:
print("YES")
else:
print("NO")
|
dc1e8a1b7ebc1f6dc7472bd65d1ffe5c5d30c45b | mixbened/pyhton_games | /numberguess.py | 494 | 4.125 | 4 | from random import randint
## generate hint
def generate_hint(inp, num):
if num > inp:
return 'Your Guess is too low!'
else:
return 'Your Guess is too high!'
## Welcome and run the logic
print('Welcome to the Number Guessing Game!')
num = randint(1,10)
# print(num)
## get user input
inp = int(input('Please guess a number.'))
## print as long as number is wrong
while num != inp:
print(generate_hint(inp, num))
inp = int(input('Please guess a number.'))
|
b5e366bf8cf20a1466345a748edc9066eeefe482 | kwujciak/Final-Project | /FP_FlightTime.py | 3,054 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Kate Wujciak
Worked alone
FP_FlightTime.py
Flight time duration calculator.
"""
import pandas as pd
import numpy as np
flight_time = pd.read_csv("flight_times.csv")
ft = np.array(flight_time)
def Main_flights(destination):
# Parameters:
# destination: the desired destination based on user input.
#Function purpose:
# This is the main flight duration function. Based on user input, it will
# determine the origin location.
#Return value:
# Void
origin = input("Are you flying from your current location? ")
if origin == "yes" or origin == "Yes":
departure(destination)
else:
depart = input("Where will you be flying from? ")
col = for_departure(depart)
row = arrival(destination)
print("The flight duration will be " + str(flight_time.iloc[row, col]))
def departure(destination):
# Parameters:
# destination: the desired destination based on user input.
#Function purpose:
# This function finds the flight duration if the user is leaving from their
# current location.
#Return value:
# Void
current_timezone = input("What is your current timezone (EDT, CDT, MDT, or PDT)? ")
if current_timezone == "EDT":
col = 7
elif current_timezone == "CDT":
col = 6
elif current_timezone == "MDT":
col = 5
elif current_timezone == "PDT":
col = 4
if destination == "London":
row = 0
elif destination == "Rome":
row = 1
elif destination == "Tokyo":
row = 2
elif destination == "Los Angeles":
row = 3
elif destination == "Denver":
row = 4
elif destination == "Chicago":
row = 5
elif destination == "New York":
row = 6
print("The flight duration will be " + str(flight_time.iloc[row, col])+ ".")
def for_departure(depart):
# Parameters:
# depart: the desired departing location based on user input.
#Function purpose:
# Assigns appropriate column based on location.
#Return value:
# col: column of departing location.
if depart == "London":
col = 1
elif depart == "Rome":
col = 2
elif depart == "Tokyo":
col = 3
elif depart == "Los Angeles":
col = 4
elif depart == "Denver":
col = 5
elif depart == "Chicago":
col = 6
elif depart == "New York":
col = 7
return col
def arrival(destination):
# Parameters:
# destination: the desired departing location based on user input.
#Function purpose:
# Assigns appropriate row based on destination.
#Return value:
# row: row of destination.
if destination == "London":
row = 0
elif destination == "Rome":
row = 1
elif destination == "Tokyo":
row = 2
elif destination == "Los Angeles":
row = 3
elif destination == "Denver":
row = 4
elif destination == "Chicago":
row = 5
elif destination == "New York":
row = 6
return row
|
14e4612a71806a31913e4ff31437bad0ed830f8c | zhansoft/pythoncourseh200 | /labs/lab6/matplotlibtest.py | 5,966 | 3.828125 | 4 |
# matplotlib usage guide
import matplotlib.pyplot as plt
# top of hierarchy w/ simple functions to create figures and explicitly create/keep track of figures/axes
# no pyplot = object oriented approach
import numpy as np
import pandas
# figure keeps track of all child 'axes' [titles, legends, etc] and the canvas [irrelevant for now]
fig = plt.figure()
fig.suptitle('No axes on this figure')
fig, ax_lst = plt.subplots(2, 2) # figure with grid of 2 x 2 axes
# axes: can only belong to one figure & has 2-3 axises; set_xlim(), set_ylim(), set_title(), set_xlabel(), set_ylabel()
# axis: set graph limits/generate ticks/ticklabels; location: Locator obj; ticklabel strings formatted by Formatter
# artist: everything visible on figure; drawn to canvas;most are tied to an axes but not shared or moved from one another
# for inputs: it expects np.array or np.ma.masked_array as input; change any other classes to np.array objects
# conversion of pandas.DataFrame
a = pandas.DataFrame(np.random.rand(4,5), columns = list('abcde'))
a_asarray = a.values
# conversion of np.matrix
b = np.matrix([[1,2], [3,4]])
b_asarray = np.asarray(b)
# plt.plot() creates axes from the first call
x = np.linspace(0, 2, 100) # returns array of numbers between (start, end, how many numbers you want)
y = np.linspace(0, 2, 100) # this creates the axes
plt.plot(x, x, label = 'linear')
plt.plot(x, x**2, label = 'quadratic')
plt.plot(x, x**3, label = 'cubic')
plt.plot(y, 2*(y**2), label = 'calciisucks') # still follows a f(x) format basically.
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("simple plot shit")
plt.legend()
#plt.show()
# pylab is for cluttered messy bitches. use pyplot instead
# coding styles: use the imports typically at the top
x = np.arange(0, 10, 0.2) # (start, end, increments)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
#plt.show()
# recommended function signature
def my_plotter(ax, data1, data2, param_dict):
"""
A helper function to make a graph
Parameters
----------
ax: Axes
The axes to draw to
data1: array
The x data
data2: array
The y data
param_dict : dict
Dictionary of kwargs to pass to ax.plot
Returns
-------
out: list
list of artists added
"""
out = ax.plot(data1, data2, **param_dict)
return out
# this turns into:
data1, data2, data3, data4 = np.random.randn(4,100)
fig, ax = plt.subplots(1,1) # row col
my_plotter(ax, data1, data2, {'marker': 'x'})
#plt.show()
# or for two
fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
plt.show()
"""
backends: matplotlib has many different case uses and cant arget different outputs and thus each capability is a
BACKEND
-does all the hard work behind-the-scenes to make the figure:
-user interface backends "interactive" and hardcopy backends to make images "non-interactive"
# four ways to configure backend; if conflicting, the method mentioned last in the following list will be used
# use() will overide the setting in matplotlibrc
1. backend parameter in matplotlibrc file:
backend: WXAgg # use wxpython with antigrain (agg) rendering *** what the fuck
# okay so wxpython is the gui module; antigrain is just some fucking thing
2. setting MPLBACKEND environment variable either for the current shell or single script
windows: set MPLBACKEND=module://my_backend
python simple_plot.py
# will override the backend parameter in ANY matplotlibrc so like try not to set it globally lmaooooo
3. use() # done before importing matplotlib.pyplot and will require changes in code if you want a different backend
# avoid explicit usee unless absolutely necessary
"""
"""
writing graphical user interfaces or web apps:
matplotlib separates the renderer (drawing mechanism) from the canvas (window/place where drawing is)
-canon renderer = Agg (Anti-Grain Geometry C++ Library) to make a pixel image
-raster renderer & filetypes of png & non-interactive (capable of writing to a file)
-raster renderers: pixel representation of line whose accuracy dependent on DPI setting
-vector renderers: commands needed like "line from here to there"
-other renderers that are interactive (capabel of displaying to the screen & writing a file using non-interactive renderers)
"""
# you can use the interactive backend of matplotlib but like that depends on funcs/methods
# so like matplotlib.pyplot.ion() or matploylib.pyplot.ioff()
# plt.ion()
# plt.plot([1.6, 2.7])
# plt.title("interactive test")
# plt.xlabel("index")
# ax = plt.gca()
# ax.plot([3.1, 2.2])
# plt.draw() #only call if it's not updtaed immediately
#non-interactive example
#import your shit
# plt.ioff()
# plt.plot([1.6, 2.7])
# plt.show()
# see it but terminal command line is unresponsive
# so non-interactive is actually more efficient
# summary: plt.show() = non-interactive; called multiple times & plt.draw() = interactive if shit broke
"""
Performance in matplotlib:
You can significantly reduce the rendering time by changing the appearance slightly of your graph but that's dependent
on the type of graph.
# line segment simplification lol ok
-path.simplify() #boolean whether they are & path.simplify_threshold() #controls how much line segments are simplified; the higher the better
example code:
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
y = np.random.rand(100000)
y[50000:] *= 2
y[np.logspace(1, np.log10(50000), 400).astype(int)] = -1
mpl.rcParams['path.simplify'] = True
mpl.rcParams['path.simplify_threshold'] = 0.0
plt.plot(y)
plt.show()
mpl.rcParams['path.simplify_threshold'] = 1.0
plt.plot(y)
plt.show()
'''
default simplifcation value: 1/9
# marker simplification but i'm really too fucking lazy
# splitting lines into smaller chunks whoops
# good ol fast style
'''
import matplotlib.style as mplstyle
mplstyle.use('fast')
'''
boom
|
006c1ba4448386807006fcfb6ad542b7bf6d0b83 | jangjichang/Today-I-Learn | /Algorithm/Programmers/큰수만들기/test_큰수만들기.py | 1,312 | 3.984375 | 4 | def make_largest_number(number, k):
start_number = number[:len(number) - k + 1]
largest_number = remove_one_number_to_make_largest_number(start_number)
for i in range(len(number) - k + 1, len(number)):
largest_number = remove_one_number_to_make_largest_number(
largest_number + number[i])
return largest_number
def remove_one_number_to_make_largest_number(number):
for index in range(len(number)-1):
if number[index] < number[index+1]:
return number[:index] + number[index+1:]
return number[:-1]
def test_make_largest_number():
assert make_largest_number("192", 1) == "92"
assert make_largest_number("192", 2) == "9"
assert make_largest_number("1924", 2) == "94"
assert make_largest_number("1231234", 3) == "3234"
assert make_largest_number("4177252841", 4) == "775841"
def test_remove_one_number_to_make_largest_number():
assert remove_one_number_to_make_largest_number("192") == "92"
assert remove_one_number_to_make_largest_number("912") == "92"
assert remove_one_number_to_make_largest_number("921") == "92"
assert remove_one_number_to_make_largest_number("129") == "29"
assert remove_one_number_to_make_largest_number("19") == "9"
assert remove_one_number_to_make_largest_number("91") == "9"
|
7ef0942278b1d7cffa48389799e8efa0048603ae | rdmagm062699/project_euler_python_kata | /src/problem_11/solution/quads.py | 430 | 3.59375 | 4 |
def get_max_product_of_adjacent(list_of_numbers):
max_value = 0
start = 0
while len(list_of_numbers[start:start+4]) == 4:
value = _get_product(list_of_numbers[start:start+4])
if value > max_value:
max_value = value
start += 1
return max_value
def _get_product(list_of_numbers):
value = 1
for number in list_of_numbers:
value = value * number
return value
|
3650d27ff737171924cca73ca87a4ef73014ce4a | iCodeIN/ProjectEuler | /11-20/prob16.py | 203 | 3.640625 | 4 | #What is the sum of the digits of the number 2^1000?
def sum_digits(value):
return sum (map(int,str(value)))
def main():
value = 2**1000
print(sum_digits(value))
if __name__ == '__main__':
main()
|
3011d2612a9379aca4cf1de906c331010dfb2489 | jonatas2014/plp_atividade_final | /Python/heranca.py | 610 | 3.625 | 4 | #Superclasse ou classe pai, também chamada de classe base
class Funcionario:
def __init__(self, id, nome, depto, salario):
self.id = id
self.nome = nome
self.depto = depto
self.salario = salario
#Classes filhas (extendem a superclasse)
class Engenheiro(Funcionario):
def __init__(self, id, nome, depto, salario, crea):
super().__init__(id, nome, depto, salario)
self.crea = crea
class Advogado(Funcionario):
def __init__(self, id, nome, depto, salario, n_oab):
super().__init__(id, nome, depto, salario)
self.n_oab = n_oab
|
2dfb91150b78f45e72e04268095c3243cab88a2f | Narvaez0993/practica-python | /ejercicios.py | 5,231 | 4.21875 | 4 | #PUNTO 1 - Imprimir el factorial de cualquier numero
"""factorial = input ('ingresa un numero ')
factorial = int (factorial)
def calculafactorial(factorial):
if factorial==0 or factorial==1:
resultado=1
elif factorial > 1:
resultado=factorial*calculafactorial(factorial-1)
return resultado
print("el factorial de",factorial ,"es: ",calculafactorial(factorial))"""
# punto 2 - Mostrar los N primeros números de la serie Fibonacci
"""num = input('ingresa un numero ')
num = int(num)
def calcularFibonacci(num):
i = 0
n1 = 0
n2 = 1
for i in range(num):
print(num, end=' ')
num = (num-1) + (num-2)
return num
print(calcularFibonacci(num)) """
"""num = input("ingrese el numero limite del fibonacci a imprimir: ")
num = int(num)
def calcularFibonacci(num):
#ingresar un numero correcto
n1= 0
n2 = 1
count = 1
if num <= 0:
print("Opss ingresaste un numero incorrecto, revisa y intentalo nuevamente")
else:
print("secuencia fibonacci: ")
while count < num:
print(n1)
resultado = n1 + n2
n1 = n2
n2 = resultado
count = count + 1
return n1
print(calcularFibonacci(num))"""
# punto 3 - Retornar el valor de la cuota de un prestamo, teniendo en cuenta que se debe especificar el valor del préstamo, número de cuotas, tasa mensual
"""VlorPrestamo = int(input("Ingrese la cantidad de dinero que requiere: "))
NumeroCuotas = int(input("Ingrese el numero de cuotas a pagar: "))
def calcularCuota(VlorPrestamo,NumeroCuotas):
cantidadPago = VlorPrestamo / NumeroCuotas
TasaInteres = cantidadPago * 0.03
total = cantidadPago + TasaInteres
total = int(total)
return total
print("El valor total de la cuota mensual es: ",calcularCuota(VlorPrestamo,NumeroCuotas))"""
#punto 4 - Mostrar los datos de cualquier array
"""numero = ["hola","arreglo","array"]
print(numero)"""
#punto 5 - Mostrar los datos de cualquier diccionario
"""diccionario = {
"nombre": "sebastian",
"apellido": "mejia",
"telefono": "3197060463"
}
print(diccionario)"""
#punto 6 . Retornar el total de los pagos del diccionario dpagos= {"placa":"tis123","marca":"Aveo","pagos":[100,200,30,400], enviado como parámetro
# punto pendiente, no se entiende del todo!
"""def imprimirPagos():
dpagos= {
"placa":"tis123",
"marca":"Aveo",
"pagos":[100,200,30,400]
}
return dpagos.get("pagos");
print (sum(imprimirPagos()));"""
# punto 7 Crear un diccionario con variables
"""nombre = input("ingrese su nombre ");
apellido = input("ingrese su apellido ");
edad = input("ingrese su edad ");
diccionario = {
"Nombre": nombre,
"Ciudad": apellido,
"Edad": edad,
}
print(diccionario)"""
# punto 8 Crear una lista con los números del 1 al 50
# punto 9 - Crear una lista con los números impares de la lista generada en el numeral 3.
"""dato = int(input("Ingrese la cantidad de numeros que quiere imprimir: "))
lista = []
impares = []
count = 0
numero = 0
while count < dato:
numero = numero + 1
if numero%2 != 0:
impares.append(numero)
count = count + 1
lista.append(numero)
print(lista)
print(impares)"""
# 10 - Crear un diccionario con los datos de un vehiculo (placa, marca, modelo,valor)
"""placa = input("ingrese la placa del vehiculo ")
marca = input("ingrese la marca del vehiculo ")
modelo = input("ingrese el modelo del vehiculo ")
valor = input("ingrese el costo del vehiculo ")
def RegistrarVehiculo(placa,marca,modelo,valor):
Vehiculo = {
"placa": placa,
"marca": marca,
"modelo": modelo,
"valor": valor
}
return Vehiculo
print(RegistrarVehiculo(placa,marca,modelo,valor))"""
#11 Listar los datos del diccionario generado en el numeral 5 - pendiente
#12 Crear una lista, con datos por teclado, que contenga las ciudades turísticas de Colombia
"""ciudades = []
cantCiudades = input("ingrese la cantidad de ciudades que desea registrar: ")
cantCiudades = int(cantCiudades)
for x in range(cantCiudades):
Ciudad = input("Ingrese Ciudades turisticas de colombia: ")
ciudades.append(Ciudad)
print(ciudades)
#13 Agregar una ciudad turística a la lista de ciudades turísticas
añardirCiudad = input("ingrese la ciudad a agregar: ")
ciudades.append(añardirCiudad)
print(ciudades)
#14 Ingresar el nombre de una ciudad y borrarla de la lista ciudades turísticas
eliminarCiudad = input("Ingrese la ciudad que quiere eliminar: ")
if(eliminarCiudad in ciudades):
print("Ciudad eliminada correctamente: ")
ciudades.remove(eliminarCiudad)
print (ciudades)
else:
print("La ciudad ingresada no existe, intentalo nuevamente")"""
#15 Crear una clase con los datos de un vehículo (placa, marca, modelo, precio). Los atributos son privados
"""class vehiculo():
def __init__(self, placa, marca, modelo, precio):
self.placa = placa
self.marca = marca
self.modelo = modelo
self.precio = precio
def __repr__(self):
return f"Placa: {self.placa}\nMarca: {self.marca}\nModelo: {self.modelo}\nPrecio: {self.precio}"
vehiculo1 = vehiculo('ews396', 'Tesla', '2021', '2000000')
print(vehiculo1)"""
|
88767ca05efefa3f8516f94c8c0a08616dfcc619 | orphanBB/hnist_oj | /1029.机票打折/t1029.py | 265 | 3.84375 | 4 | x = int(input())
if x < 1000:
if x >= 500:
print("{:.2f}".format(x * 0.8))
elif x >= 200:
print("{:.2f}".format(x * 0.9))
else:
print("{:.2f}".format(x))
else:
print("{:.2f}".format(x * 0.5))
#1029 水题,分支结构。
|
52d30bc488e66e9695135aa5d866e1a22ec8698d | dubblin27/algorithms | /Algo_DS/SEARCH/LinearSearch.py | 300 | 3.796875 | 4 | #Linear Search
n = int(input("enter size of the list: "))
lst = list(map(int,input().split()))
found = False
x = int(input("enter an element to be searched for : "))
#1
for i in range(len(lst)):
if x == lst[i]:
found = True
print(x,i)
#2
if x in lst:
print(x,lst.index(x)) |
9e838e3750a4e699fe975a9f0e47596cd80e4bf8 | AsadGondal/Coursera_Python_For_Everybody | /Course 3 Using Python to Access WebData/Week 4/Assignment2.py | 2,122 | 3.84375 | 4 | '''Following Links in Python
In this assignment you will write a Python program that expands
on http://www.py4e.com/code3/urllinks.py.
The program will use urllib to read the HTML from the data files below, extract the href= vaues
from the anchor tags, scan for a tag that is in a particular position relative to the first name
in the list, follow that link and repeat the process a number of times and report the
last name you find.
We provide two files for this assignment.
One is a sample file where we give you the name for your testing and the other is the
actual data you need to process for the assignment
Sample problem: Start at http://py4e-data.dr-chuck.net/known_by_Fikret.html
Find the link at position 3 (the first name is 1). Follow that link.
Repeat this process 4 times. The answer is the last name that you retrieve.
Sequence of names: Fikret Montgomery Mhairade Butchi Anayah
Last name in sequence: Anayah
Actual problem: Start at: http://py4e-data.dr-chuck.net/known_by_Clodagh.html
Find the link at position 18 (the first name is 1). Follow that link. Repeat this process 7 times.
The answer is the last name that you retrieve.
Hint: The first character of the name of the last page that you will load is: A'''
#in Py4e this progname is loop.py
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
position=input('Enter the position you want to go\t')
pos=int(position)
loopNo=input('Enter the number of iterations\t')
lN=int(loopNo)
url = input('Enter the html link- \n')
for itv in range(lN):
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('a')
nameList=list()
loc=''
count=0
for tag in tags:
loc=tag.get('href',None)
nameList.append(loc)
print('Retrieving the URL:',url)
print('Retrieved URL:',nameList[pos-1])
url=nameList[pos-1]
print('this is the end of iteration:',itv+1)
|
fd264ed1bb73f74b0cc4a27566249432d3ee0b15 | AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3 | /World 2/Challenge052.py | 279 | 4.0625 | 4 | sum = 0
n = int(input('Type any number: '))
for c in range(2, n):
if n % c == 0:
sum = sum + 1
else:
sum = sum
if sum == 0:
print('The number {} is considered a PRIME NUMBER'.format(n))
else:
print('The number {} is NOT a PRIME number'.format(n))
|
b89928cd7dfc5dc52654aa6edf2e15c844bf2c6a | kristinbrooks/CSE110-python | /src/sphere_pack.py | 1,052 | 4.3125 | 4 | # Write a program to determine how many oranges can fit into one standard shipping container.
# What if it were ping-pong balls instead? What if it was your kitchen?
# In this challenge, you must choose your own input variables, variable names, and design your own tests to
# verify the program operation.
# The output value should be written into a variable called "packed_items"
# When you click the Run Button, your program will be executed, and the value of the "packed_items" variable will
# be printed below.
import math
math.pi
radius_of_average_orange_inches = 1.25
sphere_volume_inches_cubed = (4/3) * math.pi * radius_of_average_orange_inches ** 3
shipping_container_width_inches = 18
shipping_container_length_inches = 24
shipping_container_height_inches = 16
shipping_container_volume_inches_cubed = shipping_container_width_inches * shipping_container_length_inches *\
shipping_container_height_inches
packed_items = int(shipping_container_volume_inches_cubed / sphere_volume_inches_cubed)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.