blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4e8d81e831111b9ba0024a049a9746fec7a5aeb9 | thsmcoding/P_Projects | /Miscellaneous/Python/Challenges.py | 3,022 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 10:48:42 2019
@author: HTT
@task: training
"""
''' GOOGLE CHALLENGE : Find the longest word in a dictionary that is a subsequence of a given string'''
def dictString(word):
dict = {}
for index, w in enumerate(word):
if(w in dict):
dict[w].append(index)
else:
dict[w] = []
dict[w].append(index)
return dict
def subsequenceFound(liste1):
if not liste1:
return False
for i in range(0,len(liste1)-1):
if not (liste1[i] < liste1[i+1]):
return False
return True
def weaveLists(mylist1, mylist2,prefix,bigList):
if ( not mylist1 or not mylist2):
newList = prefix.copy()
newList.extend(mylist1)
newList.extend(mylist2)
bigList.append(newList)
return
headFirst = mylist1[0]
mylist1.remove(mylist1[0])
r = len(prefix)
prefix.insert(r, headFirst)
weaveLists(mylist1, mylist2, prefix, bigList)
prefix.remove(prefix[r])
mylist1.insert(0,headFirst)
headSecond = mylist2[0]
mylist2.remove(headSecond)
r = len(prefix)
prefix.insert(r, headSecond)
weaveLists(mylist1, mylist2, prefix, bigList)
prefix.remove(prefix[r])
mylist2.insert(0,headSecond)
def maximumLength(l):
if not l:
return
max =-1;
for i in range(0, len(l)-1):
print( len(l[i]))
if ( len(l[i]) > max):
max = len(l[i])
return max
def findLargerNumber(last, myList):
if not myList:
return False
ll = sorted(myList)
r = len(myList)
if (ll[r-1]<=last):
return False
for u in ll:
if ( u > last):
last = u
return True
return False
def buildValuesWords(one_word, given_word, all_words_dict):
if (not one_word or not given_word):
return
big_dict = dictString(given_word)
last =-1
for i in range(0,len(one_word)-1):
if (given_word.count(one_word[i]) == 0) :
all_words_dict[one_word] = -1
return
else:
l1 = big_dict[one_word[i]]
if not (findLargerNumber(last, l1) == True):
all_words_dict[one_word] = -1
return
all_words_dict[one_word] = len(one_word)
def findLongestSubsequence(given_word,all_words_dict):
for w in all_words_dict.keys():
buildValuesWords(w, given_word,all_words_dict)
values_sorted = sorted(all_words_dict.values())
r = len(values_sorted)
max = values_sorted[r-1]
print ( max)
subsequence = [key for (key, value) in all_words_dict.items() if value == max]
print ( subsequence[0])
return subsequence[0]
the_given_word ="ABPPPLEE"
the_dict = {"ABLE":0, "ALE":0,"APPLE":0,"BALE":0,"KANGAROO":0}
the_subsequence = findLongestSubsequence(the_given_word,the_dict)
|
28673d40fc45a3d8790b62e902424c97e9b4ac94 | Pnickolas1/Code-Reps | /AlgoExpert/Recursion/getNthFib.py | 844 | 3.703125 | 4 |
"""
memoized version
time: O(n)
space: O(n)
iterative approach
time: O(n)
space: O(1)
fibs =>
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,
1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393,
196418, 317811,
"""
#memoize versions
def getNthFib_memoize(n, memoize = {1: 0, 2: 1}):
if n in memoize:
return memoize[n]
else:
memoize[n] = getNthFib_memoize(n -1, memoize) + getNthFib_memoize(n-2, memoize)
return memoize[n]
print(getNthFib_memoize(11))
# iterative approach
def getNthFib_iterative(n):
lastTwo = [0, 1]
counter = 3
while counter <= n:
nextFib = lastTwo[1] + lastTwo[0]
lastTwo[0] = lastTwo[1]
lastTwo[1] = nextFib
counter += 1
return lastTwo[1] if n > 1 else lastTwo[0]
print(getNthFib_iterative(11)) |
bdd90025509fda03f0288de05550daa05f4cd81e | Pkpallaw16/Tree-level-2 | /19 vertical order traversal.py | 2,058 | 3.890625 | 4 | # User function Template for python3
from _collections import deque
class pair:
def __init__(self, node=None, vlevel=0):
self.node = node
self.vlevel = vlevel
class Solution:
# Function to find the vertical order traversal of Binary Tree.
def verticalOrder(self, root):
# Your code here
lh = 0
rh = 0
dic = {}
q = deque()
q.append(pair(root, 0))
while len(q) > 0:
rem = q.popleft()
if rem.vlevel < lh:
lh = rem.vlevel
elif rem.vlevel > rh:
rh = rem.vlevel
if rem.vlevel in dic:
dic[rem.vlevel].append(rem.node.data)
else:
vnode = []
vnode.append(rem.node.data)
dic[rem.vlevel] = vnode
if rem.node.left != None:
q.append(pair(rem.node.left, rem.vlevel - 1))
if rem.node.right != None:
q.append(pair(rem.node.right, rem.vlevel + 1))
ans = []
for i in range(lh, rh + 1):
for ele in dic[i]:
dic[i].sort()
ans.append(ele)
return ans
lh=0
rh=0
def Width_Of_Shadow_Of_Binary_Tree_2nd(root,count):
global lh,rh
if root==None:
return
if count<lh:
lh=count
elif count>rh:
rh=count
Width_Of_Shadow_Of_Binary_Tree_2nd(root.left,count-1)
Width_Of_Shadow_Of_Binary_Tree_2nd(root.right,count+1)
def width(root):
if root==None:
return 0
Width_Of_Shadow_Of_Binary_Tree_2nd(root,0)
return rh+lh+1
def verticalOrder_2nd(root):
global lh, rh
w = width(root)
lis = [None for i in range(w)]
q = deque()
q.append(pair(root, abs(lh)))
while len(q) > 0:
rem = q.popleft()
lis[rem.vlevel] = rem.node.data
if rem.node.left != None:
q.append(pair(rem.node.left, rem.vlevel - 1))
if rem.node.right != None:
q.append(pair(rem.node.right, rem.vlevel + 1))
return lis |
2fad853fa3f0eb619dbd9a13980317513bc80129 | antonylu/leetcode2 | /Python/606_construct-string-from-binary-tree.py | 2,262 | 3.890625 | 4 | """
https://leetcode.com/problems/construct-string-from-binary-tree/description/
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".
Example 2:
Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
# Approach #1, dfs, pre-order, with careful placement of (,)
# () must be removed for non-necessary items
# so it must be placed outside the dfs(node)
# O(n), 12%
self.ans = ""
def dfs(node):
self.ans += str(node.val)
if node.left:
self.ans += "("
dfs(node.left)
self.ans += ")"
elif node.right:
self.ans += "()"
if node.right:
self.ans += "("
dfs(node.right)
self.ans += ")"
if t: dfs(t)
return self.ans
if __name__ == '__main__':
s = Solution()
tc = [ [1,2,3,4], [1,2,3,None,4]]
ans = [ "1(2(4))(3)", "1(2()(4))(3)"]
from helper import TestHelper
th = TestHelper()
for i in range(len(tc)):
t = th.listToBinaryTree(tc[i])
r = s.tree2str(t)
print (r)
assert(r == ans[i])
|
26f7265ec60e184425e4d98fc4c8093c25a6f520 | sigridjb/adventofcode2019 | /day01.py | 418 | 3.546875 | 4 | import pandas as pd
import numpy as np
d = pd.read_csv("input",header=None)
d["fuel1"] = np.floor(d/3)-2
print("Day 1 - part 1: "+str(int(d.fuel1.sum())))
def getfuel(val):
fuelneeded = 0
while (np.floor(val/3)-2)>0:
fuelneeded += np.floor(val/3)-2
val = np.floor(val/3)-2
return(fuelneeded)
d["fuel2"] = d[0].apply(lambda x: getfuel(x))
print("Day 1 - part 2: "+str(int(d.fuel2.sum()))) |
2c56a3b04fc375ff2d78fdd163ad230f67cb55af | JFerRG/MySQL_Py | /GitHub/ComprobacionDeCuadrados.py | 643 | 4 | 4 | def validacion():
while True:
try:
num = int(input('Ingresa el valor: '))
if num > 0:
return num
break
else:
print('El número ha de ser mayor que cero')
except Exception as e:
print('Error al obtener el número\n' + str(e))
def dobles (a,b):
if b == (a**2):
print('{} es el cuadrado exacto de {}'.format(b,a))
elif b < (a**2):
print('{} es menor que el cuadrado de {}'.format(b,a))
elif b > (a**2):
print('{} es mayor que el cuadrado de {}'.format(b,a))
dobles(validacion(),validacion())
|
a1c9dce40b93c0011c070577332314be1616ac75 | yakann/Algorithms | /Searching Algorithms/Binary Search/Python/binary_search.py | 468 | 3.890625 | 4 | def binarySearch(seq,f):
left = 0
right = len(seq)-1
while left <= right:
mid = round((left + right)/2)
if seq[mid] == f:
return seq[mid]
elif seq[mid] < f:
left = mid + 1
else:
right = mid - 1
seq = [1,2,5,6,7,8,9,44,46,71,79,88]
print("Searched number: 88")
print("Result: ",binarySearch(seq,88))
"""
Worst Case: O(Logn)
Best Case: O(1)
Time Complexity: T(n) = T(n/2) + c
""" |
34a7e10a55c4d3d1ceaf93236ebfa311be3e6c66 | ryannhanna/DC-Class-Sept-17 | /wk 1 python/py-exercises day 2/vowelsreal.py | 63 | 3.609375 | 4 |
word = 'boo'
word = word.replace('oo', 'ooooo')
print(word)
|
dc8afd61482f947b5cde950a91f3429ebf665df5 | Richiewong07/Python-Exercises | /python-assignments/functions/degree_conversion_plot.py | 323 | 4.34375 | 4 | # 7. Degree Conversion
# Write a function that takes a temperature in Celcius and converts it Fahrenheit. Plot it on a graph.
import matplotlib.pyplot as plot
def f(x):
return x * 1.8 + 32
xs = list(range(0, 38))
ys = []
for x in xs:
ys.append(f(x))
plot.plot(xs, ys)
plot.axis([0, 37.8, 30, 100])
plot.show()
|
e7701b826a79e7587d0e85bbc12e7c60208af055 | richardOlson/Data-Structures | /data_structures/singly_linked_list/singly_linked_list.py | 3,247 | 4.3125 | 4 | # This the place where the Node and the single linked list
class Node:
def __init__(self, value=None, next_node=None):
self.next_node = next_node
self.value = value
# The linked list will use the nodes and then will make the linked list
class LinkedList():
def __init__(self):
# Getting the info that will be stored ready to be used
self.head = None # The head and the tail will
# both eventually store a node
self.tail = None
self.length = 0 # I will be using the lenth to help
# help with my linked list class
# method the add to the tail
def add_to_tail(self, value):
new_node = Node(value=value)
# Checking to see the length of the linked list
if self.length == 0:
# here head and the tail are the same
self.head = new_node
self.tail = new_node
else:
self.tail.next_node = new_node
# now assigning the newNode to be the tail
self.tail = new_node
# incrementing the length
self.length += 1
def add_to_head(self, value):
# instanciating a new node
new_node = Node(value=value)
self.length += 1
# Checking to look
if self.length == 0:
self.head = new_node
self.tail = new_node
else:
new_node.next_node = self.head
# now assigning the new node to the head
self.head = new_node
def remove_head(self): # Taking the head off and then assing new head
"""
Function will return The head value. If there is no value then
it will return None
"""
if self.length == 0:
return None # will return -
# getting the value of the head that is being removed
theValue = self.head.value
# This is the value that will be assigned to the head
new_head = self.head.next_node
# assigning the new_head
self.head = new_head
# if there is only one Node then we will need to set the tail
if self.length == 1:
self.tail = None
# decrementing the length
self.length -= 1
return theValue
def contains(self, searchValue):
if self.length == 0:
return False
else:
theNode = self.head
# Will start at the head and then traverse the list
while theNode != None:
if theNode.value == searchValue:
return True
else: # will now increment to the next_node
theNode = theNode.next_node
return False
# This is the function that will get the maximun of the linked list
def get_max(self):
# if the linked list has a lenght of 0 will return None
if self.length == 0:
return None
val = self.head.value
node = self.head
while True:
if node.value > val:
val = node.value
# move to the next node
node = node.next_node
if node == None:
return val
|
a1de304530dfb08aa2be1609cb9e951cc93878ef | AvikramS/Python-Projects | /Data Cosistency.py | 168 | 4.34375 | 4 | name = input("What is your name? ")
country = input("What country do you live in? ")
country = country.upper()
print('Hello ' + name + ". You live in "+ country)
|
a598a79ef45a3bc1b939b2d9c88d179690bffa90 | adqz/interview_practice | /pathrise/16_paint_house.py | 3,370 | 4 | 4 | '''
There are a row of n houses, each house can be painted with one of the three colors: red, blue or green.
The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by a n x 3 cost matrix.
For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
Example:
Input: [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Minimum cost: 2 + 5 + 3 = 10.
'''
'''
Recursion
n = 4
houses = [0, 1, 2, 3]
red = 1
blue = 2
green = 3
At index i, cost[houses[i:]] = min of
1. red + cost[houses[i+1:]]
2. blue + cost[houses[i+1:]]
3. green + cost[houses[i+1:]]
1 2 3 4
red. 10
green 20
blue 30
ADNAN
Communication = 4.5/5
Problem-Solving = 4.5/5
Syntax = 3.5/5
Verification = 3/5
MIKE
Communication = 5/5
Problem-Solving = 5/5
Syntax = 3.5/5
Verification = 3/5
'''
# Time Complexity
# Recursion - O(2^n)
# DP - O(n)
class Solution():
def minCost(self, cost):
if not cost:
return 0
self.cost = cost
self.n = len(cost)
self.cache = dict()
min_cost = min(
self.getMinCost(0, 0), #red
self.getMinCost(0, 1), #blue
self.getMinCost(0, 2), #green
)
return min_cost
def getMinCost(self, curr_index, prev_color_index):
if (curr_index, prev_color_index) in self.cache:
return self.cache[(curr_index, prev_color_index)]
# Base
if curr_index == self.n-1:
if prev_color_index == 0: #red
return min(self.cost[curr_index][1], self.cost[curr_index][2])
elif prev_color_index == 1: #blue
return min(self.cost[curr_index][0], self.cost[curr_index][2])
elif prev_color_index == 2: #green
return min(self.cost[curr_index][0], self.cost[curr_index][1])
# Recursive Case
if prev_color_index == 0: #red
min_cost = min(
self.cost[curr_index][1] + self.getMinCost(curr_index+1, prev_color_index = 1),
self.cost[curr_index][2] + self.getMinCost(curr_index+1, prev_color_index = 2)
)
elif prev_color_index == 1: #blue
min_cost = min(
self.cost[curr_index][0] + self.getMinCost(curr_index+1, prev_color_index = 0),
self.cost[curr_index][2] + self.getMinCost(curr_index+1, prev_color_index = 2)
)
elif prev_color_index == 2: #green
min_cost = min(
self.cost[curr_index][0] + self.getMinCost(curr_index+1, prev_color_index = 0),
self.cost[curr_index][1] + self.getMinCost(curr_index+1, prev_color_index = 1)
)
self.cache[(curr_index, prev_color_index)] = min_cost
return min_cost
if __name__ == "__main__":
sol = Solution()
cost = [[17,2,17],[16,16,5],[14,3,19]]
print(sol.minCost(cost)) #10
|
8480d2ef230d868ebee247ca1c7d78b6032419fb | guilhermeagostinho22/exercicios-e-exemplos | /exercicio11.11/exercicio2.2.py | 538 | 3.921875 | 4 | def leiaint():
try:
c = float(input("Digite um valor real: "))
d = float(input("Digite um valor real: "))
t = c/d
print("O resultado foi: ", t)
except(ValueError, TypeError):
print("Infelizmente tivemos um problema com o valor digitado :( ")
except(ZeroDivisionError):
print("Infelizmente não é possivel dividir um número por zero :( ")
except:
print("Infelizmente tivemos um problema: ( ")
finally:
print("Volte sempre, Muito Obrigado!!!")
leiaint() |
0b21e38a0fb84bae1ad70e345bf6afac02a72207 | iiinjoy/algorithms_python_lessons | /level1/test_lesson5.py | 509 | 3.640625 | 4 | #!/usr/bin/env
import unittest
from lesson5 import *
class TestQueue(unittest.TestCase):
def test_queue(self):
Q = Queue()
self.assertEqual(Q.size(), 0)
Q.enqueue(1)
Q.enqueue(2)
self.assertEqual(Q.size(), 2)
item1 = Q.dequeue()
item2 = Q.dequeue()
self.assertEqual(item1, 1)
self.assertEqual(item2, 2)
self.assertEqual(Q.size(), 0)
self.assertIsNone(Q.dequeue())
if __name__ == '__main__':
unittest.main()
|
6697f40f3afbeeadf4750341596aca4b942b43ac | jonstrutz11/AdventOfCode2020 | /05.py | 2,182 | 3.5625 | 4 | """Advent of Code - Problem 5"""
class BoardingPass():
"""Store boarding pass code and parsed seat location information."""
def __init__(self, seat_code):
self.seat_code = seat_code
self.row, self.col = self._parse_seat_code()
self.id = self._calculate_id()
def _parse_seat_code(self):
"""Convert binary space partitioning code to row and column number."""
# Write in binary form
row_bin = self.seat_code[:7].replace('F', '0').replace('B', '1')
col_bin = self.seat_code[7:].replace('L', '0').replace('R', '1')
# Convert from binary to decimal
row = int(row_bin, 2)
col = int(col_bin, 2)
return row, col
def _calculate_id(self):
"""Calculate seat ID."""
return self.row * 8 + self.col
def read_and_parse_boarding_pass_data(filepath):
"""Read and parse boarding pass data."""
with open(filepath, 'r') as infile:
lines = infile.readlines()
boarding_passes = []
for line in lines:
seat_code = line.strip()
boarding_pass = BoardingPass(seat_code)
boarding_passes.append(boarding_pass)
return boarding_passes
if __name__ == '__main__':
DATA_FILEPATH = '05.txt'
boarding_passes = read_and_parse_boarding_pass_data(DATA_FILEPATH)
# Part A
highest_id = max([bp.id for bp in boarding_passes])
print('Part A - Highest ID:', highest_id)
# Part B
possible_ids = list(range(128 * 8))
for bp in boarding_passes:
possible_ids.remove(bp.id)
# Remove front IDs
prev_id = -1
for index, possible_id in enumerate(possible_ids):
if possible_id == prev_id + 1:
prev_id = possible_id
else:
possible_ids = possible_ids[index:]
break
# Remove back IDs
prev_id = 1024
for index, possible_id in enumerate(possible_ids[::-1]):
if possible_id == prev_id - 1:
prev_id = possible_id
else:
possible_ids = possible_ids[:-index]
break
# Should only be one ID left
assert len(possible_ids) == 1
print('Part B - Final Remaining ID:', possible_ids[0])
|
d4325344433397aacfcba40c08f5bf6363fb41c0 | TrellixVulnTeam/Demo_933I | /Demo/tkinter编程/messagebox.py | 323 | 3.78125 | 4 | from tkinter import *
import tkinter.messagebox as messagebox
root = Tk()
def callback():
# 消息窗体提醒
if messagebox.askyesno('Wang', 'Hi sjaf'):
print("Yes")
else:
print("No")
button = Button(root, text='Button1', command=callback)
button.pack()
root.mainloop()
|
3bb7b3747e7b6b5551dd8e8b62f7f6ad93c7f8f5 | m-fahad-r/python-scripts | /Script sample.py | 11,239 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The Ship Rendezvous Problem
This code will:
1. Read a problem instance (data) from a CSV file;
2. Run the greedy heuristic against the problem instance to obtain a solution.
3. Output the resulting path to a CSV file.
4. Output key performance indicators of the solution to a second CSV file.
"""
import math
import numpy as np
def main(csv_file):
'''
Main function for running and solving an instance of the SRP.
Keyword arguments:
csv_file -- the csv file name and path to a data for an instance of
ship rendezvous problem.
'''
# read in the csv file to a numpy array
problem_data = read_srp_input_data(csv_file)
initial_data = [problem_data[0, 0], problem_data[0, 1]]
# create an index and add to the problem data
index = np.arange(-1, problem_data.shape[0]-1)
problem_data = np.insert(problem_data, 0, index, axis=1)
# calculate speed of the support ship
ss_speed = math.sqrt(problem_data[0, 3]**2)
# target is the solution array for the SRP
target = final_tour(problem_data, ss_speed)
filename = 'solution.csv'
save_to_csv(filename, target)
# calling the kpi function
kpi(target, initial_data, ss_speed)
print('\n === Final result written to solution csv file ===')
print('\n === Key performance indicators written to kpi csv file ===')
print (kpi)
def read_srp_input_data(csv_file):
'''
Problem instances for the SRP are stored within a .csv file
This function reads the problem instance into Python.
Returns a 2D np.ndarray (4 columns).
Skips the headers and the first column.
Columns are:
x-coordinate, y-coordinate, x-speed and y-speed
Keyword arguments:
csv_file -- the file path and name to the problem instance file
'''
input_data = np.genfromtxt(csv_file, delimiter=',',
dtype=np.float64,
skip_header=1,
usecols=tuple(range(1, 5)))
return input_data
def solve_quadratic_equation(x_0, y_0, x_1, y_1, vx1, vy1, ss_speed):
'''
Returns time taken for the support ship to move from its current position
and intercept cruise ship (i). It is found by finding the smallest
positive root of the quadratic equation.
Keyword arguments:
x0 and y0 -- Support ship coordinates
x1 and y1 -- Cruise ship coordinates
vx1 and vy1 -- Cruise ship velocity
ss_speed -- speed of the support ship
'''
a = (vx1**2) + (vy1**2) - (ss_speed**2)
b = 2*(vx1*(x_1-x_0)+vy1*(y_1-y_0))
c = ((x_1-x_0)**2) + ((y_1-y_0)**2)
if a == 0:
if (-c/b) > 0:
return -c/b
else:
return -1
if ((b**2)-(4*a*c)) < 0:
return -1
ans1 = (-b - (math.sqrt((b**2)-(4*a*c)))) / (2*a)
ans2 = (-b + (math.sqrt((b**2)-(4*a*c)))) / (2*a)
if ans1 >= 0 and ans2 >= 0:
return min(ans1, ans2)
if ans2 < 0 <= ans1:
return ans1
if ans1 < 0 <= ans2:
return ans2
if ans1 < 0 and ans2 < 0:
return -1
def intercept_times(problem_data, ss_speed):
'''
Returns in an array the time taken for the support ship to move from
its current position and intercept all the cruise ships. Also notes the
position of the minimum intercept time.
Keyword arguments:
problem_data -- array containing coordinates from the input file
ss_speed -- speed of the support ship
'''
n_times = problem_data.shape[0]-1
ship_times = np.zeros(n_times)
x_0 = problem_data[0, 1]
y_0 = problem_data[0, 2]
# calculating the intercept times and storing them in the ship_times array
for i in range(n_times):
root_x = solve_quadratic_equation(x_0, y_0, problem_data[i+1][1],
problem_data[i+1][2],
problem_data[i+1][3],
problem_data[i+1][4], ss_speed)
if root_x >= 0:
ship_times[i] = root_x
else:
ship_times[i] = np.inf
# below variables record the minimum time and its position
nearest_cs = min(ship_times)
nearest = np.argmin(ship_times)
# if 2 ships have the same minimum time, below sets the nearest position...
# ...of the cruise ship with the highest Y coordinate. If this is also...
# ...tied, python automatically picks the ship with the smallest index
for i in range(nearest+1, n_times):
if ship_times[i] == nearest_cs:
if problem_data[i+1][2] > problem_data[nearest+1][2]:
nearest = i
return nearest, ship_times
def update(problem_data, ss_speed):
'''
Updates the coordinates of all the ships. The coordinates of the nearest
ship are noted in an array and then deleted from the problem_data to avoid
visiting it again.
Keyword arguments:
problem_data -- array containing coordinates from the input file
ss_speed -- speed of the support ship
'''
n_times = problem_data.shape[0]-1
ship_order = np.full([n_times, 4], -1.0)
time = 0
for j in range(n_times):
nearest_ship, s_times, = intercept_times(problem_data, ss_speed)
cs_speed = math.sqrt((problem_data[nearest_ship+1][3]**2) +
(problem_data[nearest_ship+1][4]**2))
# checks whether the support ship is faster than the cruise ship.
# if not, the cruise ship cannot be visited and that row is deleted.
# n_times is also updated in each loop to ensure correct number of...
# ...loops are performed.
if cs_speed < ss_speed:
for i in range(n_times):
# updating cruise ship coordinates
problem_data[i+1][1] = problem_data[i+1][1]+(min(s_times)
* problem_data
[i+1][3])
problem_data[i+1][2] = problem_data[i+1][2]+(min(s_times)
* problem_data
[i+1][4])
# updating support ship coordinates
problem_data[0, 1] = problem_data[nearest_ship+1][0:3][1]
problem_data[0, 2] = problem_data[nearest_ship+1][0:3][2]
# calculating the running total of intercept times and adding it...
# ...to the array where visited ship coordinates were stored.
next_target = problem_data[nearest_ship+1][0:3]
time += min(s_times)
next_target = np.append(next_target, time)
problem_data = np.delete(problem_data, nearest_ship+1, axis=0)
n_times = problem_data.shape[0]-1
ship_order[j] = next_target
else:
problem_data = np.delete(problem_data, nearest_ship+1, axis=0)
n_times = problem_data.shape[0]-1
return ship_order
def final_tour(problem_data, ss_speed):
'''
Here the function shifts any unvisited ship to the end of the array.
Keyword arguments:
problem_data -- array containing coordinates from the input file
ss_speed -- speed of the support ship
'''
ship_order = update(problem_data, ss_speed)
size = len(ship_order)
count = 0
j = 0
# a count is performed of the ships visited based on which an array is...
# ...created.
for i in range(size):
if ship_order[i][0] != -1:
count += 1
final_path = np.zeros([count, 4])
# all ships visited are added to the final_path array.
for i in range(size):
if ship_order[i][0] != -1:
final_path[j] = ship_order[i]
j += 1
# an array of unvisited ships is created with -1 values and is added...
# ...to the end of the final_path array.
not_reached = np.full([size-count, 4], -1)
final_path = np.concatenate((final_path, not_reached))
return final_path
def kpi(target, initial_data, ss_speed):
"""
This function calculates the different key performance indicators.
Keyword arguments:
target -- the final order of cruise ships to be visited
initial_data -- slice of the original input data
ss_speed -- speed of the support ship
"""
# Ships visited
n_ships = 0
for i in range(len(target)):
if target[i][0] >= 0:
n_ships += 1
else:
continue
if n_ships == 0:
n_ships = -1
# Total time for the support ship to complete its tour
# adds the last ships intercept time with the time it takes to return...
# ...to the initial coordinates.
if n_ships > 0:
total_time = target[n_ships-1, 3] + (solve_quadratic_equation
(initial_data[0],
initial_data[1],
target[n_ships-1, 1],
target[n_ships-1, 2], 0,
0, ss_speed))
max_wait = target[n_ships-1, 3]
else:
total_time = -1
max_wait = -1
# Furthest Y coord.
if n_ships > 0:
y_coord = np.full(n_ships, -1.0)
for i in range(len(target)):
if target[i][0] >= 0:
y_coord[i] = target[i][2]
max_y = max(y_coord)
else:
max_y = -1
# Furthest distance - distance for each ship visited is calculated and...
# ...stored in a new array from which the maximum is returned.
fur_dist = np.zeros(len(target))
for i in range(len(target)):
if target[i][0] >= 0:
fur_dist[i] = math.sqrt((initial_data[0] - target[i][1])**2 +
(initial_data[1] - target[i][2])**2)
else:
if n_ships > 0:
fur_dist[i] = -np.inf
else:
fur_dist[i] = -1
furthest_distance = max(fur_dist)
# Avg. waiting time
if n_ships >= 0:
avg_time = sum(target[:, 3][:n_ships])/n_ships
else:
avg_time = -1
# Below code writes the output to a csv file
_kpi = n_ships, total_time, max_wait, max_y, furthest_distance, avg_time
np.savetxt("kpi.csv", _kpi, delimiter=',')
print (_kpi)
def save_to_csv(filename, output):
"""
This function wrties the final solution to a csv file.
Keyword arguments:
filename and output
"""
np.savetxt(filename, output, delimiter=',',
header='Ship_index,interception_x_coordinate,'
'interception_y_coordinate,estimated_time_of_interception'
, comments=" ")
if __name__ == '__main__':
PROBLEM_FILE = 'sample_srp_data.csv'
main(PROBLEM_FILE)
|
cb2f2c0cfee7a4a4ed1f9f41309f5fd6bf08a409 | Shulamith/csci127-assignments | /hw_08/hw_08.py | 1,602 | 4.1875 | 4 | filename = "moby-small.txt"
filenameTwo = "moby-medium.txt"
filenameThree = "moby-large.txt"
s = 'one two three four five four six three seven three two three eight nine'
def build_word_counts(words):
d={}
for word in words.split():
d.setdefault(word,0)
d[word]=d[word]+1
return d
def clean_data(s):
result=""
for letter in s:
if letter in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
result = result + letter.lower()
else:
result = result + " "
return result
##d=build_word_counts(s)
##print(d)
f = open(filename)
s = f.read()
words_uncleaned = build_word_counts(s)
print(words_uncleaned)
cleaned_string = clean_data(s)
print(cleaned_string)
print("-------------------")
words = build_word_counts(cleaned_string)
print(words)
common_words=[]
vals = words.values()
vals = sorted(vals)
##print(vals)
##for k in words:
## if words[k]>1000:
## common_words.append([k,words[k]])
def build_phrases(cleaned_string):
clean_list=cleaned_string.split()
new_d={}
for i in range(0,len(clean_list)-1):
#print(word)
new_d.setdefault(clean_list[i],[]).append(clean_list[i+1])
return new_d
print(build_phrases(cleaned_string))
##common_words = [ [k,words[k]]for k in words]
#interstingproject to consider: patterns in zen and the art of motorcycle, udit's poem, and most commmon music note beethoven
#make a dictionary with word and word after it:
#hw8
#Call:[me,it] me:[Ishmael] Ishmael:[some] |
18e12dd100296ebf2b189f91ee84c75e54ebcac8 | kodurivamshi/data-science | /linear reg with scklearn.py | 1,076 | 3.75 | 4 | #importing all libraries..
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#importing libraries from sklearn..
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
import os
os.chdir("C:/Users/user/Downloads/headbrain")
df=pd.read_csv("headbrain.csv")
x=df['Head Size(cm^3)'].values
y=df['Brain Weight(grams)'].values
x=x.reshape(len(x),1) #reshaping the array to 2D..
#performing train_test_split i.e dividing the data into training data to fit the regression line model and for testing the model y predictions
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)
model=LinearRegression()
model.fit(x_train,y_train)
y_p=model.predict(x_test)
print(r2_score(y_test,y_p))
#data visualization..
plt.scatter(x,y)
plt.plot(x_test,y_p,color='#58b970',label='regression line')
plt.show()
#testing the algorithm by own values through predictions
print('Brain size =')
print(model.predict([[200]]))
|
8de59040316f2b00f1dc4cc544b2a5683d39b440 | wendeel-lima/Logica-de-Programacao | /02-07/ex0207.py | 1,115 | 3.859375 | 4 | class Netflix:
def __init__(self, nome, ano):
self.__nome = nome.title()
self.ano = ano
self.__like = 0
@property
def nome(self):
return self.__nome
@nome.setter
def nome(self, nome):
self.__nome = nome
@property
def like(self):
return self.__like
def dar_like(self):
self.__like += 1
class Filme(Netflix):
def __init__(self,nome, ano, duracao):
super().__init__(nome, ano)
self.duracao = duracao
def __str__(self):
return f'''
Nome: {self.nome}
Ano: {self.ano}
Duração: {self.duracao} min
Likes: {self.like}
'''
class Serie(Netflix):
def __init__(self, nome, ano, temporadas):
super().__init__(nome, ano)
self.temporadas = temporadas
def __str__(self):
return f'''
Nome: {self.nome}
Ano: {self.ano}
Temporadas: {self.temporadas}
Likes: {self.like}
'''
vingadores = Filme('guerra infitina', 2018, 160)
vingadores.dar_like()
print(vingadores)
|
877e23af9cfe9100afcdaf8fa9c7e194804e33d1 | shivamagrawal3900/pythonTutorial | /day3_string/rotate_word_via_slicing.py | 97 | 3.78125 | 4 | a1 = input("Enter a word:\n")
for i in range(1, len(a1) + 1):
print(a1[i:], a1[:i], sep="")
|
0791e438601d204dffa890a13bb18532d976f1b4 | liuminzhao/eulerproject | /euler41.py | 522 | 3.546875 | 4 | __author__ = 'liuminzhao'
import math
def isprime(x):
return not [t for t in range(2,int(math.sqrt(x))+1) if not x%t]
import itertools
x = list(itertools.permutations("87654321"))
for num in x:
tmp = ""
for i in range(8):
tmp += num[i]
tmp = int(tmp)
if isprime(tmp):
print tmp
break
x = list(itertools.permutations("7654321"))
for num in x:
tmp = ""
for i in range(7):
tmp += num[i]
tmp = int(tmp)
if isprime(tmp):
print tmp
break |
9e3e988c1f265f0b060d6e80d8e59ec2871abaed | simonhoch/python_basics | /04_working_with_list/4_15_code_review.py | 436 | 3.890625 | 4 | rectangles = [(80, 50), (40,50), (30,40)]
print ('Rectangles:\n')
for rectangle in rectangles:
print ('the dimention of the rectangle n' + str(rectangles.index(rectangle)+1) + ' is ' + str(rectangle[0]) + '*' + str(rectangle[1]))
arrays = [rectangle[0] * rectangle[1] for rectangle in rectangles]
print ('\n')
for array in arrays:
print ('the array of the rectangle n' + str(arrays.index(array)+1) + ' is ' + str(array))
|
e95f9370fe7225885ea7b9722c3b2cdb6bc15f31 | mxmaria/coursera_python_course | /week1/Сумма цифр трехзначного числа.py | 174 | 3.671875 | 4 | # Дано трехзначное число. Найдите сумму его цифр.
n = int(input())
a = n // 100
b = (n // 10) % 10
c = n % 10
print(a + b + c)
|
a3a3987d53a110b622d2db5370f90958f82a6fa6 | Jimmyjtc001/assignment1 | /a1_t6_2.py | 187 | 3.65625 | 4 |
from collections import defaultdict
d = defaultdict(int)
for i in [1, 1, 2, 3, 3, 3, 4, 5]:
d[i] += 1
for item, count in d.items():
print('Mode: {} Count: {}'.format(item, count))
|
a744cd5b6d3a9219368f73cf011699dbf381b18d | jvautrain/FEDREPO | /businessstarts.py | 1,868 | 3.515625 | 4 | class BusStarts:
def __init__(self):
self.date = ""
self.measure = 0
self.FIPS = ""
def set_FIPS(self, inval):
self.FIPS = inval
def get_FIPS(self):
return self.FIPS
def set_measure(self, inval):
self.measure = inval
def get_measure(self):
return self.measure
def set_date(self, inval):
self.date = inval
def get_date(self):
return self.date
class BlsCount:
def __init__(self):
self.quarter = ""
self.businesscount = 0
self.state = ""
self.year = ""
self.FIPS = ""
def set_yearquarter(self,inval):
self.year = inval[0:4]
self.quarter = inval[4:6]
def get_year(self):
return self.year
def get_quarter(self):
return self.quarter
def set_businesscount(self, inval):
if inval=='':
inval=0
self.businesscount = int(inval)
def get_businesscount(self):
return self.businesscount
def set_state(self, inval):
self.state = inval
def get_state(self):
return self.state
def set_FIPS(self, inval):
self.FIPS = inval
def get_FIPS(self):
return self.FIPS
def get_date(self):
retval=""
if self.quarter=='Q1':
retval="01/01/"+self.year
elif self.quarter=='Q2':
retval = "04/01/" + self.year
elif self.quarter=='Q3':
retval = "07/01/" + self.year
else:
retval = "10/01/" + self.year
return retval
def print(self):
self.county = ""
print("QUARTER: " + self.quarter + " | YEAR: " + self.year + " | STATE: " + self.state + " | FIPS: " + self.FIPS +" | COUNT: " + str(self.businesscount))
|
00a635bfb9999ba8b5c62d65163caa69a9d039a5 | mayakota/KOTA_MAYA | /Semester_1/Lesson_04/Circle.py | 187 | 4.03125 | 4 | r = float(input("The radius of the circle is: "))
def calcArea(r):
a = 3.14159 * (r * r)
return(a)
print("The area of a circle with a radius of" , r , "is" , calcArea(r))
|
b9f9600fc4528089ddae44597e060964fae5c297 | novayo/LeetCode | /0022_Generate_Parentheses/try_4.py | 705 | 3.75 | 4 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def recursive(left, right):
if left == right == 0:
return [""]
if 0 <= left <= right:
left_list = recursive(left-1, right)
for i in range(len(left_list)):
left_list[i] = "(" + left_list[i]
right_list = recursive(left, right-1)
for i in range(len(right_list)):
right_list[i] = ")" + right_list[i]
return left_list + right_list
else:
return []
return recursive(n, n)
|
e52459733af61b7cd0563529317d91bd5f384a8b | GarryG6/PyProject | /13.py | 598 | 3.796875 | 4 | # Дано натуральное число. Определить: номер минимальной цифры числа при счете слева направо (известно, что такая цифра – одна)
n = int(input('Введите натуралное число: '))
count = 0
n1 = n
while n1 > 0:
n1 = n1 // 10
count = count + 1
print(count)
min = n // 10 ** (count - 1)
pos = 1
res = pos
while pos < count:
pos = pos + 1
temp = n % 10 ** (count - pos + 1) // 10 ** (count - pos)
if temp < min:
min = temp
res = pos
print(res)
|
f57a57cff7e3bd0b9e9dddcf632662559f4126be | orlandosaraivajr/dojo | /2018_OUT_15/dojo.py | 664 | 3.75 | 4 | def abnt(nome):
nomes = nome.split(" ")
sobr = ['JUNIOR', 'FILHO', 'FILHA', 'NETO', 'NETA']
dos = ['do']
tam = len(nomes)
result = nomes[-1].upper()
if result in sobr :
result = nomes[-2].upper() + " " + result
tam -= 1
result += ","
for x in range(tam - 1):
result += " "
if
result += nomes[x].capitalize()
print(result)
return result
assert(abnt('Orlando Saraiva') == 'SARAIVA, Orlando')
assert(abnt('pedro Pimentel') == 'PIMENTEL, Pedro')
assert(abnt('pedro Pagearo pimentel') == 'PIMENTEL, Pedro Pagearo')
assert(abnt('Orlando Saraiva Junior') == 'SARAIVA JUNIOR, Orlando')
assert(abnt('Orlando Saraiva do Nascimento Junior') == 'NASCIMENTO JUNIOR, Orlando Saraiva do') |
d7991f4e7a4634c587609d53c76005e4da6185b9 | maxnovak/ConnQuest | /Direction.py | 4,110 | 3.984375 | 4 | #Movement method
#By Max Novak
#4/19/10
#This class will control all movements around the game world
class Direction():
def __init__(self, location):
"""sets up the location variable"""
self.location=location
def printLocation(self):
"""will display the current location"""
print self.location
def north(self):
"""the parameters for northern movement"""
if self.location["EW"]!=1 and self.location["UD"]!=1:
if self.location["NS"]<2:
self.location["NS"]+=1
else:
print "Can't go that way."
else:
print "Can't go that way."
def south(self):
"""the parameters for southern movement"""
if self.location["EW"]!=1 and self.location["UD"]!=1:
if self.location["NS"]>0:
self.location["NS"]+=-1
else:
print "Can't go that way."
else:
print "Can't go that way."
def east(self):
"""the parameters for eastern movement"""
if self.location["UD"]==-1:
if self.location["NS"]==0:
if self.location["EW"]>-2 and self.location["EW"]<=0:
self.location["EW"]+=-1
else:
print "Can't go that way."
if self.location["NS"]==1:
if self.location["EW"]<=1 and self.location["EW"]>-2:
self.location["EW"]+=-1
if self.location["NS"]==2:
print "Can't go that way."
if self.location["UD"]==0:
if self.location["NS"]==1:
if self.location["EW"]==1:
self.location["EW"]+=-1
else:
print "Can't go that way."
else:
print "Can't go that way."
if self.location["UD"]==1:
print "Can't go that way."
def west(self):
"""the parameters for western movement"""
if self.location["UD"]==-1:
if self.location["NS"]==0:
if self.location["EW"]>=-2 and self.location["EW"]<0:
self.location["EW"]+=1
else:
print "Can't go that way."
if self.location["NS"]==1:
if self.location["EW"]>=-2 and self.location["EW"]<1:
self.location["EW"]+=1
if self.location["NS"]==2:
print "Can't go that way."
if self.location["UD"]==0:
if self.location["NS"]==1:
if self.location["EW"]==0:
self.location["EW"]+=1
else:
print "Can't go that way."
else:
print "Can't go that way."
if self.location["UD"]==1:
print "Can't go that way."
def up(self):
"""the parameters for moving up"""
if self.location["NS"]==1 and self.location["EW"]==1 and self.location["UD"]==-1:
self.location["UD"]+=1
if self.location["NS"]==1 and self.location["EW"]==0 and self.location["UD"]==0:
self.location["UD"]+=1
else:
print "Can't go that way."
def down(self):
"""the parameters for moving down"""
if self.location["NS"]==1 and self.location["EW"]==1 and self.location["UD"]==0:
self.location["UD"]+=-1
if self.location["NS"]==1 and self.location["EW"]==0 and self.location["UD"]==1:
self.location["UD"]+=-1
else:
print "Can't go that way."
def main():
location={"NS":0,"EW":0,"UD":0}
space=Direction(location)
while True:
word=raw_input("direction: ")
if word == "north":
space.north()
if word == "south":
space.south()
if word == "east":
space.east()
if word == "west":
space.west()
if word == "up":
space.up()
if word == "down":
space.down()
space.printLocation()
if __name__=="__main__":
main()
|
cf13cc67e3be9eb78d62c68e748d41160e8134d4 | KaylaBaum/astr-119-hw-1 | /if_else_control.py | 481 | 3.96875 | 4 | #define a function
def flow_control(k):
#define a string based on the value of k
if(k==0):
s = "Variable k = %d equals 0." % k
elif(k==1):
s = "Variable k = %d equals 1." % k
else:
s = "Variable k = %d does not equal 0 or 1." % k
#print the variable (the string s)
print(s)
#define a main function
def main():
#try flow_control for 0, 1, 2
for i in range(3):
flow_control(i)
#run the program
if __name__ == "__main__":
main()
|
14183da3776e239e3659399136eb39fb75c210ed | chaofan-zheng/tedu-python-demo | /month01/all_code/day11/demo03.py | 1,254 | 3.828125 | 4 | """
属性各种写法
"""
# 写法1:读写属性
"""
# 适用性:有一个实例变量,但是需要在读取和写入过程中进行限制
# 快捷键:props + 回车
class MyClass:
def __init__(self, data=0):
self.data = data
@property
def data(self):
return self.__data
@data.setter
def data(self, value):
self.__data = value
m01 = MyClass(10)
print(m01.data) # 读取操作
m01.data = 20 # 写入操作
"""
# 写法2:只读属性
"""
# 快捷键:prop + 回车
# 适用性:有一个私有变量,只想提供读取功能,不希望类外修改.
class MyClass:
def __init__(self):
self.__data = 520
@property
def data(self):
return self.__data
m01 = MyClass()
print(m01.data) # 读取操作
# AttributeError: can't set attribute
# m01.data = 20 # 写入操作
"""
# 写法3:只写属性
# 适用性:只需要修改实例变量,不需要读取.
# 快捷键:无
class MyClass:
def __init__(self, data=0):
self.data = data
data = property()
@data.setter
def data(self, value):
self.__data = value
m01 = MyClass(10)
# AttributeError: unreadable attribute
# print(m01.data) # 读取操作
m01.data = 20 # 写入操作
print(m01.__dict__)
|
1181234e659e137e825a6abbf3892f5cfc5d49f4 | c109156126/h | /62.py | 261 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 9 20:29:58 2021
@author: 曾睿恩
"""
a={"蘋果":"紅色","香蕉":"黃色","葡萄":"紫色","藍莓":"藍色","橘子":"橘色"}
print(a.keys())
fruit=input("請輸入水果")
print(fruit,"是",a.get(fruit)) |
e07eb2819e34b36938666852655b39e2811bb1ef | MikhailChernetsov/python_basics_task_1 | /Hometask5/ex2/main.py | 641 | 4.03125 | 4 | '''
2. Создать текстовый файл (не программно), сохранить в нем
несколько строк, выполнить подсчет количества строк, количества
слов в каждой строке.
'''
with open('text_2.txt', 'r', encoding='utf-8') as my_file:
number_of_strings = 0
for line in my_file:
line = line.split()
print(f'Количество слов в строке {number_of_strings+1}: {len(line)} слов(а)')
number_of_strings += 1
print(f'Общее количество строк в файле: {number_of_strings}')
|
749128f2cbefbd69eee3507b7836355553845b91 | gil9red/SimplePyScripts | /tkinter_examples/center_window.py | 672 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
def center_window(root, width=300, height=200):
# get screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# calculate position x and y coordinates
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
if __name__ == "__main__":
import tkinter as tk
app = tk.Tk()
app.title("center_window")
center_window(app)
label = tk.Label(app, text="Hello World!", font="Arial 16", fg="red")
label.pack()
app.mainloop()
|
c3f377adfd05f5235afec1709e31913d65adc1b7 | Nate8888/programming-contest-practice | /programming-team/First Semester/Learn Problems/IntroProblems/trip.py | 173 | 3.53125 | 4 | cases = int(input())
for i in range(cases):
line = input().rstrip().split(" ")
total = float(line[0]) * int(line[2]) + float(line[1]) * int(line[3])
print(round(total,2)) |
de76c74c8697465dd100fbe9a088f62d64b4da4d | insoPL/PythonHomework | /python11/11.3.py | 848 | 3.984375 | 4 | # -*- coding: utf-8 -*-
import random
def random_list(n):
re_list = range(n)
random.shuffle(re_list)
return re_list
def swap(L, left, right):
"""Zamiana miejscami dwóch elementów."""
# L[left], L[right] = L[right], L[left]
item = L[left]
L[left] = L[right]
L[right] = item
def quicksort(L, left, right, compare=cmp):
if left >= right:
return
swap(L, left, (left + right) / 2) # element podziału
pivot = left # przesuń do L[left]
for i in range(left + 1, right + 1): # podział
if compare(L[i], L[left]) < 0:
pivot += 1
swap(L, pivot, i)
swap(L, left, pivot) # odtwórz element podziału
quicksort(L, left, pivot - 1)
quicksort(L, pivot + 1, right)
lista = random_list(16)
quicksort(lista, 0, 15)
print lista
|
1f9653bfe59d629527d231e2e360e0b0192b9ce7 | harpolea/AOC19 | /day6.py | 1,534 | 3.78125 | 4 | import numpy as np
import sys
def count_orbits(input_file):
orbits = {'COM': None}
satellites = set()
# read file and make a dictionary of orbits
with open(input_file, 'r') as infile:
for line in infile:
inner, outer = line.replace('\n', '').split(')')
orbits[outer] = inner
satellites.add(outer)
satellites.add(inner)
# loop over satellites to count orbits
counter = 0
for s in satellites:
outer = s
inner = orbits[outer]
while inner is not None:
counter += 1
outer = inner
inner = orbits[outer]
print(f'There are {counter} orbits')
return orbits
def orbit_transfers(orbits):
# to do this shall find orbits from YOU, SAN to COM, then count lengths of
# paths to first common satellite
YOU_path = []
outer = 'YOU'
inner = orbits[outer]
while inner is not None:
YOU_path.append(inner)
outer = inner
inner = orbits[outer]
SAN_path = []
outer = 'SAN'
inner = orbits[outer]
while inner is not None:
SAN_path.append(inner)
outer = inner
inner = orbits[outer]
# now find first common satellite
for i, s in enumerate(YOU_path):
try:
print(f'{i + SAN_path.index(s)} transfers are needed')
break
except ValueError:
continue
if __name__ == "__main__":
orbits = count_orbits(sys.argv[1])
orbit_transfers(orbits) |
31f08aa56d0d69151f39a7928b1bc0c9c5432c31 | lidongdongbuaa/leetcode2.0 | /数据结构与算法基础/leetcode周赛/200329/Count Number of Teams.py | 2,737 | 3.9375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/29 12:21
# @Author : LI Dongdong
# @FileName: Count Number of Teams.py
''''''
'''
题目概述:
题目考点:
解决方案:
方法及方法分析:
time complexity order:
space complexity order:
如何考
'''
'''
from head to end, choose arr which is ascedning or descending with 3 elem, soldier are unique
input: arr,list; lenght range? from 1 to 200; value range? 1 to 10^5; repeated value? N; oder? N
output: int;
corner case
length of arr < 3, return 0
no such arr, return 0
A. brute force - backtracking
Method:
1. corner case
2. find all 3 elem combination by backtracking, save them in list
3. traversal the list, find the number of ascending or descending ones
4. return
Time: O(n^3)
Space: O(n^3)
'''
from copy import deepcopy
class Solution:
def numTeams(self, rating) -> int:
if len(rating) < 3: # corner case
return 0
def backtrack(i, item, res): # return all combination of 3 elem
if len(rating) - 1 < i:
return
item.append(rating[i])
if len(item) == 3:
res.append(deepcopy(item))
backtrack(i + 1, item, res)
item.pop()
backtrack(i + 1, item, res)
res = []
backtrack(0, [], res)
ans = 0
for elem in res:
if elem[0] < elem[1] < elem[2]:
ans += 1
elif elem[0] > elem[1] > elem[2]:
ans += 1
return ans
'''
B optimzed res space
'''
from copy import deepcopy
class Solution:
def numTeams(self, rating) -> int:
if len(rating) < 3: # corner case
return 0
def backtrack(i, item, res): # return all combination of 3 elem
if len(rating) - 1 < i:
return
item.append(rating[i])
if len(item) == 3:
if item[0] < item[1] < item[2] or item[0] > item[1] > item[2]:
res.append(1)
backtrack(i + 1, item, res)
item.pop()
backtrack(i + 1, item, res)
res = []
backtrack(0, [], res)
ans = sum(res)
return ans
'''
C.brute force
'''
class Solution:
def numTeams(self, rating: List[int]) -> int:
if len(rating) < 3: # corner case
return 0
res = 0
length = len(rating)
for i in range(length - 2):
for j in range(i + 1, length - 1):
for k in range(j + 1, length):
if rating[i] < rating[j] < rating[k] or rating[i] > rating[j] > rating[k]:
res += 1
return res
|
c7000099e13df771a687b4e9ee32dada6ea55e40 | judy2k/python_and_mongodb | /src/main.py | 8,001 | 3.515625 | 4 | from datetime import datetime
import os
# Import the `pprint` function to print nested data:
from pprint import pprint
from dotenv import load_dotenv
import bson
import pymongo
from pymongo import MongoClient
def print_title(title, underline_char="="):
"""
Utility function to print a title with an underline.
"""
print() # Print a blank line
print(title)
print(underline_char * len(title)) # Print an underline made of `underline_char`
# Load config from a .env file:
load_dotenv(verbose=True)
MONGODB_URI = os.environ["MONGODB_URI"]
# Connect to your MongoDB cluster:
client = MongoClient(MONGODB_URI)
# Get a reference to the "recipes" collection:
db = client.get_database("cocktails")
recipes = db.get_collection("recipes")
# recipes.insert_one(
# {
# "name": "Dodgy Cocktail",
# "ingredients": [
# {
# "name": "Water",
# "quantity": {"unit": "ml", "amount": 30},
# }
# ],
# "instructions": [
# "Pour yourself some water from the tap.",
# ],
# }
# )
print_title("All Documents")
cursor = recipes.find(
sort=[
("name", pymongo.ASCENDING),
],
)
for recipe in cursor:
print("Cocktail:", recipe["name"])
print_title("Negroni Sbagliato")
query = {"name": "Negroni Sbagliato"}
cursor = recipes.find(query)
for recipe in cursor:
pprint(recipe)
"""
{'_id': ObjectId('5f7b4b6204799f5cf837b1e1'),
'garnish': 'Orange Twist',
'ingredients': [{'name': 'Campari', 'quantity': {'unit': 'ml', 'value': 30}},
{'name': 'Sweet Vermouth',
'quantity': {'unit': 'ml', 'value': 30}},
{'name': 'Prosecco', 'quantity': {'unit': 'ml', 'value': 30}}],
'instructions': ['Stir Campari & vermouth with ice',
'Pour into a champagne flute',
'Add wine & gently combine',
'Serve with orange twist'],
'name': 'Negroni Sbagliato',
"""
print_title("Vodka Cocktails")
query = {"ingredients": {"$elemMatch": {"name": "Vodka"}}}
project = {"reviews": 0}
cursor = recipes.find(query, projection=project)
for recipe in cursor:
print(" *", recipe["name"])
print_title("Empty Aggregation Pipeline")
query = []
cursor = recipes.aggregate(query)
for recipe in cursor:
print(" *", recipe["name"])
print_title("Vodka Cocktail Reviews")
query = [
{"$match": {"ingredients": {"$elemMatch": {"name": "Vodka"}}}},
{
"$lookup": {
"from": "reviews",
"localField": "_id",
"foreignField": "recipe_id",
"as": "reviews",
}
},
]
cursor = recipes.aggregate(query)
for recipe in cursor:
pprint(recipe)
print_title("Cocktail Ratings")
query = [
{
"$lookup": {
"from": "reviews",
"localField": "_id",
"foreignField": "recipe_id",
"as": "reviews",
},
},
{"$sort": {"rating": -1}},
{
"$project": {
"name": 1,
"rating": 1,
"exact_rating": 1,
"rating_count": 1,
"ratings": {
"$map": {
"input": "$reviews",
"as": "review",
"in": "$$review.rating",
}
},
"exact_rating": {"$avg": "$reviews.rating"},
"rating": {
"$divide": [
{"$round": {"$multiply": [{"$avg": "$reviews.rating"}, 2]}},
2,
],
},
"rating_count": {"$size": "$reviews.rating"},
},
},
]
cursor = recipes.aggregate(query)
for recipe in cursor:
pprint(recipe)
try:
print_title("Watch for Changes")
print("Waiting for updates ... Ctrl-C to move on.")
for update in recipes.watch():
pprint(update)
"""
{'_id': {'_data': '825FA81A1D000000022B022C0100296E5A100457432E8F24D941BF9A9D4EDAD5FD837646645F696400645F7DAA018EC9DFB536781AFA0004'},
'clusterTime': Timestamp(1604852253, 2),
'documentKey': {'_id': ObjectId('5f7daa018ec9dfb536781afa')},
'fullDocument': {'_id': ObjectId('5f7daa018ec9dfb536781afa'),
'ingredients': [{'name': 'Dark rum',
'quantity': {'quantity': '45',
'unit': 'ml'}},
{'name': 'Peach nectar',
'quantity': {'quantity': '2', 'unit': 'oz'}},
{'name': 'Orange juice',
'quantity': {'quantity': '3',
'unit': 'oz'}}],
'instructions': ['Pour all of the ingredients into a '
'highball glass almost filled with ice '
'cubes',
'Stir well.'],
'name': 'Abilene'},
'ns': {'coll': 'recipes', 'db': 'cocktails'},
'operationType': 'replace'}
"""
except KeyboardInterrupt:
print() # Print a line break
print_title("Transaction test")
from pymongo import WriteConcern, ReadPreference
from pymongo.read_concern import ReadConcern
import random
try:
with client.start_session() as session:
def transactional_function(session):
db = session.client.get_database("cocktails")
recipes = db.get_collection("recipes")
reviews = db.get_collection("reviews")
# Important:: You must pass the session to the operations.
recipe_id = recipes.insert_one(
{"name": "The Ghost"}, session=session
).inserted_id
for i in range(5):
reviews.insert_one(
{"recipe_id": recipe_id, "rating": random.randint(1, 5)},
session=session,
)
if i == 2:
raise Exception(
"Oops, failed transaction after the third review insertion"
)
wc_majority = WriteConcern("majority", wtimeout=1000)
session.with_transaction(
transactional_function,
read_concern=ReadConcern("local"),
write_concern=wc_majority,
read_preference=ReadPreference.PRIMARY,
)
except Exception as e:
print(e)
print("Is there a recipe in the database?", end=" ")
if recipes.find_one({"name": "The Ghost"}) is None:
print("Nope!")
else:
print("Oh dear, yes.")
print_title("Updating Part of a Document")
recipes.update_one(
{"name": "Negroni Sbagliato"},
{
"$push": {
"reviews": {"rating": 4, "when": datetime.now()},
},
},
)
pprint(
recipes.find_one(
{"name": "Negroni Sbagliato"},
)
)
"""
{'_id': ObjectId('5f7b4b6204799f5cf837b1e1'),
'garnish': 'Orange Twist',
'ingredients': [{'name': 'Campari', 'quantity': {'unit': 'ml', 'value': 30}},
{'name': 'Sweet Vermouth',
'quantity': {'unit': 'ml', 'value': 30}},
{'name': 'Prosecco', 'quantity': {'unit': 'ml', 'value': 30}}],
'instructions': ['Stir Campari & vermouth with ice',
'Pour into a champagne flute',
'Add wine & gently combine',
'Serve with orange twist'],
'name': 'Negroni Sbagliato',
'reviews': [{'rating': 4,
'when': datetime.datetime(2020, 11, 8, 16, 53, 25, 905000)},
{'rating': 4,
'when': datetime.datetime(2020, 11, 8, 16, 54, 15, 279000)},
{'rating': 4,
'when': datetime.datetime(2020, 11, 8, 16, 54, 23, 818000)},
{'rating': 4,
'when': datetime.datetime(2020, 11, 8, 16, 54, 26, 744000)},
{'rating': 4,
'when': datetime.datetime(2020, 11, 8, 17, 40, 26, 656000)},
{'rating': 4,
'when': datetime.datetime(2020, 11, 8, 17, 51, 2, 903000)}]}
""" |
acd90374fa435eba71ad75bffa19f1e4b5fcecb0 | constklimenko/PY | /6 week/boots.py | 1,365 | 4.125 | 4 | """В обувном магазине продается обувь разного размера.
Известно, что одну пару обуви можно надеть на другую,
если она хотя бы на три размера больше. В магазин
пришел покупатель.Требуется определить,
какое наибольшее количество пар обуви сможет
предложить ему продавец так, чтобы он смог
надеть их все одновременно.
Формат ввода
Сначала вводится размер
ноги покупателя (обувь
меньшего размера он надеть не сможет),
в следующей строке — размеры каждой пары обуви
в магазине через пробел. Размер — натуральное
число, не превосходящее 100."""
n = int(input())
NumList1 = list(map(int, input().split()))
NumList1.sort()
x = 0
ans = []
while NumList1[x] < n:
x += 1
currentSize = NumList1[x]
ans.append(NumList1[x])
for y in range(x + 1, len(NumList1)):
if NumList1[y] >= currentSize + 3:
ans.append(NumList1[y])
currentSize = NumList1[y]
else:
continue
print(len(ans))
|
ca7a132da5fa1faa4445cc191b906829c8cc0dd7 | pedal-edu/pedal | /examples/submissions/student_code.py | 153 | 3.84375 | 4 | print("Hello", 1+input("What is your name? "))
def add(a, b):
return a + b
def bad_add(a, b):
return a - b
x = 0
add
bad_add
x
#print(x + "")
|
e51927913300fb437e4e71079b9ee2877a9f1fc1 | cs-learning-2019/python1contsat | /Lessons/Week12/Animations/Animations.pyde | 4,077 | 4.65625 | 5 | # Focus Learning: Python Level 1 Cont
# Animations
# Kavan Lam
# Dec 12, 2020
# Contents
# 1) Simple animation of a ball moving to the right
# 2) Animation of a ball moving up and down (bouncing off walls)
# 3) Same as 2 but with a square
# 4) Be able to switch the direction of animation with mouse pressed
# 5) Keep track of number of bounces and display on the screen
"""
# Section 1
x = 100
y = 300
def setup():
size(900, 900)
def draw():
global x
global y
background(0, 0, 0) # Clears the previous frame
fill(255, 0, 0)
ellipse(x, y, 50, 50)
x = x + 5
"""
"""
# Section 2
x = 450
y = 450
direction = 1 # Either 1 or -1, 1 = move down and -1 = move up
def setup():
size(900, 900)
def draw():
global x
global y
global direction
background(0, 0, 0) # Clears the previous frame
fill(255, 0, 0)
ellipse(x, y, 50, 50)
y = y + (5 * direction)
# Detect collisions
if y >= 900:
direction = -1 # We need to move up
elif y <= 0:
direction = 1 # We need to move down
"""
"""
# Section 3
x = 450
y = 450
direction = 1 # Either 1 or -1, 1 = move down and -1 = move up
def setup():
size(900, 900)
def draw():
global x
global y
global direction
background(0, 0, 0) # Clears the previous frame
fill(255, 0, 0)
rect(x, y, 50, 50)
y = y + (10 * direction)
# Detect collisions
if y >= 850:
direction = -1 # We need to move up
elif y <= 0:
direction = 1 # We need to move down
"""
"""
# Section 4
x = 450
y = 450
direction = 1 # Either 1 or -1, 1 = move down and -1 = move up
case = 1 # Either 1 or 2, 1 = move up and down ....... 2 = move left and right
def setup():
size(900, 900)
def draw():
global x
global y
global direction
global case
background(0, 0, 0) # Clears the previous frame
fill(255, 0, 0)
ellipse(x, y, 50, 50)
if case == 1:
y = y + (5 * direction)
elif case == 2:
x = x + (5 * direction)
# Detect collisions
if x >= 900:
direction = -1 # We need to move up
elif x <= 0:
direction = 1 # We need to move down
if y >= 900:
direction = -1 # We need to move up
elif y <= 0:
direction = 1 # We need to move down
def mousePressed():
global case
if case == 1:
case = 2
elif case == 2:
case = 1
"""
# Section 5
x = 450
y = 450
direction = 1 # Either 1 or -1, 1 = move down and -1 = move up
case = 1 # Either 1 or 2, 1 = move up and down ....... 2 = move left and right
num_bounce = 0 # This is an int
def setup():
global font1
size(900, 900)
font1 = loadFont("BodoniMTCondensed-BoldItalic-48.vlw")
def draw():
global x
global y
global direction
global case
global num_bounce
global font1
background(0, 0, 0) # Clears the previous frame
# Draw the circle
pushStyle()
fill(255, 0, 0)
ellipse(x, y, 50, 50)
popStyle()
# Draw some text
pushStyle()
textFont(font1, 40)
text("The num of bounces: " + str(num_bounce), 50, 50)
popStyle()
if case == 1:
y = y + (5 * direction)
elif case == 2:
x = x + (5 * direction)
# Detect collisions
if x >= 900:
direction = -1 # We need to move left
num_bounce = num_bounce + 1
elif x <= 0:
direction = 1 # We need to move right
num_bounce = num_bounce + 1
if y >= 900:
direction = -1 # We need to move up
num_bounce = num_bounce + 1
elif y <= 0:
direction = 1 # We need to move down
num_bounce = num_bounce + 1
def mousePressed():
global case
if case == 1:
case = 2
elif case == 2:
case = 1
|
e320d11929e87fcba8dc84c1fa4966af364b4701 | oscar-oneill/RockPaperScissors | /rock.py | 517 | 3.9375 | 4 | import random
def play():
user = input("What's your choice? Select 'r' for Rock, 'p' for Paper, 's' for scissors: ")
computer = random.choice(['r', 'p', 's'])
if user == computer:
return "Tie Game..."
if is_winner(user, computer):
return "You win!"
return "You lose!"
def is_winner(player, opponent):
if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') \
or (player == 'p' and opponent == 'r'):
return True
print(play()) |
2d0cae4e44c62316876916fbe1250b1f82f00e6e | VargheseVibin/dabble-with-python | /Day24(SnakeGameHighScore)/main.py | 1,432 | 3.78125 | 4 | from turtle import Screen, Turtle
import time
from snake import Snake
from food import Food
from scoreboard import ScoreBoard
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
def draw_border():
border = Turtle()
border.hideturtle()
border.color("white")
border.penup()
border.goto(-280, 280)
border.pendown()
border.goto(280, 280)
border.goto(280, -280)
border.goto(-280, -280)
border.goto(-280, 280)
snake = Snake()
food = Food()
scoreboard = ScoreBoard()
draw_border()
screen.listen()
screen.onkeypress(fun=snake.move_up, key="Up")
screen.onkeypress(fun=snake.move_down, key="Down")
screen.onkeypress(fun=snake.move_right, key="Right")
screen.onkeypress(fun=snake.move_left, key="Left")
game_on = True
while game_on:
time.sleep(0.1)
screen.update()
snake.move()
# Detect collision with Food
if snake.head.distance(food) <= 15:
food.refresh()
scoreboard.increase_score()
snake.eats_food()
# Detect collision with wall
if snake.detect_wall_collision():
game_on = False
scoreboard.game_over()
print("Oops.. Sorry! Game Over!")
# Detect collision with tail
for block in snake.blocks[1:]:
if snake.head.distance(block) < 10:
game_on = False
scoreboard.game_over()
screen.exitonclick()
|
0ee00e912ded3d5b339a97e80a5d555739427c30 | chamulovidio/clases | /ejercicios.py | 3,514 | 3.96875 | 4 | # En este ejemplo se solicitara la introduccion de datos
dato = input('Digite su Nombre: ')
dato1 = input('Diguite su apellido: ')
print(dato, dato1)
# Crear una variable, una lista, luego digitar un dato, verificar si
# en la lista y mostrar el dato introducido
var = input('Ingrese un Dato: ')
lista = ["Hola", "Mundo", "Chanchito", "Feliz", "Dragones"]
if lista.count(var) > 0:
print('El dato existe :', var)
else:
print('El dato no existe :', var)
# Ejercisio, definir una variable, solicitar la introduccion de un dato
# definir una lista y evaluar si el dato digitado existe en la lista creada,
# luego imprimir un mensaje diciendo si existe el dato o si no existe
nombre = input('Digite su Nombre : ')
listnombre = ["Daniela", "Ovidio", "Silvia", "Daniel", "Dayana"]
if listnombre.count(nombre) > 0:
print('Si existe este nombre :' , nombre)
else:
print('Este nombre no existe :' , nombre)
# Ej. de Sumas, primero se crean las variables se convierten a numeros enteros
primero = input('Ingrese el Primer Numero :')
segundo = input('Ingrese el segundo Numero :')
pnumero = int(primero)
snumero = int(segundo)
print(pnumero+snumero)
# Otra forma seria evaluando el valor digitado, si no es numero tratar de
# convertirlo a numero y si no se puede mandar un mensaje de que no se
# digitaron numeros
numero = input('Ingrese el Primer Numero :')
try:
numero = int(numero)
except:
numero = 'Chanchito Feliz'
numero1 = input('Ingrese el Segundo Numero :')
try:
numero1 = int(numero1)
except:
numero1 = 'Chanchito Feliz'
if numero == 'Chanchito Feliz' or numero1 == 'Chanchito Feliz':
print('Los datos digitados no son numeros, intente digitando numero')
else:
print(numero+numero1)
# Otra forma seria la siguiente
numero = input('Digite el primer numero :')
try:
numero = int(numero)
numero1 = input('Digite el segundo numero :')
try:
numero1 = int(numero1)
print(numero+numero1)
except:
print('Los datos digitados no son numero, intente digitando numeros')
except:
print('Los datos digitados no son numero, intente digitando numeros')
# Ej. de como detener la ejecucion al momento de digitar mal el dato
numero = input('Ingrese el Primer Numero :')
try:
numero = int(numero)
except:
numero = 'chanchito feliz'
if numero == 'chanchito feliz':
print('Los datos digitados no son numero')
exit()
numero1 = input('Ingrese el Segundo Numero :')
try:
numero1 = int(numero1)
except:
numero1 = 'Chanchito Feliz'
if numero1 == 'Chanchito Feliz':
print('Los datos digitados no son numeros')
exit()
print(numero+numero1)
# Agregando mas operaciones a la calculadora
numero = input('Digite el primer Numero: ')
try:
numero = int(numero)
except:
numero = ('No es numero')
if numero == ('No es numero'):
print('El dato digitado no es un numero, intente digitando un numero entero')
exit()
numero1 = input('Digite el segundo numero: ')
try:
numero1 = int(numero1)
except:
numero1 = ('No es numero')
if numero1 == ('No es numero'):
print('El dato digitado no es un numero, intente digitando un numero entero')
exit()
operador = input('Digite el tipo de Operacion: ')
if operador == '+':
print('Suma: ', numero + numero1)
elif operador == '-':
print('Resta: ', numero - numero1)
elif operador == '*':
print('Multiplicacion: ', numero * numero1)
elif operador == '/':
print('Divicion: ', numero / numero1)
else:
print('El simbolo ingresado no es Valido') |
9ebbbbfd7d867c295c79682de4db902abaa4cd09 | taaeyoon/Ace_todolist | /search.py | 2,371 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# todo table에 존재하는 todo 항목을 검색하여 찾는 함수...
import sqlite3
import list_todo as printer
def search(option=None):
conn = sqlite3.connect("ace.db")
cur = conn.cursor()
# 검색한 항목을 담은 list
search_list = []
search_answer_list = ["i", "d", "t", "c"]
# 어떤 방법으로 찾고 싶은 지에 대한 input 함수 / 조건문
if option is None:
search_type = input("How do you want to search? (i: id, t: title, d: due, c: category) ")
while search_type not in search_answer_list:
print()
print("Incorrect type")
search_type = input("How do you want to search? (i: id, t: title, d: due, c: category) ")
else:
search_type = option
if search_type == "i":
search_id = input("what id: ")
sql = "select * from todo where id=?"
cur.execute(sql, (search_id, ))
rows = cur.fetchall()
for row in rows:
search_list.append(row)
printer.print_list(search_list)
elif search_type == "t":
search_title = input("what title: ")
search_list = contain_thing(search_title, 1)
printer.print_list(search_list)
elif search_type == "d":
search_due = input("what due: ")
search_list = contain_thing(search_due, 3)
printer.print_list(search_list)
elif search_type == "c":
search_category = input("what category: ")
search_list = contain_thing(search_category, 2)
printer.print_list(search_list)
cur.close()
conn.close()
return search_list
# 검색하는 단어를 포함하는 항목 모두 찾기
def contain_thing(what_search, num_index):
conn = sqlite3.connect("ace.db")
cur = conn.cursor()
# 검색하는 단어를 포함한 모든 항목 리스트
contain_list = []
# 존재하는 모든 항목에 대한 리스트
all_list = []
# 존재하는 모든 항목 담기
sql = "select * from todo where 1"
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
all_list.append(row)
# 검색하는 단어를 포함하는 항목 모두 찾기
for elem in all_list:
if what_search in elem[num_index]:
contain_list.append(elem)
cur.close()
conn.close()
return contain_list
|
9f46b703dcbfcf9d178cffd754acc4360d6dd877 | FefAzvdo/Python-Training | /Exercicios/Aula 13/054.py | 728 | 3.8125 | 4 | mulheres_com_menos_de_20 = []
soma_idade = 0
nome_homem_mais_velho = ""
idade_homem_mais_velho = 0
for c in range(0, 4):
nome = input("Digite o seu nome: ")
idade = int(input("Digite a sua idade: "))
sexo = input("Digite o seu sexo: 'M' ou 'F' : ")
soma_idade = soma_idade + idade
if(sexo == 'F'):
if(idade < 20):
mulheres_com_menos_de_20.append(nome)
else:
if(idade_homem_mais_velho < idade):
nome_homem_mais_velho = nome
idade_homem_mais_velho = idade
print("A média da idade do grupo é: ", soma_idade/4)
print("O nome do homem mais velho é: ", nome_homem_mais_velho)
print(f"Existem {len(mulheres_com_menos_de_20)} mulheres com menos de 20")
|
3857d9d475081ff0e2d775e8d86f7ca6d958f2a0 | venkatram64/python_ml | /my_graphs/g_histo_gram_4.py | 556 | 3.796875 | 4 | import matplotlib.pyplot as plt
population_ages = [22, 44, 62, 45, 21, 22, 34, 42, 42, 4, 99, 102, 110, 120, 121, 122, 130, 111, 115, 112, 80, 75, 65, 54, 44, 43, 42,48]
"""ids = [x for x in range(len(population_ages))]
plt.bar(ids, population_ages, label="BARS1") """
bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130]
# histogram shows the distribution not like bar chart
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Interesting Graph\nCheck it out')
#plt.legend()
plt.show()
|
2abef8ae1622397d73ea39194ee45cd06c770cc2 | jacopodisi/mru_securitygame | /mru/test/testfunctions.py | 630 | 3.71875 | 4 | import numpy as np
def compare_row_mat(x_mat, y_mat):
""" Compare rows of 2, unordered, matrices
Parameter
---------
x_mat: 1st matrix to compare
y_mat: 2nd matrix to compare
Return
------
boolean: True if the 2 matrices contains the same rows
(also in different order), False otherwise
"""
x_temp = np.vstack({tuple(row) for row in x_mat})
y_temp = np.vstack({tuple(row) for row in y_mat})
if x_temp.shape[0] != y_temp.shape[0]:
return False
for x in x_temp:
if not np.any(np.all(x == y_temp, axis=1)):
return False
return True
|
88fe417718946be243638b7b0b45e1e70d48a210 | ashwinitangade/PythonProgramming | /PythonAss1/14.py | 1,969 | 4.125 | 4 | #Write a program to create two list A & B such that List A contains Employee Id, List B contain Employee name (minimum 10 entries in each list) & perform following operation
a) Print all names on to screen
b) Read the index from the user and print the corresponding name from both list.
c) Print the names from 4th position to 9th position
d) Print all names from 3rd position till end of the list
e) Repeat list elements by specified number of times (N- times, where N is entered by user)
f) Concatenate two lists and print the output.
g) Print element of list A and B side by side.(i.e. List-A First element, List-B First element )
employeeNameList = ['Aarav', 'Amita','Biren','Cavin','Danny','Gopal','Hetal','Leena','Meena','Neena','Vinay']
employeeIdList = ['123','234','345','456','567','678','789','890','247','347','457']
if len(employeeNameList) != len(employeeIdList):
print('\nBoth the lists must have same length')
exit(0)
for emp in employeeNameList:
print(emp)
index = int(input("Enter index of employee: "))
if index > len(employeeNameList):
print('\nPlease enter an index less than total number of employees which is: ',len(employeeNameList))
else:
print('\nThe name of employee at index ',index,'is: ',employeeNameList[index],'and the id is: ',employeeIdList[index])
print('\nThe names from 4th position to 9th position are: ', employeeNameList[4:10:1])
print('\nThe names from 3rd position to 9th position are: ', employeeNameList[3::])
print('\n ')
repeatNum = int(input("Please enter by how many times you want to repeat the list: "))
newList = employeeNameList*repeatNum
print('\nThe new list is :',newList)
concatList = employeeNameList + employeeIdList
print('\nThe concatenated list of name and id is :',concatList)
print('\nName EmpId')
for (name,empid) in zip(employeeNameList,employeeIdList):
print('\n',name,' ', empid)
|
ec5b632bdd243f7b68c4223354cb27e8a418ac15 | 1987617587/lsh_py | /basics/day11/lzt/single_test.py | 2,129 | 3.609375 | 4 | # author:lzt
# date: 2019/11/20 15:44
# file_name: single_test
from typing import Any
class Book:
def __new__(cls, name) -> Any:
print("类的构造执行了 对象就会出生")
return super().__new__(cls)
def __init__(self, name) -> None:
super().__init__()
print("初始化方法执行了")
self.name = name
def __str__(self) -> str:
return self.name
class Book_DB:
"""
书籍的存储类:书的仓库
"""
_instance = None
_flag = False
def __new__(cls) -> Any:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self) -> None:
if not Book_DB._flag:
super().__init__()
self.__books = []
Book_DB._flag = True
# books = []:存储书籍的列表 不推荐使用类变量
def add_book(self, book):
self.__books.append(book)
def show_books(self):
for i in range(len(self.__books)):
print(self.__books[i])
book_db = Book_DB()
book_db.add_book(Book("红与黑"))
# 若此时有另外的程序也需要书籍仓库
book_db2 = Book_DB()
book_db2.add_book(Book("编程从精通到放弃"))
# book_db.show_books()
book_db2.show_books()
class OnlyObjClass:
# 设定一个类变量 用于保存唯一实例的地址 也为了监视是否已产生过对象
_instance = None
# 类变量:初始化标识
_init_flag = False
def __new__(cls, name) -> Any:
# 构造中判断监视变量是否已经指向一个对象:
if cls._instance is None:
# 未保存任何对象
cls._instance = super().__new__(cls)
# 已经有对象
return cls._instance
def __init__(self, name) -> None:
if not OnlyObjClass._init_flag:
super().__init__()
print("初始化对象")
self.name = name
OnlyObjClass._init_flag = True
# o1 = OnlyObjClass("张三")
# o2 = OnlyObjClass(None)
# print(id(o1), id(o2))
# o2.name = "李四"
# print(o1.name)
# print(o2.name)
|
43dde6a93adc53e43becae46d8821a97b9468298 | Simran-Sahni/LeetCode-Solutions | /Python/baseK.py | 517 | 4.0625 | 4 | def sumBase(n: int, k: int) :
"""
Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.
After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
TC : O(N)
SC : O(1)
n : int (integer base 10)
k : int (base to be converted to)
return value : int
"""
summation=0
while n >= k :
summation = summation + n%k
n=n//k
print(n)
return (summation + n) |
93e375e270504890db29cc68dec14ff88053d16e | usamah13/Python-games- | /CMPUT 175/parcheck.py | 1,006 | 3.90625 | 4 | from Stack import Stack
#an example of abstraction
def parcheck(symbolString):
index = 0
aStack = Stack()
balanced = True
open_brackets = ['(','[','{']
while index < len(symbolString) and balanced:
if symbolString[index] in open_brackets:
aStack.push(symbolString)
else:
if not aStack.isEmpty():
balanced = False
else:
top = aStack.pop()
result = match(top, symbolString[index])
if result == False:
balanced = False
index = index +1
if aStack.isEmpty() and balanced:
return True
else:
return False
def match(open_symbol,close_symbol):
open_brackets ='({['
close_brackets = ')}]'
if open_brackets.index(open_symbol) == close_brackets.index(close_symbol):
return True
else:
return False
def main():
expression = input('enter expression >')
print(parcheck(expression))
main()
|
8344bbf55bab18d971ccc068e453a99cbbe7cb0b | DuongTuan3008/duongquoctuan-fundamentals-c4e26 | /lab1/crawl_data.py | 897 | 3.515625 | 4 | #1. Creat connection
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pyexcel
url = "https://dantri.com.vn"
conn = urlopen(url)
#2. Download content
raw_data= conn.read()
page_content = raw_data.decode("utf8")
with open("dantri.html","wb") as f:
f.write(raw_data)
# # print(page_content)
# #3. Find ROI
# soup = BeautifulSoup(page_content,"html.parser")
# # print(soup.prettify())
# ul = soup.find("ul","ul1 ulnew")
# #4. Extract ROI
# li_list = ul.find_all("li")
# new_list = []
# for li in li_list:
# # li= li_list[0]
# h4= li.h4
# a = h4.a
# link =url + a["href"]
# title = a.string
# news = {
# "link":link,
# "title": title
# }
# new_list.append(news)
# print(title)
# print(link)
# pyexcel.save_as(records=new_list, dest_file_name="namth3.xlsx")
# print(h4)
# print(li)
# print(ul.prettify())
#5. Save |
33fd170874d95a599842f18f35e2cba1e5a08cdb | SaFed23/helper | /3/2.py | 239 | 3.921875 | 4 | arr_of_days = ["Среда", "Четверг", "Пятница", "Суббота", "Воскресенье", "Понедельник", "Вторник"]
number = int(input("Введите чило: "))
print(arr_of_days[(number % 7) - 1])
|
3a47db15df8b70c5f810a1022d7637ae5b8b8182 | cademccu/cs152 | /programs/A10.py | 3,035 | 4.3125 | 4 | # Your program should count the number of word occurrences contained in a file and
# output a table showing the top 20 frequently used words in decreasing order of use.
def extract_words(string):
"""
Returns a list containing each word in the string, ignoring punctuation, numbers, etc.
DO NOT CHANGE THIS CODE
"""
l = []
word = ''
for c in string+' ':
if c.isalpha():
word += c
else:
if word != '':
l.append(word.lower())
word = ''
return l
def count_words(filename):
"""Returns a dictionary containing the number of occurrences of each word in the file."""
# create a dictionary
my_dict = {}
with open(filename, 'r') as f:
text = f.read()
''' fine, I have to use his method
_words = text.split()
# remove not alpha num bs
# not gonna use anything fancy
words = []
for s in _words:
w = ""
for char in s:
if char.isalpha():
w += char
words.append(w.lower())
'''
words = extract_words(text)
for word in words:
if word in my_dict:
my_dict[word] += 1
else:
my_dict[word] = 1
# open the file and read the text
# extract each word in the file
# count the number of times each word occurs.
# return the dictionary with the word count.
return my_dict
def report_distribution(count):
"""Creates a string report of the top 20 word occurrences in the dictionary."""
# create a list containing tuples of count and word,
# while summing the total number of word occurrences
num = 0
tup_list = []
for key, value in count.items():
num += int(value)
tup_list.append((value, key))
# make me use string formatting smh im gonna use lambas i don't care what we have learned
#tup_list.sort(key = lambda t: t[0], reverse = True)
tup_list.sort(reverse = True)
s_list = []
s_list.append("{:>5}".format(num))
max = 20
for tup in tup_list:
if max == 0:
break
else:
max -= 1
s_list.append("{:>5}".format(tup[0]) + " " + tup[1])
format_string = "count word\n"
for i in s_list:
format_string = format_string + i + "\n"
# remove last new line im too lazy to do it right in the for-loop
#format_string = format_string[:-1]
# add lines with the title and total word count to the output string
# sort the list from largest number to smallest,
# add a line to the output for each word in the top 20 containing count and word
# return the string containing the report
return format_string
def main():
"""
Prints a report with the word count for a file.
DO NOT CHANGE THIS CODE
"""
filename = input('filename?\n')
print(report_distribution(count_words(filename)))
if __name__ == '__main__':
main()
|
1dad3b765ae627f18d43a233e6e15faafcd8e41d | Varsha1230/python-programs | /ch7_loops.py/ch7_prob_04.py | 273 | 4.15625 | 4 | num = int(input("please enter a number of which you want to check whether it is prime or not: "))
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
break
if prime:
print("This no. is prime")
else:
print("This no. is not prime") |
27e7bbc22cdc282b500d85bc0e2ef12f3b8fec7d | Zarwlad/coursera_python_hse | /week5/task14.py | 174 | 3.65625 | 4 | string = str(input())
s = string.split()
evens = []
for sas in s:
sas = int(sas)
if sas % 2 == 0:
evens.append(sas)
for e in evens:
print(e, end=" ")
|
ed92a77ef364c98353312cbc9279bce4b828c52c | Awesome94/Algorithms | /insertion_Sort.py | 422 | 4.25 | 4 | def insertion_sort(nums):
for i in range(len(nums)):
j = 1
while j>0 and nums[j-1] > nums[j]:
swap(nums, j, j-1)
j = j-1
return nums
def swap(nums, i, j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
if __name__ == "__main__":
nums = [1,5,3,2,429,12,4]
print(insertion_sort(nums))
# disadvantage is that we have to make alot of swap operations.
|
6cee67f5b3a578a7c8e8126f033f61321d5445c4 | klhoab/leetcode | /python/array and string/reverse-string.py | 313 | 3.75 | 4 | #https://leetcode.com/problems/reverse-string/
class Solution:
def reverseString(self, s: List[str], i = 0) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if i < len(s) //2:
s[i], s[-i-1] = s[-i-1], s[i]
self.reverseString(s, i+1) |
7e2102d40c76b12d2e592cb842e4024fad88d179 | 2226171237/Algorithmpractice | /chapter02_stack_queue_hash/t2.5.py | 2,004 | 4.125 | 4 | #-*-coding=utf-8-*-
'''
如何用O(1)的时间复杂度求栈中最小的元素
'''
class LNode:
def __init__(self, x, next=None):
self._data = x
self.next = next
class MyStack:
def __init__(self):
self.head = None # 栈顶
self._length = 0
def is_empty(self):
return self.head is None
def push(self, x):
if self.is_empty():
self.head = LNode(x)
else:
tmp = self.head
self.head = LNode(x)
self.head.next = tmp
self._length += 1
def pop(self):
if self.is_empty():
return None
node = self.head
self.head = self.head.next
self._length -= 1
return node._data
def top(self):
if self.is_empty():
return None
return self.head._data
def length(self):
return self._length
# 方法:使用两个栈,一个栈村原始数据,另一个栈村最小值
class Stack:
def __init__(self):
self.stack=MyStack()
self.min_stack=MyStack() # 栈低存放当前栈的最小值
def is_empty(self):
return self.stack.is_empty()
def push(self,x):
if self.is_empty():
self.min_stack.push(x)
else:
min=self.min_stack.top()
if min>x:
self.min_stack.push(x)
else:
self.min_stack.push(min)
self.stack.push(x)
def pop(self):
self.min_stack.pop()
return self.stack.pop()
def size(self):
return self.stack.length()
def getMin(self):
if self.is_empty():
return
else:
return self.min_stack.top()
if __name__ == '__main__':
S=Stack()
for x in [9,4,3,2,3,10]:
S.push(x)
print(S.getMin())
S.pop()
print(S.getMin())
S.pop()
print(S.getMin())
S.pop()
print(S.getMin())
S.pop()
print(S.getMin())
S.pop()
print(S.getMin()) |
4b275a04c0313edf4b5831eb4a2fc7593a504643 | sudiq/leetcode | /search-a-2d-matrix-ii.py | 1,168 | 4.03125 | 4 | # https://leetcode.com/problems/search-a-2d-matrix-ii/
# Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:
# Integers in each row are sorted in ascending from left to right.
# Integers in each column are sorted in ascending from top to bottom.
# Example 1:
# Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
# Output: true
# Example 2:
# Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
# Output: false
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
l, r = 0, len(matrix[0])-1
def binary_search(arr,l=0,r=r):
c = (l+r)//2
if l>r:
return False
if arr[c] == target:
return True
elif arr[c]> target:
return binary_search(arr,l,c-1)
else:
return binary_search(arr,c+1,r)
for arr in matrix:
if binary_search(arr):
return True
return False |
9691a7fea3fa65ab4d5c2fe7744824d762a8dbc4 | SilverWin/HackerRankPython | /set_intersection_operation.py | 287 | 3.734375 | 4 | #!/usr/bin/env python
"""Solution for: https://www.hackerrank.com/challenges/py-set-intersection-operation/problem"""
__author__ = "Filip Jankowski"
n = int(input())
ns = set(input().split(" "))
b = int(input())
bs = set(input().split(" "))
com = ns.intersection(bs).__len__()
print(str(com)) |
5b11dea2e0a90cea12dbe5a4440b6b2e33065eb3 | rodrigograca31/Sprint-Challenge--Hash | /hashtables/ex4/ex4.py | 437 | 4.125 | 4 | def has_negatives(a):
"""
YOUR CODE HERE
"""
hashtable = {}
result = []
for index, number in enumerate(a):
# opposite = -number
if -number in hashtable:
result.append(abs(number))
hashtable[number] = number
return result
if __name__ == "__main__":
# print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
# print()
print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
|
9851c88515b9638af79a1e5b99486f4240a975de | willmead/intro_to_python | /src/Day1/rocket_builder.py | 768 | 3.734375 | 4 | """
Rocket Builder
Author: Will M
Date: 18.06.20
Use variables to store information about a new rocket.
"""
height = 60
width = 10
weight = 1000
power = 10
name = "Explorer"
destination = "Jupiter"
material = "Metal"
fuel = "Hydrogen"
is_manned = False
has_experiments = True
will_return = False
is_due = True
print(f"Height: {height}m")
print(f"Width: {width}m")
print(f"Weight: {weight}kg")
print(f"Power: {power} / 10")
print()
print(f"Name: {name}")
print(f"Destination: {destination}")
print(f"Material: {material}")
print(f"Fuel: {fuel}")
print()
print(f"Is the ship manned? {is_manned}")
print(f"Does the ship contain experiments? {has_experiments}")
print(f"Will the ship return to earth? {will_return}")
print(f"Is the ship due to launch? {is_due}")
|
0652c2cdda9e7eab1566b0ba04ba24b1dd42a1ba | CAdummyaccount/fishtank | /project2.py | 1,929 | 4.0625 | 4 |
#change initial tank size input
#change calculations to look up contents of dictionary
#add calculations for water change amounts
#add round function to Alkalinity "needs" to prevent floats
#find a way to add a dictionary, while & for loops
print ("please enter length")
L=input()
print ("please enter width")
W=input()
print ("please enter height")
H=input()
litres=round((int(L)*int(W)*int(H)/276)*4.454)
print (str(litres) + " Litres")
ideal_C = 425
ideal_M = 1350
ideal_Al = 8.5
# print ("Ammonia")
# A=int(input())
# if A>0:
# print ("-Perform a water change-")
# if A==0: print ("-All Well-")
# print ("NitrItes")
# nI=int(input())
# if nI>0:
# print ("-Perform a water change-")
# if nI==0: print ("-All Well-")
# print ("NitrAtes")
# nA=int(input())
# if nA>20:
# print ("-Perform a water change-")
# if nA in range (0,21):
# print ("-All Well-")
# print ("Phosphate")
# P=float(input())
# if P>0.03:
# print ("-Perform a water change-")
# if P>0 and P<0.029: print ("-All Well-")
# print ("Calcium")
# C=int(input())
# if C>430:
# print ("-Perform a water change-")
# elif C<420:
# diff_C = ideal_C - C
# print ("-Dose Calcium- (needs {})".format(diff_C))
# print ("Dose " + str(round(0.0074*litres*diff_C)) + " ml's")
# else:
# print ("-All Well-")
# print ("Magnesium")
# M=int(input())
# if M>1360:
# print ("-Perform a water change-")
# elif C<1340:
# diff_M = ideal_M - M
# print ("-Dose Magnesium- (needs {})".format(diff_M))
# print ("Dose " + str(round(0.017*litres*diff_M)) + " ml's")
# else:
# print ("-All Well-")
print ("Alkalinity")
Al=float(input())
if Al>d["Alkalinity"][1]
print ("-Perform a water change-")
elif Al<d["Alkalinity"][0]
diff_Al = ideal_Al - Al
print ("-Dose Alkalinity- (needs {})".format(diff_Al))
print ("Dose " + str(round(0.38*litres*diff_Al)) + "ml's")
else:
print ("-All Well-") |
c82de7ba37660963b0b29d9112a9d5af5e3ece68 | TaoCurry/Basic_Python3 | /递归例子/递归表示Fibo.py | 244 | 3.765625 | 4 | def fibo(n):
if n < 1:
print('输入有误')
return -1
elif n ==1 or n ==2:
return 1
else:
return fibo(n-1) + fibo(n-2)
result = fibo(35)
if result != -1:
print('一共有%d小兔崽子'% result)
|
5d8481aa452e1d923f9fa5fe5100a35237969fc2 | hugovk/twitter-tools | /bot_authorise.py | 1,512 | 3.640625 | 4 | #!/usr/bin/env python
"""
Authorise a Twitter bot account against a Twitter bot application.
It works by giving you a URL to authorise with, you paste that into a browser
that's logged in as the given (bot) user. You'll get a PIN back, which the app
is now waiting for -- from there you get your access key and secret.
Based on beaugunderson's:
https://gist.github.com/moonmilk/035917e668872013c1bd#gistcomment-1333900
"""
import argparse
import tweepy
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Authorise a Twitter account against an app.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("consumer_key", help="From your app settings page")
parser.add_argument("consumer_secret", help="From your app settings page")
args = parser.parse_args()
auth = tweepy.OAuthHandler(args.consumer_key, args.consumer_secret)
auth.secure = True
auth_url = auth.get_authorization_url()
print()
print(
"Please open this URL in a browser that's logged in as your bot,\n"
"authorise the application, and then type in the PIN back here."
)
print()
print(auth_url)
verifier = input("PIN: ").strip()
auth.get_access_token(verifier)
print()
print("consumer_key: " + args.consumer_key)
print("consumer_secret: " + args.consumer_secret)
print("access_token: " + auth.access_token)
print("access_token_secret: " + auth.access_token_secret)
# End of file
|
97e031dea3086caae21ec15114a5a39caa46a413 | neumann-mlucas/belousov-zhabotinsky | /belousov_zhabotinsky/render.py | 6,742 | 3.515625 | 4 | #!/usr/bin/python
import curses
import argparse
from .functions import *
def parse_args():
COEFFICIENTS = (1.0, 1.0, 1.0)
COLORS = np.random.choice(6, 10) + 1 # valid range is 1-7
ASCIIS = list(map(lambda x: " .:?!@~¨*&+"[x], np.random.choice(10, 10)))
# ASCIIS = (" ", ".", " ", ":", "*", "*", "#", "#", "@", "@")
# COLORS = (1, 1, 2, 2, 2, 3, 3, 3, 7, 1)
# COLORS = (1, 2, 3, 4, 1, 2, 3, 4, 1, 2)
# ASCIIS = list(map(str, range(10)))
parser = argparse.ArgumentParser(
prog="belousov-zhabotinsky",
description="""The python package you never knew you needed! Now you
can appreciate all the glory of the Belousov-Zhabotinsky reaction from
the comfort of your console window with a state of the art ASCII art
rendering. Your life will never be the same!""",
epilog="""You can exit
the program by pressing any key, but using the Ctrl key can cause the
terminal to bug. For bug report or more information:
https://github.com/neumann-mlucas/belousov-zhabotinsky""",
)
parser.add_argument(
"-a",
"--asciis",
action="store",
default=ASCIIS,
nargs=10,
help="""10 ASCII characters to be use in the rendering. Each point in
the screen has a value between 0 and 1, and each ASCII character used
as an input represents a range of values (e.g. 0.0-0.1, 0.1-0.2 etc)""",
)
parser.add_argument(
"-b",
"--background",
action="store",
default=0,
type=int,
help="""Background color [int 0-7]. 0:black, 1:red, 2:green, 3:yellow,
4:blue, 5:magenta, 6:cyan, and 7:white""",
)
parser.add_argument(
"-c",
"--colors",
action="store",
default=COLORS,
nargs=10,
type=int,
help="""10 numbers in the [0-7] range for mapping colors to the ASCII
characters. 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta,
6:cyan, and 7:white""",
)
parser.add_argument(
"-coef",
"--coefficients",
action="store",
default=COEFFICIENTS,
nargs=3,
type=float,
help="""Values for alpha, beta and gamma -- changes the reaction's
behavior. Default is alpha=1.0, beta=1.0, gamma=1.0""",
)
parser.add_argument(
"-s",
"--symmetry",
action="store",
default=1,
type=int,
help="""Symmetric mode, generates a n-fold symmetric grid""",
)
parser.add_argument(
"-ch",
"--cahn-hillard",
action="store_true",
default=False,
help="""Use the Cahn-Hillard equations""",
)
parser.add_argument(
"-gs",
"--gray-scott",
action="store_true",
default=False,
help="""Use the Gray-Scott equations""",
)
parser.add_argument(
"-p",
"--add-perturbation",
action="store_true",
default=False,
help="""Add a perturbation to the uncial grid""",
)
parser.add_argument(
"-fn",
"--fitzhugh-nagumo",
action="store_true",
default=False,
help="""Use the FitzHugh-Nagumo equations (Turing patterns)""",
)
parser.add_argument(
"-vc",
"--variable-coefficients",
action="store_true",
default=False,
help="""Make coefficients variable within the grid [TESTING]""",
)
args = parser.parse_args()
# I NEED TO THINK IN A BETTER WAY OF DOING THIS
if args.fitzhugh_nagumo:
args.update_grid = update_fn
args.dim = 2
args.step_size = 10
if args.coefficients == COEFFICIENTS:
args.coefficients = (-0.005, 10)
elif args.cahn_hillard:
args.update_grid = update_ch
args.dim = 1
args.step_size = 50
if args.coefficients == COEFFICIENTS:
args.coefficients = (0.05,)
elif args.gray_scott:
args.update_grid = update_gs
args.dim = 2
args.step_size = 50
args.add_perturbation = True
if args.coefficients == COEFFICIENTS:
args.coefficients = (0.0374, 0.0584)
else:
args.update_grid = update_bz
args.dim = 3
args.step_size = 1
args.coefficients = args.coefficients[: args.dim]
return args
def init_screen(args):
""" Set ncurses screen and returns the screen object """
screen = curses.initscr()
curses.curs_set(0)
curses.start_color()
curses.init_pair(1, 1, args.background)
curses.init_pair(2, 2, args.background)
curses.init_pair(3, 3, args.background)
curses.init_pair(4, 4, args.background)
curses.init_pair(5, 5, args.background)
curses.init_pair(6, 6, args.background)
curses.init_pair(7, 7, args.background)
screen.clear()
return screen
def render(args):
""" Initializes grid then update and render it ad infinitum """
# Local variables are faster than objects attributes
asciis = args.asciis
colors = args.colors
coefficients = args.coefficients
step_size = args.step_size
update_grid = args.update_grid
# Initialize screen and grid
screen = init_screen(args)
height, width = screen.getmaxyx()
size = (args.dim, height, width)
grid = init_grid(size, args.symmetry)
if args.variable_coefficients:
coefficients = variable_coefficients(coefficients, size)
if args.add_perturbation:
grid = add_perturbation(grid, size)
# Error on addstr(height, width)
grid_idxs = [(i, j) for i in range(height) for j in range(width)]
grid_idxs.pop()
while True:
# Update grid (some equations are 'slower' than others)
for _ in range(step_size):
grid = update_grid(grid, size, coefficients)
# Update screen
for line, column in grid_idxs:
# Array values are floats, indexes are ints
idx = int(grid[0, line, column] * 10)
# Get current char and calculate new char
now_char = screen.inch(line, column) | curses.A_CHARTEXT
new_char = asciis[idx]
# Update only if char has changed
if now_char != new_char:
new_color = curses.color_pair(colors[idx]) | curses.A_BOLD
screen.addstr(
line, column, new_char, new_color,
)
else:
continue
screen.refresh()
screen.timeout(25)
# Ends rendering
if screen.getch() != -1:
curses.endwin()
break
def main():
args = parse_args()
render(args)
if __name__ == "__main__":
main()
|
c9b50baf2b37e1b2be26bd22227f51d084b2ce5e | hojin-shin/AnalyticswithPython | /analytics/chap1.py | 1,121 | 3.84375 | 4 | #!/usr/bin/env python3
'''
Foundation for analytics with Python
Lesson1))
'''
string1 = "My deliverable is due in May"
string1_list1 = string1.split()
string1_list2 = string1.split(" ", 2)
print("Output #21 : {0}".format(string1_list1))
print("Output #22 : FIRST PIECE : {0} SECOND PIECE : {1} THIRD PIECE :{2}"\
.format(string1_list2[0], string1_list2[1], string1_list2[2]))
string2= "Your, deliverable,is,due,in,June"
string2_list = string2.split(',')
print("Output #23 : {0}".format(string2_list))
print("Output #24 : {0} {1} {2}".format(string2_list[1], string2_list[5], string2_list[-1]))
print("Output #25 : {0}".format(','.join(string2_list)))
string3 = " Remove unwanted characters from this string.\t\t \n"
print("output #26 : string3 : {0:s}".format(string3))
string3_lstrip = string3.lstrip()
print("Output #27 : lstrip : {0:s}".format(string3_lstrip))
string3_rstrip = string3.rstrip()
print("Output #28 : rstrip : {0:s}".format(string3_rstrip))
string3_strip = string3.strip()
print("Output #29 : strip : {0:s}".format(string3_strip))
|
5b4c25340d1f97fefc18550f617ea44997cfd568 | daniel-reich/ubiquitous-fiesta | /YSJjPdkwrhQCfnkcZ_24.py | 117 | 3.890625 | 4 |
def repeat_string(txt, n):
x=str(txt)*n
if type(txt) is str:
return x
else:
return "Not A String !!"
|
f8ffc08448fc769fbf237ae0f72bc5bf7880ddcd | MysteriousSonOfGod/python-workshop-demos-june-27 | /src/loops.py | 445 | 3.890625 | 4 |
numbers = [2, 3, 5, 7, 11, 13]
for n in numbers:
print(n)
print(n*n)
print()
# greeting = input("Say something: ")
#
# while greeting != "bye":
# print("You said " + greeting)
# greeting = input("Say something: ")
while True:
greeting = input("Say something: ")
if greeting == 'shh':
continue
print("You said " + greeting)
if greeting.lower().strip() == 'bye':
break
print("Good bye")
|
5a4af2c9fe869252b7c7a0978f45a8e1d18d95ff | Angie-0901/AngieDeLaCruzRamos-AlvaroRojasOliva | /verificador16.py | 618 | 3.96875 | 4 | print("EJERCICIO N°16")
#Este programa calculara la energia cinetica de un X cuerpo
#INPUT
masa=float(input("la masa es: "))
velocidad_1=float(input("la velocidad 1 es: "))
velocidad_2=float(input("la velicidad 2 es:"))
#PROCESSING
Ec= (masa*velocidad_1 * velocidad_2)/2
#VERIFICADOR
Ec_verificado =(Ec >= 200)
#OUTPUT
print("La masa de la energia es: " + str(masa))
print("La velocidad 1 es: " + str(velocidad_1))
print("la velocidad 2 es: " + str(velocidad_2))
print("La energia cinetica es: " + str(Ec))
print("La energia cinetica hallada es mayor o igual que 200?: " + str(Ec_verificado))
|
b504e13544af2c59f60b8c473d3afd1c5a2144c3 | malaikact/Number-Guessing-Game- | /guessing_game.py | 1,689 | 3.953125 | 4 | import random
def start_game():
scores = [100]
name = input("Hi there \U0001F44B, welcome to the Number Guessing Game! \U0001F3AE What is your name? ")
print("The highscore is {}, let's see if you can beat it.".format(min(scores)))
print("Let's get started {}!".format(name))
number = random.randint(1,10)
guess = guess_again(0)
attempts = 1
while guess != number:
if guess > 10 or guess < 1:
print("Oops! That number is not within the range. Try again")
guess = guess_again(guess)
elif guess > number:
print("It's lower")
attempts +=1
guess = guess_again(guess)
else:
print("It's higher")
attempts +=1
guess = guess_again(guess)
scores.append(attempts)
highscore = min(scores)
print("Got it!")
print("Congratulations {}, \U0001F389 you have guessed the correct number! It only took you {} attempts and your highscore is now {}. Way to go smarty pants! The game is now over.".format(name, attempts, highscore))
play_again = input("Would you like to play again? (Yes/No)")
if play_again.lower() == "yes":
start_game()
elif play_again.lower() == "no":
print("Thanks for playing with us {}. See you next time!".format(name))
def guess_again(guess):
while True:
try:
guess = int(input("Pick a random number from 1 to 10: "))
break
except ValueError:
print("Oops! You need to type in the numerical value of any number from 1 to 10. Try again")
continue
return guess
start_game() |
76f8ac4d0c14217cc3a60754784c47d35db09a7b | Mrzhaohan/python-one | /lei/neisuanfuchongzu.py | 474 | 3.828125 | 4 | class list_new():
def __init__(self,*agrs):
self.__mylist=[i for i in agrs]
def __add__(self,x):
return [i+x for i in self.__mylist]
def __sub__(self,x):
return [i-x for i in self.__mylist]
def __mul__(self,x):
return [i*x for i in self.__mylist]
def __div__(self,x):
return [i/x for i in self.__mylist]
def show(self):
print(self.__mylist)
l=list_new(1,2,3,4,5,6)
l.show()
print(l+7)
|
83a9dd7a55b62c372938197d276eac77abb17702 | wanqiangliu/python | /parrot.py | 121 | 3.578125 | 4 | #input学习,编写交互式程序
message = input("Tell me somthing,and I will repeat it back to you:")
print(message) |
a993451a2c693d20231689c5c95b5a96240d0580 | duongnt52/ngotungduong-fundamentals-c4e25 | /Fundamentals/Session1/age_cale.py | 72 | 3.5 | 4 | yob = int(input("Your year of birth? "))
print("Your age: ", 2018 - yob) |
292e7b9b70e41bf9d878b8d2b635c4cfc979ccbf | kirigaikabuto/Python19Lessons | /lesson23/1.py | 338 | 3.515625 | 4 | from cat import Cat
from dog import Dog
cat1 = Cat(name="cat1", age=10)
cat2 = Cat(name="cat2", age=12)
cat3 = Cat(name="cat3", age=1)
cat4 = Cat(name="cat4", age=13)
cats = [cat1, cat2, cat3, cat4]
maxi = cats[0].age
maxi_cat = cats[0]
for i in cats:
if i.age > maxi:
maxi = i.age
maxi_cat = i
maxi_cat.printData()
|
31b0f58fff7b31d0c2c0036f101cc82b279feccb | abi-oluwade/engineering-48-open-close-improved | /test_unittest_simple_calc.py | 732 | 3.640625 | 4 | import unittest # unittest is a LIBRARY
from simple_calc import SimpleCalc # we do not currently have this {file} or this {class}.
class Calctest(unittest.TestCase):
calc = SimpleCalc()
def test_add(self):
self.assertEqual(self.calc.add(2, 4), 6)
self.assertEqual(self.calc.add(4, 4), 8)
def test_subtract(self):
self.assertEqual(self.calc.subtract(2, 4), -2)
self.assertEqual(self.calc.subtract(10, 5), 5)
def test_multiply(self):
self.assertEqual(self.calc.multiply(2, 3, ), 6)
self.assertEqual(self.calc.multiply(10, 8, ), 80)
def test_divide(self):
self.assertEqual(self.calc.divide(8, 4), 2)
self.assertEqual(self.calc.divide(16, 8), 2)
|
78717c6e3930f1e65eec08d5f13d3ea5f2797986 | websvey1/TIL | /algorithm/algorithm_week/week5/problem_2(준석).py | 1,427 | 3.765625 | 4 | import sys
sys.stdin = open("problem_2.txt")
def iswall(x, y, n):
if x < 0 or x >= n: return True
if y < 0 or y >= n: return True
return False
def start(x):
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == 2:
return [i, j]
def finder(x, y):
global miro, result, cnt
if miro[x][y] == 3:
result = 1
miro[x][y] = 1
visited.append([x, y])
cnt = 0
T = int(input())
for n in range(1, T+1):
N = int(input())
miro = [list(map(int, input())) for i in range(N)]
visited = [start(miro)]
result = 0
while len(visited) != 0:
cnt = 0
while cnt != 1:
cnt += 1
x = visited[-1][0]
y = visited[-1][1]
if (not iswall(x+1, y, N)) and (miro[x+1][y] == 0 or miro[x+1][y] == 3):
x = x + 1
finder(x, y)
elif (not iswall(x, y-1, N)) and (miro[x][y-1] == 0 or miro[x][y-1] == 3):
y = y - 1
finder(x, y)
elif (not iswall(x, y+1, N)) and (miro[x][y+1] == 0 or miro[x][y+1] == 3):
y = y + 1
finder(x, y)
elif (not iswall(x-1, y, N)) and (miro[x-1][y] == 0 or miro[x-1][y] == 3):
x = x - 1
finder(x, y)
if result == 1:
break
visited.pop()
print(f'#{n} {result}')
|
ed98a735591c71d72997fe2047f6274a8d9ac9c1 | thanh-falis/Python | /bai__75+76+77+78+79+80+81+82/PhuongThucThuongDung/Sort.py | 438 | 3.796875 | 4 | """Python hỗ trợ hàm sort để sắp xếp list"""
from random import randrange
lst = [0]*10
for i in range(len(lst)):
lst[i] = randrange(100)
print(lst)
lst.sort()
print(lst)
print("*"*20)
lst = [4, 2, 10, 8]
print(lst)
#sorted ko làm thay đổi bản chất của chuỗi
lst1 = sorted(lst)
print(lst1)
print(lst)
print("*"*20)
# Sắp xếp giản dần
lst = [2, 3, 8, 10]
print(lst)
lst.sort(reverse=True)
print(lst)
|
d552099536526c6cc26c85fabd10da818b69ef48 | osmium18452/dmt-fig | /histogram.py | 452 | 3.578125 | 4 | import matplotlib.pyplot as pyplot
import numpy as np
def calHistogram(img):
if len(img.shape) != 2:
print("wrong image size")
return None
histogram=np.zeros(256)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
histogram[img[i][j]] += 1
return histogram
def drawHistoGram(histogram):
pyplot.figure()
pyplot.axis([0, 256, 0, max(histogram)])
pyplot.grid(True)
x=np.arange(0,256,1)
pyplot.bar(x,histogram)
pyplot.show()
|
48b234f98df84f1725c47d2f07b9b84535d95031 | CameronHG/PythonProject | /CameronHG_1_3_6.py | 496 | 3.65625 | 4 | import random
#a = (6, 7, 9)
some_values = ('a', 'b', 3)
#print(some_values[0:2])
a = 10
tup = (9, a, 11)
print(tup[1] == 10)
print(tup[1])
values = [1, 2, 3]
print(values[1:])
values2 = ['a','b','c']
values2[2] = '3'
print(values[2] == 3)
values += [4, 5]
print(values)
values.append([6,7])
print(values)
a = 6
a *= 3
print(a)
def roll_two_dice():
dieOne = random.randint(1, 6)
dieTwo = random.randint(1, 6)
dieSum = dieOne + dieTwo
print(dieSum)
roll_two_dice() |
a72c38f21869d4941b128f95219e3264e9d67bec | alisson-fs/POO-II | /Exercício VPL - Herança e Classes Abstratas/animal.py | 433 | 3.734375 | 4 | from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, tamanho_passo: int):
self.__tamanho_passo = tamanho_passo
@property
def tamanho_passo(self):
return self.__tamanho_passo
@tamanho_passo.setter
def tamanho_passo(self, tamanho_passo):
self.__tamanho_passo = tamanho_passo
def mover(self):
return 'ANIMAL: DESLOCOU '+str(self.__tamanho_passo)
@abstractmethod
def produzir_som(self):
pass
|
e3ab9b8724d2ef8726efb237fa197fe88c5d1099 | pandapranav2k20/Python-Programs | /Lab 5/ENGR102_504_23_bisection.py | 1,962 | 4.15625 | 4 | # By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do."
# "I have not given or received any unauthorized aid on this assignment."
#
# Names: Damon Tran
# Benson Nguyen
# Matt Knauth
# Pranav Veerubhotla
# Section: 504
# Assignment: lab 5-2
# Date: 23 Sept 2019
'''This program uses a binary search in order to find the roots of a cubic
function with coefficients a, b, c, and d'''
import math
#Take in the user input for the coefficients:
A = float(input("Please enter the value for the coeffcient a:"))
B = float(input("Please enter the value for the coeffcient b:"))
C = float(input("Please enter the value for the coeffcient c:"))
D = float(input("Please enter the value for the coeffcient d:"))
#Take in the user input for the bounds:
bound_low = float(input("Please enter the lower bound:"))
bound_high = float(input("Please enter the upper bound:"))
#Calculate the values of the slope of thecubic function at the lower and upper bounds
slope_lower = 3 * A*bound_low**2 + 2 * B*bound_low**1 + C
slope_upper = 3 * A*bound_high**2 + 2 * B*bound_high**1 + C
#Calculate the values at the lower and upper bounds
interval = bound_high - bound_low
while interval > 10**(-6):
value_lower = (A *((bound_low)**3)) + (B *((bound_low)**2)) + (C * bound_low) + D
value_upper = (A *((bound_high)**3)) + (B *((bound_high)**2)) + (C * bound_high) + D
if (value_lower < 0 or value_upper < 0) and (value_lower > 0 or value_upper > 0):
p = (bound_low + bound_high) / 2
#Calculate f(p)
value_p = A *p**3 + B *p**2 + C *p**1 + D
#Determine whether f(p) is negative, positive, or the solution
if value_p == 0:
finalSolution = p
elif value_p < 0:
bound_low = p
elif value_p > 0:
bound_high = p
interval = bound_high - bound_low
print(finalSolution) |
97575b0b14abe6c020188b640500683c53e39a05 | dahyeeeon/Python | /Hello/test/Step15_random.py | 854 | 3.578125 | 4 | #-*-coding:utf-8 -*-
'''
random package 사용하기
'''
import random as ran #import 된 random의 별칭ㅂ여
ranNum=ran.random() #0이상 1미만의 무작위 실수
ranNum2=int(ran.random()*10) #0이상 10미만
ranNum3=int(ran.random()*10)+10 # 10이상 20미만
ranNum4=int(ran.random()*45)+1 # 1이상 45미만
#로또번호
nums=set() #로또번호를 담을 set객체
while True: #반복문 돌면서 무작위 로또 번호를 얻어냄
lottoNum=ran.randint(1,45)
#set에 추가(중복된건 안함)
nums.add(lottoNum)
#set에 번호 6개가 담기면 반복문 탈출
if len(nums)==6:
break
#set에 있는 숫자를 이용해서 list객체
lottoList=list(nums)
#오름차순 정렬
#내림차순 sort(reverse)
lottoList.sort()
#list 구조 확인
print lottoList
|
31ac06150e3850733cf2de74b6e70fa88c5819b9 | longfight123/17-CoffeeMachineProjectOOP | /oop-coffee-machine-start/main.py | 962 | 3.515625 | 4 | from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
coffee_maker_object = CoffeeMaker()
money_machine_object = MoneyMachine()
def make_a_drink():
a_menu_object = Menu()
print(a_menu_object.get_items())
user_drink = input('What would you like?')
if user_drink == 'report':
coffee_maker_object.report()
money_machine_object.report()
make_a_drink()
elif user_drink == 'off':
return
user_drink = a_menu_object.find_drink(user_drink)
if not user_drink:
make_a_drink()
if coffee_maker_object.is_resource_sufficient(user_drink):
print(f'Please make payment, the cost of your drink is {user_drink.cost}:')
if money_machine_object.make_payment(user_drink.cost):
coffee_maker_object.make_coffee(user_drink)
make_a_drink()
else:
make_a_drink()
make_a_drink()
make_a_drink()
|
2fcc42c9b1246db1cfdc17097385ad8cdd98ea85 | DongHyukShin93/BigData | /pandas/pandas03/Pandas03_03_ClassEx03_신동혁.py | 674 | 3.640625 | 4 | #Pandas03_03_ClassEx03_신동혁
class FourCal() :
def setdata(self, first, second) :
self.first = first
self.second = second
def sum(self) :
result = self.first + self.second
return result
def sub(self) :
result = self.first - self.second
return result
def mul(self) :
result = self.first * self.second
return result
def div(self) :
result = self.first / self.second
return result
a = FourCal()
a.setdata(6,3)
print("%d+%d = %d" %(a.first, a.second ,a.sum()))
print("%d-%d = %d" %(a.first, a.second ,a.sub()))
print("%d×%d = %d" %(a.first, a.second, a.mul()))
print("%d÷%d = %d" %(a.first, a.second, a.div())) |
bc55e21af2f1b4417a941c14f4519aae8e93a90b | chrislarabee/kivy-studio | /kivy-studio/scripts/new_app/lib.py | 1,904 | 3.515625 | 4 | from pathlib import Path
from kivyhelper import lib
def setup_kivy_app_py(app_name: str) -> str:
"""
Generates a file string for the *App python file in the root kivy
app.
Args:
app_name: A string, the name of the app.
Returns: A string, the python code to save to the App.py file.
"""
return (
"from kivy.app import App\n"
"from kivy.uix.boxlayout import BoxLayout\n\n\n"
"class AppFrame(BoxLayout):\n"
" pass\n\n\n"
f"class {app_name}App(App):\n"
" def build(self):\n"
" return AppFrame()\n\n\n"
"if __name__ == '__main__':\n"
f" {app_name}App().run()\n"
)
def setup_kivy_app_kv() -> str:
"""
Generates a file string for the *App kv file in the root kivy app.
Returns: A string, the kvlang code to save to the App.kv file.
"""
return (
"<AppFrame>:\n"
" orientation: 'vertical'\n"
)
def create_new_app(app_name: str, dir_: str):
"""
Convenience function for creating all the basic python and kv files
needed by kivy apps.
Args:
app_name: A string, the name of the kivy app.
dir_: A string, the path to the directory to create the new app
in.
Returns: None
"""
d = Path(dir_) if dir_ else Path.cwd()
lib.print_pycharm_bar()
print(f'[KIVYHELPER:new_app] Creating Kivy app {app_name} in {d}...')
app_dir = d.joinpath('game')
app_dir.mkdir(exist_ok=True)
print(f'-- Populating {app_dir}')
print(f'-- Creating {app_name}App.py...')
app_py = app_dir.joinpath(f'{app_name}App.py')
app_py.write_text(setup_kivy_app_py(app_name))
print(f'-- Creating {app_name}.kv...')
app_py = app_dir.joinpath(f'{app_name}.kv')
app_py.write_text(setup_kivy_app_kv())
print('-- App creation complete.')
lib.print_pycharm_bar()
|
cf59c7e17dfbb4d5abfc2cff7f4a0135c2cd17ed | cascam07/csf | /unique_column.py | 967 | 3.8125 | 4 | def unique_column_values(rows, column_name):
"""
Given a list of rows and the name of a column (a string), returns a set
containing all values in that column.
"""
result = set()
for poll in rows:
result.add(poll[column_name])
return result
poll_rows1 = [{"ID":1, "State":"WA", "Pollster":"A", "Date":"Jan 07 2010"},
{"ID":2, "State":"WA", "Pollster":"B", "Date":"Mar 21 2010"},
{"ID":3, "State":"WA", "Pollster":"A", "Date":"Jan 08 2010"},
{"ID":4, "State":"OR", "Pollster":"A", "Date":"Feb 10 2010"},
{"ID":5, "State":"WA", "Pollster":"B", "Date":"Feb 10 2010"},
{"ID":6, "State":"WA", "Pollster":"B", "Date":"Mar 22 2010"}]
answer1 = unique_column_values(poll_rows1, "ID")
answer2 = unique_column_values(poll_rows1, "State")
answer3 = unique_column_values(poll_rows1, "Pollster")
answer4 = unique_column_values(poll_rows1, "Date")
|
6aac6c9eea7524b25c751a7931e76a30dd2acc0f | mjnorona/codingDojo | /Python/python_fundamentals/typeList.py | 899 | 4.03125 | 4 |
def printList(list):
elType = type(list[0])
mixed = False
text = ""
sum = 0;
for i in range(0, len(list)):
if type(list[i]) is not elType:
mixed = True
if type(list[i]) is float or type(list[i]) is int:
sum += list[i]
elif type(list[i]) is str:
text += list[i] + " "
if mixed is True:
print "The array you entered is of mixed type"
print "String: " + text
print "Sum: " + str(sum)
else:
if elType is int:
print "The array you entered is of integer type"
print "Sum: " + str(sum)
elif elType is str:
print "The array you entered is of string type"
print "String: " + text
l = ['magical unicorns',19,'hello',98.98,'world']
printList(l)
k = [2,3,1,7,4,12]
printList(k)
j = ['magical','unicorns']
printList(j)
|
2ceafb364ae0863085962f5f4dcefc060de2c47a | SriVasudhaKilaru/Datascience-Projects | /LinearReg/linearReg.py | 1,418 | 3.9375 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the dataset
dataset = pd.read_csv('C://Users/Prani/Desktop/python/salary.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
#Taking care of missing data
"""from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN', strategy='mean', axis=0)
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.fit_transform(X[:, 1:3])"""
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
#Fitting simple linear regression to the training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#Predicting the test results
y_pred = regressor.predict(X_test)
#Visualising the Training set results
plt.scatter(X_train, y_train, color='red')
plt.plot(X_train, regressor.predict(X_train), color ='blue')
plt.xlabel('Years of exp')
plt.ylabel('salary')
plt.title('Salary Vs Exp')
plt.show()
#Visualising the Test set results
plt.scatter(X_test, y_test, color='red')
plt.plot(X_train, regressor.predict(X_train), color ='blue')
plt.xlabel('Years of exp')
plt.ylabel('salary')
plt.title('Salary Vs Exp')
plt.show() |
af69e62b41b7748153d31567b61260cedec5d73f | Z-App-Xpert/project0 | /test/loops1.py | 65 | 3.5 | 4 | names = ["Alice", "Bob", "Charlie"]
for x in names:
print(x)
|
9763beacdc255af2bfd6d1ddebfd98495e336cb7 | azarrias/udacity-nd256-problems | /src/min_operations.py | 1,772 | 4.375 | 4 | """
Min Operations
Starting from the number 0, find the minimum number of operations required to reach
a given positive target number. You can only use the following two operations:
1. Add 1
2. Double the number
Example:
1. For Target = 18, output = 6, because it takes at least 6 steps shown below to reach the target
start = 0
step 1 ==> 0 + 1 = 1
step 2 ==> 1 * 2 = 2 # or 1 + 1 = 2
step 3 ==> 2 * 2 = 4
step 4 ==> 4 * 2 = 8
step 5 ==> 8 + 1 = 9
step 6 ==> 9 * 2 = 18
2. For Target = 69, output = 9, because it takes at least 8 steps to reach 69 from 0 using the allowed operations
start = 0
step 1 ==> 0 + 1 = 1
step 2 ==> 1 + 1 = 2
step 3 ==> 2 * 2 = 4
step 4 ==> 4 * 2 = 8
step 5 ==> 8 * 2 = 16
step 6 ==> 16 + 1 = 17
step 7 ==> 17 * 2 = 34
step 8 ==> 34 * 2 = 68
step 9 ==> 68 + 1 = 69
"""
def min_operations(target):
"""
Return number of steps taken to reach a target number
input: target number (as an integer)
output: number of steps (as an integer)
"""
steps = 0
number = target
while number > 0:
if number % 2 == 0:
number /= 2
else:
number -= 1
steps += 1
return steps
def test_function(test_case):
target = test_case[0]
solution = test_case[1]
output = min_operations(target)
if output == solution:
print("Pass")
else:
print("Fail")
if __name__ == '__main__':
# Test 1
target = 18
solution = 6
test_case = [target, solution]
test_function(test_case)
# Test 2
target = 69
solution = 9
test_case = [target, solution]
test_function(test_case)
|
7d7e00ac11748cbff75e84f0b6fd87c8e6b1c816 | akuchlous/leetcode | /168.py | 672 | 3.5 | 4 | import pdb
import string
import string
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
allS = string.ascii_uppercase
# base 26
buf = ""
remainders = []
#pdb.set_trace()
while (n >0):
print ( " ", n)
remainders.insert(0, (n-1)%26)
n = (n-1)/26
print (remainders)
for r in remainders :
buf+=allS[r]
return buf
# for x in range(28):
# print (x,Solution().convertToTitle(x))
print (Solution().convertToTitle(26))
print (Solution().convertToTitle(27))
print (Solution().convertToTitle(500))
|
e29c67b7024824419a42abee383426187150c969 | royalbhati/ComputerVision | /smiledetector.py | 2,176 | 3.609375 | 4 | import cv2
#We need two classifiers one to detect frontal face and one to detect eye
face_clf=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile=cv2.CascadeClassifier('haarcascade_smile.xml')
# we define a detect function which takes a gray scale image to processs and a normal
# image to return after processing
def facedetect(gray,frame):
#for face we'll use the face classifier and a function which takes three
# arguments - image,scaling factor (by how much it scales image) and min neighbours to check
face=face_clf.detectMultiScale(gray,1.3,5)
# face will return a tuple of 4 things- x coordinate ,y coord
# width ,length of detected face
#we will iterate through the faces to draw rectange over detected images
for (x,y,w,h) in face:
#we use rectangle function to draw rectangle on detected faces
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
# to detect smiles we will scan inside the faces and to do that we need
# two regions of interest(roi) 1-for grascale 2- for original image
roi_gray=gray[y:y+h,x:x+w]
roi_color=frame[y:y+h,x:x+w]
# just like we did for face we do for smiles
smiles=smile.detectMultiScale(roi_gray,1.1,100)
for (x,y,w,h) in smiles:
cv2.rectangle(roi_color,(x,y),(x+w,y+h),(0,255,0),2)
return frame
#Now we need to initialize webcam to record video
video_cap=cv2.VideoCapture(0)# 0 for internal webcam,1 for external webcam
while True:# We repeat infinitely (until break):
_,frame=video_cap.read() # We get the last frame.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # We do some colour transformations.
canvas = facedetect(gray, frame) # We get the output of our detect function.
cv2.imshow('Video', canvas) # We display the outputs.
if cv2.waitKey(1) & 0xFF == ord('q'): # If we type on the keyboard:
break
video_cap.release() # We turn the webcam off.
cv2.destroyAllWindows() # We destroy all the windows inside which the images were displayed.
|
7482289d1dec29b72c75477a647089d168be1ed5 | dumin199101/PythonLearning | /python3/016闭包/001.py | 416 | 3.96875 | 4 | #coding=utf-8
#闭包:如果一个函数内部定义了一个函数,并且用到了外部函数的变量,那么这个内部函数可以称之为闭包!
#在未调用内部函数之前,外部函数的变量不会释放!!!
def test(num):
print("-----1------")
def test1(num2):
print("----2------")
print(num+num2)
print("------3-----")
return test1
a = test(100)
a(200) |
b304734735544e2c4050ba1df34c0d7f542b9576 | LouiGi9/pace_giver | /speed_and_pitch_change.py | 1,607 | 3.546875 | 4 | from pydub import AudioSegment
class PaceGiver:
def speed_change(sound, speed=1.0):
# This is a copy-paste of a solution posted by a stackoverflow user here:
# https://stackoverflow.com/questions/43408833/how-to-increase-decrease-playback-speed-on-wav-file
# This method alters the pitch as well as the speed.
# Ideally, it would be replaced with an algorithm which preserves the original pitch.
sound_with_altered_frame_rate = sound._spawn(sound.raw_data, overrides={
"frame_rate": int(sound.frame_rate * speed)
})
return sound_with_altered_frame_rate.set_frame_rate(sound.frame_rate)
def pace_giver(self, distance, time):
test_sound = AudioSegment.from_wav("musicfile.wav")
# As I add more songs to the library, I should consider using a tempo detection algorithm.
# For now, the song I am using for testing purposes was recorded with a tempo of 136 bpm.
song_bpm = 136
# The default step length is defined as one meter here. A future version could allow users
# to customize this.
runner_step = 1
running_distance = distance * 1000
running_steps_min = (running_distance / runner_step) / time
speed_change_factor = running_steps_min / song_bpm
sound = PaceGiver.speed_change(test_sound, float(speed_change_factor))
return sound
def main():
pg = PaceGiver()
test_run_song = pg.pace_giver(5, 25)
test_run_song.export("song.wav", format="wav")
if __name__ == "__main__":
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.