blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b579c70ca6c69a24d139b79eff4d35be6b3a3da5 | betty29/code-1 | /recipes/Python/573453_String_representatidict_sorted/recipe-573453.py | 662 | 3.5 | 4 | def genkvs(d, keys, joiner):
for key in keys:
yield '%s%s%s' % (key, joiner, d[key])
def dictjoin(_dict, joiner, sep):
keys = sorted(_dict.iterkeys())
return sep.join(genkvs(_dict, keys, joiner))
def test_dictjoin():
"""This test function can be used for testing dictjoin with py.test of
nosetests."""
def dictjointest(_dict, expected):
assert dictjoin(_dict, '=', '; ') == expected
yield dictjointest, {}, ''
yield dictjointest, dict(a=1), 'a=1'
yield dictjointest, dict(a=1, b=2), 'a=1; b=2'
if __name__ == '__main__':
# Simple demonstration
print dictjoin(dict(a=1, b=2, c=3, d=4), ' = ', '; ')
|
1354105660b167e33f7cbcc9205820b1609c6186 | AaronTengDeChuan/leetcode | /leetcode/45.JumpGameII_AC.py | 422 | 3.703125 | 4 | #!usr/bin/env python
#-*-coding:utf-8-*-
import sys
class Solution(object):
def jump(self, nums):
curMax = 0
curLen = 0
step = 0
for i in range(len(nums)):
if curLen < i:
step += 1
curLen = curMax
curMax = max(curMax, nums[i] + i)
return step
solution = Solution()
nums = [1,2,3,1,1,1,2,1,1,0]
print solution.jump(nums)
|
9a7c1a9ab6ffdcd61c57325721a31f2411660693 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2908/60759/258584.py | 143 | 3.5625 | 4 | n = int(input())
strSet = set()
for i in range(n):
item = ''.join(sorted(input())).strip()
strSet.add(item)
print(len(strSet), end='')
|
e4997f7c1dfbc920d3f254304b41e82273a6a428 | laoniule/pythoncrashcourse | /Chapter07/rollercoaster.py | 216 | 4.09375 | 4 | #!/usr/bin/python
height = input("How tall are you, in CM\n")
height = int(height)
if height > 170:
print("\nyou are enough tall to ride")
else:
print("\nYou will be able to ride when you're allite older")
|
dd3f38ce711633d336bfbbf76c9e07e558d221cf | rlavanya9/cracking-the-coding-interview | /recursion/quarters.py | 1,046 | 3.828125 | 4 | def count_money(n):
countHelper(n, "Quarter")
def countHelper(n, tyoe):
count = 0
sum = 0
if tyoe == "Quarter":
while n > count*25:
sum+= countHelper(n - count*25, "Dime")
elif tyoe == "Dime":
while n > count*10:
sum+=countHelper(n - count*10, "Nickel")
elif tyoe == "Nickel":
while n > count*5:
sum+=countHelper(n - count*5, "Penny")
elif tyoe == "Penny":
return 1
return sum
# def count_money(n):
# return count_helper(n, 'quarter')
# def count_helper(n, types):
# sum = 0
# count = 0
# if types == 'quarter':
# while n > count*25:
# sum += count_helper(n - count*25, 'dime')
# elif types == 'dime':
# while n > count*10:
# sum += count_helper(n - count*10, 'nickel')
# elif types == 'nickel':
# while n > count*5:
# sum += count_helper(n - count*5, 'penny')
# elif types == 'penny':
# return 1
# return sum
print(count_money(5)) |
4053912f6ba6448270f646efce7aadc02530c338 | FelSiq/statistics-related | /dist_sampling_and_related_stats/normal_sampling_box_muller.py | 2,346 | 3.796875 | 4 | """Samples from normal distribution using Box-Muller transformation.
The transformation is applied to the bivariate normal distribution.
"""
import typing as t
import numpy as np
def sample_normal(num_inst: int = 1,
loc: float = 0.0,
scale: float = 1.0,
random_state: t.Optional[int] = None) -> np.ndarray:
"""Sample ``num_inst`` instances from normal distribution.
Arguments
---------
num_inst : :obj:`int`
Number of samples to output.
loc : :obj:`float`
Mean of the normal distribution.
scale : :obj:`float`
Standard deviation (not the variance!) of the normal distribution.
random_state : :obj:`int`, optional
If not None, set numpy random seed before the first sampling.
Returns
-------
:obj:`np.ndarray`
Samples of the normal distribution with ``loc`` mean and ``scale``
standard deviation.
Notes
-----
Uses the Box-Muller bivariate transformation, which maps two samples
from the Uniform Distribution U(0, 1) into two samples of the Normal
Distribution N(0, 1).
"""
if random_state is not None:
np.random.seed(random_state)
remove_extra_inst = False
if num_inst % 2:
num_inst += 1
remove_extra_inst = True
uniform_samples = np.random.uniform(0, 1, size=(2, num_inst // 2))
aux_1 = np.sqrt(-2 * np.log(uniform_samples[0, :]))
aux_2 = 2 * np.pi * uniform_samples[1, :]
samples = np.concatenate((aux_1 * np.cos(aux_2), aux_1 * np.sin(aux_2)))
samples = loc + scale * samples
if remove_extra_inst:
return samples[1:]
return samples
def _test():
import matplotlib.pyplot as plt
import scipy.stats
plt.subplot(1, 2, 1)
vals = np.linspace(-4, 4, 100)
plt.plot(vals, scipy.stats.norm(loc=0, scale=1).pdf(vals))
samples = sample_normal(num_inst=1000, random_state=16)
plt.hist(samples, bins=64, density=True)
plt.title("N(0, 1)")
plt.subplot(1, 2, 2)
vals = np.linspace(-20, 20, 100)
plt.plot(vals, scipy.stats.norm(loc=6, scale=3).pdf(vals))
samples = sample_normal(loc=6, scale=3, num_inst=1000, random_state=32)
plt.hist(samples, bins=64, density=True)
plt.title("N(6, 3)")
plt.show()
if __name__ == "__main__":
_test()
|
42c1c96bb6f3d31508024329487787de13e64d5f | emastr/2D_Solar_System_Simulation | /plotData2.py | 1,746 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
def readData(filename):
print("Reading...")
file = open(filename + ".txt")
text = file.read()
file.close()
print("Evaluating...")
data = eval(text)
print("Done!")
return data
def plotAngles():
data = readData("angleTest")
plt.plot(data["Angles"], data["Distances"])
plt.show()
def plotTemps(save):
data = readData("TempData3")
mass = data["Masses"]
maxTs = data["Maxtemps"]
minTs = data["Mintemps"]
plt.xscale("log")
plt.plot(mass, [m*2.2E7 for m in mass], label = "Fitted function", color = "black", lw = .6)
plt.plot(mass, [m*(-.9E6) for m in mass], color = "black", lw = .6)
plt.scatter(mass, [T-maxTs[0] for T in maxTs], label = r"$\Delta T_{max}$", s = 6)
plt.scatter(mass, [T-minTs[0] for T in minTs], label = r"$\Delta T_{min}$", s = 6)
plt.title("Earth temperature")
plt.xlabel("Asteroid mass [MS]")
plt.ylabel("Final temperature [K]")
plt.legend()
plt.tight_layout()
if save:
plt.savefig("temps.png", dpi = 200)
plt.show()
plotTemps(True)
def plotEns():
data = readData("IntegratorData")
time = data["Time"]
Es1 = data["TotEns"][0]
Es2 = data["TotEns"][1]
Es3 = data["TotEns"][2]
plt.plot(time, Es1, label = "Euler")
plt.plot(time, Es2, label = "Euler-Cromer")
plt.plot(time, Es3, label = "Verlet")
plt.legend()
plt.xlim(.8, 1)
plt.ylim(-8, 0)
plt.title("Integrator comparison")
plt.xlabel("Time [years]")
plt.ylabel(r"Energy [$ M_s au^2 yrs^{-2}$]")
plt.tight_layout()
plt.savefig("integrators.png", dpi = 200)
plt.show() |
71f3c64e410dce1821fde4daedf027529983795a | nagask/leetcode-1 | /503 Next Greater Element II/sol.py | 970 | 3.671875 | 4 | """
Similar to next greater element I, we keep a stack containing the indexes of the items that haven't been assigned a successor yet.
The stack will contain a decreasing sequence, so the first item that is greater than the top of the stack is going to be the successor
of the top of the stack.
We have to traverse the array twice, in order to allow the latest element to get their successor too
O(N) time and space
"""
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
def find_successor(nums, stack, result):
for i in range(len(nums)):
while stack and nums[stack[-1]] < nums[i]:
predecessor_index = stack.pop()
result[predecessor_index] = nums[i]
stack.append(i)
result = [-1 for _ in nums]
stack = []
find_successor(nums, stack, result)
find_successor(nums, stack, result)
return result
|
a77f28d9ebce756667d18318897dbffe6b667991 | Vanditg/Leetcode | /Number_of_1_bits/EfficientSolution.py | 1,308 | 3.828125 | 4 | ##==================================
## Leetcode
## Student: Vandit Jyotindra Gajjar
## Year: 2020
## Problem: 191
## Problem Name: Number of 1 Bits
##===================================
#
#Write a function that takes an unsigned integer and return the number of '1' bits it has
#(also known as the Hamming weight).
#
#Example 1:
#
#Input: 00000000000000000000000000001011
#Output: 3
#Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
#Example 2:
#
#Input: 00000000000000000000000010000000
#Output: 1
#Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
#Example 3:
#
#Input: 11111111111111111111111111111101
#Output: 31
#Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
from collections import Counter as c #Import Counter module
class Solution:
def hammingWeight(self, n):
tmp = "{:032b}".format(n) #Initialize tmp and find binary representation
tmpCount = c(tmp) #Initialize tmpCount and use Counter for tmp
for key, val in tmpCount.items(): #Loop through tmpCount
if key == '1': #Condition-check: If we find '1' bit
return val #Return value for key == '1'
return 0 #Otherwise return 0
|
5c08fcc433079c5e2aca8b086c9625a7e3942245 | niujie/Python_Course_2020 | /code/P2/fibonacci_recursion.py | 325 | 4.46875 | 4 | def fibonacci_recursion(n):
"""calculate Fibonacci sequence using recursion"""
if n < 3: # n == 1 | n == 2
return 1
else:
return fibonacci_recursion(n - 1) + \
fibonacci_recursion(n - 2)
if __name__ == '__main__':
for i in range(21):
print(i, fibonacci_recursion(i))
|
49764303d5eb617c03f73c006b51478d386c5b45 | pablosq83/Pruebas3 | /superpos.py | 1,178 | 3.84375 | 4 | #!usr/bin/python
# -*- coding: utf -8 -*-
"""
Función que recibe como parámetro dos arreglos y se debe determinar si hay elementos en común o no. Devuelve cierto si hay al menos uno en común o de lo contrario devuelve falso.
Autor: Pablo Sulbarán (psulbaran@cenditel.gob.ve)
Fecha: 27-02-2018
"""
vector1 = []
n = int(input("Introduzca la cantidad de elementos a procesar de la lista "))
for i in range(n):
elem = int(input("Introduzca un numero entero "))
vector1.append(elem)
print"Segunda lista"
vector2 = []
m = int(input("Introduzca la cantidad de elementos a procesar de la 2 lista "))
for j in range(m):
elem2 = int(input("Introduzca un numero entero "))
vector2.append(elem2)
def superposicion(vector1, vector2):
i=0
j=0
cont= 0
cont2= 0
for i in range(n):
for j in range(m):
if (vector1[i]==vector2[j]): #Compara ambas listas
cont= cont+1
else:
cont2= cont2+1
if (cont>0):
valor= True
else:
valor= False
return valor
if (superposicion(vector1, vector2)==True):
print "Los arreglos tienen elementos en comun"
else:
print "Los arreglos son distintos"
|
bd6eabd145679684b1ca0b551bfdcc01c2be7aa6 | dnov09/InterviewPrep | /Sorting Algorithms/algos.py | 1,493 | 4.15625 | 4 | # Sorting Algorithms
#%%
def selection_sort(lst):
# find the minimum in the unsorted subarray
for i in range(len(lst)):
min_idx = i
# checks the next number and performs the check
for j in range(i + 1, len(lst)):
if lst[min_idx] > lst[j]:
min_idx = j
# Swap the new minimum with the current minimum
lst[i], lst[min_idx] = lst[min_idx], lst[i]
print("Selection sort: {}".format(lst))
def insertion_sort(lst):
# Swapping method
for i in range(1, len(lst)):
for j in range(i-1, -1, -1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
else:
break
#Shifting method -> 2x faster because no swapping
# for i in range(1, len(lst)):
# curr_num = lst[i]
# for j in range(i-1, -1, -1):
# if lst[j] > curr_num:
# lst[j+1] = lst[j]
# else:
# lst[j+1] = curr_num
# break
print("Insertion sort: {}".format(lst))
def mergesort(lst):
pass
def quicksort(lst):
pass
def heapsort(lst):
pass
def create_array(size=10, max=100):
from random import randint
return [randint(0, max) for _ in range(size)]
# --------------------------------------------------------------- #
#%%
selection_sort(create_array())
insertion_sort(create_array())
# quicksort(create_array())
# mergesort(create_array())
# heapsort(create_array())
|
d07ae0bf949aaf7512b46343ec11d4a6bd462a7f | Jesus-Acevedo-Cano/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 335 | 3.59375 | 4 | #!/usr/bin/python3
"""
Method that calculates the fewest number of operations
"""
def minOperations(n):
count = 0
div = 2
if not isinstance(n, int) or n <= 1:
return 0
while n > 1:
if n % div != 0:
div += 1
else:
n = n / div
count += div
return count
|
fd2ff6b7c8ea0ed252092c453d1eb5924ad2b09c | winterfellding/mit-cs-ocw | /6.006/clrs/chap2.py | 2,224 | 3.96875 | 4 | def insert_sort(ary):
for i in range(1, len(ary)):
key = ary[i]
j = i - 1
while j >= 0 and ary[j] > key:
ary[j + 1] = ary[j]
j -= 1
ary[j + 1] = key
ary = [5, 2, 4, 6, 1, 3]
print(ary)
insert_sort(ary)
print(ary)
"""
ex2.1-1
[31, 41, 59, 26, 41, 58]
[31, 41, 59, 26, 41, 58]
[31, 41, 59, 26, 41, 58]
[26, 31, 41, 59, 41, 58]
[26, 31, 41, 41, 59, 58]
[26, 31, 41, 41, 58, 59]
"""
"""
ex2.1-2
"""
def decrease_insert_sort(ary):
for i in range(1, len(ary)):
key = ary[i]
j = i - 1
while j >= 0 and ary[j] < key:
ary[j + 1] = ary[j]
j -= 1
ary[j + 1] = key
ary = [31, 41, 59, 26, 41, 58]
print(ary)
decrease_insert_sort(ary)
print(ary)
"""
ex2.1-3
idx = 0
for idx in range(ary.length)
if ary[idx] == v:
return idx
return nil
"""
"""
ex2.1-4
"""
def add_two_bi_bit_arry(ary, ary2):
carry = 0
result = [None] * (len(ary) + 1)
print(result)
for i in range(len(ary) - 1, -1, -1):
result[i + 1] = (carry + ary[i] + ary2[i]) % 2
carry = (carry + ary[i] + ary2[i]) // 2
result[0] = carry
return result
ary = [1, 0, 1, 0]
ary2 = [0, 1, 0, 1]
print(add_two_bi_bit_arry(ary, ary2))
ary = [1, 1, 1, 1]
ary2 = [0, 0, 0, 1]
print(add_two_bi_bit_arry(ary, ary2))
"""
merge sort
"""
def merge_sort(ary, l, r):
if r > l:
m = (l + r) // 2
merge_sort(ary, l, m)
merge_sort(ary, m + 1, r)
merge(ary, l, m, r)
def merge(ary, l, m, r):
L = [0] * (m - l + 1)
R = [0] * (r- m)
for i in range(0 , len(L)):
L[i] = ary[l + i]
for j in range(0 , len(R)):
R[j] = ary[m + 1 + j]
l_i, r_i, ary_i = 0, 0, l
while l_i < len(L) and r_i < len(R):
if L[l_i] <= R[r_i]:
ary[ary_i] = L[l_i]
l_i += 1
else:
ary[ary_i] = R[r_i]
r_i += 1
ary_i += 1
while l_i < len(L):
ary[ary_i] = L[l_i]
l_i += 1
ary_i += 1
while r_i < len(R):
ary[ary_i] = R[r_i]
r_i += 1
ary_i += 1
ary = [12, 11, 13, 5, 6, 7]
merge_sort(ary, 0, len(ary) - 1)
print(ary) |
7b441bf0e6044f6d50e5760f359f59e9ec5bf766 | jakobpederson/cookbook | /flatten_a_nested_sequence.py | 379 | 3.578125 | 4 | from collections import Iterable
class FlattenANestedSequence():
def flatten(self, lst):
return list(self.recurs(lst))
def recurs(self, lst):
print(lst)
for value in lst:
if isinstance(value, Iterable) and type(value) not in (str, bytes):
yield from self.recurs(value)
else:
yield value
|
ea74dd0a425c0f42188884e7758a1051c6a674d9 | whalejasmine/leetcode_python_summary | /2-24/314-Binary-Tree-Vertica- Order-Traversal.py | 2,803 | 4.34375 | 4 | # Time: O(n) loop all tree node
# Space: O(1)
# Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
# If two nodes are in the same row and column, the order should be from left to right.
# Examples 1:
# Input: [3,9,20,null,null,15,7]
# 3
# /\
# / \
# 9 20
# /\
# / \
# 15 7
# Output:
# [
# [9],
# [3,15],
# [20],
# [7]
# ]
# Examples 2:
# Input: [3,9,8,4,0,1,7]
# 3
# /\
# / \
# 9 8
# /\ /\
# / \/ \
# 4 01 7
# Output:
# [
# [4],
# [9],
# [3,0,1],
# [8],
# [7]
# ]
# Examples 3:
# Input: [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5)
# 3
# /\
# / \
# 9 8
# /\ /\
# / \/ \
# 4 01 7
# /\
# / \
# 5 2
# Output:
# [
# [4],
# [9,5],
# [3,0,1],
# [8,2],
# [7]
#]
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def verticalOrder(self, root: 'TreeNode') -> 'List[List[int]]':
"""
:type root: TreeNode
:rtype: List[List[int]]
this problem seemed very hard but actually once you draw a picture on a paper or in your brain, it becomes pretty clear.
- for the left node, you set its index as index - 1
- for the right node, you set its index as index + 1
- use queue to loop through all the nodes in a tree
- set index as a key to the hashmap() and value as a list of vals
- add node.data into hashmap() with index as a key
- keep track of min and max index and store into solution list and return it
"""
if not(root): return []
res, MIN,MAX=[],0,0 # why keep track of min and max index (keep track how many columns of the tree in order to loop all index to get result)
table={} # store as key is index and node value; same index append that node value
queue=[(root,0)] # in order to pop to get tree node and node's index as the node has leafs
while queue:
node, index=queue.pop(0)
#print(node)
#print(index)
if index not in table:
table[index]=[node.val]
#print(table)
else:
table[index].append(node.val)
if node.left:
MIN=min(MIN,index-1)
queue.append((node.left,index-1))
if node.right:
MAX=max(MAX,index+1)
queue.append((node.right,index+1))
for i in range(MIN,MAX+1):
#print(i)
res.append(table[i])
return res
|
336cdaa8db21efa587a762e00adfe4e4dbafa28a | sipakhti/code-with-mosh-python | /CS 112 Spring 2020/Functions.py | 8,182 | 4.28125 | 4 |
def count_multiples(num1, num2, N):
""" Reutrns the number of multiples of N that exist between num1 and num2
N cannot be 0 while num1 and num2 can be in any order
"""
count = 0
if num1 > num2:
num1, num2 = num2, num1
for i in range(num1, num2 + 1):
if i % N == 0:
count += 1
return count
def skip_sum(num1, num2, N):
"""Returns the sum of the integers between numl and num2 inclusive
but it skips every Nth number in this sequence.
N is always larger than 1 while num1 and num2 can be in any order
"""
count = 0
total = 0
if num1 > num2:
num1, num2 = num2, num1
for i in range(num1, num2+1):
count += 1
# using another variable count as a counter so that Nth number can be skipped
if count % N != 0:
total += i
else:
pass
return total
def cubic_root(num):
""" Given a positive number num,
it returns its cubic root only if it's a whole number.
"""
for i in range(num):
if (i * i * i) == num:
return i
return num if num == 1 else None
def count_moves(start, end, step):
count = 0
position = start
while position < end:
position += step
count += 1
if position % 10 == 7 or position % 10 == 8:
position += position % 10
else:
pass
if position % 10 == 3 or position % 10 == 5:
step += position % 10
else:
pass
return count
def max_dna(num):
base_a = 0
base_t = 0
base_g = 0
base_c = 0
count = 1
# anything divided(//) by 10,100,1000.....will strip the last digits from the right
# correspoding to the number of 0s
# by striping down the most least significant number the number can be iterated through
# and by taking the modulus by 10 at every stage will procide the last digit thus isolating it for operations
while num % count != num:
if (num // count) % 10 == 1:
base_a += 1
elif (num // count) % 10 == 2:
base_c += 1
elif (num // count) % 10 == 3:
base_g += 1
elif (num // count) % 10 == 4:
base_t += 1
else:
pass
count *= 10
if base_a > base_c and base_a > base_g and base_a > base_t:
return "A"
if base_c > base_a and base_c > base_g and base_c > base_t:
return "C"
if base_g > base_a and base_g > base_c and base_g > base_t:
return "G"
if base_t > base_a and base_t > base_c and base_t > base_g:
return "T"
def scrabble_number(num):
"""Returns a scrabbled version of num by swapping the two digits
of every consecutive pair of digits starting from the right.
"""
diviser = 1
digit_tacker = 0 # to keep track of digits in number
scrambled_num = 0
# this while loop gives correct results if the number of digits are even
while num % diviser != num:
pair = (num // diviser) % 100
first_digit = pair // 10
second_digit = pair % 10
if diviser == 1:
scrambled_num += second_digit * 10 + first_digit
elif diviser > 1:
scrambled_num += second_digit * \
(diviser*10) + first_digit * (diviser)
diviser *= 100
digit_tacker += 1
count = 0
diviser = 1
# loops through the number to count the digits
while num % diviser != num:
diviser *= 10
count += 1
# check whether digits in number are even or odd
if count % 2 != 0:
diviser = 1 # it iterates through the number in blocks of two
limiter = 1 # local while loop variable for increment and make sure that the loop stops
# before the first digit is reached
scrambled_num = 0
# for numbers who have odd number of digits but the logic is the same for extraction of pairs
while limiter < digit_tacker:
pair = (num // diviser) % 100
first_digit = pair // 10
second_digit = pair % 10
if diviser == 1:
scrambled_num += second_digit * 10 + first_digit
elif diviser > 1:
scrambled_num += second_digit * \
(diviser*10) + first_digit * (diviser)
diviser *= 100
limiter += 1
# adds the single digit at the extreme left in case of odd number of digits
scrambled_num += (num//diviser) * diviser
return scrambled_num
class Unknown():
# constructor
def __init__(self, num):
self.num = num
def scrabble_number(self):
"""Returns a scrabbled version of num by swapping the two digits
of every consecutive pair of digits starting from the right.
"""
diviser = 1
digit_tacker = 0 # to keep track of digits in number
scrambled_num = 0
# this while loop gives correct results if the number of digits are even
while self.num % diviser != self.num:
pair = (self.num // diviser) % 100
first_digit = pair // 10
second_digit = pair % 10
if diviser == 1:
scrambled_num += second_digit * 10 + first_digit
elif diviser > 1:
scrambled_num += second_digit * \
(diviser*10) + first_digit * (diviser)
diviser *= 100
digit_tacker += 1
count = 0
diviser = 1
# loops through the number to count the digits
while self.num % diviser != self.num:
diviser *= 10
count += 1
# check whether digits in number are even or odd
if count % 2 != 0:
diviser = 1 # it iterates through the number in blocks of two
limiter = 1 # local while loop variable for increment and make sure that the loop stops
# before the first digit is reached
scrambled_num = 0
# for numbers who have odd number of digits but the logic is the same for extraction of pairs
while limiter < digit_tacker:
pair = (self.num // diviser) % 100
first_digit = pair // 10
second_digit = pair % 10
if diviser == 1:
scrambled_num += second_digit * 10 + first_digit
elif diviser > 1:
scrambled_num += second_digit * \
(diviser*10) + first_digit * (diviser)
diviser *= 100
limiter += 1
# adds the single digit at the extreme left in case of odd number of digits
scrambled_num += (self.num//diviser) * diviser
return scrambled_num
def max_dna(self):
base_a = 0
base_t = 0
base_g = 0
base_c = 0
count = 1
# anything divided(//) by 10,100,1000.....will strip the last digits from the right
# correspoding to the number of 0s
# by striping down the most least significant number the number can be iterated through
# and by taking the modulus by 10 at every stage will procide the last digit thus isolating it for operations
while self.num % count != self.num:
if (self.num // count) % 10 == 1:
base_a += 1
elif (self.num // count) % 10 == 2:
base_c += 1
elif (self.num // count) % 10 == 3:
base_g += 1
elif (self.num // count) % 10 == 4:
base_t += 1
else:
pass
count *= 10
if base_a > base_c and base_a > base_g and base_a > base_t:
return "A"
if base_c > base_a and base_c > base_g and base_c > base_t:
return "C"
if base_g > base_a and base_g > base_c and base_g > base_t:
return "G"
if base_t > base_a and base_t > base_c and base_t > base_g:
return "T"
test = Unknown(4379971)
print(test.scrabble_number())
test.num = 1222134312343114233324
print(test.max_dna())
|
cea1df4b30ce59cee68d61e845046444747aa76b | idotc/Interview-And-Algorithm-Experience | /第一章/1.1节/1_1-2.py | 626 | 3.875 | 4 | import sys
def ReverseWord(s, to):
start = 0
while(start < to):
t = s[start]
s[start] = s[to]
s[to] = t
start = start + 1
to = to - 1
return s
def LeftRotateWord(s):
s = s.split(" ")
n = len(s)
s = ReverseWord(s, n-1)
str = []
for i in range(2*n-1):
if(i % 2 == 0):
str.append(s[int(i/2)])
else:
str.append(" ")
str = ''.join(str)
return str
def main():
str = input("Enter a sentence:")
n = len(str)
str = LeftRotateWord(str)
print (str)
if __name__ == "__main__":
sys.exit(main())
|
ec7c0724f1e35485301cef84330976386244fc91 | tsotonov2604/StringManipulation- | /ReverseStr+RemoveNonLetters.py | 334 | 4.0625 | 4 | import string
def reverse_letter(stri):
letters = string.ascii_letters
reverse = stri[::-1]
new = []
for letter in reverse:
for char in letters:
if letter == char:
new.append(letter)
word = "".join(new)
print(word)
reverse_letter('krish21an')
|
02ddf965ba6d702b8adbfd667a95d4f4c70289c3 | PdxCodeGuild/class_mudpuppy | /Assignments/Brea/Class Examples/Test_3.31.20.py | 678 | 3.59375 | 4 | #Test for March 31st, 2020
#
# military_gen.py
# user_letters = input("Give me some letters : ")
# mil_dict = {'a': 'alpha',
# 'b': 'bravo',
# 'c': 'charlie',
# 'd': 'delta',
# 'e': 'echo',
# 'f': 'foxtrot',
# 'g': 'golf'}
# output = ''
# for letter in user_letters:
# output += mil_dict[letter] + ''
# print(output)
#lunch_order.py
#[number of sandwiches][number of soups][number of waters]
#342 means 3 sandwiches, 4 soups, 2 waters
input_order = int(input("What's the order? : "))
sandwich_num = input_order // 100
soup_num = (input_order % 100) // 10
water_num = input_order % 10
print(f"{sandwich_num} sandwiches, {soup_num} soups, and {water_num} waters") |
1237b2a0a4e8960afa3b501262bfb94926d6dfc2 | richruizv/Ejercicio_Media | /media.py | 1,086 | 4.21875 | 4 | import random as rd
def run():
print('''
************************************************************
WELCOME TO MEDIA CALCULATOR
This program calculates the media of a random sample from a series of numbers.
************************************************************
''')
print('Please, insert the numbers of the series delimited by coma ( example: 4,5,3,7,1,3,5,7 ): ')
array_numbers = input()
array_numbers = array_numbers.split(',')
array_numbers = [int(x) for x in array_numbers]
print('Insert the sample: ')
sample = int(input())
## Default sample and array
#array_numbers = (3,4,5,6,7,3,1)
#sample = 3
sample = rd.sample(array_numbers, sample)
sum = count = media = 0
for s in sample:
sum += s
count += 1
media = sum / count
s_sample = ",".join(str(s) for s in sample)
print(f'''
The sample obtained was : {s_sample}
Media of the sample is: {str(round(media,2))}
''')
if __name__ == '__main__':
run() |
02983b7ce46fd0556f8cdd4d61b78545d21c30b8 | ivan-fr/oc_projet_8 | /purbeurre/utils.py | 1,837 | 3.53125 | 4 | def get_words_from_sentence(sentence):
"""Get words from sentence."""
cursor, i, sentence = 0, 0, sentence.strip().lower() + " "
while i <= len(sentence) - 1:
if not sentence[i].isalpha() and not sentence[i] == "'":
if i - 1 >= cursor:
word = sentence[cursor:i]
if "'" in word:
word = word[word.index("'") + 1:]
yield word
delta = 1
while i + delta <= len(sentence) - 1:
if sentence[i + delta].isalpha():
break
delta += 1
i = cursor = i + delta
i += 1
def wash_product(product: dict):
# wash categories keys
if product.get('categories_hierarchy'):
i = 0
while i <= len(product['categories_hierarchy']) - 1:
if ':' in product['categories_hierarchy'][i]:
product['categories_hierarchy'][i] = \
(product['categories_hierarchy'][i].split(':'))[1]
i += 1
if product.get('categories'):
product['categories'] = product['categories'].split(',')
i = 0
while i <= len(product['categories']) - 1:
if ':' in product['categories'][i]:
product['categories'][i] = \
(product['categories'][i].split(':'))[1]
i += 1
# wash ingredients keys
if product.get('ingredients_text_fr', None):
product['ingredients_text_fr'] = (
' '.join(get_words_from_sentence(ingredient)) for ingredient
in
product['ingredients_text_fr'].split(','))
else:
product['ingredients'] = (
' '.join(get_words_from_sentence(ingredient['text'])) for
ingredient
in product.get('ingredients', ()))
return product
|
b0d07a7552b88785387c63cc677186fbe47c9c2c | SebastianColorado/DylansBot | /Main.py | 1,329 | 3.5625 | 4 | """Tweets out a random city name + the phrase."""
import csv
import twitter
import os
import random
import time
numRows = 15633
cities = []
with open('cities.csv', 'rt') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
cities.append(row[0])
# Authenticate the twitter bot by passing the twitter api keys retrieved from
# environment variables
consumer_key = os.environ['CONSUMER_KEY']
consumer_secret = os.environ['CONSUMER_SECRET']
access_token_key = os.environ['ACCESS_TOKEN']
access_token_secret = os.environ['ACCESS_TOKEN_SECRET']
print(consumer_key + " " + consumer_secret + " " + access_token_key + " " + access_token_secret)
twitterApi = twitter.Api(consumer_key, consumer_secret, access_token_key, access_token_secret)
def postTweet(city):
"""Post tweet with given parameters."""
try:
status = twitterApi.PostUpdate(city + " niggas? They trained to go.")
except twitter.error.TwitterError as e:
print('There was an error: ' + e.message[0]['message'])
else:
print("%s just posted: %s" % (status.user.name, status.text))
return
def getCity():
"""Get a random city from the array."""
return cities[random.randrange(numRows)]
while True:
currentCity = getCity()
postTweet(currentCity)
time.sleep(17280)
|
4ef3686e8a60f113c0db1882a7fee486b2b59afb | ShafiqullahTurkmen/kodluyoruzilkrepo | /Simple Coffee Machine/coffee_machine.py | 2,075 | 4.15625 | 4 | water = 400
milk = 540
coffee_beans = 120
cups = 9
money = 550
print('Write action (buy, fill, take, remaining, exit):')
n = input()
print()
while n != 'exit':
if n == 'buy':
print('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:')
x = input()
if x == '1' and water >= 250 and coffee_beans >= 16 and cups >= 1:
print('I have enough resources, making you a coffee!')
water -= 250
coffee_beans -= 16
cups -= 1
money += 4
elif x == '2' and water >= 350 and milk >= 75 and coffee_beans >= 20 and cups >= 1:
print('I have enough resources, making you a coffee!')
water -= 350
milk -= 75
coffee_beans -= 20
cups -= 1
money += 7
elif x == '3' and water >= 200 and milk >= 100 and coffee_beans >= 12 and cups >= 1:
print('I have enough resources, making you a coffee!')
water -= 200
milk -= 100
coffee_beans -= 12
cups -= 1
money += 6
elif x == 'back':
print()
else:
print('Sorry, not enough water!')
elif n == 'fill':
print('Write how many ml of water you want to add:')
water += int(input())
print('Write how many ml of milk you want to add:')
milk += int(input())
print('Write how many grams of coffee beans you want to add:')
coffee_beans += int(input())
print('Write how many disposable coffee cups you want to add:')
cups += int(input())
elif n == 'take':
print(f'I gave you ${money}')
money -= money
elif n == 'remaining':
print(f'The coffee machine has:\n{water} of water\n{milk} of milk\n{coffee_beans} of coffee beans\n{cups} of '
f'disposable cups\n{money} of money')
print()
print('Write action (buy, fill, take, remaining, exit):')
n = input()
print()
|
6b847d057c4b53910eaa50a0eefa4a2cd256acf4 | jdanray/leetcode | /minCostClimbingStairs.py | 806 | 3.5 | 4 | # https://leetcode.com/problems/min-cost-climbing-stairs/
class Solution(object):
def minCostClimbingStairs(self, cost):
memo = [0 for _ in range(len(cost))]
memo[0] = cost[0]
memo[1] = cost[1]
for i in range(2, len(cost)):
memo[i] = cost[i] + min(memo[i - 1], memo[i - 2])
return min(memo[-1], memo[-2])
class Solution(object):
def minCostClimbingStairs(self, cost):
A = cost[0]
B = cost[1]
for i in range(2, len(cost)):
A, B = cost[i] + min(A, B), A
return min(A, B)
class Solution(object):
def minCostClimbingStairs(self, cost):
memo = {}
def helper(i):
if i >= len(cost):
return 0
if i not in memo:
memo[i] = cost[i] + min(helper(i + 1), helper(i + 2))
return memo[i]
return min(helper(0), helper(1))
|
f7495ff73c18c6eb62a34418cac696a2d8555f4d | Gratisfo/HSE-Programming | /hw2/Caeser's_cipher.py | 253 | 3.75 | 4 | #Caesar's cipher
alpha = ' абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
n = int(input())
s = input()
res = ''
for letter in s:
res += alpha[(alpha.index(letter) + n)]
print('Result: ', res)
|
06c5e879bdf271151b5407c55d2bb1d580f228a8 | ganzevoort/project-euler | /problem67.py | 866 | 3.828125 | 4 | """
Maximum path sum II
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right
click and 'Save Link/Target As...'), a 15K text file containing a
triangle with one-hundred rows.
NOTE: This is a much more difficult version of Problem 18. It is
not possible to try every route to solve this problem, as there are
299 altogether! If you could check one trillion (1012) routes every
second it would take over twenty billion years to check them all.
There is an efficient algorithm to solve it. ;o)
"""
import problem18
def solution():
return problem18.solution(grid_text=open('p067_triangle.txt').read())
|
1ef5d11717692288de6b9b8b61816c1fdaf5109c | jethrozperez/python_work | /python_for_everybody_solutions/ch_7_ex.py | 743 | 3.8125 | 4 | ### Write a program that prompts for a file name then opens that file
### and reads through looking for ''X-DSPAM-Confidence: 0.8475'
### Count those lines and extract floating point values, extract the
### value and average those values to produce the output 'Average spam confidence: 0.750718518519'
fname = input('Enter file name: ')
count = 0
tot = 0
col = ':'
try:
fn = open(fname)
except:
print('File cannot be opened: ', fname)
quit()
for line in fn:
if not line.startswith('X-DSPAM-Confidence:') : continue
indx = (line.find(col))
value = (line[indx + 1:]).strip()
num = float(value)
tot = tot + num
count = count + 1
average = round(tot/count,12)
print('Average spam confidence:',average)
|
d83d23ff486a2c3660ee1b0db8004addb6ba7a47 | RodrigoSierraV/holbertonschool-interview | /0x13-count_it/0-count.py | 1,337 | 3.84375 | 4 | #!/usr/bin/python3
""" Recursive function that queries the Reddit API"""
import requests
def count_words(subreddit, word_list, after="", to_print={}):
"""
Function that queries the Reddit API
"""
if not after:
for word in word_list:
to_print[word] = 0
url = "https://www.reddit.com/r/{}/hot.json{}".format(subreddit, after)
response = requests.get(url, headers={'User-Agent': 'rosierrav20'})
if response.status_code == 200:
json_response = response.json()
reddit_list = json_response.get('data').get('children')
for reddit in reddit_list:
title = reddit.get('data').get('title')
tittle_word_list = title.split()
for word in word_list:
for tittle_word in tittle_word_list:
if word.lower() == tittle_word.lower():
to_print[word] += 1
next_name = json_response.get('data').get('after')
after = "?after={}".format(next_name)
if next_name is not None:
count_words(subreddit, word_list, after, to_print)
else:
for word_count in sorted(to_print.items(),
key=lambda item: item[1],
reverse=True):
if word_count[1] != 0:
print("{}: {}".format(word_count[0], word_count[1]))
|
e3ca668d88674d2934ac7994f959d526b392cc59 | dimasiklrnd/python | /highlighting numbers, if, for, while/The number of even elements.py | 610 | 4.28125 | 4 | '''Посчитать количество четных элементов в массиве целых чисел, заканчивающихся нулём. Сам ноль учитывать не надо.
Формат входных данных
Массив чисел, заканчивающийся нулём (каждое число с новой строки, ноль не входит в массив)
Формат выходных данных
Одно число — результат.'''
n = int(input())
x = 0
while n != 0:
if n % 2 == 0:
x += 1
n = int(input())
print(x)
|
c0096bceeb31121799415080ba033af2173780ae | OO7kartik/AllMachineLearning | /K_nearest_neighbours.py | 1,968 | 3.828125 | 4 | # training data = training_set
# training labels = training_labels ( either 1 or 0 )
# validation_set
# validation_labels
# THE MANUAL METHOD
#euclidean distance
def distance(obj1,obj2):
squared_difference = 0
for i in range(len(obj1)):
squared_difference += (obj1[i] - obj2[i])**2
return squared_difference**0.5
#classify(unknown data,training dataset, traning labels, nearest neighbours )
def classify(unknown,dataset,labels,k):
distances = []
#to find the k nearest ( to find similar ojb )
for value in dataset:
obj = dataset[value]
distance_to_point = distance(obj,unknown)
#noting this value down
distances.append([distance_to_point,value])
#sorting the distances accending order
distances.sort()
#extracting only the K nearest
neighbours = distances[0:k]
num_good = 0
num_bad = 0
for neighbour in neighbours:
value = neighbour[1]
if(labels[value] == 1):
num_good += 1
elif(labels[value] == 0):
num_bad += 1
if num_good > num_bad:
return 1
else:
return 0
#function to check the accuracy of our model
def find_validation_accuracy(training_set, training_labels,validation_set,validation_labels,k):
num_correct = 0.0
for value in validation_set:
guess = classify(validation_set[movie],training_set,training_labels,k)
if(validation_labels[value] == guess):
num_correct += 1
return num_correct / len(validation_set)
#low value of k -> overfitting
#high value of k -> underfitting
#checking the accuracy with k = 3
print(find_validation_accuracy(training_set, training_labels, validation_set, validation_labels, 3))
#USING INBUILT FUNCTION METHOD
#after extracting all our data
from sklearn.neighbours import KNeighborsClassifier
#we enter the number of neighbors, to create the KNeighborsClassifier object
classifier = KNeighborsClassifier( n_neighbors = 5 )
#traning the classifier
classifier.fit(dataset_set,dataset_set_labels)
#to predict
classifier.predict(values_to_predict)
|
a7d01fd2e5119213ad1b9ef672a7347924a96f95 | jackowayed/advent2020 | /10.py | 1,280 | 3.546875 | 4 | #!/usr/bin/env python3
import fileinput
import re
def jumps(nums, n):
return sum(nums[i] + n in nums for i in range(len(nums) - 1))
def read():
raw = sorted([int(line.strip()) for line in fileinput.input()])
nums = [0]
nums.extend(raw)
nums.append(nums[-1] + 3)
return nums
def part1():
nums = read()
voltage = 0
one_jumps = 0
three_jumps = 0
while voltage < nums[-1]:
if (voltage + 1) in nums:
one_jumps += 1
voltage += 1
elif (voltage + 3) in nums:
three_jumps += 1
voltage += 3
return one_jumps * three_jumps
mem = dict()
def arrangements(nums, after_idx):
if after_idx in mem:
return mem[after_idx]
r = arrangements_logic(nums, after_idx)
mem[after_idx] = r
return r
def arrangements_logic(nums, after_idx):
if after_idx == len(nums) - 1:
return 1
sum = 0
for idx in range(after_idx + 1, after_idx + 4):
if idx < len(nums):
pass#print(nums[idx] - nums[after_idx])
if idx < len(nums) and (nums[idx] - nums[after_idx]) <= 3:
sum += arrangements(nums, idx)
return sum
def part2():
nums = read()
return arrangements(nums, 0)
#print(part1())
print(part2()) |
e1decf06a38d8f20b6cc7c7938c9972fefe21d87 | darkhipo/Air_Traffic_Controller | /AirTrafficController_Python/FlightCombinator.py | 1,396 | 4.09375 | 4 | """
This file contains the algorithm of how all the FlightPlan possibilities are calculated.
"""
import itertools
from math import factorial
class FlightCombinator: # public class FlightCombinator implements Iterable<FlightPlan>{
def __init__(self, lf, r):
self.lf = lf
self.r = r
self.i = 0
self.comb = list(itertools.combinations(lf, r))
self.perm = []
for x in self.comb: # Calculate all the possible combinations
self.perm.extend(list(itertools.permutations(x))) # and permutations and put them in a list.
def has_next(self):
"""
Test if a certain combination still has permutation.
Return:
a boolean expression of if a certain combination has run out of permutations or not.
"""
return self.i < factorial(len(self.lf))/factorial(len(self.lf) -self.r)
def get_next(self):
"""
Get the permutation of a certain combination.
Return:
new_i: a permuted tuple
"""
new_i = self.perm[self.i]
self.i += 1
return new_i
# def test_FC():
# fc = FlightCombinator([2, 3,1,1, 1], 3)
#
# while fc.has_next():
# print(fc.get_next())
#
# test_FC()
#
#
|
ae36b475a1bb460c95f07e3787858af6ba6650b8 | haivmptit/ManageAccount | /test.py | 422 | 3.609375 | 4 | def allLongestStrings(inputArray):
lenn = 0
out = []
for i in inputArray:
if len(i) > lenn:
lenn = len(i)
print(lenn)
for i in inputArray:
print(i + " " + str(len(i)))
if len(i) == lenn:
out.append(i)
return out
a = ["a",
"abc",
"cbd",
"zzzzzz",
"a",
"abcdef",
"asasa",
"aaaaaa"]
print(allLongestStrings(a))
# print(checkPalindrome("aba")) |
e61563a47486fcd8f79e658e536167f6e03274ae | nojongmun/python_basics | /step05_array/array/arrayEx5.py | 566 | 3.75 | 4 | # 크기가 5인 정수형 배열을 만들고
# 배열에 데이터를 입력 받아서 출력하고 최대 , 최소값을 구하세요
# ar[0]의 값을 입력하세요 : 25
# ar[1]의 값을 입력하세요 : 25
# ar[2]의 값을 입력하세요 : 25
# ar[3]의 값을 입력하세요 : 2
# ar[4]의 값을 입력하세요 : 25
# 최대값 : 25
# 최소값 : 2
import array
ar=array.array('i')
for i in range(0,5):
ar.append(int(input('ar[%d]의 값을 입력하세요 : ' % i)))
print(ar)
print('최대값 : ', max(ar))
print('최소값 : ', min(ar))
|
57d16485447515b0a032e8cf171047f208c2b353 | emuuli/advent_of_code_2018 | /1_exercise/solution.py | 784 | 3.734375 | 4 | FILE_NAME = "input.txt.txt"
def read_in_file(file_name):
with open(file_name, 'r') as input_file:
result = [int(line) for line in input_file]
return result
def find_first_duplicate(i_list):
results = set()
current_result = 0
results.add(current_result)
while True:
for i in i_list:
current_result += i
if current_result in results:
return current_result
else:
results.add(current_result)
if __name__ == '__main__':
input_list = read_in_file(FILE_NAME)
input_list_sum = sum(input_list)
print("Sum of input.txt list: {}".format(input_list_sum))
first_duplicate = find_first_duplicate(input_list)
print("First duplicate: {}".format(first_duplicate))
|
2548010404a3be8ff220048ea763862d8d546b5f | jakesig/cs2020fall | /Week 7/Week 7 - Web/lab4.py | 311 | 3.703125 | 4 | #!/usr/bin/python
print( "Content-type: text/html\n\n" )
print("<TITLE>Lab 4</TITLE>")
print("<h1>Lab 4</h1>")
print( """
<html>
<body>
<table>
""" )
for x in range(100):
print("<tr><td>%s</td><td>%s</td></tr>" % (x+1, (x+1)*100))
print( """
</table>
</body>
</html>
""" )
|
df59099ceb33d93ad6e3f47b700162479f46286e | timing2211/sawppy_ros | /scripts/chassis_wheel_calculator.py | 1,932 | 4.28125 | 4 | #!/usr/bin/python3
import sys
class chassis_wheel:
"""Information needed to calculate angle and speed for a specific wheel
Axis orientation conforms to REP103. (+X is forward, +Y is left, +Z is up)
https://www.ros.org/reps/rep-0103.html"""
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
class chassis_wheel_angle_speed:
"""Results of chassis geometry calculation for the named wheel"""
def __init__(self, name, angle, velocity):
self.name = name
self.angle = angle
self.velocity = velocity
class chassis_wheel_calculator:
"""Given a overall desired motion for a robot chassis, calculate the
individual angle and velocity required for each wheel on board the robot
chassis.
Chassis configuration is given as a list of chassis_wheeel class, one
for each wheel."""
def __init__(self, chassis):
"""Initializes an instance of chassis wheel calculator class.
chassis -- a list of chassis_wheel instances, one for each wheel
aboard the robot."""
self.chassis = chassis
def calculate(self, angular=0, linear=0):
"""Given a desired angular and linear velocity for robot chassis
center, calculate necessary angle and speed for each wheel on board.
angular -- desired turning speed for robot chassis in radians/sec
about the Z axis, counter-clockwise is positive.
linear -- desired forward speed for robot chassis in meters/sec
along the X axis. forward is positive."""
results = list()
for wheel in self.chassis:
answer = chassis_wheel_angle_speed(wheel.name,0,0)
results.append(answer)
return results
if __name__ == '__main__':
print("Running under Python " + str(sys.version_info[0]))
print("This class has no functionality when run directly.")
|
b42681078fd055e910b0866022f905c98303f796 | ywcmaike/OJ_Implement_Python | /leetcode/16.11. 跳水板.py | 958 | 3.671875 | 4 | # author: weicai ye
# email: yeweicai@zju.edu.cn
# datetime: 2020/7/27 上午10:12
# 你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为shorter,长度较长的木板长度为longer。你必须正好使用k块木板。编写一个方法,生成跳水板所有可能的长度。
#
# 返回的长度需要从小到大排列。
#
# 示例 1
#
# 输入:
# shorter = 1
# longer = 2
# k = 3
# 输出: [3,4,5,6]
# 解释:
# 可以使用 3 次 shorter,得到结果 3;使用 2 次 shorter 和 1 次 longer,得到结果 4 。以此类推,得到最终结果。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/diving-board-lcci
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
class Solution:
def divingBoard(self, shorter: int, longer: int, k: int) -> List[int]:
if __name__ == "__main__":
pass |
173d8ab466575fef56d453d44697ba2812dbd08f | tushant1037/InfyTQ | /assign20.py | 818 | 4.0625 | 4 | '''
Write a python function, find_pairs_of_numbers() which accepts a list of positive integers with no repetitions and returns count of pairs of numbers in the list that adds up to n. The function should return 0, if no such pairs are found in the list.
Also write the pytest test cases to test the program.
Sample Input Expected Output
[1, 2, 7, 4, 5, 6, 0, 3],6 3
[3, 4, 1, 8, 5, 9, 0, 6],9 4
'''
#PF-Assgn-34
def find_pairs_of_numbers(num_list,n):
count=0
for i in num_list:
a = i
b = n-i
if b in num_list:
count = count +1
num_list.remove(a)
num_list.remove(b)
return count
#Remove pass and write your logic here
num_list=[1, 2, 4, 5, 6]
n=6
print(find_pairs_of_numbers(num_list,n)) |
4f5cd77c02bfd0baa7045c6bf02e42ee714bbbd9 | Govrie/Govrie.github.io | /HW1-5.py | 401 | 3.765625 | 4 | #!/usr/bin/env python3 -tt
"""File: hello.py """
def get_digit_d(n):
string_repr = str(abs(n))
digit_d = 0
for digit in string_repr:
if (n % int(digit)) > 0:
digit_d +=1
if digit_d == 0:
return True
else:
return False
#Run only if called as a script
if __name__ == '__main__':
n = int(input("Enter a number = "))
print(get_digit_d(n))
|
218bbe55c6d949964db7d0a5b907b679c51f52d6 | mucius/misc_patches | /viewvc/forChardet/toutf8.py | 236 | 3.578125 | 4 | import chardet
def toutf8(txt):
if not txt:
return txt
c = chardet.detect( txt)
try:
u = unicode( txt, c['encoding'])
return u.encode('utf-8')
except UnicodeError:
pass
except TypeError:
pass
return txt
|
ea6d8b05e06f9526c3cbaed12f313eac35e2ce40 | alexthefatcat/CuratedCode-GIT | /Advanced_Python/object_orintated_stuff.py | 1,051 | 4 | 4 | # -*- coding: utf-8 -*-
"""Created on Mon Nov 18 15:45:02 2019
@author: Alexm"""
# Dynamically add methods to a Object
if ("Dynamically add methods",True)[1]:
class A:
def __init__(self,name,age):
self.name = name
self.age = age
a = A("monkeyman",(12,3))
def printname(self):
print(self.name)
setattr(A, 'printname', printname)
def calc_monthsold(self):
self.months = (self.age[0]*12) +self.age[1]
setattr(A, 'calc_monthsold', calc_monthsold)
a.printname()
a.calc_monthsold()
a.months
class Foo():
def __init__(self):
self._bar = 0
@property
def bar(self):
return self._bar + 5
fooy = Foo()
fooy.bar
class Test:
def __getitem__(self, arg):
return str(arg)*2
def __call__(self, arg):
return str(arg)*5
test = Test()
print( test[0] )
print( test['kitten '] )
# calling __call__ obj()
print( test(2) )
print( test('dog ') )
|
3785a9eaf0c7ba28ec7562943b6ca04e38263aac | Zaymes/python-assignment | /data types/data_types5.py | 992 | 4.21875 | 4 | # question 41
# convert tuple to string
def tuple_to_string(tup):
if type(tup) not str:
tup = str(tup)
str = ''.join(tup)
return str
tuple1 = ('p','y','t','h','o','n')
string = tuple_to_string(tuple1)
print(string)
print(tuple_to_string(1,2,3,4))
# question 42
# convert list to a tuple
def list_to_tuple(list):
return tuple(list)
li = [1,2,3,4,5,6,7,8,9]
new_tuple = list_to_tuple(li)
print(new_tuple)
# question 43
# remove an item from tuple
def rmv_tuple_item(tup,item):
tup = list(tup)
tup.remove(item)
tup = tuple(tup)
return tup
tup = (1,2,3,4,5,6,7,8,9)
tup = rmv_tuple_item(tup,2)
print(tup)
# question 44
# slices a tuple
tup = (1,2,3,4,5,6)
tup = tup[2:4]
print(tup)
# question 45
# find index of item in a tuple
a = (1,1,2,3,4,5,6,7,4)
print('the index of 2 is',a.index(2))
print('the index of 1 is',a.index(1))
# question 46
# length of tuple
tup = (1,2,3,4,5,6)
print('length of tuple tup is ',len(tup)) |
9d5e6c6c99626ccbc84e29a4b0100a54c2ef050e | CX-Bool/LeetCodeRecord | /Python/Easy/206. 反转链表.py | 961 | 3.8125 | 4 | '''执行用时 :
36 ms
, 在所有 Python 提交中击败了
54.75%
的用户
内存消耗 :
13.6 MB
, 在所有 Python 提交中击败了
44.51%
的用户'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
stack = []
while head:
stack.append(head)
head = head.next
i = len(stack) -1
if not stack:
return head
while i > 0:
stack[i].next = stack[i-1]
i-=1
stack[0].next = None
return stack[-1]
### recursion
# if not head or not head.next:
# return head
# newHead = self.reverseList(head.next)
# head.next.next = head
# head.next = None
# return newHead
|
9f4da80ab4893b4e179e92863527a3561671c90a | lbxa/first-neural-net | /src/feed_forward_net.py | 9,064 | 3.640625 | 4 | '''
Feed-Foward Artificial Neural Network
-------------------------------------
Feed-foward nets are the simplest NN's to master. They are comprised of
an input layer, one or more hidden layers and an output layer. Since the
dimensionality of out data is 2 inputs to 1 output, there will be 2 input
neruons and a single output neuron. For sake of simplicty this net will
restrict itself to a single hidden layer (deep belief networks can be for
another time).
This model revolves around on estimating your SAT score based on the amount of
hours you slept and the amount of hours you studied the night before. For
more information including the theory papers for the algorthms behind the
backpropagation refer to the user manual.
This software does requires 2 dependencies:
> Numpy Library (https://docs.scipy.org/doc/numpy-1.13.0/user/install.html)
> Scipy Library (https://www.scipy.org/install.html)
Python Version: 3.6
28.07.2017 | Oakhill College | SDD | Open Source Software (C) | Lucas Barbosa
'''
# dependencies for operation
import sys
import numpy as np
from scipy import optimize
class Neural_Network(object):
def __init__(self, learning_rate=0):
# define hyperparameters
self.input_layer_size = 2
self.hidden_layer_size = 3
self.output_layer_size = 1
# define parameters
self.W1 = np.random.randn(self.input_layer_size, self.hidden_layer_size)
self.W2 = np.random.randn(self.hidden_layer_size, self.output_layer_size)
# regularization parameter
self.learning_rate = learning_rate
# forward propagation
def forward(self, X):
self.z2 = np.dot(X, self.W1)
self.a2 = self.sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.W2)
prediction = self.sigmoid(self.z3)
return prediction
# activation functions
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
# derivative of sigmoid function
def sigmoid_prime(self, z):
return np.exp(-z) / ((1 + np.exp(-z))**2)
# efficient backprop
def cost_function(self, X, desired_output):
self.prediction = self.forward(X)
total_error = ((1/2) * sum((desired_output - self.prediction)**2)) / X.shape[0] + \
(self.learning_rate / 2) * (np.sum(self.W1**2) + np.sum(self.W2**2))
return total_error
def cost_function_prime(self, X, desired_y):
self.prediction = self.forward(X)
# layer 3 backprop error
l3_backprop_error = np.multiply(-(desired_y - self.prediction), \
self.sigmoid_prime(self.z3))
# divide by X.shape[0] to account for the scale of the data
cost_in_terms_of_W2 = np.dot(self.a2.T, l3_backprop_error) / X.shape[0] + \
(self.learning_rate * self.W2)
# layer 2 backprop error
l2_backprop_error = np.dot(l3_backprop_error, self.W2.T) * \
self.sigmoid_prime(self.z2)
# divide by X.shape[0] to account for the scale of the data
cost_in_terms_of_W1 = np.dot(X.T, l2_backprop_error) / X.shape[0] + \
(self.learning_rate * self.W1)
return cost_in_terms_of_W1, cost_in_terms_of_W2
# altering and setting the parameters during training
def get_params(self):
# get W1 & W2 rolled into a vector
params = np.concatenate((self.W1.ravel(), self.W2.ravel()))
return params
def set_params(self, params):
# set W1 & W2 using single parameter vector
W1_start = 0
W1_end = self.hidden_layer_size * self.input_layer_size
# reshape the W1 weights
self.W1 = np.reshape(params[W1_start : W1_end], \
(self.input_layer_size, self.hidden_layer_size))
W2_end = W1_end + self.hidden_layer_size * self.output_layer_size
# reshape the W2 weights
self.W2 = np.reshape(params[W1_end : W2_end], \
(self.hidden_layer_size, self.output_layer_size))
def compute_gradient(self, X, desired_y):
cost_in_terms_of_W1, cost_in_terms_of_W2 = self.cost_function_prime(X, desired_y)
return np.concatenate((cost_in_terms_of_W1.ravel(), cost_in_terms_of_W2.ravel()))
class Helper(object):
def __init__(self, Local_Ref):
# set a local reference to NN class
self.Local_Ref = Local_Ref
# normalize data to account for different units
def scale_data(self, hours, test_score):
MAX_SCORE = 100.
hours /= np.amax(hours, axis=0)
test_score /= MAX_SCORE
return hours, test_score
# print out the results of the NN's predicitons
def print_predictions(self, train_x, train_y):
print("="*50)
print("Expected Scores:")
for i in range(0, len(train_y)):
print(int(train_y[i] * 100), "/100", sep="")
print("="*50)
predictions = NN.forward(train_x)
print("Predicted Scores:")
for i in range(0, len(train_x)):
print(int(predictions[i] * 100), "/100", sep="")
print("="*50)
# checking gradients with numerical gradient computation avoiding logic errors
def compute_numerical_gradient(self, X, desired_y):
initial_params = self.Local_Ref.get_params()
numerical_gradient = np.zeros(initial_params.shape)
perturb = np.zeros(initial_params.shape)
# epsilon value needs to be small enough act as a 'zero'
epsilon = 1e-4
for i in range(len(initial_params)):
# set perturbation vector to alter the original state of the initial params
perturb[i] = epsilon
self.Local_Ref.set_params(initial_params + perturb)
loss_2 = self.Local_Ref.cost_function(X, desired_y)
self.Local_Ref.set_params(initial_params - perturb)
loss_1 = self.Local_Ref.cost_function(X, desired_y)
# computer numerical gradient
numerical_gradient[i] = (loss_2 - loss_1) / (2 * epsilon)
perturb[i] = 0
self.Local_Ref.set_params(initial_params)
return numerical_gradient
class Trainer(object):
def __init__(self, Local_Ref):
# make local reference to NN
self.Local_Ref = Local_Ref
def cost_function_wrapper(self, params, X, desired_y):
self.Local_Ref.set_params(params)
total_cost = self.Local_Ref.cost_function(X, desired_y)
gradient = self.Local_Ref.compute_gradient(X, desired_y)
return total_cost, gradient
# track cost function value as training progresses
def callback(self, params):
self.Local_Ref.set_params(params)
self.cost_list.append(self.Local_Ref.cost_function(self.train_x, self.train_y))
self.test_cost_list.append(self.Local_Ref.cost_function(self.test_x, self.test_y))
def train(self, train_x, train_y, test_x, test_y):
# internal variable for callback function
self.train_x = train_x
self.train_y = train_y
self.test_x = test_x
self.test_y = test_y
# empty lists to store costs
self.cost_list = []
self.test_cost_list = []
initial_params = self.Local_Ref.get_params()
# using scipy's built in Quasi-Newton BFGS mathematical optimization algorithm
options = {"maxiter": 200, "disp": True}
_result = optimize.minimize(self.cost_function_wrapper, initial_params, jac=True, \
method="BFGS", args=(train_x, train_y), options=options, \
callback=self.callback)
# once the training is complete finally set the new values of the parameters in
self.Local_Ref.set_params(_result.x)
self.optimization_results = _result
if __name__ == "__main__":
# check if numpy and scipy are installed before running any code
if "numpy" not in sys.modules or "scipy" not in sys.modules:
raise AssertionError("The required dependencies have not been imported.")
# training data
train_x = np.array(([3,5],[5,1],[10,2],[6,1.5]), dtype=float)
train_y = np.array(([75],[82],[93],[70]), dtype=float)
# testing data
test_x = np.array(([4, 5.5],[4.5, 1],[9,2.5],[6,2]), dtype=float)
test_y = np.array(([70],[89],[85],[75]), dtype=float)
# initialize all the classes
NN = Neural_Network(learning_rate=0.0001)
Aux = Helper(NN)
T1 = Trainer(NN)
# normalize data
train_x, train_y = Aux.scale_data(train_x, train_y)
test_x, test_y = Aux.scale_data(test_x, test_y)
# check to see gradients have been correctly calculated
numerical_gradient = Aux.compute_numerical_gradient(train_x, train_y)
computed_gradient = NN.compute_gradient(train_x, train_y)
# train the network
T1.train(train_x, train_y, test_x, test_y)
# observe the results of the tests on above datasets
Aux.print_predictions(train_x, train_y)
|
5b5c1f8d450908ea49ead75ed88a128f1f9f15ac | buru255/Calculator | /calculator.py | 3,515 | 3.78125 | 4 | from tkinter import*
import math
def btnClick(numbers):
global operator
operator=operator + str(numbers)
text_Input.set(operator)
def btnClearDisplay():
global operator
operator=""
text_Input.set("")
def btnEqualInput():
global operator
sumup=str(eval(operator))
text_Input.set(sumup)
operator=""
cal = Tk()
cal.title("Calculator")
operator=""
text_Input =StringVar()
txtDisplay = Entry(cal, font=('arial',20,'bold'), textvariable=text_Input, bd=30, insertwidth=4,
bg="powder blue", justify='right').grid(columnspan=4)
btn7=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="7", bg="powder blue",command=lambda:btnClick(7)).grid(row=1,column=0)
btn8=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="8", bg="powder blue",command=lambda:btnClick(8)).grid(row=1,column=1)
btn9=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="9", bg="powder blue",command=lambda:btnClick(9)).grid(row=1,column=2)
Addition=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="+", bg="powder blue",command=lambda:btnClick("+")).grid(row=1,column=3)
btn4=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="4", bg="powder blue",command=lambda:btnClick(4)).grid(row=2,column=0)
btn5=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="5", bg="powder blue",command=lambda:btnClick(5)).grid(row=2,column=1)
btn6=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="6", bg="powder blue",command=lambda:btnClick(6)).grid(row=2,column=2)
Substraction=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="-", bg="powder blue",command=lambda:btnClick("-")).grid(row=2,column=3)
btn1=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="1", bg="powder blue",command=lambda:btnClick(1)).grid(row=3,column=0)
btn2=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="2", bg="powder blue",command=lambda:btnClick(2)).grid(row=3,column=1)
btn3=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="3", bg="powder blue",command=lambda:btnClick(3)).grid(row=3,column=2)
Multiplication=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="*", bg="powder blue",command=lambda:btnClick("*")).grid(row=3,column=3)
btndot=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text=".", bg="powder blue",).grid(row=4,column=0)
btn0=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="0", bg="powder blue",command=lambda:btnClick(0)).grid(row=4,column=1)
Divission=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="/", bg="powder blue",command=lambda:btnClick("/")).grid(row=4,column=2)
Enter=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="Enter", bg="powder blue",command = btnEqualInput).grid(row=4,column=3)
btnC=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="c", bg="powder blue",command=btnClearDisplay).grid(row=5,column=0)
btnexponent=Button(cal, padx=16, bd=8, fg="black",font=('arial',20,'bold'),
text="raise", bg="powder blue",command=lambda:btnClick("**")).grid(row=5,column=2)
cal.mainloop()
|
7f330c060b987141c23e39702fa351a972957a98 | q737645224/python3 | /python基础/python笔记/day06/exercise/list1.py | 941 | 4.0625 | 4 | # 练习:
# 1. 写程序,让用户输入一些整数,当输入-1时结束输入,
# 将这些数存于列表L中
# 1) 打印用户共输入了几个数?
# 2) 打印您输入的数的最大数是多少
# 3) 打印您输入的数的最小数是多少
# 4) 打印您输入的这些数的平均值是多少?
# 1. 写程序,让用户输入一些整数,当输入-1时结束输入,
# 将这些数存于列表L中
L = []
while True:
x = int(input('请输入整数: '))
if x == -1:
break # 结束循环输入
L += [x]
# print("L=", L)
# 1) 打印用户共输入了几个数?
print("输入的数字个数是:", len(L))
# 2) 打印您输入的数的最大数是多少
print("最大数是:", max(L))
# 3) 打印您输入的数的最小数是多少
print("最小数是:", min(L))
# 4) 打印您输入的这些数的平均值是多少?
print("平均数是:", sum(L) / len(L))
|
c6efa04b5744f23fe94de8f33477d554abc972be | mangeshii/hackerrank-python-practice | /Built-Ins/any-or-all.py | 547 | 3.984375 | 4 | '''
Task
You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer.
Input Format
The first line contains an integer . is the total number of integers in the list.
The second line contains the space separated list of integers.
Output Format
Print True if all the conditions of the problem statement are satisfied. Otherwise, print False.
'''
n = int(input())
m = input().split()
print(all([int(i) > 0 for i in m]) and (any([j == j[::-1] for j in m])))
|
d4d7ded7eca5dac68fc192ea17bb3c85a103a64d | oustella/coding-exercises | /myLinkedList.py | 3,297 | 4.34375 | 4 | # all things LinkedList
class ListNode():
def __init__(self, x):
self.value = x
self.next = None
def print(self):
temp = self
while temp and temp.next:
print(temp.value, end='->')
temp = temp.next
print(temp.value)
# singly linked list
class LinkedList():
def __init__(self):
self.head = None
def getHead(self):
return self.head
def insert(self, data): # insert a new head at the beginning of the linked list
newNode = ListNode(data)
newNode.next = self.head # point to the existing head first and inherit all the links
self.head = newNode # reassign the head to the new head
def push(self, data): # add a new node at the end of the linked list
newNode = ListNode(data)
current = self.head
# if the LinkedList is empty
if current:
while current.next: # you want current to arrive at the last node after the last iteration
current = current.next
current.next = newNode
else:
self.head = newNode
# This push method is fine in a class, but as an independent function it will lose the head.
# See 'merge_two_sorted_linkedlist.py' for an alternative push that keeps the head.
# def reverse(self): # see tutorials at https://www.geeksforgeeks.org/reverse-a-linked-list/
# prev = None
# current = self.head
# next = None
# while current:
# next = current.next # save the next element before redirecting the current pointer. Otherwise you will lose it.
# current.next = prev # point current to the previous element or None for the first element
# prev = current # move prev and current one node forward
# current = next
# self.head = prev # in the end current and next become none and prev arrives at the last element which is the first.
# def removeKFromList(self, k): # remove nodes if value equal to k
# current = self.head
# while current: # you want to go through the entire linked list so the last element needs to be examined
# if current.value == k: # if the head value is k, assign a new head to the next element
# self.head = current.next
# current = current.next # move along the pointer
# elif current.next and current.next.value == k: # if the next value is k, skip that node
# current.next = current.next.next
# current = current.next
# else:
# current = current.next
# def getMiddle(self): # return the start of the second half of the linked list.
# m = self.head # m moves one node at a time
# n = self.head # n moves two nodes at a time. By the time n reaches the end, m is half way through.
# while n and n.next:
# m = m.next
# n = n.next.next
# return m.value # m arrives at N//2 where N is the length of the linked list. m has moved N//2 times from first position.
# if __name__ == "__main__":
# ll = LinkedList()
# # ll.insert(1)
# # ll.insert(2)
# # ll.printLL()
# ll.push(2)
# ll.push(3)
# ll.printLL() |
e7f37b8ad28a81df73c4cd37c154d831ecded30d | minhoryang/advertofcode | /2017/17/spinlock.py | 472 | 3.984375 | 4 | class SpinLock(object):
def __init__(self):
self._data = [0]
self.len = 1
self.idx = 0
def spin(self, next=3):
for _ in range(next):
self.idx += 1
if self.idx == self.len:
self.idx = 0
return self._data[self.idx]
def insert(self, data):
self.len += 1
self.idx += 1
self._data.insert(self.idx, data)
if __name__ == "__main__":
cl = SpinLock()
hop = int(input())
for i in range(2017):
cl.spin(hop)
cl.insert(i + 1)
print(cl.spin(1))
|
ded2f4ba5c99b8372adfd2b5255967173f04394b | Yingying0618/DS-Career-Resources | /leetcode/remove_duplicates_linked_list.py | 457 | 3.796875 | 4 |
'''
83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
'''
# Standard approach - O(n) time, O(n) space
def deleteDuplicates(self, head):
curr = head
while curr and curr.next:
if curr.val == curr.next.val:
curr.next = curr.next.next
else:
curr = curr.next
return head
|
0ce076fc50f93a7aad19f78f5349258c56f50a5e | MrittikaDutta12/MrittikaDutta12.github.io | /dictionaryatack.py | 708 | 3.9375 | 4 | f = open("dictionary.txt","r")
file = f.readlines()
print("Can your password survive a dictionary attack?")
#Take input from the keyboard, storing in the variable test_password
c =input(" Enter password to be checked ")
for i in range(100):i
if c.casefold() in open("dictionary.txt","r").read():
print("weak password")
else:
print("strong password")
#Write logic to see if the password is in the dictionary file below here:
break
if c.isdigit() in open("dictionary.txt","r").read():
print("weak password")
else:
print("strong password")
string = c
for x in ("dictionary.txt")
print("choose another word")
else:
print("great")
|
a16d09f32cb31addc651f9d7352ea056b8ea3b2f | simdis/distributedCNNs | /graph.py | 8,051 | 3.546875 | 4 | import numpy as np
from matplotlib import pyplot as plt
import os
def euclidean_distance(x1, x2, y1, y2):
x = x1 - x2
y = y1 - y2
return np.sqrt(x * x + y * y)
def create_graph(nodes=10):
g = dict()
for i in range(nodes):
g[i] = set()
return g
def add_node_to_graph(graph):
n = len(graph)
graph[n] = set()
return graph
def generate_random_positions(nodes, minx=-10, maxx=10, miny=-10, maxy=10):
xl = maxx - minx
yl = maxy - miny
x = np.zeros(0)
y = np.zeros(0)
for i in range(nodes):
x = np.append(x, np.random.uniform(0, 1, 1) * xl + minx)
y = np.append(y, np.random.uniform(0, 1, 1) * yl + miny)
return x, y
def add_arcs_with_max_distance(graph, xpos, ypos, dmax=2.5):
# Add the arc (i,j) iff d_e(i,j) < dmax, where d_e is the Euclidean distance
for i in range(len(graph)):
for j in range(i + 1, len(graph)):
if euclidean_distance(xpos[i], xpos[j], ypos[i], ypos[j]) < dmax:
# Add both the arc (i,j) and (j,i) since the graph is acyclic.
graph[i].add(j)
graph[j].add(i)
return graph
def find_all_paths(graph, a, b, path=list(), already_visited_nodes=set()):
"""
Recursively find all paths starting from a and reaching b.
"""
path = path + [a]
# Check for the end of recursion
if a == b:
# print('*** !!! Find Path {} !!! ***'.format(path))
return [path]
# Check if a is isolated (in that case return empty list)
if not len(graph[a]):
return list()
# Create the list of paths
paths = list()
for node in graph[a]:
# Check if the node has been already visited to avoid infinite
# recursion due to cycles.
if not len(already_visited_nodes) or node not in already_visited_nodes:
if not len(already_visited_nodes):
avn = {a}
else:
avn = already_visited_nodes
avn.add(a)
recursive_paths = find_all_paths(graph, node, b, path=path,
already_visited_nodes=avn)
for p in recursive_paths:
paths.append(p)
return paths
def find_min_distance(graph, a, b):
paths = find_all_paths(graph, a, b)
if not len(paths):
return np.inf
return min({len(p) for p in paths}) - 1
def plot(graph, xpos, ypos, xm=5, outdir='.', figname=None, figsize=(15, 10),
source_available=True, sink_different_from_source=False,
num_sources=1, annotate=False,
color=None, marker=None, size=None, sequence=None):
# Compute useful stuff
num_nodes = len(xpos) - num_sources * source_available \
- num_sources * source_available * sink_different_from_source
plt.figure(figsize=figsize)
# Get axes reference to number nodes
ax = plt.gca()
plot_nodes(ax, xpos, ypos, xm,
source_available, sink_different_from_source,
num_sources, annotate,
color, marker, size, sequence)
# Compute the arcs
for k in graph:
for d in graph[k]:
if k >= num_nodes:
# The arc is from the source or to the sink.
ax.plot([xpos[k], xpos[d]], [ypos[k], ypos[d]],
linewidth=0.5, c='orange')
elif d > k:
ax.plot([xpos[k], xpos[d]], [ypos[k], ypos[d]],
linewidth=0.25, linestyle='--', c='darkblue')
# Save the figure
if figname is None:
plt.show()
else:
plt.savefig(os.path.join(outdir, figname))
plt.close('all')
def path_plot(xpos, ypos, path, xm=5, outdir='./', figname=None, figsize=(15, 10),
source_available=True, sink_different_from_source=False,
num_sources=1, path_source_idx=0,
annotate=False, color=None, marker=None, size=None, sequence=None,
path_color='darkred', out_prob=None, ax=None, plot_background=True):
# Compute useful stuff
num_nodes = len(xpos) - num_sources * source_available \
- num_sources * source_available * sink_different_from_source
if ax is None:
plt.figure(figsize=figsize)
# Get axes reference to number nodes
ax = plt.gca()
if plot_background:
plot_nodes(ax, xpos, ypos, xm,
source_available, sink_different_from_source,
num_sources, annotate,
color, marker, size, sequence)
# Add source and sink to the path
if source_available and sink_different_from_source:
# Save source idx in the path
path = np.append(-2*num_sources+path_source_idx, path)
elif source_available:
# Save source idx in the path
path = np.append(-num_sources+path_source_idx, path)
# Sink idx in the path
path = np.append(path, -num_sources+path_source_idx)
# Plot all the arcs
for i in range(len(path) - 1):
a = path[i]
b = path[i + 1]
if out_prob is None or i < len(path) - 2:
plot_arc(ax, x0=xpos[a], x1=xpos[b],
y0=ypos[a], y1=ypos[b],
color=path_color)
if out_prob is not None and i > 0 and out_prob[i-1] > 0:
plot_arc(ax, x0=xpos[a], x1=xpos[-num_sources+path_source_idx],
y0=ypos[a], y1=ypos[-num_sources+path_source_idx],
color=path_color, ls='-.',
annotate='{:.3f}'.format(out_prob[i-1]))
# Save the figure
if figname is None:
pass #plt.show()
else:
plt.savefig(os.path.join(outdir, figname))
plt.close('all')
return ax
def plot_nodes(ax, xpos, ypos, xm=5,
source_available=True, sink_different_from_source=False,
num_sources=1, annotate=False,
color=None, marker=None, size=None, sequence=None):
# Compute useful stuff
num_nodes = len(xpos) - num_sources * source_available \
- num_sources * source_available * sink_different_from_source
ax.set_xlim([-xm, xm])
ax.set_ylim([-xm, xm])
# Plot the nodes and annotate them (the last coordinate is the source)
if sequence is None:
ax.scatter(xpos[:num_nodes], ypos[:num_nodes], c='darkblue', marker='O', s=50)
else:
# Both markers and colors are different from None
for idx, value in enumerate(sequence):
ax.scatter(xpos[idx], ypos[idx], c=color[value], marker=marker[value], s=size[value])
if annotate:
for i in range(num_nodes):
ax.annotate(str(i + 1), (xpos[i], ypos[i]))
# Plot the source
if source_available and sink_different_from_source:
ax.scatter(
xpos[-2*num_sources:-num_sources],
ypos[-2*num_sources:-num_sources],
c='orange', s=200, marker='*'
)
for i in range(num_sources):
ax.annotate('S{}'.format(i+1), (xpos[-2*num_sources+i], ypos[-2*num_sources+i]))
ax.scatter(
xpos[-1*num_sources:],
ypos[-1*num_sources:],
c='darkred', s=200, marker='*'
)
for i in range(num_sources):
ax.annotate('Sink {}'.format(i+1), (xpos[-num_sources+i], ypos[-num_sources+i]))
elif source_available:
ax.scatter(
xpos[-1*num_sources:],
ypos[-1*num_sources:],
c='orange', s=200, marker='*'
)
for i in range(num_sources):
ax.annotate('S{}'.format(i+1), (xpos[-num_sources+i], ypos[-num_sources+i]))
def plot_arc(ax, x0, x1, y0, y1, color, lw=1, ls='--', annotate=None):
ax.plot([x0, x1], [y0, y1],
linewidth=lw, linestyle=ls, color=color)
xm = 0.5 * (x0 + x1)
ym = 0.5 * (y0 + y1)
dx = (x1 - x0) / 10
dy = (y1 - y0) / 10
ax.arrow(xm, ym, dx, dy, head_width=0.2, head_length=0.2, fc=color, ec='white')
if annotate is not None:
ax.annotate(annotate, (xm, ym))
|
f6f290488d31d9915a3031b24f8c972f29f988ca | jennyliuwhu/Data-Visualization | /relational_data.py | 9,862 | 3.53125 | 4 | import csv
import math
import sqlite3
import matplotlib.pyplot as plt
import pandas as pd
# Use svg backend for better quality
import matplotlib
import time
matplotlib.use("svg")
plt.style.use('ggplot')
# you should adjust this to fit your screen
matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)
__author__ = 'jialingliu'
def load_twitter_data_sqlite3(conn, users_filepath, edges_filepath, tweets_filepath) :
""" Load twitter data in the three files as tables into an in-memory SQLite database
Input:
conn (sqlite3.Connection) : Connection object corresponding to the database; used to perform SQL commands.
users_filepath (str) : absolute/relative path to users.csv file
edges_filepath (str) : absolute/relative path to edges.csv file
tweets_filepath (str) : absolute/relative path to tweets.csv file
Output:
None
"""
cursor = conn.cursor()
cursor.execute("drop table if EXISTS users")
cursor.execute("drop table if EXISTS tweets")
cursor.execute("drop table if EXISTS edges")
users_sql = "CREATE TABLE IF NOT EXISTS users (" \
"name TEXT, screen_name TEXT, " \
"location TEXT, created_at TEXT, " \
"friends_count INTEGER, followers_count INTEGER, " \
"statuses_count INTEGER, favourites_count INTEGER)"
edges_sql = "CREATE TABLE IF NOT EXISTS edges (screen_name TEXT, friend TEXT)"
tweets_sql = "CREATE TABLE IF NOT EXISTS tweets (" \
"screen_name TEXT, created_at TEXT, " \
"retweet_count INTEGER, favorite_count INTEGER, " \
"text TEXT)"
cursor.execute(users_sql)
cursor.execute(edges_sql)
cursor.execute(tweets_sql)
conn.commit()
with open(users_filepath) as f:
u = csv.reader(f)
next(u, None)
for row in u:
cursor.execute("INSERT INTO users VALUES (?,?,?,?,?,?,?,?);", row)
conn.commit()
with open(edges_filepath) as f:
e = csv.reader(f)
next(e, None)
for row in e:
cursor.execute("INSERT INTO edges VALUES (?,?);", row)
conn.commit()
with open(tweets_filepath) as f:
t = csv.reader(f)
next(t, None)
for row in t:
cursor.execute("INSERT INTO tweets VALUES (?,?,?,?,?);", row)
conn.commit()
# test
conn = sqlite3.connect(":memory:")
conn.text_factory = str
# call to your function
load_twitter_data_sqlite3(conn, 'users.csv', 'edges.csv', 'tweets.csv')
# make sure to change the path to csv files appropriately
cursor = conn.cursor()
# prints all tables in the database
for row in cursor.execute("SELECT name FROM sqlite_master WHERE type = 'table';"):
print row
for row in cursor.execute("SELECT Count(*) FROM users"):
print row
for row in cursor.execute("SELECT Count(*) FROM edges"):
print row
for row in cursor.execute("SELECT Count(*) FROM tweets"):
print row
def trending_tweets(cursor, topical_phrases=['Hillary', 'Clinton'], N=5):
""" Retrieves the top N trending tweets containing one or more of the given topical phrases.
Input:
cursor (sqlite3.Cursor): Cursor object to query the database.
topical_phrases (list of strings): A list of keywords identifying a topic.
N: Number of trending tweets to retrieve
Output:
results (sqlite3.Cursor): Cursor object which can be used to iterate over the retrieved records/tuples.
"""
# cannot pass test
# s = "SELECT DISTINCT tweet, trending_score FROM (SELECT `text` AS tweet, retweet_count + favorite_count AS trending_score FROM tweets WHERE `text` LIKE "
# prefix = ""
# for phrase in topical_phrases:
# s += prefix + "'%{}%'".format(phrase)
# prefix = " OR `text` LIKE "
# s += " ORDER BY trending_score DESC, tweet ASC) LIMIT {}".format(N)
# query = s
# results = cursor.execute(query)
# return results
query = "SELECT DISTINCT(text) AS tweet, (retweet_count + favorite_count) AS trending_score FROM tweets WHERE " + " OR ".join(("tweet LIKE '%" + phrase + "%'" for phrase in topical_phrases)) + " ORDER BY trending_score DESC LIMIT " + str(N) # your query here
results = cursor.execute(query)
return results
# test
results = trending_tweets(conn.cursor())
for row in results:
print row
def num_tweets_in_feed(cursor):
""" Retrieves the number of tweets STR recommends to each Twitter user.
Input:
cursor (sqlite3.Cursor): Cursor object to query the database.
Output:
results (sqlite3.Cursor): Cursor object which can be used to iterate over the retrieved records/tuples.
"""
query = "SELECT a1.screen_name, a1.cnt + ifnull(a2.cnt, 0) as num_tweets FROM (SELECT screen_name, 0 as cnt FROM users) AS a1 LEFT JOIN (SELECT edges.screen_name, COUNT(*) AS cnt FROM edges, tweets WHERE edges.friend = tweets.screen_name GROUP BY edges.screen_name) AS a2 ON a1.screen_name == a2.screen_name"
return cursor.execute(query)
t1 = time.time()
results = num_tweets_in_feed(conn.cursor())
count = 0
for row in results:
count += 1
t2 = time.time()
print t2 - t1
# print results
# debug
# results = num_tweets_in_feed(conn.cursor())
# i = 0
# for row in results:
# # if row[1] == 0:
# i += 1
# print row
# # if i > 20:
# # break
# # i += 1
#
# print i
# check edges
# slaves = []
# # masters = []
# for row in cursor.execute(query):
# print row
# slaves.append(row[0])
# masters.append(row[1])
#
# original_slaves = []
# original_masters = []
# count = 0
# with open("edges.csv", 'r') as f:
# for line in f:
# if count == 0:
# count += 1
# continue
# split_line = line.split(",")
# original_slaves.append(split_line[0])
# original_masters.append(split_line[1])
# with open("edges.csv", 'r') as f:
# edges_file = f.read()
#
# for row in csv.reader(edges_file.splitlines(), delimiter=','):
# if count == 0:
# count += 1
# continue
# # split_line = row.split(",")
# original_slaves.append(row[0])
# original_masters.append(row[1])
#
# c1 = 0
# c2 = 0
# for i in range(len(original_slaves)):
# if original_slaves[i] != slaves[i]:
# c1 += 1
# print "slave: ", slaves[i], "!=", original_slaves[i]
#
# for i in range(len(original_masters)):
# if original_masters[i] != masters[i]:
# c2 += 1
# print masters[i][-1] + "!=" + original_masters[i][-1]
# print c1, c2
def load_twitter_data_pandas(users_filepath, edges_filepath, tweets_filepath):
""" Loads the Twitter data from the csv files into Pandas dataframes
Input:
users_filepath (str) : absolute/relative path to users.csv file
edges_filepath (str) : absolute/relative path to edges.csv file
tweets_filepath (str) : absolute/relative path to tweets.csv file
Output:
(pd.DataFrame, pd.DataFrame, pd.DataFrame) : A tuple of three dataframes, the first one for users,
the second for edges and the third for tweets.
"""
users = pd.read_csv(users_filepath, na_filter=False)
edges = pd.read_csv(edges_filepath, na_filter=False)
tweets = pd.read_csv(tweets_filepath, na_filter=False)
return users, edges, tweets
# test
(users_df, edges_df, tweets_df) = load_twitter_data_pandas('users.csv', 'edges.csv', 'tweets.csv')
# make sure to change the path to csv files appropriately
print users_df.head()
print edges_df.head()
print tweets_df.head()
def plot_friends_vs_followers(users_df):
""" Plots the friends_count (on y-axis) against the followers_count (on x-axis).
Input:
users_df (pd.DataFrame) : Dataframe containing Twitter user attributes,
as returned by load_twitter_data_pandas()
Output:
(matplotlib.collections.PathCollection) : The object returned by the scatter plot function
"""
y = users_df['friends_count']
x = users_df['followers_count']
return plt.scatter(x, y)
p = plot_friends_vs_followers(users_df)
plt.show()
def average(x):
assert len(x) > 0
return float(sum(x)) / len(x)
def pearson_def(x, y):
assert len(x) == len(y)
n = len(x)
assert n > 0
avg_x = average(x)
avg_y = average(y)
diffprod = 0
xdiff2 = 0
ydiff2 = 0
for idx in range(n):
xdiff = x[idx] - avg_x
ydiff = y[idx] - avg_y
diffprod += xdiff * ydiff
xdiff2 += xdiff * xdiff
ydiff2 += ydiff * ydiff
return diffprod / math.sqrt(xdiff2 * ydiff2)
def correlation_coefficient(users_df):
""" Plots the friends_count (on y-axis) against the followers_count (on x-axis).
Input:
users_df (pd.DataFrame) : Dataframe containing Twitter user attributes,
as returned by load_twitter_data_pandas()
Output:
(double) : correlation coefficient between friends_count and followers_count
"""
# n = len(users_df.index)
# d1 = (users_df['friends_count'] * users_df['followers_count']).sum
return pearson_def(users_df['friends_count'], users_df['followers_count'])
# test
print correlation_coefficient(users_df)
def degree_distribution(edges_df):
""" Plots the distribution of .
Input:
edges_df (pd.DataFrame) : Dataframe containing Twitter edges,
as returned by load_twitter_data_pandas()
Output:
(array, array, list of Patch objects) : Tuple of the values of the histogram bins,
the edges of the bins and the silent list of individual patches used to create the histogram.
"""
counts = edges_df['screen_name'].value_counts().to_dict()
result = plt.hist(counts.values())
return result
# test
degree_distribution(edges_df) |
80a3e4b667e72a113896491f5738a01ee01964b3 | macosta-42/100_days_of_code | /1_Beginner/day4_Rock_Paper_Scissors/main.py | 943 | 4.15625 | 4 | # Rock Paper Scissors
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
import random
possibles = [rock, paper, scissors]
computer_choice = random.randint(0,2)
my_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for scissors.\n"))
print(possibles[my_choice])
print("Computer chose:")
print(possibles[computer_choice])
if my_choice > 2:
print("Invalid choice")
elif my_choice == 0 and computer_choice == 2:
print("You Win")
elif my_choice == 1 and computer_choice == 0:
print("You win")
elif my_choice == 2 and computer_choice == 1:
print("You Win")
elif my_choice == computer_choice:
print("It's a Draw")
else:
print("You Lose")
|
f3cf8b58d42c6629ea3bdffddd63b1f60effc61c | linegpe/FYS2160 | /Oblig1/opg1q.py | 929 | 3.640625 | 4 | from random import randint
from numpy import zeros, histogram, linspace, exp
import matplotlib.pyplot as plt
N = 50
M = 10000
M_values = zeros(M)
Omega0 = 1100
Omega = zeros(M)
# Create random integers and make s = +/- 1
# Store final values in array M_values
print "Looping..."
for j in range(0,M):
i = 0
s = 0
while i < N+1:
rand = randint(0,1)
i += 1
if rand == 1:
s += 1
elif rand == 0:
s -= 1
else:
print 'Error: random integer not 1 or 0'
M_values[j] = s
print 'Done!' # It might take some time to run
M_values = - M_values
x = linspace(-30,30,M)
print 'Second loop...'
for n in range(0,M):
Omega[n] = exp((-2*x[n]**2)/(4*N))*Omega0
#print len(x)
#print len(Omega)
#print Omega
# Histogram and plot
b = linspace(-29,30,60)-0.5
font = {'size' : 18}
plt.rc('font', **font)
plt.plot(x,Omega,linewidth=2)
plt.hist(M_values, bins = b)
plt.xlabel('Energy [$\mu$B]')
plt.ylabel('Counts')
plt.show() |
0acc2a152c7721369a2799fcd47e2085482d6e14 | urquia22/Interfacing-Pinguino-Matplotlib-1.01 | /AnalogReadSerialMatplotlib-1.01.py | 1,585 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import PBpinguino # importamos librerias necesarias // import necessary libraries
import matplotlib.pyplot as plt
from collections import deque
a = PBpinguino.TAPinguino() # iniciamos comunicacion via serial // start communication via serial with pinguino
a.pin_mode(13, "input") # pin 13 como entrada // pin 13 as input
Leer = 13 # asignamos a la variable Leer = 13 // assign to the variable Read = 13
onda = deque([0]*290 , maxlen=290) # asignamos a onda = deque con longitud máxima "290" // onda = deque with maximum length "290"
c = 0.004887585533
fig, ax = plt.subplots() # creamos la figura // create the figure
linea, = ax.plot(onda) # dibujamos la figura // draw the figure
while True:
ax.set_xlim(-2, 300) # fija limites de "x" // fixed limits of "x"
y = (a.analog_read(Leer))*c # y = lectura analogica en el pin 13 // assign to variable y = analog reading on pin 13
onda.append(y) # agregamos "y" a onda // add "y" to onda
linea.set_ydata(onda) # actualiza data de "y" // update data from "y"
ax.set_ylim(-0.2, 5.2)
plt.pause(1000 ** -2) # pausa la graficacion y almacena valores // Pause the graphing and store values
plt.show() # Mustrar la grafica // Show the graph
|
8eb09d680f9b9461049573011822daa19dea0d9e | joyceromao22/phyton_fundamentals | /Aulas/erros_excessoes.py | 527 | 4.03125 | 4 | # -*- coding: utf-8 -*-
#erros e excessoes
# while True:
# try:
# x = int(input('Digite o primeiro numero: '))
# y = int(input('Digite o segundo numero: '))
# print(f'resultado: {x +y}')
# except Exception as e:
# print('Digite apenas numeros!')
funcionarios = ['rafael', 'mariana', 'paulo']
try:
f = input('nome: ')
if f in funcionarios:
print('voce e um funcionario')
else:
raise NameError, ('voce e um funcionario')
except NameError as n:
print (n) |
15cd91de9ef6f695c3ebd3881a1ea47e1d9bd3da | anisinha77/sil_lab | /skill_lab/lab02-ass01/q09.py | 274 | 3.640625 | 4 | p = float(input("enter principal amount: "))
r = float(input("enter rate per annum: "))
t = float(input("enter time in years: "))
si = (p * r * t) / 100.0
ci_amt = p * pow((1 + r / 100), t)
ci = ci_amt - p
print(f"simple interest: {si}")
print(f"compound interest: {ci}")
|
d0f6dee3f81467329590f2c726a69ac523a9fbbc | shyamala987/CtCI_Py_Solns | /chap2/1_removeDup.py | 955 | 3.71875 | 4 | '''
Write code to remove duplicates from an unsorted linked list
Follow up: How would this change if a temp buffer is not allowed?
i/p
1 -> 3 -> 5 -> 2 -> 4 -> 2 -> 3 -> 5 -> 6
o/p
1 -> 6
'''
import linkedList
from linkedList import Node, LinkedList
class Solution:
def __init__(self):
self.cache = {}
def removeDups(self, head):
curr = head
dummy = Node(0)
while curr is not None:
if curr.val not in self.cache:
self.cache[curr.val] = True
dummy.next = curr
dummy = dummy.next
curr = curr.next
return head
if __name__ == '__main__':
ls = LinkedList()
for i in [1, 3, 5, 2, 4, 2, 3, 5, 6]:
node = Node(i)
ls.addNode(node)
ls.getValues()
s = Solution()
res = s.removeDups(ls.head)
while res is not None:
print(str(res.val) + ' -> ', end="")
res = res.next
print("None\n") |
63ea9e7395b964601b02092e32342a4634b62b88 | nedimperva/simple_python_projects | /higher-lower/main.py | 1,347 | 3.640625 | 4 | import random
from art import logo, vs
from gameData import data
import os
score = 0
should_end = False
#function for clearing command line screen
clear = lambda: os.system('cls') #instead of'cls' put 'clear' on Linux systems
#function to print game data
def print_data(a):
a_name = a["name"]
a_description = a["description"]
a_country = a["country"]
return(f"{a_name}, {a_description} from {a_country}")
#function to check answer
def check_answer(a_followers,b_followers, guess):
a_followers = a["follower_count"]
b_followers = b["follower_count"]
if a_followers > b_followers:
if guess == "a":
return True
else:
return False
a = random.choice(data)
b = random.choice(data)
if a == b:
b = random.choice(data)
while not should_end:
print(logo)
print(f"Compare A: {print_data(a)}")
print(vs)
print(f"Compare B: {print_data(b)}")
guess = input("Who has more followers, A or B: ").lower()
#check user answer
is_correct = check_answer(a,b,guess)
#give feedback
if is_correct:
clear()
score += 1
print(f"You got it right, your current score is {score}")
guess = a
b = random.choice(data)
else:
print(f"The answer wasn't correct, final score is {score}")
should_end = True
|
070da229b01c36653b4bc66a69c0eb782547e9e7 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex048.py | 435 | 3.953125 | 4 | """
Faca um programa que calcule a soma entre todos os numeros impares que sao
multiploes de 3 que se encontram no intervalo de 1 ate 500.
"""
count = 0
soma = 0
for c in range(1, 501):
if c % 3 == 0 and c % 2 != 0:
print(c, end=' ')
count += 1
soma += c
print('\nA soma de todos os valores impares entre 1 e 500 e {}.'.format(soma))
print('\nO total de numeros impares entre 1 e 500 e {}.'.format(count))
|
d3adbd3e3ff871dc5fb52cef87c3675e0bdb9dd1 | Satendarsingh/pythonlab | /shivraj.py | 245 | 3.8125 | 4 | def func1(m):
print("hii",m)
func1("man")
def func(a,b,c):
d=a+b+c
print(a,b,c,d)
func(3,5,8)
def func2(a,b):
c=a+b
return c
def func3():
print("hello,i am going to call the function")
s=func2(2,7)
print("''addition is",s)
func3()
|
bcb96a4e39d0f023c2babe901e8316a7340c352b | KlimChugunkin/PyBasics-Course | /Perper_Leonid_dz_8/task_8_3.py | 1,270 | 3.671875 | 4 | """
Задание 3
Написать декоратор для логирования типов позиционных аргументов функции. Если аргументов несколько - выводить данные о
каждом через запятую. Вывести тип значения функции. Решить задачу для именованных аргументов. Замаскировать работу
декоратора. Вывести имя функции.
"""
from functools import wraps
def type_logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f'Name: {func.__name__}')
print(*[f'{arg}: {type(arg)}' for arg in args], sep=', ')
if kwargs:
print(*[f'{key} = {val}: {type(val)}' for key, val in kwargs.items()], sep=', ')
return func(*args, **kwargs)
return wrapper
@type_logger
def divide(*args, divider=10, divider_correct=1, div_zero_correct=False):
if div_zero_correct and divider == 0:
divider = divider_correct
result = []
for arg in args:
result.append(arg / divider)
return result
test_list = [5, 8, 10, 6, 12]
print(divide(*test_list, divider=5, div_zero_correct=True))
print(divide.__name__)
|
f6846b8ab88110f09359da376e6ddad90112ec07 | kamkarm/Stock-Analysis | /graph_data/first_day_difference.py | 1,059 | 3.765625 | 4 | """
Create a line graph of how the stock value compares to it's value on 1/02/2019
for each stock.
For each stock, the query will find the difference between the stock's
value at day X and 1/02/2019
Query is then plotted on as a bar graph on matplotlib
"""
import psycopg2
import matplotlib.pyplot as plt
import sys
sys.path.append('../')
import db
if __name__ == "__main__":
con = db.connect()
cur = con.cursor()
try:
cur.execute(open('sql_queries/first_day_difference.sql').read())
except psycopg2.DatabaseError as error:
print(error)
else:
result = cur.fetchall()
data = {'AAPL' : [], 'FB': [], 'GOOG': []}
for symbol, val in result:
data[symbol].append(val)
xTickMarks = [i for i in range(len(data['AAPL']))]
for stock, vals in data.items():
plt.plot(xTickMarks,vals)
plt.xlabel('Days Since January 2nd 2019')
plt.ylabel('Current Day and January 2nd 2019 Stock Price Difference')
plt.title('Stock Growth from January 2nd 2019 per Day for ' + stock)
plt.show()
finally:
if con is not None:
con.close() |
b7b96d107c7d04fb841ba85f9448ebb1cd4d3257 | Mpatel1618/Python_Data_Analysis | /project_final_facebook.py | 5,217 | 3.765625 | 4 | # import pandas library as pd and matplotlib.pyplot linrary as plt
import pandas as pd
import matplotlib.pyplot as plt
#Part 2: graphs and relationships with time series
df = pd.read_csv('123_employee_reviews.csv', encoding = 'latin-1')
#locating the company data in the dataframe
facebook_data = df.loc[df['company'] == 'facebook']
def no_none(stars_1):
'''gets rid of all of the nones in the data'''
stars_2 = []
for i in stars_1:
if i != 'none':
stars_2.append(float(i))
return stars_2
#plt.plot(x,y)
#this is very time consuming and python is hard to handle this big amount of data, so we decide to divide the dates by years
#for facebook
fac1=facebook_data['dates']
years=[]
for d in fac1:
y=d.split('/')[2] #find only the years
years.append(int(y))
facebook_data['years']=years #create another column called 'years' which only contains the years
def graph(category):
'''this function makes a graph for each of the categories that is inputted by calculating the average of that category from a certain year'''
fac2008=facebook_data[facebook_data.years==2008]
fac2008_fixed = no_none(fac2008[category])
facebook_y2008=float(sum(fac2008_fixed))/(float(len(fac2008_fixed)))
fac2009=facebook_data[facebook_data.years==2009]
fac2009_fixed = no_none(fac2009[category])
facebook_y2009=float(sum(fac2009_fixed))/(float(len(fac2009_fixed)))
fac2010=facebook_data[facebook_data.years==2010]
fac2010_fixed = no_none(fac2010[category])
facebook_y2010=float(sum(fac2010_fixed))/(float(len(fac2010_fixed)))
fac2011=facebook_data[facebook_data.years==2011]
fac2011_fixed = no_none(fac2011[category])
facebook_y2011=float(sum(fac2011_fixed))/(float(len(fac2011_fixed)))
fac2012=facebook_data[facebook_data.years==2012]
fac2012_fixed = no_none(fac2012[category])
facebook_y2012=float(sum(fac2012_fixed))/(float(len(fac2012_fixed)))
fac2013=facebook_data[facebook_data.years==2013]
fac2013_fixed = no_none(fac2013[category])
facebook_y2013=float(sum(fac2013_fixed))/(float(len(fac2013_fixed)))
fac2014=facebook_data[facebook_data.years==2014]
fac2014_fixed = no_none(fac2014[category])
facebook_y2014=float(sum(fac2014_fixed))/(float(len(fac2014_fixed)))
fac2015=facebook_data[facebook_data.years==2015]
fac2015_fixed = no_none(fac2015[category])
facebook_y2015=float(sum(fac2015_fixed))/(float(len(fac2015_fixed)))
fac2016=facebook_data[facebook_data.years==2016]
fac2016_fixed = no_none(fac2016[category])
facebook_y2016=float(sum(fac2016_fixed))/(float(len(fac2016_fixed)))
fac2017=facebook_data[facebook_data.years==2017]
fac2017_fixed = no_none(fac2017[category])
facebook_y2017=float(sum(fac2017_fixed))/(float(len(fac2017_fixed)))
fac2018=facebook_data[facebook_data.years==2018]
fac2018_fixed = no_none(fac2018[category])
facebook_y2018=float(sum(fac2018_fixed))/(float(len(fac2018_fixed)))
#doing the plot
xfacebook=['2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018']
yfacebook=[facebook_y2008,facebook_y2009,facebook_y2010,facebook_y2011,facebook_y2012,facebook_y2013,facebook_y2014,facebook_y2015,facebook_y2016,facebook_y2017,facebook_y2018]
plt.plot(xfacebook,yfacebook)
plt.xlabel('Year')
plt.ylabel('Rating')
plt.title('Facebook')
#calls the graph function to plot the points
graph('overall-ratings')
graph('work-balance-stars')
graph('carrer-opportunities-stars')
graph('comp-benefit-stars')
graph('senior-mangemnet-stars')
#special case for culture values because there are so many 'none's
fac2012=facebook_data[facebook_data.years==2012]
fac2012_fixed = no_none(fac2012['culture-values-stars'])
facebook_y2012=float(sum(fac2012_fixed))/(float(len(fac2012_fixed)))
fac2013=facebook_data[facebook_data.years==2013]
fac2013_fixed = no_none(fac2013['culture-values-stars'])
facebook_y2013=float(sum(fac2013_fixed))/(float(len(fac2013_fixed)))
fac2014=facebook_data[facebook_data.years==2014]
fac2014_fixed = no_none(fac2014['culture-values-stars'])
facebook_y2014=float(sum(fac2014_fixed))/(float(len(fac2014_fixed)))
fac2015=facebook_data[facebook_data.years==2015]
fac2015_fixed = no_none(fac2015['culture-values-stars'])
facebook_y2015=float(sum(fac2015_fixed))/(float(len(fac2015_fixed)))
fac2016=facebook_data[facebook_data.years==2016]
fac2016_fixed = no_none(fac2016['culture-values-stars'])
facebook_y2016=float(sum(fac2016_fixed))/(float(len(fac2016_fixed)))
fac2017=facebook_data[facebook_data.years==2017]
fac2017_fixed = no_none(fac2017['culture-values-stars'])
facebook_y2017=float(sum(fac2017_fixed))/(float(len(fac2017_fixed)))
fac2018=facebook_data[facebook_data.years==2018]
fac2018_fixed = no_none(fac2018['culture-values-stars'])
facebook_y2018=float(sum(fac2018_fixed))/(float(len(fac2018_fixed)))
#doing the plot for culture values
xfacebook=['2012','2013','2014','2015','2016','2017','2018']
yfacebook=[facebook_y2012,facebook_y2013,facebook_y2014,facebook_y2015,facebook_y2016,facebook_y2017,facebook_y2018]
plt.plot(xfacebook,yfacebook) |
476d111c29d5f8a7bf120b81f136a06d69aff77b | ritwiktiwari/AlgorithmsDataStructures | /Recursion/problem-19.py | 294 | 4.03125 | 4 | """
Find greatest common divisor using recursion
"""
def gcd(a: int, b: int):
assert a == int(a) and b == int(b), "a and b must be integers"
if a != 0 and b == 0:
return a
# if a % b == 0:
# return b
return gcd(b, a % b)
print(gcd(48, 18))
print(gcd(48, 0))
|
f5e8ecaab2b55fed4994ee77859dcae7317d6ba3 | kbutler52/Teach2020 | /typesData.py | 626 | 4.03125 | 4 | #06-02-2020
#while loop
i=0
while i < 10:
print(f"We have {i} things")
i=i+1
a = 0
for q in range (1,10):
print("We have %d cats." %(q))
apples = 25
pears = 20
print(apples < pears)
print(not(apples < pears))
print(apples %2==0)
print(not(apples %2==0))
print(pears %2==0)
print(not(pears %2==0))
if (apples < pears):
print("We have less pears than apples")
elif(not(apples < pears)):
print(" We have %d pears." %(20))
elif(apples %2==0):
print("We have a even number of apples")
elif(not(apples %2==0)):
print("we have a odd number of apples {}." .format(25))
|
dcba53c8778b92abd32fe83508139c39588cad00 | Vk-Demon/vk-code | /ckarray16.py | 314 | 3.609375 | 4 | nnum=int(input()) # You are given an array of ids of prisoners. The jail authority found that there are some prisoners of same id. Your task is to help the authority in finding the common ids
lt=[int(i) for i in input().split()]
st=[]
for i in range(0,len(lt)-1):
if(lt[i]==lt[i+1]):
print(lt[i],end="")
|
37222b5f144cd1d2bda87e50f683473f2574cc17 | sergeichestakov/InterviewPrep | /palindromePartitioning.py | 950 | 3.640625 | 4 | # Given a string s, partition s such that every substring of the partition is a palindrome.
# Return all possible palindrome partitioning of s.
class Solution:
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
ret = []
self.generatePartitions(ret, [], s, 0)
return ret
def generatePartitions(self, ret, tempList, s, start):
if start == len(s):
ret.append(tempList[:])
else:
for index in range(start, len(s)):
if self.isPalindrome(s, start, index):
tempList.append(s[start:index + 1])
self.generatePartitions(ret, tempList, s, index + 1)
del tempList[-1]
def isPalindrome(self, s, low, high):
while low < high:
if s[low] != s[high]:
return False
low += 1
high -= 1
return True
|
7cbafb9f1fb77a9b029173d83aba7439183f67c6 | kimoba/Code-in-Place-2021 | /Extra Work/05 Lists/Shorten/shorten.py | 395 | 4.25 | 4 | SAMPLE_LIST = ['a', 'b', 'c', 'd', 'e']
MAX_LENGTH = 3
def shorten(lst, max_len):
# removes items from the end of the list
while len(lst) > max_len:
removed_item = lst.pop()
print(removed_item)
# prints item until lst is max_len items long
print("The new list is: ", lst)
def main():
shorten(SAMPLE_LIST, MAX_LENGTH)
if __name__ == "__main__":
main()
|
505dc2ebb3f741864cdc4fecdffe9f47c56961cf | OldTaoge/python_edu | /#4/test6.py | 96 | 3.5 | 4 | #4-6
table = []
for num in range(1,21,2):
table.append(num)
for num in table:
print(num) |
7012239f7799ae9aefba18ba7655ef5574b6169b | Cluxnei/uri-online-judge-problems | /INICIANTE/NIVEL-1/1002/1002.py | 71 | 3.6875 | 4 | radius = float(input())
print('A={:.4f}'.format(radius ** 2 * 3.14159)) |
5e5e9fa40c8398677050ced6c24c6c19db8389d0 | NeonMiami271/Work_JINR | /Python/max_among_parity.py | 241 | 3.59375 | 4 | import random
N = 5
max = 0
x = list()
for i in range (0,N):
a = random.randint(-100,100)
x.append(a)
print(str(x))
for i in range (0,N):
if ((i+1) % 2 == 0) and (x[i] > max):
max = x[i]
print("Ответ: " + str(max))
|
1c56a4c6b5b48db444809d291c3f2197f7f82858 | agamat/genetics-multiple-alignment | /utils.py | 4,898 | 4 | 4 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from numpy.random import choice
def cost(letter1, letter2):
""" Calculate the cost or score of the alignment of 2 letters.
Parameters:
----------
letter1: character
letter2: character
Return:
------
score: int
score of the alignment (-1 if the 2 letters are different, 2 if they are similar)
"""
if letter1 == letter2:
return 2
else:
return -1
def addgap(seq, gaplist, verbose=0):
""" Insert gaps into sequence.
Parameters:
----------
seq: string of characters
sequence of nucleotides
gaplist: list of int
list of gaps to insert successively in the sequence seq
Return:
------
newseq: string of characters
the modified sequence with inserted gaps
"""
newseq = seq[:]
for g in gaplist:
if g > len(newseq):
print("gap postion bigger than sequence length -> gap inserted at the end of the sequence")
newseq = newseq[:g] + '_' + newseq[g:]
if verbose > 0:
print("gap introduced in {}th position -> new sequence equals {}.".format(g, newseq))
return newseq
def substitution(seq, pos, verbose=0, value=None, alphabet=["A", "C", "G", "T"]):
""" Induce a mutation of the sequence by substituting a letter.
Parameters:
----------
seq: string of characters
sequence of nucleotides
pos: int in [-len(seq), len(seq)]
position of the mutation
verbose: int (default=0)
level of verbosity
value: None or alphabet item (default=None)
new letter induced by the mutation.
if None, an item different from the initial one is randomly chosen in alphabet.
alphabet: list of characters (default=["A", "C", "G", "T"])
list of nucleotides to consider in sequences
Return:
------
seqr: string
the modified sequence containing the mutation
"""
seqr = list(seq[:])
alphabis = alphabet.copy()
alphabis.remove(seqr[pos])
if value == None:
seqr[pos] = choice(alphabis, 1)[0]
elif value in alphabet:
seqr[pos] = value
else:
return "error"
seqr = "".join(seqr)
if verbose > 0:
print(seqr)
return seqr
def insertion(seq, pos, verbose=0, value=None, alphabet=["A", "C", "G", "T"]):
""" Induce a mutation of the sequence by inserting a new letter.
Parameters:
----------
seq: string of characters
sequence of nucleotides
pos: int in [-len(seq), len(seq)]
position of the mutation
verbose: int (default=0)
level of verbosity
value: None or alphabet item (default=None)
new letter induced by the mutation.
if None, an item different from the initial one is randomly chosen in alphabet.
alphabet: list of characters (default=["A", "C", "G", "T"])
list of nucleotides to consider in sequences
Return:
------
seqr: string
the modified sequence containing the mutation
"""
seqr = seq[:]
if value is None:
value = choice(alphabet, 1)[0]
seqr = seqr[:pos] + value + seqr[pos:]
seqr = "".join(seqr)
if verbose > 0:
print(seqr)
return seqr
def deletion(seq, pos, verbose=0):
""" Induce a mutation of the sequence by deleting a letter.
Parameters:
----------
seq: string of characters
sequence of nucleotides
pos: int in [-len(seq), len(seq)]
position of the mutation
verbose: int (default=0)
level of verbosity
Return:
------
seqr: string
the modified sequence containing the mutation
"""
seqr = list(seq[:])
del seqr[pos]
seqr = "".join(seqr)
if verbose > 0:
print(seqr)
return seqr
def print_table(table):
""" Display the score or path matrix as a table.
Parameters:
----------
table: matrix of floats or int
score or path matrix
Return:
------
none
"""
plt.figure()
tb = plt.table(cellText=table.astype(int), loc=(0,0), cellLoc='center')
tc = tb.properties()['child_artists']
for cell in tc:
cell.set_height(1/table.shape[0])
cell.set_width(1/table.shape[1])
ax = plt.gca()
ax.set_xticks([])
ax.set_yticks([])
plt.show()
if __name__ == "__main__":
alphabet = ["A", "C", "G", "T"]
print("TEST ADDGAP FUNCTION")
seq = choice(alphabet, 7)
seq = ''.join(seq)
gaplist = [1, 4, 7, 0, 0]
newseq = addgap(seq, gaplist)
print("The initial sequence equals: {} and the gaplist equals: {}. "
"The final sequence equals: {}.".format(seq, gaplist, newseq))
print("TEST COST FUNCTION")
for i in range(5):
l1 = choice(alphabet)
l2 = choice(alphabet)
print("The cost of ({}, {}) equals {}.".format(l1, l2, cost(l1, l2)))
|
29cfba5aca32dec55cb8c5ea709b70232178ff7d | MaksymSkorupskyi/HackerRank_Challenges | /30 Days of Code/Day 03 - Intro to Conditional Statements.py | 763 | 4.40625 | 4 | """Day 3: Intro to Conditional Statements
https://www.hackerrank.com/challenges/30-conditional-statements/problem
Given a positive integer, n, perform the following conditional actions:
If is odd, print Weird
If is even and in the inclusive range 2 of 5 to , print Not Weird
If is even and in the inclusive range of 6 to 20, print Weird
If is even and greater than 20, print Not Weird
Complete the stub code provided in your editor to print whether or not is weird.
"""
n = int(input().strip())
if n % 2:
print('Weird')
elif n in (2, 4) or n > 20:
print('Not Weird')
else:
print('Weird')
"""
n = int(input().strip())
if n % 2 != 0:
print('Weird')
elif (n >= 2 and n <= 5) or n > 20:
print('Not Weird')
else:
print('Weird')
""" |
15db6018c8a8c0c72dcd50c83cd9a7c7c2166996 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2_neat/16_0_2_AmolMandhane_BL.py | 813 | 3.609375 | 4 | cases = input()
def successor(stack, move):
move += 1
new_stack = [""] * len(stack)
for i in xrange(len(stack)):
if i < move:
new_stack[i] = "+" if stack[move - 1 - i] is "-" else "-"
else:
new_stack[i] = stack[i]
return "".join(new_stack)
for T in xrange(cases):
pancakes = raw_input().strip()
num = len(pancakes)
count = 0
index = num - 1
while index >= 0:
if pancakes[index] is "+":
index -= 1
continue
if pancakes[0] is "-":
flip = index
index -= 1
else:
flip = index
while pancakes[flip] is "-":
flip -= 1
pancakes = successor(pancakes, flip)
count += 1
print "Case #%d: %d" % (T + 1, count)
|
b3fd0b6ef8aaa326f37c796b765f044327d7c5d3 | wuyongqiang2017/AllCode | /day29/继承与派生.py | 2,912 | 4.0625 | 4 | # class ParentClass1:#定义父类
# pass
# class ParentClass2:#定义父类
# pass
# class SubClass1(ParentClass1):#单继承,基类是ParentClass1,派生类是SubClass
# pass
# class SubClass2(ParentClass1,ParentClass2):#python支持多继承,用逗号分隔开多个继承的类
# pass
#
# print(ParentClass1.__bases__)
# print(SubClass1.__bases__)
# print(SubClass2.__bases__)
# class Animal:
# def __init__(self,name,age):
# self.name = name
# self.age = age
# def walk(self):
# print('%s is walking'%self.name)
# def say(self):
# print('%s is saying'%self.name)
# class People(Animal):
# pass
# class Pig(Animal):
# pass
# class Dog(Animal):
# pass
# p1 = People('obama',50)
# print(p1.name)
# print(p1.age)
# p1.walk()
# class Hero:
# def __init__(self,nickname,aggressivity,life_value):
# self.nickname=nickname
# self.aggressivity=aggressivity
# self.life_value=life_value
# def attack(self,enemy):
# enemy.life_value -= self.aggressivity
# class Teacher:
# def __init__(self,name,sex,course):
# self.name=name
# self.sex=sex
# self.course=course
# class Student:
# def __init__(self,name,sex,course):
# self.name=name
# self.sex=sex
# self.course=course
# class Course:
# def __init__(self,name,price,period):
# self.name=name
# self.price=price
# self.period=period
# python_obj=Course('python',15800,'7m')
# t1=Teacher('egon','male',python_obj)
# s1=Student('cobila','male',python_obj)
#
# print(s1.course.name)
# print(t1.course.name)
# class Teacher:
# def __init__(self,birth):
# self.birth=birth
# class Student:
# def __init__(self,birth):
# self.birth=birth
# class Birth:
# def __init__(self,year,mouth,day63):
# self.year=year
# self.mouth=mouth
# self.day63=day63
# t1=Teacher()
# class Interface:
# def read(self):
# pass
# def write(self):
# pass
# class Txt(Interface):
# def read(self):
# print ("dududu")
# def write(self):
# print ("xiexiexie")
# class Sata(Interface):
# def read(self):
# print ("yinpandudud")
# def write(self):
# print ("yingpanxiexie")
# class Process(Interface):
# def read(self):
# print ("jinchengdudu")
# def write(self):
# print ("jincengxiexi")
# def add(s,x):
# return s+x
# def generator():
# for i in range(4):
# yield i
# base = generator()
# for n in [1,11]:
# base = (add(i,n) for i in base)
# print(list(base))
# def add(s, x):
# return s + x
# def generator():
# for i in range(4):
# yield i
# base = generator()
# n = 1
# base1 = (add(i, n) for i in base)
# n=11
# base2 = (add(i, n) for i in base1)
# print(list(base2))
#原谅我还是不会
|
a62bf7fe40e5aceb6fdcb761c7eebfe6acdef75c | amanullah28/code_practice | /python_practice/oop/class_var.py | 583 | 3.8125 | 4 | class Pet:
allowed = ['cat', 'dog', 'hen']
def __init__(self, name, species):
if species not in Pet.allowed:
raise ValueError(f"You can't have {species} pet!")
self.name = name
self.species = species
def set_species(self, species):
if species not in Pet.allowed:
raise ValueError(f"You can't have {species} pet!")
self.species = species
pet1 = Pet('jingle', 'cat')
pet2 = Pet('jhandu', 'dog')
print(pet2.species)
# pet2.species = "dfjdf"
pet2.set_species('cat')
print(pet2.species)
pet2.species = 'dfndf'
print(pet2.species)
# print(cat.name, cat.species)
|
419e5ff62d7d9c8b398442d904dd3ca2612a0489 | JiahuiQiu/Python-Learning | /ZJU-Python/CH3/ch3-6.py | 703 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
求整数序列中出现次数最多的数
本题要求统计一个整型序列中出现次数最多的整数及其出现次数。
输入格式:
输入在一行中给出序列中整数个数N(0<N≤1000),以及N个整数。数字间以空格分隔。
输出格式:
在一行中输出出现次数最多的整数及其出现次数,数字间以空格分隔.
题目保证这样的数字是唯一的。
输入样例:
10 3 2 -1 5 3 4 3 0 3 2
输出样例:
3 4
"""
list1 = input().split(" ")
list2 = list1[1:]
most_occur_num = max(list2, key=list2.count)
occur_freq = list2.count(most_occur_num)
print(most_occur_num, occur_freq)
|
ce07e9b6609d74050f7eadbadba0d17892acbea9 | crobarcro/pyscape-presentation | /presentscape.py | 8,390 | 3.828125 | 4 | #!/usr/bin/python
#
# This script converts a presentation made in inkscape and saved
# as SVG to a PDF presentation.
#
# Invoke the script on the command line with:
#
# presentscape.py <yoursvgname.svg>
#
# This is done by converting layers in the SVG to individual pdf files
# and merging them. Merging will only be done if the 'pdftk' program is
# available. This would be done manually with the command:
#
# pdftk slide*.pdf output presentation.pdf
#
# The script has a few assumptions:
#
# 1. Slide labeled "TITLE" is the first slide of the presentation (the title
# slide, obviously)
#
# 2. The master slide (the template for the presentation) is after the title
# slide
#
# 3. The final "thank you" slide is labelled "END"
#
# 4. Additional layer/slide labelled "STOP" is put after "END" and possible
# backup slides, so the script knows when to stop.
#
# 5. A layer labelled "NUMBER" may also be placed somewhere after "STOP".
# It should contain only a text element positioned appropriately as a
# placeholder for the slide number text. The Label property of this
# text object should be changed to "slidenumber" (this will already be
# set in the template svg). If you need to change it, click on the text
# object and go to Object->Object Properties. The text can be anything
# you like, pyscape will search for "NS" in the text and replace it
# with the slide number if it is found. pyscape will also search for
# "NT" and replace this with the total number of slides in the
# presentation. e.g. the text "Slide NS of NT" would become
# "Slide 02 of 10" for slide 2 of a 10 slide presentation.
# The number text will not appear on the title slide.
#
import xml.etree.ElementTree as xmltree
import sys
import os
import subprocess
import shutil
import glob
import tempfile
import distutils.spawn
nargs = len(sys.argv)
# the svg file to work on
input_fname = str(sys.argv[1])
# temp files directory
tempdir = os.path.join (tempfile.gettempdir(), 'slides')
# make sure temp slide directory is cleared of old files by deleting it
# and all contents
if os.path.exists(tempdir):
shutil.rmtree(tempdir)
# create the empty directory again
os.makedirs(tempdir)
# define temp name for svg, you don't really need to worry about this
tmp_fname = os.path.join (tempdir, 'temppi.svg')
# define some parameters
label = "{http://www.inkscape.org/namespaces/inkscape}label" #namespace for inkscape label
name = 'slidenumber' #just the name of the slidenumber quantity
def is_svg(filename):
tag = None
with open(filename, "r") as f:
try:
for event, el in xmltree.iterparse(f, ('start',)):
tag = el.tag
break
except xmltree.ParseError:
pass
return tag == '{http://www.w3.org/2000/svg}svg'
if os.path.exists(input_fname):
if is_svg (input_fname) == False:
# it's not svg
print ('The input file:\n{}\ndoes not appear to be a valid svg file.').format (input_fname)
sys.exit()
else:
# read the svg file as XML tree
tree = xmltree.parse(input_fname)
root = tree.getroot()
else:
print ('The input file:\n{}\ncould not be found').format (input_fname)
sys.exit()
# loop through layers looking for NUMBER slide layer
foundNumberElement = False
for child in root:
child.set('style','display:none')
if child.get(label) == 'NUMBER':
print ('Found NUMBER slide, now looking for label containing {}').format (name)
numberlayer = child
for subchild in child.iter():
if subchild.tag == '{http://www.w3.org/2000/svg}text':
print ('found text tag')
print (subchild.attrib)
labelFound = True
try:
#idcontents = subchild.attrib['id']
labelcontents = subchild.attrib[label]
except KeyError, e:
labelFound = False
#if subchild.get('name')==name:
if labelFound and (labelcontents == name):
print ('found label with contents {}').format (name)
tspans = subchild.findall('{http://www.w3.org/2000/svg}tspan')
number = tspans[0]
slide_num_text = tspans[0].text
print ('Template slide_num_text is: ' + slide_num_text)
#print (number)
foundNumberElement = True
break
if foundNumberElement == True:
break
if foundNumberElement == False:
print ('Number text element not found!')
break
#sys.exit ()
# if child.get(label)='NUMBER'):
# count the slides
num_slides = 0
for child in root:
if child.get(label)=='STOP':
break
if child.get(label)=='TITLE':
num_slides = 1
continue
if child.get(label)=='MASTER':
continue
elif child.get(label)=='END':
num_slides = num_slides + 1
continue
elif num_slides > 0:
num_slides = num_slides + 1
slide_counter = -1
print ('Beginning pdf creation ...')
print ('Creating individual slide pdf files in temporary directory:\n%s' % tempdir)
# ensure number layer is not displayed until we decide to
if numberlayer is not None:
numberlayer.set('style','display:none')
for child in root:
print (child.get(label))
# print child.keys()
# print child.items()
if child.get(label) == 'STOP':
print ('Found STOP, ending processing')
break
if child.get(label) == 'TITLE':
print ('Processing TITLE')
child.set('style','display:inline')
tree.write(tmp_fname)
subprocess.call(['inkscape','-A', os.path.join(tempdir, 'slide00.pdf'), tmp_fname])
child.set('style','display:none')
slide_counter = 1
continue
if child.get(label) == 'MASTER':
print ('Found MASTER')
child.set('style','display:inline')
if foundNumberElement:
numberlayer.set('style','display:inline')
elif child.get(label) == 'END':
print ('slide {:d}'.format(slide_counter))
if foundNumberElement:
temp_text = slide_num_text
temp_text = temp_text.replace ('NS', '{:02d}'.format (slide_counter))
temp_text = temp_text.replace ('NT', '{:d}'.format (num_slides))
number.text = temp_text
numberlayer.set('style','display:none')
child.set('style','display:inline')
tree.write(tmp_fname)
subprocess.call(['inkscape','-A', os.path.join(tempdir, ('slide%02d.pdf' % slide_counter)), tmp_fname])
child.set('style','display:none')
slide_counter = slide_counter + 1
elif slide_counter > 0:
print ('Processing slide {:02d}'.format (slide_counter))
if foundNumberElement:
temp_text = slide_num_text
temp_text = temp_text.replace ('NS', '{:02d}'.format (slide_counter))
temp_text = temp_text.replace ('NT', '{:d}'.format (num_slides))
number.text = temp_text
print (number.text)
#number.text = ('{:02d}'.format (slide_counter))
child.set('style','display:inline')
tree.write(tmp_fname)
subprocess.call(['inkscape','-A', os.path.join(tempdir, ('slide%02d.pdf' % slide_counter)), tmp_fname])
child.set('style','display:none')
slide_counter = slide_counter + 1
# get the list of individual slide pdf files
tmplist = glob.glob(os.path.join(tempdir, 'slide*.pdf'))
# sort the file names so the slides are in the right order
tmplist.sort ()
# this works in python 2.7
pdftkloc = distutils.spawn.find_executable ('pdftk')
if pdftkloc is not None:
print ('Combining slide pdfs into single pdf using pdftk')
# use pdftk to catenate the pdfs into one
subprocess.call(['pdftk'] + tmplist + ['output', 'presentation.pdf'])
#pdftk in1.pdf in2.pdf cat output out1.pdf
#tree.write('drawing2.svg')
print ('Deleting temporary files')
# clean up
shutil.rmtree(tempdir)
else:
print ('Cannot join individual slide pdfs into single pdf as pdftk program is not found.')
print ('You will find the individual slide pdfs in the directory:\n%s.' % tempdir)
print ('Finished!')
|
d33c1cf957ab3eeabae17bed0c721e4ad9707584 | YasserZhang/foobarChallenge | /google_foobar_level1.py | 587 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 18 22:00:12 2017
@author: ning
"""
def answer(s):
letters = "abcdefghijklmnopqrstuvwxyz"
reverse_letters = letters[::-1]
letters_dict = {}
for l, r in zip(letters, reverse_letters):
letters_dict[l] = r
translation = ""
for letter in s:
try:
translation += letters_dict[letter]
except:
translation += letter
if __name__ == '__main__':
#s = "Yvzs! I xzm'g yvorvev Lzmxv olhg srh qly zg gsv xlolmb!!"
s = "wrw blf hvv ozhg mrtsg'h vkrhlwv?"
print answer(s)
|
a0bee0002897abb0e2ccbb0fb2c91b42d67df525 | geokhoury/htu-ictc6-python-webapp-development | /W2/S3/PA01/solutions/famous_dinner.py | 2,459 | 4.5625 | 5 | # Famous Dinner
# You are inviting three famous people for dinner.
guests = ['nicola tesla', 'albert einstine', 'leonardo da vinci']
# Invite your guests to dinner.
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"\nSorry, {name} can't make it to dinner.")
# TODO: Einstine can't make it on this day! Remove him and invite Socrates instead.
del(guests[1])
guests.insert(1, 'socrates')
# TODO: Print the invitations again.
name = guests[0].title()
print(f"\n{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")
print("\nWe got a bigger table!")
# TODO: We got a bigger table, think of three more people and add them to the list.
# Use append() and insert() at least once
guests.insert(0, 'alan turing')
guests.insert(2, 'ken thompson')
guests.append('alan watts')
# TODO: Print the invitations again.
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")
name = guests[3].title()
print(f"{name}, please come to dinner.")
name = guests[4].title()
print(f"{name}, please come to dinner.")
name = guests[5].title()
print(f"{name}, please come to dinner.")
# Oh no, the table won't arrive on time!
print("\nSorry, we can only invite two people to dinner.")
# TODO: Use the following lines to remove a guest from the list, make sure you only invite two.
# name = guests.pop()
# print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
# TODO: There should be two people left. Let's invite them.
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
print("\nGood food. Good conversation.")
# Empty out your guest list.
guests.clear()
# del(guests[0])
# del(guests[0])
# Print your empty guest list
print(guests)
|
3b3f372a85c257d434972af59af347e2b9bb36b8 | NIROJ-SATYAL/database | /database.py | 3,519 | 4.0625 | 4 | from tkinter import *
import sqlite3
root=Tk()
root.title("database")
#create a database or connect to one
conn=sqlite3.connect("hello.db")
#create a curser
c=conn.cursor()
'''c.execute("""CREATE TABLE HELLO(
first_name text,
last_name text,
address text,
city text,
state text,
phone_number int
)""")'''
#create submit function for database
def sumbit():
#global f_name,l_name,address,city,state,phone_number
#create a database or connect to one
conn=sqlite3.connect("hello.db")
#create a curser
c=conn.cursor()
#insert into table
c.execute("INSERT INTO HELLO VALUES (:f_name, :l_name, :address, :city, :state, :phone_number)",
{
'f_name': f_name.get(),
'l_name': l_name.get(),
'address': address.get(),
'city': city.get(),
'state': state.get(),
'phone_number': phone_number.get()
})
#COMMIT CHANGES
conn.commit()
#connection close
conn.close()
#clear the text boxes
f_name.delete(0,END)
l_name.delete(0,END)
address.delete(0,END)
city.delete(0,END)
state.delete(0,END)
phone_number.delete(0,END)
def query():
conn=sqlite3.connect("hello.db")
#create a curser
c=conn.cursor()
#insert into table
c.execute("SELECT *, oid FROM HELLO")
hi=c.fetchall()
print(hi)
print_record=" "
for i in hi:
print_record+=str(i[0]) + " " + str(i[1]) + " " + str(i[6])+ "\n"
query_label=Label(root,text=print_record)
query_label.grid(row=12,column=1,columnspan=2)
#COMMIT CHANGES
conn.commit()
#connection close
conn.close()
def delete():
conn=sqlite3.connect("hello.db")
#create a curser
c=conn.cursor()
#delete database from table
c.execute("DELETE FROM HELLO WHERE oid=" + delete_box.get())
delete_box.delete(0,END)
conn.commit()
#connection close
conn.close()
#create text box
f_name=Entry(root,width=30)
f_name.grid(row=0,column=1,padx=20)
l_name=Entry(root,width=30)
l_name.grid(row=1,column=1)
address=Entry(root,width=30)
address.grid(row=2,column=1)
city=Entry(root,width=30)
city.grid(row=3,column=1)
state=Entry(root,width=30)
state.grid(row=4,column=1)
phone_number=Entry(root,width=30)
phone_number.grid(row=5,column=1)
delete_box=Entry(root,width=30)
delete_box.grid(row=8,column=1)
#cretae text box label
f_label=Label(root,text="first_name:")
f_label.grid(row=0,column=0)
l_label=Label(root,text="last_name:")
l_label.grid(row=1,column=0)
a_label=Label(root,text="address:")
a_label.grid(row=2,column=0)
c_label=Label(root,text="city:")
c_label.grid(row=3,column=0)
s_label=Label(root,text="state:")
s_label.grid(row=4,column=0)
p_label=Label(root,text="phone_number:")
p_label.grid(row=5,column=0)
delete_label=Label(root,text="delete database")
delete_label.grid(row=8,column=0)
#create a sumbit button
sumbit_button=Button(root,text="sumbit",command=sumbit)
sumbit_button.grid(row=6,column=0,columnspan=2,padx=10,pady=10,ipadx=100)
#create a query button
query_button=Button(root,text="query",command=query)
query_button.grid(row=7,column=0,columnspan=2,padx=10,pady=10,ipadx=100)
# create a delete button
delete_button=Button(root,text="delete",command=delete)
delete_button.grid(row=9,column=0,columnspan=2,padx=10,pady=10,ipadx=100)
#COMMIT CHANGES
conn.commit()
#connection close
conn.close()
root.mainloop()
|
dc3a4869723e65d8cd6ca8ceae8944584d364761 | celestachay/chay-family | /c2/python/prog.100/assignments/assignment6_collections.py | 1,798 | 3.859375 | 4 | # Christopher Chay
# Assignment 6
# 2016.3.15
# Grade: _____
super1 = { 'Superhero': 'Spider Man',
'Secret Identity': "Peter Parker",
'Age': 20,
'Powers': "Wall crawling, super strength, agility, web"}
super2= { 'Superhero': 'Captain America',
'Secret Identity': "Steve Rogers",
'Age': 18,
'Powers': "Super strength, super-high endurance, super-speed"}
super3 = { 'Superhero': 'Super Man',
'Secret Identity': 'Clark Kent',
'Age': 32,
'Powers': "Super strength, Flight, Laser-vision, Heat-Vision, Icy-Breath"}
supervalue = [ 'Superhero', 'Secret Identity', 'Age', 'Powers' ]
superlist = [ super1, super2, super3 ]
for i in superlist:
for x in supervalue:
print(str(x) + ': ' + str(i[x]))
print('\n')
# print('Secret Secret_Identity:', i[x])
# print('Age:', i[x])
# print('Powers:', i[x], '\n')
'''
print('\n\nMy Three Favourite Super Heroes are:\n')
for i in SuperHeroList:
print(str(SuperHeroList[i][0]) + ':\n' + str(SuperHeroList[i][1]) + '\nSuperValues = ['Secret Identity', 'Age', 'Powers' ]
SuperHeroes = ["Captain America:", CapA, '\n', "Spider-Man:",SpiderMan, '\n', "Super Man:", SuperMan]
print('My Three Favourite Super Heroes are:\n')
for i in SuperHeroes:
print(i)
'''
'''
for ii in SuperValues:
for iii in SuperAttr:
print(str(iii) + ': ' + str(ii[iii]))
print('\n')
'''
'''
for i in SuperHeroes:
print (i)
for x in SuperAttr:
print(str(x), ': ', str(i[x]))
print('\n')
for i in SuperValues:
for z in SuperHeroes:
print(z)
for x in SuperAttr:
print(str(x) + ': ' + str(i[x]))
print('\n')
# print('Secret Secret_Identity:', i[x])
# print('Age:', i[x])
# print('Powers:', i[x], '\n')
'''
|
9524919da8a6395bbfb1c818790533f36fe4c550 | ehdqhddl/python_study | /section10.py | 2,680 | 3.640625 | 4 | # Section10
# 에러 및 예외 처리
# 예외 종류
# 문법적으로 에러가 없지만, 코드 실행(런타임) 프로세스에서 발생하는 예외 처리도 중요
# linter : 코드 스타일 가이드, 문법 체크
# SyntaxError : 잘못된 문법
# print('Test)
# if True
# pass
# NameError : 참조변수 없음
# a = 10
# b = 15
# print(c)
# ZeroDivisionError : 0 나누기 에러
# print(10/0)
# IndexError : 인덱스 범위 오버
# x = [10,20,30]
# print(x[0])
# print(x[3]) # 예외 발생
# KeyError
# dic = {'Name':'Park', 'Age' : 29, 'City' : 'Seoul'}
# print(dic.get('hobby')) # 에러 미발생 None 반환
# print(dic['hobby']) # 에러 발생
# AttributeError : 모듈, 클래스에 있는 잘못된 속성 사용시에 예외
# import time
# print(time.time())
# print(time.month())
# ValueError : 참조 값이 없을 떄 발생
# x = [1,5,6]
# x.remove(10)
# x.index(10)
# FileNotFoundError
# f = open('text.txt','r')
# TypeError
# x = [1,2]
# y = (1,2)
# z = "test"
# print(x + y)
# print(x + z)
# print(x + list(y))
# 항상 예외가 발생하지 않을 것으로 가정하고 먼저 코딩
# 그 후 런타임 예외 발생시 예외 처리 코딩 권장 (EAFP 코딩 스타일)
# 예외 처리 기본
# try : 에러가 발생할 가능성이 있는 코드 실행
# except : 에러명1
# except : 에러명2
# else : 에러가 발생하지 않았을 경우 실행
# finally : 항상 실행 되는 구문
# 예제 1
name = ['Park','Kim','Lee']
try:
z = 'Cho'
x = name.index(z)
print("{} Found it!".format(z))
except:
print('Not Found it! - Occured ValueError..')
else:
print('Ok! else!')
# 예제 2
try:
z = 'Park'
x = name.index(z)
print("{} Found it!".format(z))
except:
print('Not Found it! - Occured ValueError..')
else:
print('Ok! else!')
finally:
print('Uhm, Finally Ok!')
# 예제 3
# 예외 처리는 하지 않지만, 무조건 수행되는 코딩 패턴
try:
print("Try")
finally:
print("Ok Finally!")
# 예제 4
try:
z = 'Park'
x = name.index(z)
print("{}(indxe:{}) Found it!".format(z,x+1))
except ValueError:
print('Not Found it! - Occured ValueError..')
except IndexError:
print('Not Found it! - Occured IndexError..')
except Exception as e:
print('Not Found it! - Occured Error..',e)
else:
print('Ok! else!')
finally:
print('Uhm, Finally Ok!')
# 예제 5
# 예외 발생 : raise
# raise 키워드로 예외 직접 발생
try:
a = 'Park'
if a == 'Park':
print("허가")
else:
raise ValueError
except ValueError:
print('문제 발생!')
except Exception as f:
print(f) |
9890290da015e49a451a3da94e32564054217560 | rathore99/datastructure-in-python | /max_heap.py | 2,841 | 4.1875 | 4 | '''1. implement maxheap using list
2. operations to implement
i) push()
ii) pop()
iii) peek()
'''
class MaxHeap:
def __init__(self, items = [] ):
self.heap = [0]
for item in items:
self.heap.append(item)
self.__floatup(len(self.heap)-1)
print(self.__str())
# Function to insert element in heap
def push(self, item):
self.heap.append(item)
self.__floatup(len(self.heap)-1)
self.printHeap()
def pop(self):
if len(self.heap) < 2:
print("heap is empty ...no item available to pop ")
elif len(self.heap) == 2:
return self.heap.pop()
else:
self.__swap(len(self.heap)-1, 1)
max = self.heap.pop()
self.__bubbleDown(1)
return max
def peek(self):
if len(self.heap) > 1:
return self.heap[1]
else:
return False
def __floatup(self, index):
parent = index // 2
child = index
if self.heap[child] > self.heap[parent] and parent > 0:
self.__swap(child,parent)
self.__floatup(parent)
else:
return
def __bubbleDown(self, parent):
right = 2 * parent + 1
left = 2 * parent
if left <= len(self.heap)-1 and self.heap[parent] < self.heap[left] :
self.__swap(left, parent)
self.__bubbleDown(left)
if right <= len(self.heap)-1 and self.heap[parent] < self.heap[right] :
self.__swap(right, parent)
self.__bubbleDown(right)
else:
print("heap after deletion ")
self.printHeap()
return
return
def __str(self):
return str(self.heap)
def __swap(self, child, parent):
self.heap[child], self.heap[parent] = self.heap[parent], self.heap[child]
return
def printHeap(self):
print(self.__str())
def main():
while(True):
print('''play with max heap
1. create heap(for once)
2. push element
3. pop element
4. find max
5. print heap
6. exit()''')
option = int(input())
if option == 6:
break
else:
if option == 1:
list = [int(x) for x in input().split()]
obj = MaxHeap(list)
elif option == 2:
print('enter element to push in heap ')
element = int(input())
obj.push(element)
elif option == 3:
print("element popped is ", obj.pop())
elif option == 4:
print('''Max element in heap is: ''', obj.peek() )
elif option == 5:
obj.printHeap()
if __name__ == '__main__':
main() |
a1991e92002ff09394858ed5eb98557bf49f8c20 | Sunsetjue/python | /基础语法/05.py | 2,780 | 3.75 | 4 | #汉诺塔方程
def hanno(n,a,b,c):
if n == 1:
print(a,' -> ',c)
return None
if n == 2:
print(a,' -> ',b)
print(a,' -> ',c)
print(b,' -> ',c)
return None
'''
当n=n 时候,把 n-1 个盘子从 a 借助于 c 运到 b 上,然后将 a 盘上的一个运到 c 塔上
然后将 b 塔上的 n-1 个盘子通过 a 塔运送到 c 塔上
'''
hanno(n-1,a,c,b)
print(a,' -> ',c)
hanno(n-1,b,a,c)
a = 'A'
b = 'B'
c = 'C'
n = 3
hanno(n,a,b,c)
#列表内涵 list content. 创建一个和一个列表相同的列表,创建的列表为新列表,不与原来的相同
list1 = [1,2,3,4,5]
list2 = [i for i in list1]#对于原来所有的元素再重新赋值给新的列表
print(list2)
list3 = list1
print(id(list1))
print(id(list2))
print(id(list3))
#取 a 列表里面所有的偶数来生成 b 列表,再将 b 里面的元素打印出两倍的结果
a = [i for i in range(0,51)]
b = [j*2 for j in a if j % 2 == 0]#判断语句跟在后面,运算再跟在前面
print(b)
a = '1 2 3 4 4'
print(list(a))
b = 'I love SongYue'
print(list(b))#list函数的使用
a = [1,2,'sunbin',321]
b = a[0:2]
print(a)
print(id(a))#切片会改变生成新的列表,与原列表的的地址不同
print(b)
print(id(b))
# extend 函数是指将两个函数拼接在一起,但地址并不会变,还是原来拼的第一个列表
a = [1,2,3,4,5]
b = [6,7,8,9]
c = a+b#地址这样就发生了变化
print(c)
print(id(a))
print(id(b))
print(id(c))
a.extend(b)
print(id(a))
print(a)
# count表示查找列表里面谋个元素出现的次数
a.append(8)
a.insert(2,8)
print(a.count(8))#表示a列表里面计出8所出现的次数
print(a)
a=b#简单的赋值操作会传地址
b[3] = 40
print(a)
print(id(a))
print(id(b))
#使用 a=b 简单赋值操作会传地址导致b改变使得a也随之改变,因此需要使用copy 函数
c=a.copy()#copy 函数的使用方法
c[3] = 43
print(a)
print(c)#此时a 和 c所打印出来的元素便不一样了,地址也不同
t = (1,1,3,4,5,6,100,100,7,8,89,89,102,0,3,105,105,23)
print(min(t))
print(max(t))
#元组变量的转换
a=1
b=2
print(a,b)
a,b=b,a
print(a,b)
'''
- 集合内数据无序,无法使用索引和分片
- 集合内索引具有唯一性,可以排除重复数据
- 集合用花括号表示,但如果里面没有任何东西,则会默认表示为字典dict
'''
set=set(t)
print(set)
s1={(1,2,3),('sunbin','songyue','sunyuping'),(8,9,10)}#复合集合内容用循环表示出来
for i,j,l in s1:
print(i,'- -',j,'- -',l)
for m in s1:
print(m)
a = {1,2,3,4,5,1,6,2}
b = {2,3,451,3,1,321,31,2}
c = a.union(b)#union表示并集
print(c)
d = a.difference(b)#difference 表示差集
print(d)
e = a.intersection(b)#intersection表示交集
print(e) |
87b317b234820ab86867c09eea8f1be73b2493a5 | two2er/ml-toys | /supervised/decision_tree.py | 6,976 | 3.796875 | 4 | import numpy as np
class TreeNode:
"""node of decision tree"""
def __init__(self, X, y, leaf, depth, split_feature=None, split_value=None):
self.X = X
self.y = y
# whether this node is a leaf node or not: true or false
self.leaf = leaf
self.depth = depth
# if the node is an internal node, it must have a split_feature and a split_value,
# and two children
self.split_feature = split_feature
self.split_value = split_value
self.left_child, self.right_child = None, None
# if the node is a leaf node, it must have a predict label
self.leaf_predict = None
class DecisionTree:
""" base class of DecisionTreeClassifier and DecisionTreeRegressor """
def __init__(self, min_samples_split=2, min_impurity_decrease=1e-7,
max_depth=None, max_features=None, random_state=0):
""" decision tree classifier based on CART
min_samples_split: int
The minimum number of samples needed to make a split when building a tree.
min_impurity_decrease: float
A node will be split if this split induces a decrease of the impurity greater
than or equal to this value.
max_depth: int
The maximum depth of a tree. None means inf
max_features: int
The maximum number of features considered when splitting a node.
random_state: int
Random_state is the seed used by the random number generator.
"""
self.min_samples_split = min_samples_split
self.min_impurity_decrease = min_impurity_decrease
self.max_depth = float('inf') if max_depth is None else max_depth
self.max_features = max_features
np.random.seed(random_state)
# the root node of decision tree
self.root = None
def fit(self, X, y):
self.root = self._create_node(X, y, depth=0)
self._split_node(self.root)
def _create_node(self, X, y, depth):
"""return a internal/leaf node"""
# if the number of samples is smaller than min_samples_split, return a leaf node
# if the depth is larger than max_depth, return a leaf node
if len(X) < self.min_samples_split or depth >= self.max_depth:
node = TreeNode(X, y, leaf=True, depth=depth)
node.leaf_predict = self._leaf_predict(y)
else:
node = TreeNode(X, y, leaf=False, depth=depth)
return node
def _split_node(self, node):
"""split a node and its descents recursively"""
if node.leaf:
return
# search for a feature for split that would minimize the impurity
best_feature, best_value, best_impurity_decrease = -1, -1, -float('inf')
current_impurity = self._impurity(node.y)
# try max_features features
feature_seq = np.random.permutation(range(node.X.shape[1]))[:self.max_features]
for feature in feature_seq:
feature_values = np.unique(node.X[:, feature])
# try all feature values
for feature_value in feature_values:
# split samples of the node
left_y = node.y[node.X[:, feature] <= feature_value]
right_y = node.y[node.X[:, feature] > feature_value]
if len(left_y) < self.min_samples_split or len(right_y) < self.min_samples_split:
continue
impurity_gain = current_impurity - len(left_y)/len(node.y)*self._impurity(left_y) \
- len(right_y)/len(node.y)*self._impurity(right_y)
if impurity_gain > best_impurity_decrease:
best_feature, best_value, best_impurity_decrease = feature, feature_value, impurity_gain
# if the best impurity gain is smaller than min_impurity_decrease, stop splitting
if best_impurity_decrease <= self.min_impurity_decrease:
node.leaf = True
node.leaf_predict = self._leaf_predict(node.y)
return
# split the current node into two children, and split them recursively
node.left_child = self._create_node(node.X[node.X[:, best_feature] <= best_value],
node.y[node.X[:, best_feature] <= best_value], node.depth+1)
node.right_child = self._create_node(node.X[node.X[:, best_feature] > best_value],
node.y[node.X[:, best_feature] > best_value], node.depth+1)
node.split_feature, node.split_value = best_feature, best_value
self._split_node(node.left_child)
self._split_node(node.right_child)
def _impurity(self, y):
return NotImplementedError()
def _leaf_predict(self, y):
return NotImplementedError()
@staticmethod
def _loss(pred, y):
# mse
return np.sum((pred-y)**2) / len(y)
def predict(self, X):
assert self.root, "you must fit the data first before predicting"
return np.array([self._predict_each(x, self.root) for x in X])
def _predict_each(self, x, node):
"""return the predict label of one sample"""
if node.leaf:
return node.leaf_predict
if x[node.split_feature] <= node.split_value:
return self._predict_each(x, node.left_child)
else:
return self._predict_each(x, node.right_child)
class DecisionTreeClassifier(DecisionTree):
""" targets are discrete labels """
def _impurity(self, y):
"""Gini impurity
G_i = 1 - sum_{k=1}^n p_{i,k}^2
where p_{i,k} is the ratio of class k instances among the
training instances in the ith node
"""
unique, counts = np.unique(y, return_counts=True)
G = 1
for class_type, count in zip(unique, counts):
G -= (count/len(y))**2
return G
def _leaf_predict(self, y):
"""
simple majority voting
"""
unique, counts = np.unique(y, return_counts=True)
return unique[np.argmax(counts)]
class DecisionTreeRegressor(DecisionTree):
""" targets are continuous values """
def _impurity(self, y):
""" variance """
if len(y) == 0:
return 0
return np.var(y)
def _leaf_predict(self, y):
""" mean value of samples of the leaf node """
return np.mean(y)
if __name__ == '__main__':
import pandas as pd
dataset = pd.read_csv('../dataset/abalone').values
X, y = dataset[:, 1:].astype(np.float64), dataset[:, 0]
y[y != 'M'] = -1.
y[y == 'M'] = 1.
y = y.astype(np.float64)
from sklearn.model_selection import train_test_split
train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.3, random_state=40)
model = DecisionTreeRegressor(random_state=41, max_depth=3)
model.fit(train_X, train_y)
pred = model.predict(test_X)
print('loss', model._loss(pred, test_y))
|
6ee53403ad8adad92848737cb8056ed28c13fd8a | ivan-chai/detection-adaptation | /src/dalib/config.py | 2,990 | 3.5 | 4 | r"""Tools for configuration using default config.
All configurable classes must have :meth:`get_default_config` static method
which returns dictionary of default values. Than you can use
:func:`prepare_config` function to construct actual config. Actual config
can be ``None``, ``dict`` or ``str`` containing path to the file.
**Example**::
from dalib.config import prepare_config
class Configurable():
@staticmethod
def get_default_config():
return OrderedDict([
("arg1", 10),
("arg2", None)
])
def __init__(self, *args, config=None):
config = prepare_config(self, config)
self.arg1 = config["arg1"]
self.arg2 = config["arg2"]
obj = Configurable(config={"arg1": 5})
print(obj.arg1) # 5
print(obj.arg2) # None
Config files use YAML syntax. The special key `_type` can be used in configs to specify
target class. If types are provided, they are checked during initialization.
**Example**::
system:
subsystem:
_type: SubsystemClass
arg1: [5.0, 2.0]
"""
from collections import OrderedDict
import yaml
CONFIG_TYPE = "_type"
class ConfigError(Exception):
"""Exception class for errors in config."""
pass
def read_config(filename):
with open(filename) as fp:
return yaml.safe_load(fp)
def write_config(config, filename):
with open(filename, "w") as fp:
yaml.dump(config, fp)
def prepare_config(cls_or_default, config=None):
"""Set defaults and check fields.
Config is a dictionary of values. Method creates new config using
default class config. Result config keys are the same as default config keys.
Args:
cls_or_default: Class with get_default_config method or default config dictionary.
config: User-provided config.
Returns:
Config dictionary with defaults set.
"""
if isinstance(cls_or_default, dict):
default_config = cls_or_default
cls_name = None
else:
default_config = cls_or_default.get_default_config()
cls_name = type(cls_or_default).__name__
if isinstance(config, str):
config = read_config(config)
elif config is None:
return default_config
elif not isinstance(config, dict):
raise ConfigError("Config dictionary expected, got {}".format(type(config)))
# Check type.
if CONFIG_TYPE in config:
if (cls_name is not None) and (cls_name != config[CONFIG_TYPE]):
raise ConfigError("Type mismatch: expected {}, got {}".format(
config[CONFIG_TYPE], cls_name))
del config[CONFIG_TYPE]
# Merge configs.
for key in config:
if key not in default_config:
raise ConfigError("Unknown parameter {}".format(key))
new_config = OrderedDict()
for key, value in default_config.items():
new_config[key] = config.get(key, value)
return new_config
|
54d9ab5ac2047e5c862b62fbb92fcec1d994a5f7 | doug-cady/python | /adventure.py | 6,834 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Text Adventure Game
An adventure in making adventure games.
To test your current solution, run the `test_my_solution.py` file.
Refer to the instructions on Canvas for more information.
"I have neither given nor received help on this assignment."
author: Kane van Doorn
"""
__version__ = 8
# 2) print_introduction: Print a friendly welcome message for your game
def print_introduction():
# print the introduction including the setting and some story.
print("You're riding your horse when you hear a scream coming from a dark and looming tower in the distance")
print("You think back to a few weeks ago.")
print("You overheard some men at the local brothel talking about a missing princess.")
print("You decide to take this as an opportunity to prove yourself to your guild.")
print("You approach the tower and dismount your horse.")
print("\nYou notice alligators are lurking in the water.")
# 3) get_initial_state: Create the starting player state dictionary
def get_initial_state():
# Start the player states for the beginning of the game
initial_states = {'game status': 'playing',
'location': 'The moat in front of the Tower',
'Sword': False,
'Crown': False
}
return initial_states
# 4) print_current_state: Print some text describing the current game world
def print_current_state(a_dict):
# Current location in the world, updates as the player chooses options and moves through the world.
print("\nCurrent Location: "+ a_dict['location'] + ".")
# 5) get_options: Return a list of commands available to the player right now
def get_options(the_player):
# Returns a list of options depending on where the player is in the world.
if the_player['location'] == 'The moat in front of the Tower':
a_list = ['Take the sword out of the rock, kill the alligators.',
'Attack the alligators with your fists.'
]
if the_player['location'] == 'Top of the Tower':
a_list = ['Knock on the door.',
'Use the sword to silently pick the lock.'
]
if the_player['location'] == 'Inside the bedroom':
a_list = ['Steal the crown.',
'Untie and save the princess.'
]
return a_list
# 6) print_options: Print out the list of commands available
def print_options(a_list):
# Prints the options from get_options()
print('Your options are:')
for x in a_list:
print(x)
# 7) get_user_input: Repeatedly prompt the user to choose a valid command
def get_user_input(a_list):
# While loop that will ask the user for input until a valid option is chosen or quit is chosen.
command = ""
a = True
while a == True:
command = input('What would you like to do: ')
if command in a_list:
a = False
if command.lower() == 'quit':
a = False
return command
# 8) process_command: Change the player state dictionary based on the command
def process_command(a_command, a_player):
# Process the command, this involves updating if the sword and crown have been picked up based off of what options are chosen.
if a_command == 'Take the sword out of the rock, kill the alligators.':
a_player['location'] = 'Top of the Tower'
a_player['Sword'] = True
if a_command == 'Attack the alligators with your fists.':
a_player['location'] = 'Bottom of the moat'
a_player['game status'] = 'lose'
if a_command == 'Knock on the door.':
a_player['location'] = 'Bottom of the moat'
a_player['game status'] = 'lose'
if a_command == 'Use the sword to silently pick the lock.':
a_player['location'] = 'Inside the bedroom'
if a_command == 'Untie and save the princess.':
a_player['location'] = 'Inside the bedroom'
a_player['game status'] = 'lose'
if a_command == 'Steal the crown.':
a_player['location'] = 'Outside the tower'
a_player['game status'] = 'win'
if a_command.lower() == 'quit':
a_player['game status'] = 'quit'
# 9) print_game_ending: Print a victory, lose, or quit message at the end
def print_game_ending(a_player):
# Prints an ending based off if the player chooses a losing option, winning option, or inputs quit.
if a_player['location'] == 'Bottom of the moat' and a_player['game status'] == 'lose':
print('You lost. The alligators ate you and you died. :(')
if a_player['location'] == 'Bottom of the moat' and a_player['game status'] == 'lose':
print('You lost. The evil witch heard you knocking and she killed you. :(')
if a_player['location'] == 'Inside the bedroom' and a_player['game status'] == 'lose':
print('You lost. Why would you save the princess if you could steal her crown? You are in a thiefs guild, STEAL THE CROWN')
if a_player['location'] == 'Outside the tower' and a_player['game status'] == 'win':
print('YOU WIN. You bring the crown back to the guild and sell it for a bag of gold.')
if a_player['game status'] == 'quit':
print('You quit the game. Goodbye!')
else:
print('Invalid Journey')
# Command Paths to give to the unit tester
WIN_PATH = ['Take the sword out of the rock, kill the alligators.', 'Use the sword to silently pick the lock.', 'Steal the crown.']
LOSE_PATH = ['Take the sword out of the rock, kill the alligators.', 'Use the sword to silently pick the lock.', 'Untie and save the princess.']
# 1) Main function that runs your game, read it over and understand
# how the player state flows between functions.
def main():
# Print an introduction to the game
print_introduction()
# Make initial state
the_player = get_initial_state()
# Check victory or defeat
while the_player['game status'] == 'playing':
# Give current state
print_current_state(the_player)
# Get options
available_options = get_options(the_player)
# Give next options
print_options(available_options)
# Get Valid User Input
chosen_command = get_user_input(available_options)
# Process Commands and change state
process_command(chosen_command, the_player)
# Give user message
print_game_ending(the_player)
# Executes the main function
if __name__ == "__main__":
'''
You might comment out the main function and call each function
one at a time below to try them out yourself '''
main()
## e.g., comment out main() and uncomment the line(s) below
# print_introduction()
# print(get_initial_state())
# ... |
f4f39248c2e8ed6373829c70437c6d51d5ef7733 | ugurkam/PythonSamples | /Samples/sets.py | 564 | 3.953125 | 4 | fruits = {'portakal', 'elma', 'muz'}
print(fruits)
for x in fruits:
print(x)
# Fruits setine eleman eklemek için
fruits.add('karpuz')
fruits.update(['kavun', 'visne'])
print(fruits)
myList = [1,3,5,7,1,4,3,8]
print(myList)
print(set(myList))
# Fruits setinden eleman silmek için
#fruits.remove('karpuz')
#fruits.discard('kavun')
#fruits.pop() # son elemanı siler ancak sıralı bir liste olmayıp karışık olduğundan son elemanın ne olduğu ve silineceği garanti edilemez.
fruits.clear () # tüm elemanlar silinir
print(fruits) |
0cf63f8e5fa915c9300b66836f52b6217ff5d72b | CS7591/Python-Classes | /2. Python Intermediate/6. Assorted Topics/3. Exception Handling.py | 4,471 | 4.375 | 4 | '''
Exception handling is one of the most important features in Python
Usually has the form:
try:
<code>
<code>
<code>
except:
<code>
<code>
finally:
<code>
'''
# One the most important features of Python
# # Example 1
# amount = float(input('Enter with the amount:'))
# split = float(input('Enter with the number to split the amount:'))
# result = amount/split
# print('The divided amount is:', result)
# # Example 2
# try:
# amount = float(input('Enter with the amount:'))
# split = float(input('Enter with the number to split the amount:'))
# result = amount/split
# print('The divided amount is:', result)
# except:
# # pass
# print('Could not perform operation')
# # Example 3
# try:
# amount = float(input('Enter with the amount:'))
# split = float(input('Enter with the number to split the amount:'))
# result = amount/split
# print('The divided amount is:', result)
# except:
# print('Could not perform operation')
# finally:
# print('Your program ended with no fatal errors')
# # Example 4
# try:
# amount = float(input('Enter with the amount:') or 100)
# split = float(input('Enter with the number to split the amount:') or 20)
# result = amount/split
# print('Values are:', amount, 'and', split)
# print('The divided amount is:', result)
# except ZeroDivisionError:
# print('You entered an invalid number to split the amount')
# except ValueError:
# print('Your input was invalid (not a number)')
# finally:
# print('Your program ended with no fatal errors')
# Example 5
try:
amount = float(input('Enter with the amount:') or 100)
split = float(input('Enter with the number to split the amount:') or 20)
result = amount/split
print('Values are:', amount, 'and', split)
print('The divided amount is:', result)
except ZeroDivisionError:
print('You entered an invalid number to split the amount')
except ValueError:
print('Your input was invalid (not a number)')
else:
print('Input data OK. No fatal errors')
finally:
print('Your program ended.')
'''
Exception / Cause of Error:
AssertionError
Raised when assert statement fails.
AttributeError
Raised when attribute assignment or reference fails.
EOFError
Raised when the input() functions hits end-of-file condition.
FloatingPointError
Raised when a floating point operation fails.
GeneratorExit
Raise when a generator's close() method is called.
ImportError
Raised when the imported module is not found.
IndexError
Raised when index of a sequence is out of range.
KeyError
Raised when a key is not found in a dictionary.
KeyboardInterrupt
Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError
Raised when an operation runs out of memory.
NameError
Raised when a variable is not found in local or global scope.
NotImplementedError
Raised by abstract methods.
OSError
Raised when system operation causes system related error.
OverflowError
Raised when result of an arithmetic operation is too large to be represented.
ReferenceError
Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError
Raised when an error does not fall under any other category.
StopIteration
Raised by next() function to indicate that there is no further item to be returned by iterator.
SyntaxError
Raised by parser when syntax error is encountered.
IndentationError
Raised when there is incorrect indentation.
TabError
Raised when indentation consists of inconsistent tabs and spaces.
SystemError
Raised when interpreter detects internal error.
SystemExit
Raised by sys.exit() function.
TypeError
Raised when a function or operation is applied to an object of incorrect type.
UnboundLocalError
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError
Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError
Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError
Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError
Raised when a Unicode-related error occurs during translating.
ValueError
Raised when a function gets argument of correct type but improper value.
ZeroDivisionError
Raised when second operand of division or modulo operation is zero.
''' |
fb8ea357bb9973163ed7f4c344e10e6f3ac0a869 | pseemaJohn/python-lab | /OperatorTraining.py | 226 | 3.546875 | 4 | print(2*3+4)
print("value is",len("hi how are you"))
print(2 or 0)
print(2 and 0)
print(bool(2 and 0))
print(2 | 1)
print(5 // 2)
print(5 / 2)
print("hi"+"how are you")
print("Seema" * 6,end=": \n")
print(2 ** 4)
|
a2863b2bf3b0abaf059bbffafe3789616fc6846e | aruimk/ud_pyintro | /lesson16_list.py | 827 | 3.6875 | 4 |
s = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(s)
s[0] = 'X'
print(s)
print(s[2:5])
s[2:5] = ['C', 'D', 'E']
print(s)
s[2:5] = []
print(s)
s[:] = []
print(s)
n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(n)
n.append(100) # 一番最後に要素を追加したい時
print(n)
n.insert(0, 200) # 指定した要素位置にデータを挿入したい時(この場合は 0番目に200を挿入)
print(n)
print(n.pop(0)) # 指定した要素のデータを取りだす(この場合は要素 0 )
print(n) # 取り出したので 全体の要素は減っている
print(n.pop()) # 引数を指定しないと一番最後の要素を取り出す
del n[0] # del文は完全にデータを削除する
print(n)
a = [1, 2, 3, 4, 5,]
b = [6, 7, 8, 9, 10]
print(a + b)
print(a)
a.extend(b)
print(a) |
651e45164cb6e957661a1cf73e902437a64f5aac | VFagundes/Algorithms | /challenges/data_structures/linked_lists/print_the_elements_of_a_linked_list.py | 471 | 3.984375 | 4 | #https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list/problem
from singly_linked_list import SinglyLinkedList
def printLinkedList(head):
if not head.head:
return
node = head.head
while node:
print node.data
node = node.next
data = '''2
16
13
'''
arr = data.strip().split('\n')[1:]
linked_list = SinglyLinkedList()
map(lambda x: linked_list.insert_node(int(x)), arr)
print arr
printLinkedList(linked_list)
|
bbb6a2c5e8505aa736967d64e9abf3ae8d868e2b | Madhivarman/DataStructures | /topological.py | 1,043 | 3.921875 | 4 | from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.V = vertices
self.graph = defaultdict(list)
def addEdge(self,src,dest):
self.graph[src].append(dest)
def topologicalSortUtil(self,visited,node,stack):
visited[node] = True
for i in self.graph[node]:
if visited[i] == False:
self.topologicalSortUtil(visited,i,stack)
stack.insert(0,node)
def print_the_topological_sort(self,stack):
print("The Topological Order")
print("-------------------------------------")
stack_length = len(stack)
for i in stack:
print(i,end=" ")
def topologicalSort(self):
visited = [False]*self.V
stack = [] #to store the stack result
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(visited,i,stack)
self.print_the_topological_sort(stack)
g = Graph(11)
g.addEdge(4,2)
g.addEdge(2,1)
g.addEdge(4,3)
g.addEdge(2,5)
g.addEdge(2,3)
g.addEdge(5,6)
g.addEdge(5,7)
g.addEdge(7,3)
g.addEdge(3,8)
g.addEdge(8,9)
g.addEdge(8,10)
g.topologicalSort() |
517c587459833d3710c0199b6adcc3c31293cc1d | kwoshvick/Algorithm-practice | /careercup/shadow.py | 714 | 3.921875 | 4 | # https://www.careercup.com/question?id=5655096797429760
#
# Given array of ball size we need to return the sum of shadow balls
#
# For example
#
# 7 3 2 8 1
#
# shadow ball of 7 ---> 3, 2, 1
# shadow ball of 3 ---> 2, 1
# shadow ball of 2 ---> 1
# shadow ball of 8 ---> 1
#
# Output ---> 3+2+1+1 --> 7
#
# Complexity should be better than 0(n^2)
def getShadowBalls(shadowList):
shadowCount = 0
for index in range(0,len(shadowList)):
if len(shadowList) is not index+1:
shadowBalls = [i for i in shadowList[index+1:] if shadowList[index] > i]
shadowCount += len(shadowBalls)
return shadowCount
print(getShadowBalls([7,3,2,8,1]))
print(getShadowBalls([1,2,4,3,5]))
|
d6a0da8ddd5eeda08639b6b7704581454bcf2ef5 | NovaStriker/Proyecto_Algoritmos_1ER_parcial-2T-2018 | /pry_algoritmos_1er_parcial.py | 8,702 | 3.890625 | 4 | from random import randint
import time
import os.path
from pathlib import Path
def insertionSort(alist): #definir la funcion del algoritmo que reciba una lista
for index in range(1,len(alist)): #recorrer la lista
currentvalue = alist[index] #valor que va tomando index
position = index
while position > 0 and alist[position-1] > currentvalue: #comparacion y validacion de la posicion con el indice
alist[position] = alist[position-1]
position = position-1
alist[position] = currentvalue
def mergeSort(alist):
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
salir = False
while (salir==False):
print("MENÚ PRINCIPAL")
print("(1) Realizar análisis")
print("(2) Generar archivo de números aleatorios")
print("(3) Salir")
opcion = input("Escriba una opcion: ")
print("\n")
if (opcion == "1"):
print ("REALIZAR ANÁLISIS")
nombreArchivo = input("Escriba el nombre de su archivo ubicado en la carpeta: ")
nombreArchivo = nombreArchivo + ".txt"
if (os.path.isfile(".\\" + nombreArchivo)):
print("El archivo " + nombreArchivo + " ha sido encontrado")
print("\n")
archivoAnalisis = open(".\\" + nombreArchivo,"r")
salirDeAnalisis = False
salirEscogerCantidad = False
while (salirEscogerCantidad == False):
cantidadNumeros = input("Ingrese la cantidad de números que desea tomar del archivo (Max 1000): ")
if(str.isdigit(cantidadNumeros)):
cantidadNumeros = int(cantidadNumeros)
else:
print("No ha ingresado un número válido")
contador = 0
if (cantidadNumeros <= 1000):
arregloAnalisis = [0]*cantidadNumeros
for j in archivoAnalisis:
#print(archivoAnalisis.readline())
arregloAnalisis[contador] = int(j)
contador = contador + 1
if(contador == cantidadNumeros):
break
archivoAnalisis.close()
salirEscogerCantidad = True
#print(arregloAnalisis)
while (salirDeAnalisis == False):
print("Escoja el tipo de analisis que desea")
print("\n")
print("(1) Comparación Insertion Sort vs Merge Sort")
print("(2) Comparación Insertion Sort vs Quick Sort")
print("(3) Comparación Merge Sort vs Quick Sort")
print("(4) Comparar todos los algoritmos")
print("(5) Volver al menú principal")
opcionComparacion = input("Escriba una opcion: ")
print("\n")
if (opcionComparacion == "1"):
print("Insertion Sort vs Merge Sort")
arregloA = arregloAnalisis
arregloB = arregloAnalisis
insertionSort(arregloA)
mergeSort(arregloB)
elif (opcionComparacion == "2"):
print("Insertion Sort vs Quick Sort")
arregloA = arregloAnalisis
arregloB = arregloAnalisis
insertionSort(arregloA)
quickSort(arregloB)
elif (opcionComparacion == "3"):
print("Merge Sort vs Quick Sort")
arregloA = arregloAnalisis
arregloB = arregloAnalisis
mergeSort(arregloA)
quickSort(arregloB)
elif (opcionComparacion == "4"):
print("Comparar todos los algoritmos")
arregloA = arregloAnalisis
arregloB = arregloAnalisis
arregloC = arregloAnalisis
insertionSort(arregloA)
mergeSort(arregloB)
quickSort(arregloC)
ArregloTiempoMS.append(endtime) # agregando tiempos al arreglo de MergeSort
start_time = time.time()
insertionSort(L2)
endtime = time.time() - start_time
print("Insertion sort para " + str(len(L2)) + ": --- %s seconds ---" % "{0:.22f}".format(endtime))
worksheet.write(j, 2, endtime)
ArregloTiempoIS.append(endtime) # agregando tiempos al arreglo de InsertionSort
L3 = L2.copy()
start_time = time.time()
quickSort(L3)
endtime = time.time() - start_time
print("Quick sort para " + str(len(L3)) + ": --- %s seconds ---" % "{0:.22f}".format(endtime))
worksheet.write(j, 3, endtime)
ArregloTiempoQS.append(endtime) # agregando tiempos al arreglo de Quickort
L = []
Ndatos.append(cont)
cont += 10
plt.figure()
# son los 3 ordenamientos
plt.plot(Ndatos, ArregloTiempoMS, '-')
plt.plot(Ndatos, ArregloTiempoIS, '-')
plt.plot(Ndatos, ArregloTiempoQS, '-')
plt.title("Grafico de los metodos de ordenamiento: MergeSort, InsertionSort, QuickSort")
fig = plt.gcf()
# fig.set_size_inches(200,120,True)
plotly_fig = tls.mpl_to_plotly(fig)
plotly_fig["data"][0]["error_y"].update({
"visible": True,
"color": "rgb(255,127,14)",
"value": 0.04,
"type": "constant"
})
plotly_fig["data"][0]["error_x"].update({
"visible": True,
"color": "rgb(255,127,14)",
"value": 0.04,
"type": "constant"
})
py.plot(plotly_fig, filename='Graficos Tiempo vs datos')
elif (opcionComparacion == "5"):
print("Volviendo al menú principal...")
salirDeAnalisis = True
else:
print("La opción " + opcionComparacion + " no es válida")
else:
print("El archivo " + nombreArchivo + " no existe \n")
print("Intente generar un archivo aleatorio.txt desde la opción del menú principal")
print("\n")
elif (opcion == "2"):
print ("GENERAR ARCHIVO ALEATORIO")
archivoAleatorio = open(".\\aleatorio.txt","w")
elementos = 1000
listaAleatoria = [0]*elementos
for i in range(elementos):
listaAleatoria[i] = randint(1000000, 9999999)
archivoAleatorio.write(str(listaAleatoria[i]) + "\n")
archivoAleatorio.close()
#print(listaAleatoria)
print ("Archivo generado!\n")
elif (opcion == "3"):
print ("SALIENDO...")
print ("Gracias por usar el sistema de comparación \n")
salir = True
else:
print("(" + opcion + ") no es una opción válida...")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.