blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a8ddd7435900b4a64d4a0add61b58b3506c89a5e | avenet/hackerrank | /algorithms/implementation/equalize_the_array.py | 403 | 3.546875 | 4 | from collections import defaultdict
def get_delete_count(array):
counter_dict = defaultdict(int)
for item in array:
counter_dict[item] += 1
max_repetitions = max(
counter_dict.values()
)
return len(array) - max_repetitions
_ = input()
array_items = list(
map(
int,
input().split()
)
)
print(get_delete_count(array_items))
|
8915ec83aa463b6d977c37b6c0194255cab59920 | SANDHIYA11/myproject | /b21.py | 150 | 3.9375 | 4 | def sum1(b,c,a):
sum=0
i=0
while i<a:
sum=sum+b
b=b+c
i=i+1
return sum
a=int(input("n1:"))
b=int(input("n2:"))
c=int(input("n3:"))
print(sum1(b,c,a))
|
f682148288a375c661d6bbf0be6971f36e432cbb | queenskid/MyCode | /labs/sort03/sorted03.py | 371 | 3.6875 | 4 | #!/usr/bin/env python3
firewall_ports = [5060, 5061, 80, 443, 22, 25565]
def addTen(x):
return x%10
print('Currently firewall_ports looks like this: ' + str(firewall_ports))
print('\nThe results of sorted(firewall_ports, key=addTen) function:', sorted(firewall_ports, key=addTen))
print('\nBut the firewall_ports array has not actually changed: ', firewall_ports)
|
40c443c1eca50dfa02fcb24f0d74c11a012d482d | wesleyjr01/rest_api_flask | /2_python_refresher/51-mutability.py | 505 | 4.09375 | 4 | """
In python, all things are mutable, because everything
is an object, unless there are specifically no ways
of changing the properties of the object itself.
Ex:
* For example defining tuples, they are immutable.
* Strings, Integers, Float and Booleans are also immutable.
"""
a = []
b = a
# 'a' and 'b' are names for the same object
print(id(a))
print(id(b))
print("\n")
a = 1515
b = 1515
print(id(a))
print(id(b))
print("\n")
a = 1516
print(id(a))
print(id(b))
print("\n")
|
47b3d32d3bc074d98b328aa32b150fd54f22e9d3 | forwardhuan/Python_learning | /pandas_test/1.pandas基础, Series, DataFrame.py | 2,757 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
s1 = pd.Series([4, 7, -5, 3]) # 创建一个series,索引为默认值
print(s1)
# 0 4
# 1 7
# 2 -5
# 3 3
# dtype: int64
print(s1.values) # series的值
# [ 4 7 -5 3]
print(s1.index) # series的索引
# RangeIndex(start=0, stop=4, step=1)
s2 = pd.Series([4, 0, 6, 5], index=['a', 'b', 'c', 'd']) # 指定索引
print(s2)
# a 4
# b 0
# c 6
# d 5
# dtype: int64
print(s2['b']) # 根据索引取值
# 0
print(s2[['a', 'c', 'd']]) # 根据索引取多个值
# a 4
# c 6
# d 5
# dtype: int64
print('b' in s2)
# True
# Series可以看作是一个定长的有序字典
dic1 = {'apple': 5, 'pen': 3, 'applepen': 10}
s3 = pd.Series(dic1)
print(s3)
# apple 5
# pen 3
# applepen 10
# dtype: int64
# DataFrame
data = {'year': [2014, 2015, 2016, 2017],
'income': [1000, 2000, 3000, 5000],
'pay': [500, 1000, 2000, 4000]}
df1 = pd.DataFrame(data)
print(df1)
# year income pay
# 0 2014 1000 500
# 1 2015 2000 1000
# 2 2016 3000 2000
# 3 2017 5000 4000
df2 = pd.DataFrame(np.arange(12).reshape((3, 4)))
print(df2)
# 0 1 2 3
# 0 0 1 2 3
# 1 4 5 6 7
# 2 8 9 10 11
df3 = pd.DataFrame(np.arange(12).reshape((3, 4)), index=['a', 'b', 'c'], columns=[2, 33, 44, 5])
print(df3)
# 2 33 44 5
# a 0 1 2 3
# b 4 5 6 7
# c 8 9 10 11
print(df1.columns)
# Index(['year', 'income', 'pay'], dtype='object')
print(df1.index)
# RangeIndex(start=0, stop=4, step=1)
print(df1.values)
# [[2014 1000 500]
# [2015 2000 1000]
# [2016 3000 2000]
# [2017 5000 4000]]
print(df1.describe())
# year income pay
# count 4.000000 4.000000 4.000000
# mean 2015.500000 2750.000000 1875.000000
# std 1.290994 1707.825128 1547.847968
# min 2014.000000 1000.000000 500.000000
# 25% 2014.750000 1750.000000 875.000000
# 50% 2015.500000 2500.000000 1500.000000
# 75% 2016.250000 3500.000000 2500.000000
# max 2017.000000 5000.000000 4000.000000
print(df1.T)
# 0 1 2 3
# year 2014 2015 2016 2017
# income 1000 2000 3000 5000
# pay 500 1000 2000 4000
# 列排序
print(df1.sort_index(axis=1))
# income pay year
# 0 1000 500 2014
# 1 2000 1000 2015
# 2 3000 2000 2016
# 3 5000 4000 2017
# 行排序
print(df1.sort_index(axis=0))
# year income pay
# 0 2014 1000 500
# 1 2015 2000 1000
# 2 2016 3000 2000
# 3 2017 5000 4000
print(df1.sort_values(by='pay'))
# year income pay
# 0 2014 1000 500
# 1 2015 2000 1000
# 2 2016 3000 2000
# 3 2017 5000 4000
|
d2535eed3f712355bd508808393c339657aa76b2 | 9wilson6/Chapter-1-2-3- | /chapter_three.py | 1,053 | 3.71875 | 4 | Q1. since they group code that get's executed multiple times, we don't have to copy
paste the code multiples times which also make it easy to read and debug.
Q2.When the function is called
Q3. def the functionName
Q4. A function is a gruop of code that is excuted as a unit while a function call
excutes the function.
Q5. 1 global scope and it is created when your program begins.
1 local scope and it is created whenever a function is called..
Q6. When the function returns, variables in local scope are destroyed and forgotten.
Q7. A return value is the value that a function call evaluates to.
Yes they can be part of an expresion.
Q8. None.
Q9. by using a global statement on that variable.
Q10. none is the only value of NoneType data type.
Q11. That import statement imports a module named areallyourpetsnamederic.
Q12. import spam
spam.bacon()
Q13. by using try and except statements.
Q14.try holds: the code that could result into an error
except holds: the code to be excuted in the instance
of an error from the try block
|
68dbc0ba9ad0bb92ef7bd08ab005f35be630285b | ITanmayee/codechef | /CC_Racing_horses_22032020.py | 652 | 3.5 | 4 | # There are N horses in the stable. The skill of the horse i is represented by an integer S[i]. The Chef needs to pick 2 horses for the race such that the difference in their skills is minimum. This way, he would be able to host a very interesting race. Your task is to help him do this and report the minimum difference that is possible between 2 horses in the race.
Input:
test_cases = int(input())
for i in range(test_cases) :
n = int(input())
arr = list(map(int , input().split(" ")))
arr.sort()
diff = []
for i in range(1 , n) :
diff.append(arr[i] - arr[i-1])
print(min(diff))
# input :
# 1
# 5
# 4 9 1 32 13
|
620dbde0691cdf60e8a5dcb4a7d1a11e4dd59f7d | tasharnvb/python-projects | /Python Programming Book/Chapter 4/Backwards.py | 649 | 4.53125 | 5 | # Backwards
#
# Pg 120, Challenge No. 2
#
# Create a program that gets a message from the user
# and prints it out backwards.
print("\t\tBackwards")
word = input("\n\nType in the word you want to see backwards ")
# The first letter of the word is at index 0,
# index -1 is the last letter of the word
position = -1
backwards = ""
for i in range(len(word)):
backwards += word[position]
position -= 1
# An alternate way to do this with a while loop
# position = len(word) - 1
#
# while position >= 0:
# backwards += word[position]
# position -= 1
print("\nYour word backwards is: " + backwards)
input("\n\nPress enter to exit")
|
2277bcaa104effa2ae0399913ee593c6bbb41fea | mymusic56/python-hello-world | /OOP/object/Person.py | 835 | 3.828125 | 4 | class Person:
heair = 'black'
#私有变量
__age = 10
#魔法方法,初始化方法, 类似constructor
def __init__(self, name,gender):
self.name = name
self.gender = gender
print("Person类")
def getName(self):
return self.name
def getGender(self):
return self.gender
def setAge(self,age):
self.__age = age
def getAge(self):
return self.__age
def societyPosition(self):
return "父亲2"
class Father:
def societyPosition(self):
print("Father类")
return "父亲"
#多继承
class Teacher(Father,Person):
def __init__(self,name,gender):
#调用父类的方法
super().__init__(name,gender)
print("这是Teacher 类")
def tech(self):
return "教英语"
|
147e0524a39ab9f3ef42081fd9d816aded034336 | javierpb275/python-oop | /pillars-of-oop/polymorphism.py | 938 | 4.125 | 4 | class User():
def sign_in(self):
print('logged in')
def attack(self):
print('do nothing')
class Wizard(User):
def __init__(self, name, power):
self.name = name
self.power = power
def attack(self):
User.attack(self)
print(f'attack with power of {self.power}')
class Archer(User):
def __init__(self, name, arrows):
self.name = name
self.arrows = arrows
def attack(self):
print(f'attack with {self.arrows} arrows')
wizard1 = Wizard('pepe', 20)
archer1 = Archer('paco', 40)
def player_attack(char):
char.attack()
player_attack(wizard1)
player_attack(archer1)
for char in [wizard1, archer1]:
char.attack()
# polymorphism: it allows us to have many forms. it is the ability to redefine methods
# of derived classes like wizard and archer.
# an object that gets instatiated can behave in different forms based on polymorphism
|
d87072c4c3213c5197ecce4539bcc6f041f6a43a | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/arc012/B/3509037.py | 163 | 3.671875 | 4 | list=input().split(" ")
a=int(list[1])
b=int(list[2])
c=int(list[3])
for i in range(int(list[0])):
full=c/a
full2=full*b
c=full2
print(c) |
e7ba223f4938ee458226d5ffc6be62f50b44a52d | Dave-Petrie/Udemy-Complete-Python-Bootcamp | /CE-18.py | 295 | 4.09375 | 4 | # This is Coding Exercise 18: Pick evens
# Define a function called myfunc that takes in an arbitrary number of arguments, and returns a list containing only those arguments that are even.
def myfunc(*args):
even_numbers = list(filter(lambda x: (x % 2 == 0), args))
return even_numbers |
6a76dabb5706833a4baa683b1007b467ce38fc49 | diogomatoschaves/ml-coursera-python | /ml_coursera/utils/_plotting.py | 4,802 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from ..preprocessing import feature_mapping
def plot_data(x, y, possible_labels=(0, 1), feature_names=None, logistic=True):
"""
:param x: matrix of data points of size m training examples by 2 features
:param y: vector of labels of shape (m, ).
:param possible_labels: possible categories in y vector. Defaults to 0 and 1
:param feature_names: names of features. Optional
:return: None
Plots the data points according to the labels
"""
x = np.array(x)
y = np.array(y).reshape(-1, 1)
markers = ["o", "x"]
plt.figure(figsize=(8, 6))
if not logistic or x.shape[1] == 1:
plt.scatter(x[:, 0], y[:, 0], marker=markers[0])
else:
labels = [(y == lbl) for lbl in possible_labels]
for i, label in enumerate(labels):
plt.scatter(x[label[:, 0], 0], x[label[:, 0], 1], marker=markers[i])
if isinstance(feature_names, list) and len(feature_names) >= 2:
plt.xlabel(feature_names[0])
plt.ylabel(feature_names[1])
else:
plt.xlabel("feature 1")
plt.ylabel("feature 2")
def plot_decision_boundary(
theta,
x,
y,
possible_labels=(0, 1),
feature_names=None,
legend=("positive", "negative"),
):
"""
:param theta: parameters for logistic regression. A vector of shape (n+1, ).
:param x: The input dataset. X is assumed to be a either:
1) Mx2 matrix
2) MxN, N > 2 matrix, where the N > 2 columns are the
higher order terms of the first 2 features.
:param y: vector of data labels of shape (m, ).
:param possible_labels: possible categories in y vector. Defaults to 0 and 1
:param feature_names: names of features, optional
:param legend: labels for legend
Plots the data points X and y into a new figure with the decision boundary defined by theta.
Plots the data points with * for the positive examples and o for the negative examples.
"""
theta = np.array(theta)
plot_data(x, y, possible_labels, feature_names)
# following formula: order = (n^2 + 3n) / 2
order = int(np.roots([1, 3, -2 * x.shape[1]])[1])
u = np.linspace(x[:, 0].min(), x[:, 0].max(), 50)
v = np.linspace(x[:, 1].min(), x[:, 1].max(), 50)
z = np.zeros((u.size, v.size))
# Evaluate z = theta*x over the grid
for i, ui in enumerate(u):
for j, vj in enumerate(v):
z[i, j] = (
feature_mapping(np.array([[ui, vj]]), order, intercept=True) @ theta
)
z = z.T
# Plot z = 0
plt.contour(u, v, z, levels=[0], linewidths=2, colors="r")
plt.contourf(u, v, z, levels=[np.min(z), 0, np.max(z)], cmap="seismic", alpha=0.4)
plt.legend(legend)
def plot_regression_line(theta, x, y, feature_names=None):
"""
:param theta: parameters for logistic regression. A vector of shape (n+1, ).
:param x: The input dataset. X is assumed to be a either:
1) Mx2 matrix
2) MxN, N > 2 matrix, where the N > 2 columns are the
higher order terms of the first 2 features.
:param y: vector of data labels of shape (m, ).
:param feature_names: names of features, optional
Plots the data points x and y into a new figure with the regression line defined by theta.
"""
plot_data(x, y, feature_names=feature_names, logistic=False)
# following formula: order = (n^2 + 3n) / 2
order = x.shape[1]
u = np.linspace(x[:, 0].min(), x[:, 0].max(), 50)
v = np.zeros(u.size)
# Evaluate v = theta*x over x
for i, ui in enumerate(u):
v[i] = feature_mapping(np.array([[ui]]), order, intercept=True) @ theta
plt.plot(u, v, c="r")
def plot_costs(costs):
"""
:param costs: 2-D array, consisting of the
number of iterations and associated cost
:return: None
"""
plt.figure(figsize=(8, 8))
plt.plot(costs[:, 0], costs[:, 1])
plt.xlabel("Nr Iterations")
plt.ylabel("J(\u03B8)")
plt.show()
def plot_learning_curve(error_train, error_test, m_lst, optimize_lambda_=True):
"""
Plots the learning curve for a given training and test sets.
:param error_train: vector of training errors
:param error_test: vector of test errors
:param m_lst: vector of training examples used to calculate errors
:param optimize_lambda_: if x axis is regularization parameter
:return: None
"""
plt.figure()
plt.plot(m_lst, error_train, m_lst, error_test, lw=2)
plt.title('Learning curve for linear regression')
plt.legend(['Train', 'Cross Validation'])
if optimize_lambda_:
plt.xlabel('lambda')
else:
plt.xlabel('Number of training examples')
plt.ylabel('Error')
plt.show()
|
355e7631534d49487726671e98f7dfb36bd3fc7b | SamRod33/some_game | /clock.py | 887 | 3.71875 | 4 | import pygame
class Clock():
def __init__(self, FPS, COOLDOWN_TIMER=0):
"""
creates a clock that keeps track of time.
FPS is the frames per second the clock will tick at.
"""
self._global_time = 0
self._clock = pygame.time.Clock()
self._fps = FPS
self._cool_clock = COOLDOWN_TIMER
self._cooldown = COOLDOWN_TIMER
def update(self):
"""
Updates global time and ticks the clock forward
"""
dt = self._clock.tick(self._fps)
self._global_time += dt
self._cool_clock += dt
def global_time(self):
"""
Gets the total amount of time that has passed since this clock's creation
"""
return self._global_time
def cooldown_time(self):
return self._cooldown
def reset_cooldown(self):
self._cool_clock = 0
|
5f6b56c75b4a8353041e0785538ac32f36766d3b | pramod-baikady95/Python-Codes | /Numerical Methods/Interpolation.py | 496 | 3.734375 | 4 | time = [0,20,40,60,80,100]
temp = [26, 48.6, 61.6, 71.2, 74.8, 75.2]
# y = lambda xp, x1, x2, y1, y2: y1 + (y2 - y1)/(x2 - x1)*(xp - x1)
# Y_val = y(50,40,60,61.6,71.2)
# print(Y_val)
def y(xp, x, y):
for i, xi in enumerate (x):
if xp < xi:
return y[i-1]+(y[i] - y[i-1])/(x[i] - x[i-1])*(xp - x[i-1])
else:
print ("Given x-value is out of range")
temp50 = y(50, time, temp)
print("The temperature = %f " %temp50)
|
eba3b4744c52e38bdd5dab1a33f9e95f61b8e31a | PlamenAngelov/Python-Fundamentals-03-Lambda | /000-lambda_dictionary.py | 1,261 | 3.921875 | 4 | student_grades = {
'bob': [2, 2],
'petar': [5, 2, 5],
'maria': [6, 6, 5, 6],
'alex': [2, 2]
}
key_sorted_grades = sorted(student_grades.items(), key=lambda kvp: kvp[0])
len_grades_sorted = sorted(student_grades.items(), key=lambda kvp: len(kvp[1]))
len_grades_key_sorted = sorted(student_grades.items(), key=lambda kvp: (len(kvp[1]), kvp[0]))
key_len_grades_sorted = sorted(student_grades.items(), key=lambda kvp: (kvp[0], len(kvp[1])))
len_grades_key_desc_sorted = sorted(student_grades.items(), key=lambda kvp: (len(kvp[1]), kvp[0]), reverse=True)
key_len_grades_desc_sorted = sorted(student_grades.items(), key=lambda kvp: (kvp[0], len(kvp[1])), reverse=True)
for name, grades in key_sorted_grades:
print('{}: {}'.format(name, grades))
print("="*20)
for name, grades in len_grades_sorted:
print('{}: {}'.format(name, grades))
print("="*20)
for name, grades in len_grades_key_sorted:
print('{}: {}'.format(name, grades))
print("="*20)
for name, grades in key_len_grades_sorted:
print('{}: {}'.format(name, grades))
print("="*20)
for name, grades in len_grades_key_desc_sorted:
print('{}: {}'.format(name, grades))
print("="*20)
for name, grades in key_len_grades_desc_sorted:
print('{}: {}'.format(name, grades)) |
892a4da64a11a8982469f235d8a3b7b797e280b4 | yunchui/Leedcode | /513.找树左下角的值.py | 1,253 | 3.921875 | 4 | #
# @lc app=leetcode.cn id=513 lang=python3
#
# [513] 找树左下角的值
#
# https://leetcode-cn.com/problems/find-bottom-left-tree-value/description/
#
# algorithms
# Medium (69.97%)
# Likes: 100
# Dislikes: 0
# Total Accepted: 17.6K
# Total Submissions: 24.9K
# Testcase Example: '[2,1,3]'
#
# 给定一个二叉树,在树的最后一行找到最左边的值。
#
# 示例 1:
#
#
# 输入:
#
# 2
# / \
# 1 3
#
# 输出:
# 1
#
#
#
#
# 示例 2:
#
#
# 输入:
#
# 1
# / \
# 2 3
# / / \
# 4 5 6
# /
# 7
#
# 输出:
# 7
#
#
#
#
# 注意: 您可以假设树(即给定的根节点)不为 NULL。
#
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findBottomLeftValue(self, root: TreeNode) -> int:
queue = [root]
while(queue):
print(root.val)
root = queue.pop(0)
print(root.val)
if root.right: queue.append(root.right)
if root.left: queue.append(root.left)
return root.val
# @lc code=end
|
58688dea0f313467e1133d86f54535b3af050991 | medvedodesa/Lesson_Python_Hillel | /Lesson_5/task_lesson_5/task_10.py | 2,951 | 3.671875 | 4 | # Задача #10 (Дана строка)
"""
Дана строка.
- выведите третий символ этой строки.
- выведите предпоследний символ этой строки.
- выведите первые пять символов этой строки.
- выведите всю строку, кроме последних двух символов.
- выведите все символы с четными индексами (считая, что индексация начинается с 0, поэтому
символы выводятся начиная с первого).
- выведите все символы с нечетными индексами, то есть начиная со второго символа строки.
- выведите все символы в обратном порядке, выведите все символы строки через один в
обратном порядке, начиная с последнего.
- выведите длину данной строки.
"""
s = 'Given a string.'
print('Наша стока:', s)
print('Третий символ этой строки:', s[2])
print('Предпоследний символ этой строки:', s[-2])
print('Первые пять символов этой строки:', s[:5])
print('Вся строка, кроме последних двух символов:', s[:-2])
print('Все символы с четными индексами:', s[::2])
print('Все символы с нечетными индексами:', s[1::2])
print('Все символы в обратном порядке:', s[::-1])
print('Все символы строки через один в обратном порядке:', s[-1::-2])
print('Длина этой строки:', len(s))
# Это более усовершенствованый способ решения этой задачи
while True:
s = input('Введите строку не мение 5 символов:')
if len(s) < 5:
continue
else:
print('Наша стока:', s)
print('Третий символ этой строки:', s[2])
print('Предпоследний символ этой строки:', s[-2])
print('Первые пять символов этой строки:', s[:5])
print('Вся строка, кроме последних двух символов:', s[:-2])
print('Все символы с четными индексами:', s[::2])
print('Все символы с нечетными индексами:', s[1::2])
print('Все символы в обратном порядке:', s[::-1])
print('Все символы строки через один в обратном порядке:', s[-1::-2])
print('Длина этой строки:', len(s))
break
|
abd171b0fdddc5e40b6bed1777282ffdf9f20db8 | akauntotesuto888/Leetcode-Lintcode-Python | /488.py | 1,079 | 3.53125 | 4 | from functools import lru_cache
class Solution:
def findMinStep(self, board: str, hand: str) -> int:
INF = float('inf')
def clean(ss):
i = 0
for j, ball in enumerate(ss):
if ball == ss[i]: continue
if j - i >= 3:
return clean(ss[:i] + ss[j:])
else:
i = j
return ss
@lru_cache(None)
def dfs(remain, h):
remain = clean(remain)
if remain == '#':
return 0
remain_set = set(remain)
h = ''.join(x for x in h if x in remain_set)
if not h: return INF
result = INF
for i in range(len(remain)):
for j, c in enumerate(h):
new_h = h[:j] + h[j + 1:]
new_remain = remain[:i] + c + remain[i:]
result = min(result, 1 + dfs(new_remain, new_h))
return result
result = dfs(board + '#', hand)
return result if result < INF else -1 |
5713d4a67a4fa841b823649d6ca337e24c4b4506 | dooli1971039/Codeit | /BasicPython/ch2_3_ex5.py | 83 | 3.65625 | 4 | i=2
sum=0
while i<1000:
if i%2==0 or i%3==0:
sum+=i
i+=1
print(sum) |
c1e20f4f47f10291b95bbc499481a22ff9ec1c2b | freethinkingzen/MonteHallProblem | /MonteHall.py | 2,341 | 3.640625 | 4 | #!/usr/bin/python
# This program test the results of the Monte Hall Problem
# since the results are counterintuitive to most people
import sys
import argparse
import random
ROUNDS = 1000 # Default number of rounds
helpMessage = '''
** HELP MENU **
===============================================================================
usage: MonteHall.py [-h, --help] [ROUNDS]
optional arguments:
-h, --help display this help message and exit
[ROUNDS] Number of times to repeat the Monte Hall Problem
Must be integer value betwwen 1 and 10,000
================================================================================
'''
def parseArgs():
args = len(sys.argv)
if args == 2:
arg1 = sys.argv[1]
if(arg1 == "--help" or arg1 == "-h"):
print(helpMessage)
exit()
elif(arg1.isdigit() and int(arg1) in range(1,10001)):
return int(arg1)
else:
print("\nError: invalid argument at position 1, '", arg1, "'. See usage below:")
print(helpMessage)
exit()
if args > 2:
print("\nError: invalid number of arguments, '", len(argv), "'. See usage below:")
print(helpMessage)
exit()
return ROUNDS
if __name__ =="__main__":
ROUNDS = parseArgs()
keep_door = 0 # Successful rounds when keeping door choice
switch_door = 0 # Successful rounds when switching door choice
for i in range(ROUNDS): # Perform number of rounds based on constant
doors = [0] * 3
prize_door = random.randrange(0,3)
chosen_door = random.randrange(0,3)
doors[prize_door] = 1
zonk_doors = [i for i, x in enumerate(doors) if x == 0 if i != chosen_door]
montes_door = random.choice(zonk_doors)
if(prize_door == chosen_door):
keep_door += 1
switch_to = set([0,1,2]).difference([chosen_door, montes_door])
switch_to = switch_to.pop()
if(prize_door == switch_to):
switch_door += 1
keep_success = (keep_door/ROUNDS) * 100
switch_success = (switch_door/ROUNDS) * 100
print("ROUNDS:", ROUNDS)
print("Keep: {:0.2f}%".format(keep_success))
print("Switch: {:0.2f}%".format(switch_success))
|
82c38e8e1f4b756235fe7d58a0ac1e12f76e7a80 | geekcomputers/Python | /Shortest Distance between Two Lines.py | 558 | 3.59375 | 4 | import math
import numpy as NP
LC1 = eval(input("Enter DRs of Line 1 : "))
LP1 = eval(input("Enter Coordinate through which Line 1 passes : "))
LC2 = eval(input("Enter DRs of Line 2 : "))
LP2 = eval(input("Enter Coordinate through which Line 2 passes : "))
a1, b1, c1, a2, b2, c2 = LC1[0], LC1[1], LC1[2], LC2[0], LC2[1], LC2[2]
x = NP.array(
[[LP2[0] - LP1[0], LP2[1] - LP1[1], LP2[2] - LP1[2]], [a1, b1, c1], [a2, b2, c2]]
)
y = math.sqrt(
(((b1 * c2) - (b2 * c1)) ** 2)
+ (((c1 * a2) - (c2 * a1)) ** 2)
+ (((a1 * b2) - (b1 * a2)) ** 2)
)
|
341eb65da6224c46209645dd4d00657c4526a537 | artbohr/codewars-algorithms-in-python | /7-kyu/equalize-array.py | 222 | 3.53125 | 4 | def equalize(arr):
return ['+'+str(x-arr[0]) if x-arr[0]>0-1 else str(x-arr[0]) for x in arr]
'''
No description!!!
Input :: [10,20,25,0]
Output :: ["+0", "+10", "+15", "-10"]
Show some love, rank and upvote!
'''
|
4f158a31f88ba183716ca74c933ec89237bcf56e | eronekogin/leetcode | /2021/leaf_similar_trees.py | 490 | 3.96875 | 4 | """
https://leetcode.com/problems/leaf-similar-trees/
"""
from test_helper import TreeNode
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
def get_leaves(root: TreeNode) -> list[int]:
if not root:
return []
if not root.left and not root.right:
return [root.val]
return get_leaves(root.left) + get_leaves(root.right)
return get_leaves(root1) == get_leaves(root2)
|
962ede047a37edb43238fa3289ad86490407faf5 | tkaghdo/stream-enterer | /dataquest-challenges-solutions/sql-databases-beginner/SQL Summary Statistics-181.py | 2,395 | 4.25 | 4 | ## 1. Counting in Python ##
import sqlite3
conn = sqlite3.connect("factbook.db")
facts = conn.execute("select * from facts;").fetchall()
print(facts)
facts_count = len(facts)
## 2. Counting in SQL ##
conn = sqlite3.connect("factbook.db")
birth_rate_count = conn.execute("select count(birth_rate) from facts;").fetchall()[0][0]
print(birth_rate_count)
## 3. Min and max in SQL ##
conn = sqlite3.connect("factbook.db")
min_population_growth = conn.execute("select min(population_growth ) from facts;").fetchall()[0][0]
print(min_population_growth)
max_death_rate = conn.execute("select max(death_rate ) from facts;").fetchall()[0][0]
print(max_death_rate)
## 4. Sum and average in SQL ##
conn = sqlite3.connect("factbook.db")
total_land_area = conn.execute("select sum(area_land) from facts;").fetchall()[0][0]
print(total_land_area)
avg_water_area = conn.execute("select avg(area_water) from facts;").fetchall()[0][0]
print(avg_water_area)
## 5. Multiple aggregation functions ##
conn = sqlite3.connect("factbook.db")
q = "select avg(population), sum(population),max(birth_rate) from facts;"
facts_stats = conn.execute(q).fetchall()
print(facts_stats)
## 6. Conditional aggregation ##
conn = sqlite3.connect("factbook.db")
q = "select avg(population_growth) from facts where population > 10000000;"
population_growth = conn.execute(q).fetchall()[0][0]
print(population_growth)
## 7. Selecting unique rows ##
conn = sqlite3.connect("factbook.db")
q = "select distinct birth_rate from facts"
unique_birth_rates = conn.execute(q).fetchall()
print(unique_birth_rates)
## 8. Distinct aggregations ##
conn = sqlite3.connect("factbook.db")
q1 = "select avg(distinct birth_rate ) from facts where population > 20000000"
average_birth_rate = conn.execute(q1).fetchall()[0][0]
print(average_birth_rate)
q2 = "select sum(distinct population) from facts where area_land > 1000000"
sum_population = conn.execute(q2).fetchall()[0][0]
print(sum_population)
## 9. Arithmetic in SQL ##
conn = sqlite3.connect("factbook.db")
q = "select population_growth / 1000000.0 from facts"
population_growth_millions = conn.execute(q).fetchall()
print(population_growth_millions)
## 10. Arithmetic between columns ##
conn = sqlite3.connect("factbook.db")
q = "select (population * population_growth ) + population from facts"
next_year_population = conn.execute(q).fetchall()
print(next_year_population) |
ac25c0a92399eeebbc5e4cf43021456e70b3081a | C-CCM-TC1028-111-2113/homework-4-LuisFernandoGonzalezCortes | /assignments/17NCuadradoMayor/src/exercise.py | 150 | 3.75 | 4 | import math
def main():
num = int(input("escrube un numero: "))
x= math.sqrt(num)
print("", int(x))
if __name__ == '__main__':
main()
|
d3a7d5f6b10aa35b53a23ed3cea45e4a74031dd8 | joseoliva762/curso-basico-de-python | /ejercicios/randomNum.py | 740 | 4.21875 | 4 | # -*- coding:utf-8 -*-
import random
def main():
numberFound = False
maxNumber = int(input('Ingrese el numero maximo de posibilidades: '))
randomNumber = random.randint(0,maxNumber)
while not numberFound: #mientras no encontramos el numero.
number = int(input("Ingresa un numero: "))
if number == randomNumber:
print('\tFelicidades!!! encontraste el numero. El numero es: {}\r\n'.format(randomNumber))
numberFound = True
elif number > randomNumber:
print('\r\n>>> El numero es mas pequeno.\n')
elif number < randomNumber:
print('\r\n>>> El numero es mas grande. \n')
else:
continue
if __name__ == '__main__':
main()
|
36a2a680a00706a137ec5e2a3eb19751d4a3e332 | curest0x1021/Python-Django-Web | /Velez_Felipe/Asignments/scores_grades.py | 585 | 4.0625 | 4 | def scores_and_grades(grade):
user_input = int(grade)
if 60 > user_input or user_input > 100:
print 'grade must be above 60'
if 60 <= user_input < 70:
print 'Score: ' + str(user_input) + '; Your grade is D'
elif 70 <= user_input < 80:
print 'Score: ' + str(user_input) + '; Your grade is C'
elif 80 <= user_input < 90:
print 'Score: ' + str(user_input) + '; Your grade is B'
elif 90 <= user_input <= 100:
print 'Score: ' + str(user_input) + '; Your grade is A'
index = 0
while index <= 10:
input_grade = raw_input()
index= index + 1
scores_and_grades(input_grade)
|
20fb6e94641bbc95e8b980e234ac318599a89110 | konsatanasoff/python-fundameltals-2020 | /exam_preparations/num_bers.py | 296 | 3.609375 | 4 | numbers = list(map(int, input().split()))
average = sum(numbers) / len(numbers)
grater = []
for number in sorted(numbers, reverse=True):
if number > average:
grater.append(number)
if len(grater) > 0:
print(" ".join(map(str, grater[:5])))
else:
print("No")
|
cf7d5729a8ed384ec4a2863c05e040f0804f9a3e | meloLeeAnthony/PythonLearn | /12-Numpy数学函数库/02.array创建数组.py | 532 | 3.515625 | 4 | # 导入numpy模块
import numpy as np
# 使用array函数创建一维数组
a = np.array([1, 2, 3, 4])
print(a)
print(type(a))
# 使用array函数创建二维数组
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(b)
print(type(b))
# 使用array函数创建三维数组
c = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
print(c)
print(type(c))
# array函数中dtype的使用
d = np.array([3, 4, 5], dtype=float)
print(d)
print(type(d))
# array函数中ndim的使用
e = np.array([5, 6, 7], dtype=float, ndmin=3)
print(e)
|
7fd949d4e5b3d64458f47bb04889325da6d18d1b | malladi2610/Python_programs | /Assignment_programs/Assignment_1/Assignment2.1.py | 835 | 4.28125 | 4 | """Write a program to create a list of numbers from 1 to 50 named list_1. The numbers should be present in the increasing order:
Ex list_1 = [1,2,3,4,5,....,50] i. e. index zero should be 1, index one should be 2, index two should be 3 and so on.
Given an input let's say a, you have to print the number of elements of list_1 which are divisible by a, excluding the
element which is equal to a. Ex: a=14 output=2"""
def divisibility(a):
list_1 = []
count = 0
for i in range(1,51):
list_1.append(i)
for i in list_1:
if(i%a == 0):
if(i == a):
continue
count += 1
return count
a = int(input("Enter the number :"))
count = divisibility(a)
print("The no of elements divisible by", a, "in the list in", count) |
505c94df6a027a0ce40fc3baf8b3f74d10f84355 | FateScript/numpy_deeplearning | /function/relu.py | 617 | 3.625 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
import numpy as np
from IPython import embed
class ReLU:
def forward(self, x):
self.grad_mask = x < 0
return np.maximum(x, 0)
def backward(self, grad_input):
grad_input[self.grad_mask] = 0
return grad_input
def test_ReLU(input, grad_input):
f = ReLU()
output = f.forward(input)
grad_output = f.backward(grad_input)
return output, grad_output
if __name__ == "__main__":
x = np.arange(-5, 5).reshape((2, -1))
y = np.arange(-5, 5).reshape((2, -1))
val, grad = test_ReLU(x, y)
embed(header="main")
|
02d3e4b28382b26f81fd758d098ff6f7490669c2 | jdvpl/Python | /Universidad Nacional/monitorias/Ejercicios/13-tuplas/subtuplas.py | 304 | 3.546875 | 4 | avengers = ("Ironman", "Spiderman", "Ant-man", "Hulk")
#print(avengers[:2])
#print(avengers[1:3])
#print(avengers[::])
#print(avengers[0:len(avengers):1])
avengers = (["Ironman", "Spiderman"], "Ant-man", "Hulk")
avengers[0][0] = "Mujer maravilla"
# pendiente: intentar añadir elemento a la lista
print(avengers) |
032936caa0a60ae754bd8ee9d2e80bbef3777e3c | Lancher/coding-challenge | /math/_TODO_number_digit_one.py | 211 | 3.609375 | 4 | # LEETCODE@ 233. Number of Digit One
#
# --END--
def count_digit_one(n):
ones, m = 0, 1
while m <= n:
ones += (n/m + 8) / 10 * m + (n/m % 10 == 1) * (n % m + 1)
m *= 10
return ones
|
3d1aed401c0be235214aac1a534669eef66d04d1 | rafa1285/python | /Repaso/arbol.py | 105 | 3.59375 | 4 | longitud = int(input("Elige el tamaño del arbol: "))
for i in range(longitud):
print('*' * (i+1))
|
e988d0c0f8a28fc29d79818572f5cc19738ab258 | ndubbala/ansible-scripts | /playbooks/filter_plugins/append.py | 414 | 3.625 | 4 | ## append
## Provides a helper function to append to a list
class FilterModule(object):
def filters(self):
filter_list = {
'append': append
}
return filter_list
def append(data, value):
"""Append value to list
:param data: Data to append to, in list form
:param value: Value to append
:returns: List
"""
data.append(value)
return data
|
a41bc114f69f6a7c84a5ebb43b3a5334d61c772f | laoniu85/udacity_nd000 | /inheritance.py | 451 | 3.78125 | 4 | class Parent():
def __init__(self,name,eye_color):
print "Parent custructor called!!!"
self.name=name
self.eye_color=eye_color
class Child(Parent):
def __init__(self,name,eye_color,number_toys):
print "Child custructor called!!!"
Parent.__init__(self,name,eye_color)
self.number_toys=number_toys
billy=Parent("billy","blue")
shit=Child("shit","shit",2)
print billy.name
print shit.number_toys
|
b421fb22b15f1cb3d1220450ff65699158eed3c7 | anodo123/mini-projects | /normal programs/playing with classes1.py | 326 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 13:57:58 2020
@author: DELL
"""
class hello:
def __init__(self):
self.first_data=int(input())
self.second_data=int(input())
def avg(self):
m= (self.first_data + self.second_data)/2
return m
s1=hello()
print(s1.__dict__)
|
2fe6f670b0c79bc86a1be6e29dddc2cbba43d54e | superf2t/TIL | /PYTHON/BASIC_PYTHON/수업내용/0/circle.py | 1,310 | 4.0625 | 4 | ## circle
if 1:
import math
class Circle:
def __init__(self, radius=1):
self.__radius = radius
self.__diameter = 2 * radius
self.__area = radius**2 * math.pi
@property
def radius(self):
return self.__radius
@radius.setter
def radius(self, radius):
if radius < 0 : raise ValueError("Radius cannot be negative")
self.__radius = radius
self.__diameter = 2 * radius
self.__area = radius**2 * math.pi
@property
def diameter(self):
return self.__diameter
@diameter.setter
def diameter(self, diameter):
if diameter < 0 : raise ValueError("Radius cannot be negative")
self.__diameter = diameter
self.__radius = diameter/2
self.__area = self.__radius**2 * math.pi
@property
def area(self):
return self.__area
@area.setter
def area(self, diameter):
raise AttributeError
def __repr__(self):
return f'Circle({self.__radius})'
def printCircle(self):
print(self.__radius, self.__diameter, self.__area)
|
86597107520c6af2a364b858ede7cb543f531155 | ewartj/MedCAT_Deidentification | /dictionaries/synthetic_phone_number.py | 1,600 | 3.71875 | 4 | from random import randint
from python_functions.helper import save_list_to_file, print_list_values, size_of_list_values, read_list, list_unique_vals_only, only_values_of_length
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return str(randint(range_start, range_end))
def mobile(amount_generated):
mobile = []
allowed_3rd_numbs = [1,2,3,4,5,7,8,9]
per_choice = amount_generated / len(allowed_3rd_numbs)
for i in range(0,len(allowed_3rd_numbs)):
i = allowed_3rd_numbs[i]
for j in range(0, int(per_choice)):
k = f"07{i}{random_with_N_digits(9)}"
mobile.append(k)
return mobile
def landline(amount_generated, area_codes):
landline = []
per_choice = amount_generated / len(area_codes)
for i in range(0,len(area_codes)):
i = area_codes[i]
for j in range(0, int(per_choice)):
k = '0' + str(i) + ' ' + random_with_N_digits(6)
landline.append(k)
return landline
#mob = mobile(1000000)
mob = mobile(100)
landline_lst = read_list("phone_numbers/area_codes.txt", "UTF-8")
landline_numbers = landline(100, landline_lst)
mob = list_unique_vals_only(mob)
mob_lengths = size_of_list_values(mob)
print(mob_lengths)
print(f"unique mobiles: {len(mob)}")
# landline_numbers = list_unique_vals_only(landline_numbers)
# londline_lengths = size_of_list_values(landline_numbers)
# print(londline_lengths)
# print(f"unique landlines {len(landline_numbers)}")
# save_list_to_file("mobile_numbers.txt", mob)
# save_list_to_file("landline.txt", landline_numbers) |
c2c1ddbde29f53aebd4c35050142bd63e23ada09 | claudiaquintanad/zoo-python | /Clases/pulpo.py | 390 | 3.609375 | 4 | from Clases.animal import Animal
class Pulpo(Animal):
def __init__(self, name, edad):
super().__init__("Pulpo " + name, edad, 0, 0)
super().alimento()
def alimento(self):
self.salud += 8
self.felicidad += 12
print(f"El pulpo {self.name} se alimenta. Aumenta su salud en {self.salud} y su felicidad en {self.felicidad}")
return self |
256c4ff6be9158b8b723183d3cf6cd7213d1f46d | huazhige/EART119_Lab | /hw4/submissions/soaressteven_25700_1303776_Soares_HW4_Problem_2.py | 2,843 | 3.875 | 4 | # -*- coding: utf-8 -*-
#python2.7
# =============================================================================
# Problem 2.
# =============================================================================
import numpy as np
import matplotlib.pyplot as plt
import os
import opt_utils as opt
# =============================================================================
# Define functions
# =============================================================================
def f ( t):
"""
The function f given in homework 4 problem 2
"""
c = 1.1
t_0 = 2.5
Ans = c * (t - t_0)**2
return Ans
def g ( t):
"""
The function g given in homework 4 problem 2
"""
t_0 = 2.5
A = 5.
Ans = A * t + t_0
return Ans
def diff ( t):
"""
f(t) minus g(t)
"""
c = 1.1
t_0 = 2.5
A = 5.
Ans = (c * (t - t_0)**2) - (A * t + t_0)
return Ans
def dfdt ( t):
"""
The derivative of f(t)
"""
c = 1.1
t_0 = 2.5
Ans = 2*c*(t-t_0)
return Ans
def dgdt ( t):
"""
The deriviative of g(t)
"""
A = 5.
Ans = A
return Ans
def ddiffdt ( t):
"""
Derivative of the diff function
The name is d(diff)/dt
"""
c = 1.1
t_0 = 2.5
A = 5.
Ans = 2*c*(t-t_0) - A
return Ans
# =============================================================================
# Define variables
# =============================================================================
t0 = 2.6 # Guess for where the root is
t = np.arange(-10, 11, 1)
# print(t) # Unit testing
t_root = opt.my_Newton(diff, ddiffdt, t0)
for i in np.arange(0,21,1):
if t_root == t[i]:
print t_root
if i < 20:
i += 1
else:
break
# For some reason, even though I'm setting it to a variable, the my_Newton
# function is still printing variables. I'm assuming this is causing
# the for loop I created to not work, as the code "print t_root" simply isn't
# doing anything
# From here I would see how many numbers are printed, allowing me to solve
# part a. I can see which values of t are the roots from what's printed. From
# here I can plug these values into f(t) and g(t) to solve part b.
# The following is what I would type for part c.
# =============================================================================
# plt.plot(t, diff(t), 'b-')
# plt.plot('one of the printed roots', diff('that root'), 'r*')
# plt.savefig('HW4_Problem2_plot.png')
# =============================================================================
|
245f87386e8b5258628da2ac75b8c702978fa5cc | lindo-zy/Data-structure-and-algorithm | /Stack and Queue/samples/maze_stack.py | 1,603 | 3.859375 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
迷宫问题基于栈回溯求解
ps.程序存在问题,end为(3,2)时,迷宫无出路
'''
class Stack():
def __init__(self):
self._elems = []
def is_empty(self):
return self._elems == []
def top(self):
if self._elems == []:
raise StackUnderflow('in stack top()')
return self._elems[-1]
def push(self, elem):
self._elems.append(elem)
def pop(self):
if self._elems == []:
raise StackUnderflow('in stack pop()')
return self._elems.pop()
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 东西南北方向
def mark(maze, pos):
maze[pos[0]][pos[1]] = 2 # 给迷宫maze的位置pos标2 表示’到过了‘
def passable(maze, pos):
return maze[pos[0]][pos[1]] == 0 # 检查迷宫maze的位置pos是否可行
def maze_solver(maze, start, end):
if start == end:
print(start)
return
st = Stack()
mark(maze, start)
st.push((start, 0))
while not st.is_empty():
pos, nxt = st.pop()
for i in range(nxt, 4):
nextp = (pos[0] + dirs[i][0],pos[1] + dirs[i][0])
if nextp == end:
print(end, pos, st)
return
if passable(maze, nextp):
st.push((pos, i + 1))
mark(maze, nextp)
st.push((nextp, 0))
break
print('迷宫没有出路')
maze = [[0, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 0]]
start = (0,0)
end = (3,2)
maze_solver(maze, start, end)
|
7f5c55f9c45de7de4da19217c65734825f403933 | zoelilyhuang/coding365HW | /week1/007.py | 1,906 | 3.578125 | 4 | """
a = int(input())
b = int(input())
c = int(input())
"""
"""
num = [int(input()),int(input()),int(input())] #書本數量
dis = [0,0,0] #折扣
#pri = [380,1200,180]
"""
"""
if num[0] <= 0:
dis[0] = 0
elif num[0] > 0 and num[0] <= 10:
dis[0] = 1
elif num[0] >10 and num[0] <=20:
dis[0] = 0.9
"""
"""
a = [int(input()),int(input()),int(input())]
b = [0,0,0]
"""
"""
if num[0] <= 10 and num[0] >0 : #以書本A數決定折扣
dis[0] = 1 #原價
elif num[0] <= 0 :
dis[0] = 0 #若書本A數為負或0,折扣為0
elif num[0] > 10 and num[0] <= 20 :
dis[0] = 0.9
elif num[0] > 20 and num[0] <= 30 :
dis[0] = 0.85
elif num[0] > 30:
dis[0] = 0.8
if num[1] <= 10 and num[1] >0 : #書本B
dis[1] = 1
elif num[1] <= 0 :
dis[1] = 0
elif num[1] > 10 and num[1] <= 20 :
dis[1] = 0.95
elif num[1] > 20 and num[1] <= 30 :
dis[1] = 0.85
elif num[1] > 30:
dis[1] = 0.8
if num[2] <= 10 and num[2] >0 : #書本C
dis[2] = 1
elif num[2] <= 0 :
dis[2] = 0
elif num[2] > 10 and num[2] <= 20 :
dis[2] = 0.85
elif num[2] > 20 and num[2] <= 30 :
dis[2] = 0.8
elif num[2] > 30:
dis[2] = 0.7
print('%.f' %(num[0]*dis[0]*380 + num[1]*dis[1]*1200 + num[2]*dis[2]*180)) #總價
"""
"""
print(int(num[0]*dis[0]*380 + num[1]*dis[1]*1200 + num[2]*dis[2]*180)) #總價
"""
#new
a = int(input())
b = int(input())
c = int(input())
mon = 0
if a >= 1 and a <=10:
mon += a*380
elif a > 10 and a <=20:
mon += a*380*0.9
elif a > 20 and a <= 30:
mon += a*380*0.85
elif a > 30:
mon += a*380*0.8
if b >= 1 and b <=10:
mon += b*1200
elif b > 10 and b <=20:
mon += b*1200*0.95
elif b > 20 and b <= 30:
mon += b*1200*0.85
elif b > 30:
mon += b*1200*0.8
if c >= 1 and c <=10:
mon += c*180
elif c > 10 and c <=20:
mon += c*180*0.85
elif c > 20 and c <= 30:
mon += c*180*0.8
elif c > 30:
mon += c*180*0.7
print(int(mon)) |
929ecc523f8909819e9607c8ae3c6e4555bcab80 | tkong9/AI-Programming-with-Python | /intro_python/6.scripting/read_and_write.py | 626 | 4.1875 | 4 | f = open('some_file.txt', 'r')
#Documents/udacity/ai/intro_python/6.scripting/some_file.txt
file_data = f.read()
f.close()
print(file_data)
f1 = open('my_file.txt', 'w')
f1.write("Hello there!")
f1.close()
f2 = open('my_file.txt', 'r')
file_data2 = f2.read()
f2.close()
print(file_data2)
with open('some_file.txt', 'r') as read_file:
file_data11 = read_file.read()
print('------------------')
print(file_data11)
print('-----------haha---------------')
with open('some_file.txt') as file_object:
# for line in file_object:
# print(file_object.readline())
for line in file_object:
print(line)
|
9564f8c0c9eb3826bdbba9d5766d4a235a666e7c | nguyenvo09/mcmc | /modularity.py | 8,724 | 3.53125 | 4 | import numpy as np
import networkx as nx
'''
Computing modularity of a graph G(V, E), each node 'u \in V' will belong to a community.
Details:
Implementation of http://perso.crans.org/aynaud/communities/index.html is wrong in modularity function
where there is self-looping edge. This does not matter if our graph has no self-loop edge. This implemention,
however, when applied to Louvain which includes re-creating graph after first-pass of finding community, leads to
mistake in computing modularity!!!!
@author: ben
'''
def modularity(partition, graph) :
"""Compute the modularity of a partition of a graph based on equation
https://www.cs.umd.edu/class/fall2009/cmsc858l/lecs/Lec10-modularity.pdf
@partition : dict the partition of the nodes, i.e a dictionary where keys are their nodes and values the communities
@graph : networkx.Graph the networkx graph which is decomposed
.. 1. Newman, M.E.J. & Girvan, M. Finding and evaluating community structure in networks. Physical Review E 69, 26113(2004).
Examples
--------
"""
inc = {}
deg = {}
no_links = graph.size(weight='weight')
assert type(graph) == nx.Graph, 'Bad graph type, use only non directed graph'
if abs(no_links) <= 1e-10 :
raise ValueError("A graph without link has an undefined modularity")
for node in graph :
com = partition[node]
#computing cross-edge-weight and inner-edge-weight
deg[com] = deg.get(com, 0.) + graph.degree(node, weight = 'weight')
inc[com] = inc.get(com, 0.)
#compute inner-edge weight sum.
for neighbor, datas in graph[node].items() :
weight = datas.get("weight", 1.0)
if partition[neighbor] == com :
assert neighbor != node, 'There is no self-looping, please!!!'
inc[com] = inc.get(com, 0.) + float(weight)
# if neighbor == node :
# inc[com] = inc.get(com, 0.) + float(weight)
# else :
# # This is because inner-edges will be considered twice. While cross-edges are considered only once!!!!
# inc[com] = inc.get(com, 0.) + float(weight)
modularity_ = 0.
cnt = 0
# print 'No_edges: ', no_links
for com in set(partition.values()) :
assert com in deg
cnt += 1
# modularity_ += (inc[com] / float(no_links)) - (deg[com] / (2.0*no_links) )**2
# This is because inner-edges will be considered twice. While cross-edges are considered only once!!!!s
assert deg[com] >= inc[com]
# deg[com] = deg[com] - inc[com]
# print 'Community: ', com, 'Inner-edges: ', inc[com], ' Inner+Outer-edges: ', deg[com]
a_i = deg[com] / float(2.0* no_links)
modularity_ += (inc[com] / float(2*no_links)) - a_i*a_i
return (modularity_, cnt)
def modularity_way2(partition, graph):
'''
Second implementation of modularity of G(V,E) based on dictionary of partition
:param partition: dictionary of partition of graph. Each node belongs to a community.
:param graph: undirected graph G(V,E)
:return:
'''
no_links = graph.size(weight='weight')
assert type(graph) == nx.Graph, 'Bad graph type, use only non directed graph'
if abs(no_links) <= 1e-10 :
raise ValueError("A graph without link has an undefined modularity")
rev_partitions = {}
for vertex, community in partition.iteritems():
rev_partitions[community] = rev_partitions.get(community, {})
assert vertex not in rev_partitions[community]
rev_partitions[community][vertex] = 1
DEBUG = True
if DEBUG:
r = 0
for community,vertices in rev_partitions.iteritems():
r += len(vertices)
assert r == len(graph.nodes()), 'Something wrong!!!!'
Q = 0.0
cnt = 0
for community, dict_vertices in rev_partitions.iteritems():
vertices = dict_vertices.keys()
cnt += 1
count_loop = 0
total_edge = 0
# print vertices
dict_edges = {}
'''We need to loop all possible pair of vertices in community k even if there is no edge between u and v. A_{u,v}=0!!!
Oh my gosh!!!!'''
for i in xrange(len(vertices)):
for j in xrange( len(vertices)):
count_loop += 1
u = vertices[i]
v = vertices[j]
d_i = graph.degree(u, weight='weight')
d_j = graph.degree(v, weight='weight')
t = 0
if u in graph[v] or v in graph[u]:
t = graph[u][v]['weight']
assert graph[u][v]['weight'] == graph[v][u]['weight']
total_edge += 1
x = (t - d_i * d_j / (2.0 * no_links))
Q += x
Q = Q/(2.0 * no_links)
return (Q, cnt)
def modularity_way3(partition, graph):
'''Q = 1/(2m)* Trace(S^T.dot(B).dot(S)
Where S.shape = (N,K) and B.shape = (N,N)
'''
N = len(partition) #the number of vertices.
K = len(set(partition)) #the number of community
m = graph.size(weight='weight')
#creating matrix of communities
S = np.zeros((N, K))
for vertex, comm in partition.iteritems():
v = vertex - 1
cc = comm - 1
assert v >= 0 and v < N
assert cc >= 0 and cc < K
S[v, cc] = 1.0
assert abs(np.sum(S) - N) <= 1e-10, 'There must be N entries with 1.0'
#creating vector of degree of each vertex
D = [0 for i in xrange(N)]
for node in graph:
u = node-1
assert u>=0 and u<N
D[u] = graph.degree(node, weight='weight')
D = np.array(D)
D = D[np.newaxis, :].T
assert D.shape == (N, 1)
# print 'Degree vector: ', D
#creating matrix A
A = np.zeros((N, N))
for edge in graph.edges(data=True):
u,v,info = edge
u-=1
v-=1
w = info['weight']
assert u>=0 and u<N and v >=0 and v<N
A[u][v] = float(w)
A[v][u] = float(w)
# print A
assert abs(np.sum(A) - 2*m) < 1e-10
###############################################
B = A - 1.0/(2.0*m) * D.dot(D.T)
assert B.shape == (N, N)
#based on book CommunityDetectionAndMining HuanLiu
Q = 1.0/(2.0*m) * np.trace(S.T.dot(B).dot(S))
return (Q, K)
def computeModularity(graph_file, no_comms):
fin=open(graph_file, 'rb')
partitions = {}
G = nx.Graph()
for line in fin:
line=line.replace('\n', '')
u,v,comU,comV = line.split()
partitions[u] = comU
partitions[v] = comV
G.add_edge(u,v)
modu,no_comm= modularity(partition=partitions, graph=G)
assert no_comm == no_comms
return modu, no_comm
def test_modularity1():
edges = [(1, 2, 0.1), (1, 3, 0.1), (1, 4, 0.1),
(2, 3, 0.1),
(3, 4, 0.1),
(4, 5, 0.3), (4, 6, 0.4),
(5, 6, 0.1), (5, 7, 0.1), (5, 8, 0.1),
(6, 7, 0.1), (6, 8, 0.1),
(7, 8, 0.1), (7, 9, 0.5)]
edges = [(1, 2, 1), (1, 3, 1), (1, 4, 1),
(2, 3, 1), (3, 4, 1), (4, 5, 1),
(4, 6, 1), (5, 6, 1), (5, 7, 1),
(5, 8, 1), (6, 7, 1), (6, 8, 1),
(7, 8, 1), (7, 9, 1)]
degs = (1 + 3 + 4 + 4 + 4 + 4 + 3 + 2 + 3)
membership = {1: 1, 2: 1, 3: 1, 4: 1,
5: 2, 6: 2, 7: 2, 8: 2,
9: 3}
assert len(membership) == 9
assert len(set(membership.values())) == 3
assert degs % 2 == 0
assert len(edges) == degs / 2, '%s vs %s' % (len(edges), degs / 2)
G = nx.Graph()
for e in edges:
G.add_edge(e[0], e[1], weight=e[2])
modularity_0, no_comm_1 = modularity_way3(partition=membership, graph=G)
modularity_1, no_comms = modularity(membership, G)
modularity_2, no_comms2 = modularity_way2(membership, G)
print modularity_0, modularity_1, modularity_2
assert no_comms == no_comms2 and no_comms2 == 3
assert abs(modularity_1 - modularity_2) < 1e-10, 'Mismatched value two implementations: %s vs. %s' % (modularity_1, modularity_2)
def test_modularity_of_networkx():
edges = [(1, 2, 1), (1, 3, 1), (1, 4, 1),
(2, 3, 1), (3, 4, 1), (4, 5, 1),
(4, 6, 1), (5, 6, 1), (5, 7, 1),
(5, 8, 1), (6, 7, 1), (6, 8, 1),
(7, 8, 1), (7, 9, 1), (1,1,1)]
G = nx.Graph()
membership = {1: 1, 2: 1, 3: 1, 4: 1,
5: 2, 6: 2, 7: 2, 8: 2,
9: 3}
import community
for e in edges:
G.add_edge(e[0], e[1], weight=e[2])
print community.modularity(membership, G)
if __name__ == '__main__':
print 'here'
test_modularity_of_networkx()
test_modularity1()
|
4ae991e55dde2faff1a4366efebeb906341bef2c | JosephZYU/Python-3-Advanced | /19.Clarifying the Issues with Mutable Default Arguments_1.py | 1,004 | 4 | 4 | # Best Practices:
# 🧠 def func(arg, list=None):
def add_employee(emp, emp_list=[]):
emp_list.append(emp)
print(emp_list)
# Set the default list to None if no data input
# NOTE: this is NOT an "if-else" statement, it is ONLY a pre-requisite
# if只是作为进行后序步骤的先决条件,而不是所谓的if else 二选一的判断结果!
# 🧭 重点在于提供选择权,通过每次设置为None,可以选择每次重建新的list,或是在既有list上增加!
def add_employee_fixed(emp, emp_list=None):
# If there is NO input -> set every time to a new empty list
if emp_list is None:
emp_list = []
emp_list.append(emp)
print(emp_list)
emps = ['John', 'Jane']
add_employee('Corey')
add_employee('Jason')
add_employee('James')
print()
add_employee_fixed('Corey')
add_employee_fixed('Jason')
add_employee_fixed('James')
print()
add_employee_fixed('Corey', emps)
add_employee_fixed('Jason', emps)
add_employee_fixed('James', emps)
print()
|
0a647e90a13727eb9d60a5d3ebb7c9ee999df76c | kanbujiandefengjing/python | /python实例/列表反转.py | 442 | 4.03125 | 4 | '''
列表反转
题目内容:
输入一个列表,将其反转后输出新的列表。
可以使用以下实现列表alist的输入:
alist=list(map(int,input().split()))
输入格式:
共一行,列表中的元素值,以空格隔开。
输出格式:
共一行,为一个列表。
'''
alist=list(map(int,input("请输入列表中的元素,以空格隔开:").split()))
alist.reverse()
print(alist)
|
5236952374fccd5caf3eb4ddf8cfec1393001e2e | Oyekunle-Mark/Sorting | /src/searching/searching.py | 1,809 | 4.53125 | 5 | def linear_search(arr, target):
"""A basic linear search algorithm
Arguments:
arr {list} -- the list to be searched
target {int} --the number to be searched for
Returns:
int -- -1 if target not found in arr and 1 if found
"""
for i, item in enumerate(arr):
if item == target:
return i
return -1
def binary_search(arr, target):
"""An implementation of the binary search algorithm
Arguments:
arr {list} -- the list to be searched
target {int} --the number to be searched for
Returns:
int -- -1 if target not found in arr and 1 if found
"""
# if array is empty
if len(arr) == 0:
return -1
low = 0
high = len(arr)-1
while low <= high:
midpoint = (low + high) // 2
if arr[midpoint] == target:
return arr.index(target)
if target < arr[midpoint]:
high = midpoint - 1
else:
low = midpoint + 1
return -1 # not found
def binary_search_recursive(arr, target, low, high):
"""A recursive binary search algorithm
Arguments:
arr {list} -- the list to be searched
target {int} --the number to be searched for
low {int} -- the start index
high {int} -- the end index
Returns:
int -- -1 if target not found in arr and 1 if found
"""
# if array is empty
if len(arr) == 0:
return -1
# base case
if low > high:
return -1
middle = (low + high) // 2
if arr[middle] == target:
return arr.index(target)
if target < arr[middle]:
return binary_search_recursive(arr, target, low, middle - 1)
else:
return binary_search_recursive(arr, target, middle + 1, high)
|
136da78013e5b8b76c5b63cfd72a28ef3d904189 | ksjpswaroop/python_primer | /ch_6/stars_data_dict1.py | 946 | 3.65625 | 4 | # Exercise 6.12
infile = open('stars.dat', 'r')
data = {}
for line in infile.readlines()[1:]:
words = line.split()
name = ' '.join(words[:-3])
luminosity = float(words[-1])
data[name] = luminosity
print '='*31
print '%-20s %10s' % ('Star', 'Luminosity')
print '-'*31
for star, luminosity in data.iteritems():
print '%-20s %10.5f' % (star, luminosity)
print '='*31
"""
Sample run:
python stars_data_dict1.py
===============================
Star Luminosity
-------------------------------
Wolf 359 0.00002
Sun 1.00000
Alpha Centauri C 0.00006
Alpha Centauri B 0.45000
Alpha Centauri A 1.56000
Luyten 726-8 A 0.00006
Sirius B 0.00300
Sirius A 23.60000
Luyten 726-8 B 0.00004
BD +36 degrees 2147 0.00600
Barnard's Star 0.00050
Ross 154 0.00050
===============================
"""
|
e51bbdefbb513ee8aab61738f8a8b6e4462a4726 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/ReemAlqaysi/Lesson03/list_lab.py | 2,392 | 4.28125 | 4 | #!/usr/bin/env python3
def series1():
mylist = ['Apples', 'Pears', 'Oranges', 'Peaches']
print(mylist)
#Ask the user for another fruit and add it to the end of the list.
response = input("add another fruit please: ")
mylist.append(response)
print(mylist)
response2 = input("Provide a number between 1 and {:d}: ".format(len(mylist)))
print(response2 + " is the index number for : " + mylist[int(response2)-1])
#Add another fruit to the beginning of the list using “+” and display the list.
mylist = mylist +['Banana']
print(mylist)
#Add another fruit to the beginning of the list using insert() and display the list.
mylist.insert(0,'Mango')
#Display all the fruits that begin with “P”, using a for loop.
print("Display all the fruits that begin with “P”, using a for loop.")
for name in mylist:
if name[0].upper() == "P":
print(name)
else:
continue
return mylist
def series2(mylist):
print(mylist)
#Remove the last fruit from the list.
mylist.pop()
print("Remove the last fruit from the list.")
print(mylist)
#Ask the user for a fruit to delete, find it and delete it.
response = input("please print a fruit to delete: ")
for fruit in mylist:
if response == fruit:
mylist.remove(response)
break
else:
print ('this fruit not exist in the list')
print(mylist)
def series3(mylist):
for fruit in mylist[:]:
response = input("Do you like " + fruit.lower() + "?\n")
#For each “no”, delete that fruit from the list.
if response == "no":
mylist.remove(fruit)
elif response == "yes":
continue
else:
response = input("Please answer yes or no. Do you like " + fruit.lower() + "?\n")
print(mylist)
def series4(mylist):
newlist = []
#Make a new list with the contents of the original, but with all the letters in each item reversed.
for fruit in mylist:
newlist.append(fruit[::-1])
print("Delete the last item of the original list.")
mylist.pop()
print(mylist)
print("all the letters in each item reversed.")
print(newlist)
if __name__ == '__main__':
series1_list = series1()
series2(series1_list)
series3(series1_list)
series4(series1_list) |
94d590c1b90f75675beaae1e19160e5dfa1a2e8c | Parthava/multipad | /pad.py | 685 | 3.734375 | 4 | ex1='.txt'
ex2='.doc'
ex3='.rtf'
print("Select your appropriate option: \n")
print("1. .txt\n2. .doc\n3. .rtf \n")
d=int(input("Enter here: "))
if(d==1):
file=input("Enter the filename: (F:\Projects\Python\pppp): ")
loc=file+ex1
f=open(loc,"w")
data=input("Enter your data here: ")
f.write(data)
f.close()
elif(d==2):
file=input("Enter the filename: (F:\Projects\Python\pppp): ")
loc=file+ex2
f=open(loc,"w")
data=input("Enter your data here: ")
f.write(data)
f.close()
elif(d==3):
file=input("Enter the filename: (F:\Projects\Python\pppp): ")
loc=file+ex3
f=open(loc,"w")
data=input("Enter your data here: ")
f.write(data)
f.close()
else:
print("Wrong input")
|
44703803884b07a9ce7a26f0ee72afe9e55f1df3 | sweetsinpackets/si507_project | /print_functions.py | 1,425 | 3.53125 | 4 | from class_definition import record_to_string
# return a selection dict, {count: key}
def print_mainpage(d:dict)->dict:
count = 1
selection_dict = {}
print("======================================")
print("All reports available are: ")
print("======================================")
for i in d.keys():
print(str(count) + ": " + str(i))
selection_dict[count] = i
count += 1
print("======================================")
print("")
return selection_dict
def print_records(df)->None:
count = 1
# if contains no records
if len(df) == 0:
print("No record is found! ")
elif len(df) <= 10:
print("======================================")
print("The records found are: ")
print("======================================")
for _index, row in df.iterrows():
print(str(count) + ": " + record_to_string(row))
count += 1
print("======================================")
else:
print("======================================")
print("The top 10 records found are: ")
print("======================================")
for _index, row in df[:10].iterrows():
print(str(count) + ": " + record_to_string(row))
count += 1
print("......")
print("======================================")
print("")
return
|
a9494ea29b3d7ad15457d5111ada5d446e8cb72a | Unkovskyi/PyBase08 | /calc1.py | 2,083 | 3.96875 | 4 | # функции которые используются в програме
import string
from string import whitespace, punctuation
def add(a, b):
"""add - функция которая находит сумму двух чисел"""
return a + b
def sub(a, b):
"""sub - функция которая находит разницу двух чисел"""
return a - b
def mul(a, b):
"""mul-функция которая умножает одно число на другое"""
return a * b
def div(a, b):
"""div-функция которая делит одно число на другое"""
flag = True
res = None
try:
res = a / b
flag = False
except(ZeroDivisionError) as e:
print('!!! Error2:', e)
print('Try again')
return res
# начало програмы
Flaf = False
while Flaf == False:
name = input('input yor name: ')
if name in string.punctuation or name == ' ':
print(' !!! invalid input please repeat')
else:
Flaf = True
print('Hello, ', name)
start = 'y'
list_of_oper = {'+': add, '-': sub, '*': mul, '/': div}
while start == 'y':
start = input('Do you want to calculate? [y]-yes, [any button]-no: ')
if start == 'y':
flag = True
while flag:
try:
number_1 = float(input('input number 1: '))
number_2 = float(input('input number 2: '))
oper = input('input operation from the list {}: '.format(list(list_of_oper.keys()))).strip()
flag = False
except(ValueError) as e:
print('!!! Error1:', e)
print('Try again')
res = None
if oper in list(list_of_oper.keys()):
res = list_of_oper[oper](number_1, number_2)
print('Result: {} {} {}={}'.format(number_1, oper, number_2, res))
else:
print('sorry, this operation is not in the list, try again ')
print('Ok, byе') |
34af31819be66bffbfcd85a7c94dab5343550342 | carlton435/cp1404practicals | /prac_04/lists_warmup.py | 402 | 3.953125 | 4 | numbers = [3, 1, 4, 1, 5, 9, 2]
#number[0] = 3
#numbers[-1] = 2
#numbers[3] = 1
#numbers[:-1] = [3, 1, 4, 1, 5, 9]
#numbers[3:4] = [1]
#5 in numbers = True
#7 in numbers = False
#"3" in numbers = False
#numbers + [6, 5, 3] = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
def main():
numbers[0] = "ten"
print(numbers)
numbers[-1] = 1
print(numbers)
print(numbers[2:])
print(9 in numbers)
main() |
e0b5ab69226c7115f57287cb78ce09acbf20b10f | sezerkahraman/Python | /UdemyPython/modüller/sayi_tahmin oyunu.py | 765 | 3.796875 | 4 | import random
import time
print("Sayi tahimini oyununa hoşgeldiniz")
rastgele_sayi=random.randint(1,40)
tahmin_hakkı=7
while True:
tahmin=int(input("Tahmininizi giriniz:"))
if(tahmin<rastgele_sayi):
print("Bilgileriniz kontrol ediliyor")
time.sleep(1)
print("Daha yüksek bir sayi giriniz.....")
tahmin_hakkı-=1
elif(tahmin>rastgele_sayi):
print("Bilgileriniz kontrol ediliyor")
time.sleep(1)
print("Daha düsük bir sayi giriniz.....")
tahmin_hakkı -= 1
else:
print("Bilgileriniz sorgulanıyor...")
time.sleep(1)
print("Tebrikler Sayımız",rastgele_sayi)
break
if(tahmin_hakkı==0):
print("Tahmin hakkınız bitmiştir")
break |
173fff39ab1cf7640be0bab6024a6438b2282fca | halfcress/PyCharm_handbook | /listeler.py | 1,385 | 4.21875 | 4 | kitapliste = ["abc",12,10.5] #listeler string,int,float gibi her türden tipi tutabilir. Başka bir liste de tutabilir.
for i in kitapliste:
print(type(i))
kitapliste2= ["Şeker portakalı","Nutuk","Witcher serisi","Küçük şeyler","Das Kapital"]
for i in kitapliste2:
print("Kitap adı: {}".format(i))
eklenecek = input("Eklenecek kitabın adını yazınız: ")
kitapliste2 += eklenecek #eğer bu şekilde yaparsak ve ozan diye bir kitap girersek;
#['Şeker portakalı', 'Nutuk', 'Witcher serisi', 'Küçük şeyler', 'Das Kapital', 'o', 'z', 'a', 'n'] böyle bir çıktı ile karşılaşacağız.
#bunun önüne geçmek için eklenecek değişkeninin bir liste elemanı olduğunu [eklenecek] şeklinde belirtmemiz gerekiyor ki, tek bir eleman olarak eklesin.
kitapliste3= ["Şeker portakalı","Nutuk","Witcher serisi","Küçük şeyler","Das Kapital"]
for i in kitapliste3:
print("Kitap adı: {}".format(i))
eklenecek = input("Eklenecek kitabın adını yazınız: ")
kitapliste3 += [eklenecek] #aynen bu şekilde.
print(kitapliste3)
#ancak bu düz mantıkla += operatörünü kullandığımız gibi -= operatörü ile listeden çıkartma yapamıyoruz. Bunun sebebi;
"""
string = "abc"
string -= "b" diye bir şey yapamayacak olmamız. Stringlerde çıkartma işlemi yapılamaz, ancak toplama ve çarpma yapılabilir.
""" |
3b9e4cc7c46b0d52ca114c24f3012595f0f068ad | datadesk/django-la-city-campaign-finance | /lacity/process.py | 1,396 | 3.609375 | 4 | from bs4 import BeautifulSoup
from datetime import datetime
# The rows in our data that have dates
# we will need to parse.
DATE_ROWS = [8, 9, 10, 11]
def clean_string(value, return_none=False):
"""
Simple cleanup for a raw string coming out of the download.
If return_none is True, will return None instead of an empty string.
"""
value = value.strip()
if value in [' ', 'N/A']:
value = ''
if return_none and value == '':
return None
return value
def parse_date(datestring):
"""
Takes a date formatted like "01/01/15 00:00:00.0"
Removes the bogus time, and returns a Python date object.
"""
if datestring is None or datestring == '':
return None
datestring = datestring[:8]
return datetime.strptime(datestring, '%m/%d/%y').date()
def parse_html(html):
"""
Takes an HTML table formatted data download from the county, and returns
a nice list
"""
soup = BeautifulSoup(html)
table = soup.find("table")
data = []
for row in table.findAll('tr')[1:]:
temp = []
for index, column in enumerate(row.findAll('td')):
val = clean_string(column.string)
# see if we have a date and parse it
if index in DATE_ROWS:
val = parse_date(val)
temp.append(val)
data.append(temp)
return data
|
f687eba5d1906be4eabf73bb72b1a5a0428a4d1b | x223/cs11-student-work-vianelys | /gettingloopy.py | 379 | 4.125 | 4 | print "hello"[1:]
#it dropped the 'h'
print "hello"[:4]
#it dropped the 'o'
print "hello"[2:4]
#it only kept the 'll'
print "github"[1:3]
print "hamburger"[3:]
print "dongle"[1:3]
print "snapchat"[1:4]
def fruit_pluralizer(list_of_strings):
if fruit [len(fruit)-1]=='y'
print fruit[:len(fruit)-1]+'ies'
else:
print fruit #make the ies not show up on fruits like banana
|
f67366f5f5d109a96af2bdabf721c6a8221741d1 | vam-sin/Norman | /chatbot.py | 3,398 | 3.5 | 4 | import aiml
from random import choice
handouts = {
'Deep Learning': 'N L Bhanu Murthy',
'Reinforcement Learning': 'Paresh Saxena',
'Artificial Intelligence': 'Jabez J Christopher',
'Parallel Computing': 'Geethakumari',
'Cloud Computing': 'Suvadip Batyabyal',
'Information Retrieval': 'Aruna Malapati',
'Machine Learning': 'Lov Kumar'
}
# Tasks Left
# Build android app (Done)
# Connect to the internet to get trends for subjects.
# Store the conversations in flat file (7/4)
# Make both subject and prof work (Done)
def Punctuation(string):
# punctuation marks
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# traverse the given string and if any punctuation
# marks occur replace it with null
for x in string.lower():
if x in punctuations:
string = string.replace(x, "")
# Print string without punctuation
return string
# Create the kernel and learn AIML files
kernel = aiml.Kernel()
kernel.learn("chatbot.xml")
kernel.respond("load aiml b")
# parameters
subject = ''
prof = ''
# File
# f = open('conv.txt','a')
# f.write("\n\n\n")
# user_msg = ''
# norman_msg = ''
print("\nNorman: Hi! My name is Norman!")
while True:
# Process the input. LowerCase it, remove punctuation.
string = input("User: ")
# string = string.lower()
# print string
string = Punctuation(string)
# f.write("User: " + string)
# f.write("\n")
# Get parameters
subject = kernel.getPredicate('subject')
prof = kernel.getPredicate('ppp') # ppp is the prof parameter (LOL)
# print("Parameters: " + subject + " " + prof)
if subject == 'none' and prof == 'none': # Suggest random (Working)
sub, pro = choice(list(handouts.items()))
response = "Norman: Try " + str(sub) + " offered by " + "Prof. " + str(pro)
print(response)
elif subject == 'none' and prof != '': # Working
subs = []
profs = []
for k in handouts:
a = handouts[k].lower()
if prof in a:
profs.append(handouts[k])
subs.append(k)
if len(subs) == 0:
response = "Norman: I couldn't find any courses with that preferences."
print(response)
else:
response = "Norman: You could try the following courses: \n"
for i in range(len(subs)):
response += str(subs[i]) + " offered by " + "Prof. " + str(profs[i]) + ". \n"
print(response)
elif subject != '' and prof == 'none': # Working
profs = []
subs = []
for k in handouts:
a = k.lower()
if subject in a:
profs.append(handouts[k])
subs.append(k)
if len(subs) == 0:
response = "Norman: I couldn't find any courses with that preferences."
print(response)
else:
response = "Norman: You could try the following courses: \n"
for i in range(len(subs)):
response += str(subs[i]) + " offered by " + "Prof. " + str(profs[i]) + ". \n"
print(response)
elif subject != '' and prof != '': # working
subject = subject.split()[0]
prof = prof.split()[0]
profs = []
subs = []
for k in handouts:
a = k.lower()
b = handouts[k].lower()
if (subject in a) and (prof in b):
profs.append(handouts[k])
subs.append(k)
if len(subs) == 0:
response = "Norman: I couldn't find any courses with that preferences."
print(response)
else:
response = "Norman: You could try the following courses: \n"
for i in range(len(subs)):
response += str(subs[i]) + " offered by " + "Prof. " + str(profs[i]) + ". \n"
print(response)
else:
print(kernel.respond(string))
|
885c66c58bb4128fdd760d698514a404d48ad376 | lucasb-eyer/DeepFried2 | /DeepFried2/init/Concat.py | 640 | 3.6875 | 4 | import numpy as _np
def concat(*inits, axis=-1):
"""
Initializes a tensor as a concatenation of the given `inits` along the
given `axis`, which defaults to the last one.
Useful for creating e.g. "merged dots" as in GRU/LSTM.
"""
def init(shape, fan):
N = len(inits)
assert shape[axis] % N == 0, "Number of inits ({}) doesn't divide shape ({}) on given axis ({})".format(N, shape, axis)
subshape = list(shape)
subfan = list(fan)
subshape[axis] //= N
subfan[axis] //= N
return _np.concatenate([i(subshape, subfan) for i in inits], axis=axis)
return init
|
6d0cc4f41dc0405aae919dbc4100500cd28318cf | rvcervan/ICS-31-Projects-Python | /ICS 31 Labs/Lab 1/lab1d.py | 340 | 3.640625 | 4 | # Raul Cervantes 77825705 and Emmanuel Ezenwa Jr. 44756552. ICS 31 Lab sec 3
def factorial (n: int) -> int:
'''Compute n! (n factorial)'''
if n <= 0:
return 1
else:
return n * factorial(n -1)
assert factorial(0) == 1
assert factorial(5) == 120
print("10! is", factorial(120))
print("100! is", factorial(factorial(5))) |
0600b8a8d1898108130d70bc2f9bb67c0f851c94 | ashishjsharda/AdvancedPython | /namedtuple2.py | 131 | 3.546875 | 4 | from collections import namedtuple
employee=namedtuple('Employee',['name','empid'])
emp_1=employee('Rick','201')
print(emp_1.name)
|
7c55e63d39d6e5247a22255419743ba1a7fcb443 | ZR-Huang/AlgorithmsPractices | /Leetcode/每日打卡/April/1111_Maximum_Nesting_Depth_of_Two_Valid_Parentheses_Strings.py | 1,789 | 4.09375 | 4 | '''
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")"
characters only, and:
It is the empty string, or
It can be written as AB (A concatenated with B), where A and B are VPS's, or
It can be written as (A), where A is a VPS.
We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's
depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2),
and ")(" and "(()" are not VPS's.
Given a VPS seq, split it into two disjoint subsequences A and B,
such that A and B are VPS's (and A.length + B.length = seq.length).
Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.
Return an answer array (of length seq.length) that encodes such a choice of A and B:
answer[i] = 0 if seq[i] is part of A, else answer[i] = 1.
Note that even though multiple answers may exist, you may return any of them.
Example 1:
Input: seq = "(()())"
Output: [0,1,1,1,1,0]
Example 2:
Input: seq = "()(())()"
Output: [0,0,0,1,1,0,1,1]
Constraints:
1 <= seq.size <= 10000
'''
from typing import List
class Solution:
def maxDepthAfterSplit(self, seq: str) -> List[int]:
# 分析:https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/solution/you-xiao-gua-hao-de-qian-tao-shen-du-by-leetcode-s/
ans = []
depth = 0
for c in seq:
if c == '(':
depth += 1
ans.append(depth % 2)
else:
ans.append(depth % 2)
depth -= 1
return ans
print(Solution().depth('(()())')) |
806437d35965e6bd711f07191f433e5dea40e9e5 | figgynwtn/Character-Analysis | /Ch8Ex7.py | 1,693 | 3.96875 | 4 | Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> def main():
file_variable = open("text.txt" , "r")
textList = []
for line in file_variable:
line = line.rstrip("/n")
mylist = line
textList.append(mylist)
print("finding number of uppercase Letters in text.txt file")
totalUpCaLetters = countUpperCase(textList)
print("number of uppercase Letters : ",totalUpCaLetters)
print()
print("finding number of lowercase letters in text.txt file")
totalLoCaLetters = countLowerCase(textList)
print("number of Lower case Letters : ",totalLoCaLetters)
print()
print("finding number of digits in text.txt file")
totalDigits = countDigits(textList)
print("number of digits : ",totalDigits)
print()
print("finding number of whitespaces in text.txt file")
totalWhiteSpaces = countWhiteSpace(textList)
print("number of whitespaces : ",totalWhiteSpaces)
>>> def countUpperCase(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].isupper():
count+= 1
return count
>>> def countLowerCase(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].islower():
count+= 1
return count
>>> def countDigits(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].isdigit():
count+= 1
return count
>>> def countWhiteSpace(anyList):
count = 0
for row in range(len(anyList)):
for i in range(len(anyList[row])):
if anyList[row][i].isspace():
count+= 1
return count
>>>
|
45c2a08f1b3615054925ff6d6229c9f62062e54e | jay841224/euler | /p50.py | 1,448 | 3.71875 | 4 | def is_prime(n):
if n%2 == 0:
return False
a = 3
while a < n:
if n%a == 0:
return False
a += 2
if a**2 > n:
return True
def main():
sum_primes = 5
primes = [2, 3]
x = 5
while True:
if is_prime(x):
sum_primes += x
if sum_primes > 1000000:
sum_primes = sum_primes - x
break
primes.append(x)
x += 2
#從較大質數開始減
if not is_prime(sum_primes):
temp_sum_primes1 = sum_primes
primes1 = primes.copy()
for prime in primes[::-1]:
if is_prime(temp_sum_primes1 - prime):
ans1 = temp_sum_primes1 - prime
primes1.remove(prime)
break
else:
temp_sum_primes1 -= prime
primes1.remove(prime)
#從較小質數開始減
if not is_prime(sum_primes):
temp_sum_primes2 = sum_primes
primes2 = primes.copy()
for prime in primes:
if is_prime(temp_sum_primes2 - prime):
ans2 = temp_sum_primes2 - prime
primes2.remove(prime)
break
else:
temp_sum_primes2 -= prime
primes2.remove(prime)
if len(primes1) > len(primes2):
return ans1
else:
return ans2
if __name__ == '__main__':
print(main()) |
8d652aadd8da24dd053ade4473b0b0f9750987cf | hlcr/Leetcode | /816 Ambiguous Coordinates.py | 1,244 | 3.515625 | 4 | class Solution(object):
def generate_data_list(self, lt):
ltr = []
if int(lt) == 0:
ltr = [0]
elif lt[0] == '0':
ltr = [int(lt) / (10**(len(lt)-1))]
else:
for i in range(0, len(lt)):
if i == 0:
ltr.append(int(lt))
else:
ltr.append(int(lt) / (10 ** i))
return ltr
def ambiguousCoordinates(self, S):
"""
:type S: str
:rtype: List[str]
"""
S = S[1:len(S)-1]
result = []
for i in range(1, len(S)):
lt = S[:i]
rt = S[i:]
ltr = self.generate_data_list(lt)
rtr = self.generate_data_list(rt)
for l in ltr:
for r in rtr:
result.append("({}, {})".format(l, r))
return result
def make(frag):
N = len(frag)
for d in range(1, N+1):
left = frag[:d]
right = frag[d:]
if ((not left.startswith('0') or left == '0')
and (not right.endswith('0'))):
yield left + ('.' if d != N else '') + right
print(Solution().ambiguousCoordinates("(0123)"))
for i in make("1230"):
print(i) |
c853a376ef91025e026b3e416c88c13c3ae31c55 | c-gohlke/marias-server | /game/utils.py | 3,998 | 3.609375 | 4 | # -*- coding: utf-8 -*-
def get_card(card_val):
color = int((card_val - 1) / 13)
strength = card_val % 13
if strength == 0: # is king
strength = 13
elif strength == 10:
strength = 14 # 0 is better than king
elif strength == 1:
strength = 15 # ace beats evertything
return [color, strength]
def valid_plays(hand, first_played_card, second_played_card, trump):
fcard1_info = None
fcard1_info = get_card(first_played_card)
fcard2_info = None
if second_played_card:
fcard2_info = get_card(second_played_card)
# check if has color
hand_info = [
get_card(card)
for card in hand]
play_validity = [False for i in range(len(hand_info))]
same_color = [False for i in range(len(hand_info))]
is_trump = [False for i in range(len(hand_info))]
for i in range(len(hand_info)):
card = hand_info[i]
if card[0] == fcard1_info[0]:
same_color[i] = True
# player has color of first played card
# if there is a second card played (we are player 3)
if fcard2_info:
"""first 2 cards are same colour -> play higher than max,
or trump"""
if fcard2_info[0] == fcard1_info[0]:
if card[1] > max(fcard2_info[1], fcard1_info[1]):
play_validity[i] = True
# player2 doesn't have colour and trumped
elif fcard2_info[0] == trump:
# must play any card of initial colour
play_validity[i] = True
else: # player2 played no trump or initial colour
if card[1] > fcard1_info[1]:
play_validity[i] = True
elif card[1] > fcard1_info[1]:
play_validity[i] = True
if (not any(play_validity)) and any(same_color):
"""if there are cards of the same color, but none was allowed
to be played in first checking round
than play any card of that colour"""
play_validity = same_color
if not any(play_validity):
# still no valid plays until now -> must play trump
for i in range(len(hand_info)):
card = hand_info[i]
if card[0] == trump:
is_trump[i] = True
if (not fcard2_info or
(fcard2_info[0] == trump and card[1] > fcard2_info[1])
or not trump == fcard2_info[0]):
"""we are player 2, our card is trump and first card
is not trump
-> play any trump
we are player 3, first card is not trump and player2
didn't play trump. We don't have first cards color
(else would have resolved round 1)
-> play any trump
we are player 3, first card is not trump and player 2
played trump. We know player 1 didn't play trump or
else valid plays would have resolved in first round
(same colour) we know current player(3) doesn't have
first played card's colour, or it would have
resolved in round1
-> we play any trump higher than player2's trump
"""
play_validity[i] = True
if not any(play_validity) and any(is_trump):
"""none of the trumps we have were allowed during round3 of
validation checks (means player 2 played trump bigger than any
we have), but we must still play trump because we don't have
player 1s color -> play any trump"""
play_validity = is_trump
if not any(play_validity):
"""still no valid plays untill now -> we have no trump
or cards of initial colour
-> play anything"""
play_validity = [True for i in range(len(hand))]
return play_validity
|
c94e0cb67f91072482ae16ded02e2fd93154b2da | ayush-09/Binary-Tree | /Level order traversal with direction change after every two levels.py | 3,998 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 17 20:35:52 2021
@author: Ayush
"""
from collections import deque
# Iterative
class Node:
def __init__(self,key):
self.data = key
self.left = None
self.right = None
def modifiedLevelOrder(node):
if node == None:
return
if node.left == None and node.right==None:
print(node.data, end=" ")
return
myQueue = deque()
myStack=[]
temp = None
sz=0
ct = 0
rightToLeft = False
myQueue.append(node)
while (len(myQueue)>0):
ct+=1
sz= len(myQueue)
for i in range(sz):
temp = myQueue.popleft()
if rightToLeft==False:
print(temp.data,end=" ")
else:
myStack.append(temp)
if temp.left:
myQueue.append(temp.left)
if temp.right:
myQueue.append(temp.right)
if rightToLeft==True:
while(len(myStack)>0):
temp = myStack[-1]
myStack.pop()
print(temp.data,end=" ")
if ct==2:
rightToLeft = not rightToLeft
ct=0
print()
if __name__ == '__main__':
# Let us create binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)
root.left.right.left = Node(3)
root.left.right.right = Node(1)
root.right.left.left = Node(4)
root.right.left.right = Node(2)
root.right.right.left = Node(7)
root.right.right.right = Node(2)
root.left.right.left.left = Node(16)
root.left.right.left.right = Node(17)
root.right.left.right.left = Node(18)
root.right.right.left.right = Node(19)
modifiedLevelOrder(root)
#Recursive
class NNode:
def __init__(self,data):
self.data = data
self.left= None
self.right = None
def height(root):
if root==None:
return 0
else:
lheight = height(root.left)
rheight = height(root.right)
if lheight > rheight:
return 1+ lheight
else:
return 1+ rheight
def printLevel(root,level,stack=False):
global ss
if root == None:
return
if level==1 and stack==True:
ss.append(root.data)
elif level==1 and stack==False:
print(root.data,end=" ")
elif level>1:
printLevel(root.left, level-1,stack=stack)
printLevel(root.right, level-1,stack=stack)
def print_2_Levels(root):
if root==None:
return
h = height(root)
c=0
for i in range(1,h+1):
global ss
ss=[]
if c<2:
printLevel(root, i,stack=False)
else:
printLevel(root, i,stack=True)
for i in range(len(ss)-1,-1,-1):
print(ss[i],end=" ")
if c==3:
c=-1
c +=1
print("")
if __name__ == "__main__":
root = NNode(1)
root.left = NNode(2)
root.right = NNode(3)
root.left.left = NNode(4)
root.left.right = NNode(5)
root.right.left = NNode(6)
root.right.right = NNode(7)
root.left.left.left = NNode(8)
root.left.left.right = NNode(9)
root.left.right.left = NNode(3)
root.left.right.right = NNode(1)
root.right.left.left = NNode(4)
root.right.left.right = NNode(2)
root.right.right.left = NNode(7)
root.right.right.right = NNode(2)
root.left.left.right.left = NNode(16)
root.left.right.right.left = NNode(17)
root.left.right.right.right = NNode(18)
root.right.left.right.right = NNode(19)
print("Different levels:")
# Function Call
print_2_Levels(root)
|
c11631a364b0647897ba5ff6123219327268daa1 | nikrasiya/Graph-3 | /277_find_the_celebrity.py | 1,068 | 3.71875 | 4 | # The knows API is already defined for you.
# return a bool, whether a knows b
def knows(a: int, b: int) -> bool:
pass
class Solution:
def findCelebrity(self, n: int) -> int:
# celebrity knows no one
# knows(celebrity, person) is False
# find the best suited celebrity (potential)
celebrity = 0
for person in range(n):
# the current celebrity is not the celebrity
# since he/she knows the current person
if knows(celebrity, person):
# update celebrity
# (may be the current person is the celebrity)
celebrity = person
for person in range(n):
if person == celebrity:
continue
# everyone should know the celebrity
# if even one person does not know the celebrity, he/she is not a celebrity
# or if the celebrity knows the current person
if not knows(person, celebrity) or knows(celebrity, person):
return -1
return celebrity
|
6131763857507dff74804e4a5a341fb7f0532884 | HymEric/LeetCode | /python/301-删除无效的括号/301.py | 5,601 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/2/5 0005 10:17
# @Author : Erichym
# @Email : 951523291@qq.com
# @File : 301.py
# @Software: PyCharm
"""
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 ( 和 ) 以外的字符。
示例 1:
输入: "()())()"
输出: ["()()()", "(())()"]
示例 2:
输入: "(a)())()"
输出: ["(a)()()", "(a())()"]
示例 3:
输入: ")("
输出: [""]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-invalid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
import collections
class Solution:
def removeInvalidParentheses(self, s: str) -> list: # easy way
def isvalid(s:str): # if s is valid
l_minus_r=0
for i in range(len(s)):
if s[i]=='(':
l_minus_r+=1
elif s[i]==')':
l_minus_r-=1
if l_minus_r<0:
return False # invlid
return l_minus_r==0 # valid
level={s} # init
while True:
valid=list(filter(isvalid,level))
if valid:
return valid
# level={s[:i]+s[i+1:] for s in level for i in range(len(s)) if s[i] in '()'}
temp=set()
for s in level:
for i in range(len(s)):
if s[i] in '()':
temp=temp|{s[:i]+s[i+1:]}
level=temp
def removeInvalidParentheses2(self, s: str) -> list: # BFS
res=set() # results
rmL= 0 # the remove number of left parentheses
rmR=0 # the remove number of right parentheses
for a in s: # based on the parentheses number
if a=='(':
rmL+=1
elif a==')':
if rmL!=0:
rmL-=1
else:
rmR+=1
# if the s is valid
def isValid(s:str):
l_minus_r=0
for a in s:
if a =='(':
l_minus_r+=1
elif a==')':
l_minus_r-=1
if l_minus_r<0:
return False
return l_minus_r==0
queue=collections.deque([(s,rmL,rmR)]) # 记录此时的s和需要删除的左括号和右括号
visited=set()
visited.add((s,rmL,rmR))
while queue:
temp_s,left_p,right_p=queue.pop()
print(temp_s)
# 输出条件
if left_p==0 and right_p ==0 and isValid(temp_s):
res.add(temp_s)
for i in range(len(temp_s)):
# 如果当前是字母
if temp_s[i] not in '()':
continue
if temp_s[i]=='(' and left_p>0:
t=temp_s[:i]+temp_s[i+1:]
# queue.appendleft((t, left_p - 1, right_p))
if (t,left_p-1,right_p) not in visited: # 访问过的,有可能删除符号有相同的结果,这里相当于剪枝,删去之后相同的结果只需要判定一次
queue.appendleft((t,left_p-1,right_p))
visited.add((t,left_p-1,right_p))
if temp_s[i]==')' and right_p>0:
t=temp_s[:i]+temp_s[i+1:]
# queue.appendleft((t, left_p, right_p - 1))
if (t,left_p,right_p-1) not in visited:
queue.appendleft((t,left_p,right_p-1))
visited.add((t,left_p,right_p-1))
return list(res)
def removeInvalidParentheses3(self, s: str) -> list: # DFS
# 计算字符串最长的有效括号的长度
def longestValdParentheses(s:str):
res = 0
stack = []
for a in s:
if a == '(':
stack.append("(")
elif a == ")":
if stack:
res += 2
stack.pop()
return res
# left_p,left_r是最长的有效括号的长度的一半,还需要这么些的括号,放tmp里面
# open表示左右括号抵消多少,有一个(就要有一个)
def helper(s:str,left_p,right_p,open,tmp):
#当小于0 都不满足条件
if left_p<0 or right_p<0 or open<0:
return
# s剩余的括号不够组成的
if s.count('(')<left_p or s.count(')')<right_p:
return
if not s:
if left_p==0 and right_p==0 and open==0:
res.add(tmp)
return
if s[0]=='(':
# use "("
helper(s[1:],left_p-1,right_p,open+1,tmp+"(")
# not use"("
helper(s[1:],left_p,right_p,open,tmp)
elif s[0]==")":
# use ")"
helper(s[1:],left_p,right_p-1,open-1,tmp+')')
# not use ")"
helper(s[1:],left_p,right_p,open,tmp)
else:
helper(s[1:],left_p,right_p,open,tmp+s[0])
l=longestValdParentheses(s)
res=set()
helper(s,l//2,l//2,0,"")
return list(res)
if __name__=="__main__":
n ="(a)())()"
so=Solution()
a=so.removeInvalidParentheses3(n)
print(a) |
9f411e95cdafcb3e93eeb9a916ef07fea8883d10 | angOneServe/MyPython100days | /day07/通过日期计算是一年的第几天.py | 479 | 3.640625 | 4 |
def GetDays(year,mounth,day):
runDay=(31,29,31,30,31,30,31,31,30,31,20,31)
notrunDay=(31,28,31,30,31,30,31,31,30,31,20,31)
runNian=False
if year%4==0 and year%100!=0 or year%400==0:
runNian=True
sum=0
if runNian:
for index in range(0,mounth-1):
sum+=runDay[index]
sum+=day
else:
for index in range(0,mounth-1):
sum+=notrunDay[index]
sum+=day
return sum
print(GetDays(2019,10,28))
|
14dac6980d30a2ccedf9e6b323b29b351c8ab572 | RinkuAkash/Python-libraries-for-ML | /Numpy/05_create_2d_array.py | 496 | 3.6875 | 4 | '''
Created on 20/01/2020
@author: B Akash
'''
'''
Problem statement:
Write a Python program to create a 2d array with 1 on the border and 0 inside.
Expected Output:
Original array:
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]]
1 on the border and 0 inside in the array
[[ 1. 1. 1. 1. 1.]
[ 1. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 1.]
[ 1. 0. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]
'''
import numpy as np
array=np.ones((5,5))
array[1:4,1:4]=0
print(array)
|
84bee2416411fa3e39254d9a7b18c870651c193d | phlalx/algorithms | /leetcode/668.kth-smallest-number-in-multiplication-table.py | 2,714 | 3.640625 | 4 | #
# @lc app=leetcode id=668 lang=python3
#
# [668] Kth Smallest Number in Multiplication Table
#
# https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/description/
#
# algorithms
# Hard (45.08%)
# Likes: 490
# Dislikes: 20
# Total Accepted: 19.9K
# Total Submissions: 43.9K
# Testcase Example: '3\n3\n5'
#
#
# Nearly every one have used the Multiplication Table. But could you find out
# the k-th smallest number quickly from the multiplication table?
#
#
#
# Given the height m and the length n of a m * n Multiplication Table, and a
# positive integer k, you need to return the k-th smallest number in this
# table.
#
#
# Example 1:
#
# Input: m = 3, n = 3, k = 5
# Output:
# Explanation:
# The Multiplication Table:
# 1 2 3
# 2 4 6
# 3 6 9
#
# The 5-th smallest number is 3 (1, 2, 2, 3, 3).
#
#
#
#
# Example 2:
#
# Input: m = 2, n = 3, k = 6
# Output:
# Explanation:
# The Multiplication Table:
# 1 2 3
# 2 4 6
#
# The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).
#
#
#
#
# Note:
#
# The m and n will be in the range [1, 30000].
# The k will be in the range [1, m * n]
#
#
#
#TAGS binary search
# trick: binary search the answer
# see also 378, 719
#
# Once we get the idea, two tricky things remain (see code)
#
# @lc code=start
# returns smallest x such that p[x] is True
# else j + 1
def binary_search(i, j, pred):
while i < j:
m = (i + j) // 2
assert i <= m < m + 1 <= j
# mental model: [i,m] larger by at most one of [m+1,j]
# each part is stricly smaller than [i, j]
# no risk of infinite loop here, as long as we stop the loop
# when i == j
# - - - + + +
# - - - - + +
if pred(m):
j = m
else:
i = m + 1
return i if pred(i) else i + 1
# trick 1: took me more time than needed
def count(n, p, v):
# num of elements no larger than v
res = 0
for i in range(1, n+1):
res += min(v // i, p)
return res
# trick 2: understand how to "invert" the count fonction
#
# suppose we have this array
# [1,1,2,2,3]
#
# `__item__` is not bijective. Each rank has an element, but two identical
# elements can have different ranks. It doesn't make sense to ask
# "what is the rank of 2"?
#
# Here we have access to the function `count` that returns the number of
# elements no larger than some `v`.
#
# count:
# elt -> count
# 1 -> 1
# 2 -> 2
# 3 -> 5
#
# From there we can deduce the kth-element
#
# TODO: need to grok this better
#
class Solution:
def findKthNumber(self, m: int, n: int, k: int) -> int:
pred = lambda v: count(m, n, v) >= k
return binary_search(1, m*n, pred)
# @lc code=end
|
2119922d476fb770cbfe45c9037fe4eea6217205 | Loosper/advent_of_code_2016 | /day_01/puzzle_02.py | 675 | 3.96875 | 4 | directions = input()
directions = directions.split(', ')
distance = [0] * 2
horizontal = False
direction = True
places = set()
for step in directions:
horizontal = not horizontal
if step[0] == 'R':
if not horizontal:
direction = not direction
else:
if horizontal:
direction = not direction
sign = int(step[1:])
for point in range(sign):
if not direction:
point = -1
else:
point = 1
distance[0 if horizontal else 1] += point
if tuple(distance) in places:
print(abs(distance[0]) + abs(distance[1]), end=', ')
places.add(tuple(distance))
|
f152eddfb1fb7fe1bebe2c075b35b269395c8117 | Ganesh-sunkara-1998/Python | /Important codes/fibbonaci series.py | 402 | 4.03125 | 4 | #fibonnaci series...
nterms=int(input("enter how many integers:-"))
count=0
n1=0
n2=1
if nterms<=0:
print("invalid input please enter positive numbers")
elif nterms==1:
print("fabbonice series upto",nterms,":")
else:
print("fabbonice series upto",nterms,":")
while count<nterms:
print(n1,end=',')
nth=n1+n2
n1=n2
n2=nth
count+=1
|
d38d7b4c4caacf386ed245f8f360dddbbff5b2eb | jrantunes/URIs-Python-3 | /URIs/URI1075.py | 166 | 3.546875 | 4 | #Remaining 2
restos = []
N = int(input())
for i in range(1, 10000 + 1):
if i % N == 2:
restos.append(i)
for resto in restos:
print(resto) |
5ca786aa07411457083851ba7033b19af19d1b6b | JulianEAndrews/mountain_weather_tracker | /weather_forecast.py | 4,959 | 3.65625 | 4 | import requests
from datetime import datetime
import pandas as pd
import api
#To-do List
#In Progress, ongoing: Update user input functionality to prevent errors or crashes.
#In Progress: Build classes to house functions to call each different website. *See 'WindyLIB'
#Compare data from multiple websites and create one output file with cross-referenced data points
#Explore api response from multiple weather forecast websites for implementation
#Expand csv functionality
#Make compatible with rasppi (query at 'x' time, update frequency, etc...)
#Gather string data from esac. Possibly too complicated. Need either more html experience or a way to scrape webpage data directly.
#Completed: Update function to take in any lat-lon.
#Completed: Create function to print important data (maybe daily hi/low, wind/wind direction, clouds, etc...) to .csv or .xls
API_OWM = api.API_KEY_OWM
API_WINDY = api.API_KEY_WINDY
def city_weather():
while True:
try:
city = str(input('City Name: ')).casefold().strip()
state = str(input('State Code: ')).casefold().strip()
country = str(input('Country Code: ')).casefold().strip()
break
except KeyboardInterrupt:
break
web_url = 'http://api.openweathermap.org/data/2.5/weather?'
city_url = f'q={city}'
state_url = f',{state}'
country_url = f',{country}'
api_url = f'&appid={API_OWM}'
units_url = units()
url = web_url + city_url + state_url + country_url + units_url + api_url
print(url)
check_data(url)
main()
def lat_long_weather():
while True:
try:
lat = float(input('Enter Latitude ("xx.xx"): '))
lat = str(lat)
lon = float(input('Enter Longitude ("xxx.xx"): '))
lon = str(lon)
#lat = str(37.65)
#lon = str(-118.97)
break
except KeyboardInterrupt:
break
except:
pass
web_url = 'http://api.openweathermap.org/data/2.5/weather?'
lat_url = f'&lat={lat}'
lon_url = f'&lon={lon}'
units_url = units()
api_url = f'&appid={API_OWM}'
url = web_url + lat_url + lon_url + units_url + api_url
print(url)
check_data(url)
main()
def units():
print('Please select your preferred units. Defaults to metric:')
while True:
try:
units = str(input('Standard/kelvin (s), Metric (m), or Imperial (i): ')).casefold().strip()
if units == 's':
units = 'standard'
elif units == 'm':
units = 'metric'
elif units == 'i':
units = "imperial"
else:
units = 'metric'
units_address = f'&units={units}'
except KeyboardInterrupt:
break
return units_address
def check_data(url):
json_data: dict = requests.get(url).json()
#print keys
#print(*json_data)
utc_to_date(json_data)
for key,value in json_data.items():
print(key, value)
#Check if value is a list or dictionary
#if isinstance(item, dict):
#...
#elif isinstance(item, list):
#...
make_csv(json_data)
def make_csv(json_data):
df = pd.json_normalize(json_data)
transpose_df = df.T
transpose_df.to_csv('Weather.csv')
#The manual way. icky... Works for forecast data only. Check structure of json data.
#def call_data(url):
# print(url)
# json_data = requests.get(url).json()
# utc_to_date(json_data)
# print(json_data)
# #lat/lon data
# coord_lon = json_data['coord']['lon']
# coord_lat = json_data['coord']['lat']
# print(coord_lat)
# print(coord_lon)
#for forecast data
#temp = json_data['list'][0]['main']['temp']
#sky = json_data['list'][0]['weather'][0]['main']
#print(sky)
#print(temp)
def utc_to_date(json_data):
#timestamp = json_data['dt']
#dt_object = datetime.fromtimestamp(timestamp)
json_data['dt'] = datetime.fromtimestamp(json_data['dt'])
print(json_data['dt'])
#currently only working for forecast data, not weather data
#def utc_to_date(json_data):
# timestamp = json_data['list'][0]['dt']
# dt_object = datetime.fromtimestamp(timestamp)
# print(dt_object)
#-----------------------------------------------Program UI-----------------------------------------------#
def main():
print("---Weather Forecast---")
while True:
try:
choice = str(input("Choose forecast location. Lat/Long (LL) or City, State, Country (CSC). Press 'q' to exit: " )).casefold().strip()
if choice == 'll':
lat_long_weather()
break
elif choice == 'csc':
city_weather()
break
elif choice == 'q':
exit()
except KeyboardInterrupt:
break
if __name__ == '__main__':
main() |
19b70303d460c404488321feee31eea5b79e5f47 | mic0ud/Leetcode-py3 | /src/1338.reduce-array-size-to-the-half.py | 1,814 | 3.75 | 4 | #
# @lc app=leetcode id=1338 lang=python3
#
# [1338] Reduce Array Size to The Half
#
# https://leetcode.com/problems/reduce-array-size-to-the-half/description/
#
# algorithms
# Medium (66.14%)
# Likes: 175
# Dislikes: 19
# Total Accepted: 16.5K
# Total Submissions: 25.1K
# Testcase Example: '[3,3,3,3,5,5,5,2,2,7]'
#
# Given an array arr. You can choose a set of integers and remove all the
# occurrences of these integers in the array.
#
# Return the minimum size of the set so that at least half of the integers of
# the array are removed.
#
#
# Example 1:
#
#
# Input: arr = [3,3,3,3,5,5,5,2,2,7]
# Output: 2
# Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has
# size 5 (i.e equal to half of the size of the old array).
# Possible sets of size 2 are {3,5},{3,2},{5,2}.
# Choosing set {2,7} is not possible as it will make the new array
# [3,3,3,3,5,5,5] which has size greater than half of the size of the old
# array.
#
#
# Example 2:
#
#
# Input: arr = [7,7,7,7,7,7]
# Output: 1
# Explanation: The only possible set you can choose is {7}. This will make the
# new array empty.
#
#
# Example 3:
#
#
# Input: arr = [1,9]
# Output: 1
#
#
# Example 4:
#
#
# Input: arr = [1000,1000,3,7]
# Output: 1
#
#
# Example 5:
#
#
# Input: arr = [1,2,3,4,5,6,7,8,9,10]
# Output: 5
#
#
#
# Constraints:
#
#
# 1 <= arr.length <= 10^5
# arr.length is even.
# 1 <= arr[i] <= 10^5
#
#
# @lc code=start
from collections import Counter
class Solution:
def minSetSize(self, arr: [int]) -> int:
c, n, res = Counter(arr), len(arr), 0
k, occur = n, sorted(c.values(), reverse=True)
for i in range(len(occur)):
k -= occur[i]
res += 1
if k <= n//2:
return res
return res
# @lc code=end
|
5edf3f02473c368f80d08cb16d208018d7de0725 | mo-op/LeetCode | /easy/Power-of-Three.py | 595 | 4.375 | 4 | '''
Given an integer, write a function to determine if it is a power of three.
'''
## with loop
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
if n < 1:
return False
x = n
while(x > 3):
x /= 3
if x == 3:
return True
return False
'''
## without loop
## note: not my brainchild, this is just for my reference & yours if you've taken a detour to this file
class Solution(object):
def isPowerOfThree(self, n):
return n > 0 and 1162261467 % n == 0
'''
|
bcd98fd19315a03a97245fc124738b89effd3d79 | siskakrislim/python-projects | /problem3_7.py | 273 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 25 21:31:15 2017
@author: HP
"""
#%%
def problem3_7(csv_pricefile,flower):
import csv
f=open(csv_pricefile)
dict={flower:price for flower,price in csv.reader(f)}
print(dict[flower])
f.close() |
7011208f7379715fab63bd8bbde5c2d8acc94ce4 | dongkunchen/python | /SelfDemo.py | 956 | 4.34375 | 4 | '''
self代表類的實例,而非類
那個對象調用方法,那麼該方法中的self就代表那個對象
self__class__ 代表類名_
'''
class Person(object):
# name = ""
# age = 0
# height = 0
# weight = 0
def run(self):
print("run")
print(self.__class__)
p = self.__class__("tt", 30, 10, 30)
print(p)
def eat(self, food):
print("eat " + food)
def say(self):
print("Hello! my name if %s,I am %d years old"%(self.name, self.age))
def play(a):#雖然可以用別的替代但不建議
print("play",a.name)
def __init__(self, name, age, height, weight):
#print(name,age,height,weight)
self.name = name
self.age = age
self.height = height
self.weight = weight
per1 = Person("tom", 20, 160, 80)
per1.say()
per2 = Person("dongkun", 22, 160, 80)
per2.say()
per1.play()
per1.run() |
c6a37dca4951940d93ef69e464ed183f7767c1e9 | vpontis/euler | /12.py | 324 | 3.671875 | 4 | import math
def num_divisors(x):
num = 2
y = 2
while y <= math.sqrt(x):
if x % y == 0:
if x/y == math.sqrt(x):
num += 1
else:
num += 2
y += 1
return num
triag = 1
index = 1
while True:
if num_divisors(triag) >= 500:
break
index += 1
triag += index
print triag
|
658146db9bb08fdfac5bb71cf7528b8462b74770 | jacoloves/start_Python | /src/Sample45.py | 290 | 3.78125 | 4 | class Person:
"""docstring for Person"""
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self,value):
if not value:
value = '名無しの権兵衛'
self._name = value
person = Person('')
print(person.name)
|
a92c09561ad2372b21382519b71b6a38c6c6f23c | sinvaljang/LangStudy | /python/04_dictionary/02_StudentManager.py | 1,647 | 4.03125 | 4 | ###################################################
# subject : 学生情報管理
# date : 2017-09-21 00:40
# description : 学生の情報をdictionaryに保存し、リストに保存する
# edit : EDIT-01 次の処理を行うための、ユーザ入力のプラグ設定ミス
# Ver0.1
###################################################
#変数宣言部
endFLg = 0
name = ''
age = 0
score = 0
nFlg = 0
stu_list = list()
print('学生管理システムにようこそ。\n')
#ユーザから終了を入力されるまで
while endFLg == 0 :
#学生情報を入力する
name = input('名前を入力してください :')
age = int(input('年齢を入力してください :'))
score = int(input('成績を入力してください : \n'))
#入力した情報をdictionaryに変換
student = {'name' : name, 'age' : age, 'score' : score}
#学生リストにdictionaryを保存する
stu_list.append(student)
for st in stu_list :
print(st)
#次の処理を入力する
nFlg = 0
while nFlg == 0 :
endFLg = int(input('終了(1) 登録(0)\n'))
#ユーザ入力範囲チェック
if endFLg > 1 or endFLg < 0:
print('Wrong Input')
#--------------------------------EDIT-01--------s-----------------#
#endFLg = 0
nFlg = 0
#--------------------------------EDIT-01--------e-----------------#
#範囲以内の場合
else:
if endFLg == 1:
print('終了します')
else:
print('次の入力をします')
nFlg = 1
|
a89025a1988e69a2505fcced97ebba326f61c4cd | daniel-reich/turbo-robot | /GaXXfmpM72yCHag9T_9.py | 429 | 4.0625 | 4 | """
Create a function that takes a list of numbers and return the number that's
unique.
### Examples
unique([3, 3, 3, 7, 3, 3]) ➞ 7
unique([0, 0, 0.77, 0, 0]) ➞ 0.77
unique([0, 1, 1, 1, 1, 1, 1, 1]) ➞ 0
### Notes
Test cases will always have exactly one unique number while all others are the
same.
"""
def unique(l):
return sorted(l)[0] if sorted(l)[0] != sorted(l)[1] else sorted(l)[-1]
|
9788779531932d60ff9acb038d5e2f00b8ba41a8 | Taku-orand/practice_alg | /aoj/ITP1/ex4/B.py | 109 | 3.90625 | 4 | PI = 3.141592653589
r = float(input())
area = PI * r**2
length = 2 * PI * r
print(f"{area:.6f} {length:.6f}") |
f4087157c0e1b96f3770ffc6c0dec2da07ecc064 | sarahmid/programming-bootcamp | /lab7/lab7_answers.py | 7,864 | 3.8125 | 4 | #===========================================================
# Programming Bootcamp 2015
# Lab 7 answers
#
# Last updated 7/1/15
#===========================================================
### 1a
import sys
import os
# read in command line args
if len(sys.argv) == 3:
inputFile = sys.argv[1]
outputFolder = sys.argv[2]
else:
print ">>Error: Incorrect args. Please provide an input file name and an output folder. Exiting."
sys.exit()
# check if input file / output directory exist
if not os.path.exists(inputFile):
print ">>Error: input file (%s) does not exist. Exiting." % inputFile
sys.exit()
if not os.path.exists(outputFolder):
print "Creating output folder (%s)" % outputFolder
os.mkdir(outputFolder)
### 1b
import sys
import os
import my_utils
# read in command line args
if len(sys.argv) == 3:
inputFile = sys.argv[1]
outputFolder = sys.argv[2]
else:
print ">>Error: Incorrect args. Please provide an input file name and an output folder. Exiting."
sys.exit()
# check if input file / output directory exist
if not os.path.exists(inputFile):
print ">>Error: input file (%s) does not exist. Exiting." % inputFile
sys.exit()
if not os.path.exists(outputFolder):
print "Creating output folder (%s)" % outputFolder
os.mkdir(outputFolder)
# read in sequences from fasta file & print to separate output files
# you'll get an error for one of them because there's a ">" in the sequence id,
# which is not allowed in a file name. you can handle this howevere you want.
# here I used a try-except statement and just skipped the problematic file (with a warning message)
seqs = my_utils.read_fasta(inputFile)
for seqID in seqs:
outFile = "%s/%s.fasta" % (outputFolder, seqID)
outStr = ">%s\n%s\n" % (seqID, seqs[seqID])
try:
outs = open(outFile, 'w')
outs.write(outStr)
outs.close()
except IOError:
print ">>Warning: Could not print (%s) file. Skipping." % outFile
### 1c
import sys
import glob
import os
# read in command line args
if len(sys.argv) == 2:
folderName = sys.argv[1]
else:
print ">>Error: Incorrect args. Please provide an folder name. Exiting."
sys.exit()
fastaList = glob.glob(folderName + "/*.fasta")
for filePath in fastaList:
print os.path.basename(filePath)
### 2
import optparse
import random
import my_utils
msg = "Usage: %prog OUTFILE [options]"
parser = optparse.OptionParser(usage=msg)
parser.add_option("--num", action="store", type='int', default=1, dest="NUM_SEQS", help="Number of sequences to create. Default is %default.")
parser.add_option("--len-min", action="store", type='int', default=100, dest="MIN_LEN", help="Minimum sequence length")
parser.add_option("--len-max", action="store", type='int', default=100, dest="MAX_LEN", help="Maximum sequence length")
parser.add_option("--rna", action="store_true", default=False, dest="RNA", help="Replace T's with U's?")
parser.add_option("--prefix", action="store", dest="ID_PREFIX", default="seq", help="Prefix to be added to the beginning of each sequence ID. Default is %default")
# parse args
(opts, args) = parser.parse_args()
outFile = args[0]
# generate and print sequences
outs = open(outFile, 'w')
for i in range(opts.NUM_SEQS):
if opts.RNA:
newSeq = my_utils.rand_seq(random.randint(opts.MIN_LEN, opts.MAX_LEN), rna=True)
else:
newSeq = my_utils.rand_seq(random.randint(opts.MIN_LEN, opts.MAX_LEN), rna=False)
newID = opts.ID_PREFIX + str(i)
outputStr = ">%s\n%s\n" % (newID, newSeq)
outs.write(outputStr)
outs.close()
### 3a
import time
import my_utils
seqs = my_utils.read_fasta("fake.fasta")
# test manual replacement
startManual = time.time()
for seq in seqs.values():
newSeq = ""
for nt in seq:
if nt == "T":
newSeq += "U"
else:
newSeq += nt
print "Manual replacement:", time.time() - startManual
# test built-in replacement
startBuiltIn = time.time()
for seq in seqs.values():
newSeq = seq.replace("T", "U")
print "Built-in replacement:", time.time() - startBuiltIn
# Answer: The built-in method should be much faster! Most built in functions are pretty well optimized, so they will often (but not always) be faster.
### 3b
import time
import my_utils
seqs = my_utils.read_fasta("fake.fasta")
# test manual replacement
startManual = time.time()
count = 0
for seq in seqs.values():
for nt in seq:
if nt == "A":
count += 1
print "Manual replacement:", time.time() - startManual
# test built-in replacement
startBuiltIn = time.time()
count = 0
for seq in seqs.values():
count += seq.count("A")
print "Built-in replacement:", time.time() - startBuiltIn
# Answer: Again, the built in function should be quite a bit faster.
### 3c
import time
import my_utils
seqs = my_utils.read_fasta("fake.fasta")
# test list as lookup table
startList = time.time()
seenIdList = []
for seqID in seqs:
if seqID not in seenIdList:
seenIdList.append(seqID)
print "List:", time.time() - startList
# test built-in replacement
startDict = time.time()
seenIdDict = {}
for seqID in seqs:
if seqID not in seenIdDict:
seenIdDict[seqID] = 0
print "Dictionary:", time.time() - startDict
# Answer: Dictionary should be faster. When you use a dictionary, Python jumps directly to where the requested key *should* be, if it were in the dictionary. This is very fast (it's an O(1) operation, for those who are familiar with the terminology). With lists, on the other hand, Python will scan through the whole list until it finds the requested element (or until it reaches the end). This gets slower and slower on average as you add more elements (it's an O(n) operation). Just something to keep in mind if you start working with very large datasets!
### 4a
# command-running function
# if verbose=True, prints output of the command to the screen
def run_command(command, verbose=False):
import subprocess
error = False
if verbose == True:
print command
print ""
job = subprocess.Popen(command, bufsize=0, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
jobOutput = []
if verbose == True:
for line in job.stdout:
print " ", line,
jobOutput.append(line)
else:
jobOutput = job.stdout.readlines()
result = job.wait()
if result != 0:
error = True
return (jobOutput, result, error)
# run the command
command = "ls -l"
(output, result, error) = run_command(command, verbose=True)
if error:
print ">>Error running command:\n %s\n" % command
# 4b
import sys
# command-running function
# if verbose=True, prints output of the command to the screen
def run_command(command, verbose=False):
import subprocess
error = False
if verbose == True:
print command
print ""
job = subprocess.Popen(command, bufsize=0, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
jobOutput = []
if verbose == True:
for line in job.stdout:
print " ", line,
jobOutput.append(line)
else:
jobOutput = job.stdout.readlines()
result = job.wait()
if result != 0:
error = True
return (jobOutput, result, error)
# file names
seqOutFile = "new_fake.fasta"
seqInfoFile = "new_fake.seq_info.txt"
# generate random sequence file
command = "python lab7_sequence_generator.py %s --num=10000 --len-min=500 --len-max=5000" % seqOutFile
(output, result, error) = run_command(command, verbose=True)
if error:
print ">>Error running command:\n%s\nExiting." % command
sys.exit()
# get stats about sequences
command = "python lab6_get_seq_info.py %s %s" % (seqOutFile, seqInfoFile)
(output, result, error) = run_command(command, verbose=True)
if error:
print ">>Error running command:\n%s\nExiting." % command
sys.exit()
# graph statistics (prints to a pdf)
command = "Rscript graph_gc.r %s" % seqInfoFile
(output, result, error) = run_command(command, verbose=True)
if error:
print ">>Error running command:\n%s\nExiting." % command
sys.exit()
|
479344bb363d08b42efa6ba8692521e5164d1c47 | gabriellaec/desoft-analise-exercicios | /backup/user_031/ch27_2019_08_22_00_42_08_826831.py | 134 | 3.859375 | 4 | d= int(input("quantos cigarros voce fuma por dia?"))
a= int(input("há quantos anos voce fuma?"))
s= (d*a*365*10)/(60*24)
print(s) |
0edb78b14397ef195349fa7e86468dfb872e0ee5 | aditjain588/Leet-Code-problems | /sortColor.py | 841 | 3.59375 | 4 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#pointer i traversing the list, pointer start holding the next position for 0, pointer end holding the next position for 2
# if 0 encountered put it in starting of list, if 2 encountered put it in ending of list, value 1 will automatically will be in the middle
start=0
end=len(nums)-1
i=0
while(i<=end):
if(nums[i]==0):
nums[i],nums[start] = nums[start],nums[i]
start+=1
i+=1
elif(nums[i]==2):
nums[i],nums[end] = nums[end],nums[i]
end-=1
else:
i+=1
print(i)
|
3308fdee37bf3312d80fa0f20fb8f6d0a41c9000 | mohitvenx/python-programs | /one_to_ten_numbers.py | 108 | 3.8125 | 4 | #printing first 10 numbers
n = 1
print('First ten numbers are \n')
while n<= 10:
print(n)
n = n+1
|
1c2b462f10c36da2faabd6084c4a877bfd34d24a | SurojitD/Dynamic-Programming | /grid_memoization.py | 530 | 4.125 | 4 | # Implementation of gridTraveler using memoization
rows = int(input("Enter the number of rows"))
columns = int(input("Enter the number of columns"))
memo = {}
def gridTraveler(m,n):
if (m,n) in memo:
return memo[(m,n)]
if m == 0 or n == 0:
return 0
elif m == 1 and n == 1:
return 1
else:
memo[(m,n)] = gridTraveler(m-1, n) + gridTraveler(m, n-1)
return memo[(m,n)]
print("The number of ways the traveler can travel through the grid is: ", gridTraveler(rows, columns))
|
737582c0fcc6b1bd92fe72e45e70b58a0bddbf6d | chubakur/probabilistic-python | /burnin-img.py | 667 | 3.609375 | 4 | from matplotlib import pyplot
from numpy.random import normal
import numpy
# def step(x):
# return 0.98 * x + normal(0, 0.1)
#
# SIZE = 1000
#
# def generate_points(x):
# result = []
# for i in range(0, SIZE):
# x = step(x)
# result.append(x)
# return result
#
# pyplot.figure(0)
# pyplot.plot(range(0, SIZE), generate_points(10), 'k.', label='x=10')
# pyplot.figure(1)
# pyplot.plot(range(0, SIZE), generate_points(0), 'k.', label='x=0')
# pyplot.show()
y = []
x = 2
for i in range(0, 1000):
x = 0.96 * x + normal(1, 0.1)
y.append(x)
yd = numpy.array(y)
print yd.mean()
pyplot.plot(range(0, len(y)), y, 'k.')
pyplot.show()
|
09523603401b1dcd3854244d5d0cc77bad4a65e6 | Shaunwei/Leetcode-python-1 | /LinkedList/ReverseNodesInKGroup/reverseKGroup2.py | 2,015 | 3.96875 | 4 | #!/usr/bin/python
"""
Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
"""
from sys import path as path1; from os import path as path2
path1.append(path2.dirname(path2.dirname(path2.abspath(__file__))))
import LListUtil
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @param k, an integer
# @return a ListNode
def reverseKGroup(self, head, k):
if not head: return None
dumhead = ListNode(0)
dumhead.next = head
curr, listLen = head, 0
while curr: curr, listLen = curr.next, listLen+1
curr, prev, index = head, dumhead, 1
prehead, preheadnext = dumhead, head
while curr:
if listLen-index < listLen%k: break
nextN = curr.next
curr.next = prev
if index%k == 0:
prehead.next = curr
preheadnext.next = nextN
prehead = preheadnext
prev = prehead
preheadnext = nextN
else:
prev = curr
curr, index = nextN, index+1
return dumhead.next
if __name__=="__main__":
arr = range(1,10)
head = LListUtil.buildList(arr)
LListUtil.printList(head)
LListUtil.printList(Solution().reverseKGroup(head,4))
"""
Simliar as problem 'Swap Nodes in Pairs'.
when index meet times of K (index%K==0), then reverse the list segement.
Notice, for the last few nodes (list_Length-index < list_Length%k) do nothing.
""" |
817a8dd9a885e81d089e1c674c13a986d1439c13 | StefanDjokovic/30-Day-LeetCoding-Challenge | /Day20_Construct_Binary_Search_Tree_From_Preorder_Traversal/construct_binary_search_tree_from_preorder_traversal.py | 836 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# a non-optimized version (doesn't use the "preorder" information, but just put everything in the tree iteratively)
def insertion(root, x):
if root.val > x:
if root.left == None:
root.left = TreeNode(x)
else:
insertion(root.left, x)
else:
if root.right == None:
root.right = TreeNode(x)
else:
insertion(root.right, x)
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
root = TreeNode(preorder[0])
del preorder[0]
while len(preorder) > 0:
insertion(root, preorder[0])
del preorder[0]
return root
|
f428b216eb22260883d0b5baad6e7256c5b96547 | cocoon333/lintcode | /151_solution.py | 1,888 | 3.828125 | 4 | """
151. Best Time to Buy and Sell Stock III
中文
English
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Example
Example 1
Input : [4,4,6,1,1,4,2,5]
Output : 6
Notice
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
"""
class Solution:
"""
@param: nums: A list of integers
@return: An integer denotes the sum of max two non-overlapping subarrays
"""
def maxProfit(self, nums):
for i in range(len(nums)-1):
nums[i] = nums[i+1] - nums[i]
nums = nums[:-1]
max_sum, start, end = self.max_subarray(nums)
max_gain = 0
temp = 0
for i in range(start+1, end):
if temp > 0:
temp -= nums[i]
else:
temp = -nums[i]
if temp > max_gain:
max_gain = temp
second_max = self.max_subarray(nums[:start] + nums[end+1:])[0]
return max_sum + max(second_max, max_gain)
def max_subarray(self, nums):
start = 0
max_start = 0
end = 0
max_sum = 0
temp = 0
for i in range(len(nums)):
if temp < 0:
start = i
temp = nums[i]
else:
temp += nums[i]
if temp > max_sum:
max_sum = temp
end = i
max_start = start
if temp > max_sum:
max_sum = temp
end = len(nums)-1
max_start = start
return (max_sum, max_start, end)
if __name__ == "__main__":
s = Solution()
assert(s.maxProfit([2, 1]) == 0)
assert(s.maxProfit([3, 2, 6, 5, 0, 3]) == 7)
assert(s.maxProfit([4, 4, 6, 1, 1, 4, 2, 5]) == 6)
|
9c38667e8dddc8bb4072b458f64d6719fb98ae6f | ljia2/leetcode.py | /solutions/binary.search/878.Nth.Magical.Number.py | 1,998 | 3.65625 | 4 | class Solution:
def nthMagicalNumber(self, N, A, B):
"""
A positive integer is magical if it is divisible by either A or B.
Return the N-th magical number. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: N = 1, A = 2, B = 3
Output: 2
Example 2:
Input: N = 4, A = 2, B = 3
Output: 6
Example 3:
Input: N = 5, A = 2, B = 4
Output: 10
Example 4:
Input: N = 3, A = 6, B = 4
Output: 8
:type N: int
:type A: int
:type B: int
:rtype: int
4 points to figure out:
1. Get gcd (greatest common divisor) and lcm (least common multiple) of (A, B).
(a, b) = (A, B) while b > 0: (a, b) = (b, a % b)
then, gcd = a and lcm = A * B / a
2. How many magic numbers <= x ?
By inclusion exclusion principle, we have: x / A + x / B - x / lcm
3. Set our binary search range
Lower bound is min(A, B), I just set left = 2.
Upper bound is N * min(A, B), I just set right = 10 ^ 14.
4. binary search, find the smallest x that x / A + x / B - x / lcm = N
"""
l = 2
r = 10 ** 14
mod = 10 ** 9 + 7
lcm = A * B // self.gcd(A, B)
# l and r are searching integer space
# find the smallest number (lower bound) where mid // A + mid // B - mid // lcm = N, similar to bisect_left
while l < r:
mid = (l + r) // 2
tmp = mid // A + mid // B - mid // lcm
if tmp >= N:
r = mid
else:
l = mid + 1
return l % mod
def gcd(self, A, B):
if B == 0:
return A
if A < B:
return self.gcd(B, A)
return self.gcd(B, A % B)
s = Solution()
print(s.nthMagicalNumber(10, 6, 4))
print(s.nthMagicalNumber(1, 2, 3))
print(s.nthMagicalNumber(5, 2, 4)) |
8adc7b1724c90fd14087f1aeeefb35104596ca76 | matthijskrul/PythonExercism | /Solutions/isogram.py | 265 | 3.921875 | 4 | import re
def is_isogram(string):
lowerstring = string.lower()
alphabet = re.compile("[a-z]")
for char in lowerstring:
if alphabet.search(char) and len(re.findall(char, lowerstring)) > 1:
return False
else:
return True
|
83bdcbe964ab9214567e773cdf43f9834531643a | NikiKim/1homework | /task1.py | 143 | 3.578125 | 4 | a = int(input("Введите длину:"))
b = int(input("Введите ширину:"))
s = a * b
print ("Площадь: " + str(s)) |
6e92ef095a2243c6c0589b2a3855da3628714501 | kmushegi/nic | /p5/src/data_loader.py | 7,545 | 3.546875 | 4 | """
Neural Networks for Digit Recognition - Project 4
Nature Inspired Computation
Spring 2017
Stephen Majercik
Ernesto Garcia, Marcus Christiansen, Konstantine Mushegian
This file is part of Project 5. This file
contains the implementation of data loading routine used to read the training and
testing data on the cifar10 dataset.
*_data is a tuple. First element is array of arrays of size 1024 containing
the binary image; the second element is the array of arrays containing the
information about the "desired" output formatted in a 10 output neuron way.
[1,0,0,0,0,0,0,0,0,0] ==> 0
[0,0,1,0,0,0,0,0,0,0] ==> 2
[0,0,0,0,0,0,0,0,0,1] ==> 9 and etc.
"""
from __future__ import absolute_import
import cPickle
import keras
from keras.datasets import cifar10
import numpy as np
import sys
np.set_printoptions(threshold=np.nan)
bitmap_training_data_file = "../data/bitmaps/optdigits-32x32.tra"
bitmap_testing_data_file = "../data/bitmaps/optdigits-32x32.tes"
downsampled_training_data_file = "../data/downsampled/optdigits-8x8-int.tra"
downsampled_testing_data_file = "../data/downsampled/optdigits-8x8-int.tes"
cifar_dir = "../data/cifar-10-batches-py/"
NUM_TRAINING_IMAGES = 3823
def read_data_down_sampled(data_file):
f = open(data_file)
#Containers for data and actual numbers
inputs = []
desired_outputs = []
for line in f:
tokens = line.split(',')
#Each line in data file is an element
inputs.append(" ".join(tokens[:-1]))
#Actual number for corresponding data elements
desired_outputs.append(int(tokens[-1]))
return (inputs, desired_outputs)
def read_data_bit_map(data_file):
f = open(data_file)
for i in xrange(3): #skip first 3 lines
next(f)
#Containers bits and values
inputs = []
desired_outputs = []
#Tracks each bitmap for values
counter = 0
current_input = ""
for line in f:
#While haven't reached end of bitmap
if(counter < 32):
current_input += line.strip()
counter += 1
#Insert this bitmap into input data
else:
inputs.append(current_input)
desired_outputs.append(int(line))
current_input = ""
counter = 0
return (inputs, desired_outputs)
def load_majercik_data(bit_map, num_output_neurons):
if bit_map:
#(inputs , desired_outputs) for training and testing data
(tr_i, tr_o) = read_data_bit_map(bitmap_training_data_file)
(te_i,te_o) = read_data_bit_map(bitmap_testing_data_file)
#Change each 32x32 bitmap to a list of 1024 elements
training_inputs = [np.reshape(list(x), (1024, 1)) for x in tr_i]
testing_inputs = [np.reshape(list(x), (1024, 1)) for x in te_i]
#Makes list of 10 elements with 1.0 at index = desired_output
if num_output_neurons == 10:
training_outputs = [digit_to_vector_representation(x) for x in tr_o]
testing_outputs = [digit_to_vector_representation(x) for x in te_o]
else:#Only 1 output node
training_outputs = [int(x) for x in tr_o]
testing_outputs = [int(x) for x in te_o]
#Creates a list where each element is the 1024-list paired with corr. desired output
training_data = zip(training_inputs,training_outputs)
testing_data = zip(testing_inputs,testing_outputs)
return (training_data, testing_data)
else: #down-sampled
#(inputs , desired_outputs) for training and testing data
(tr_i, tr_o) = read_data_down_sampled(downsampled_training_data_file)
(te_i, te_o) = read_data_down_sampled(downsampled_testing_data_file)
#Change list of bits and spaces to a list of 64 bits
training_inputs = [np.reshape(x.split(' '), (64, 1)) for x in tr_i]
testing_inputs = [np.reshape(x.split(' '), (64, 1)) for x in te_i]
#Makes list of 10 elements with 1.0 at index = desired_output
if num_output_neurons == 10:
training_outputs = [digit_to_vector_representation(x) for x in tr_o]
testing_outputs = [digit_to_vector_representation(x) for x in te_o]
else:#Only 1 output node
training_outputs = [int(x) for x in tr_o]
testing_outputs = [int(x) for x in te_o]
#Creates a list where each element is the 64-bit list paired with corr. desired output
training_data = zip(training_inputs, training_outputs)
testing_data = zip(testing_inputs, testing_outputs)
return (training_data, testing_data)
#load an individual dataset and format it into the NumPy array
def load_data_batch(fp):
#open and load the file
f = open(fp,'rb')
data_batch = cPickle.load(f)
data_batch_dec = {}
#decode (deserialize) cPickle data into unicode form
for key, value in data_batch.items():
data_batch_dec[key.decode('utf8')] = value
data_batch = data_batch_dec
f.close() #close the file
data = data_batch['data']
labels = np.array(data_batch['labels'])
return data,labels
#load the cifar-10 dataset into memory for use by our Multi-layer Perceptron
def load_cifar_data_nn(n_batches):
N_TRAINING_DATA = 50000
#load n_batches of cifar-10 data
for b in xrange(1,n_batches):
batch_path = cifar_dir + "data_batch_" + str(b)
print batch_path
data, labels = load_data_batch(batch_path)
#build up the entire dataset
if b == 1:
training_inputs = data
training_outputs = labels
else: #after first batch, batches get appended to the containers
training_inputs = np.append(training_inputs,data,axis=0)
training_outputs = np.append(training_outputs,labels,axis=0)
training_inputs = normalize(training_inputs)
#reshape the multi-dimensional image data into a single 3072 array
training_inputs = training_inputs.reshape(-1,3072,1)
#Makes list of 10 elements with 1.0 at index = desired_output
training_outputs = [digit_to_vector_representation(y) for y in training_outputs]
#load the test batch
batch_path = cifar_dir + "test_batch"
testing_inputs, testing_outputs = load_data_batch(batch_path)
testing_inputs = normalize(testing_inputs)
#reshape the multi-dimensional image data into a single 3072 array
testing_inputs = testing_inputs.reshape(-1,3072,1)
#Makes list of 10 elements with 1.0 at index = desired_output
testing_outputs = [digit_to_vector_representation(y) for y in testing_outputs]
#zip together the inputs and outputs
training_data = zip(training_inputs, training_outputs)
testing_data = zip(testing_inputs, testing_outputs)
return (training_data, testing_data)
#load the cifar-10 dataset into memory for use by the Keras-based CNN by using the Keras data loader
def load_cifar_data_cnn():
(x_train,y_train),(x_test,y_test) = cifar10.load_data()
#convert a class vector to binary class matrix, similar to vectorizing
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
#convert type of data from integers to floats
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train = normalize(x_train)
x_test = normalize(x_test)
return (x_train,y_train),(x_test,y_test)
#obtain data given which network and which dataset is requested. dataset defaults to bitmap, number
#of output neurons defaults to 10
def get_data(which_network,dataset='bitmap', num_output_neurons=10):
if(dataset == "bitmap"):
return load_majercik_data(bit_map=1,num_output_neurons=num_output_neurons)
elif(dataset == "downsampled"):
return load_majercik_data(bit_map=0,num_output_neurons=num_output_neurons)
elif(dataset == "cifar10"):
if(which_network == 'nn'):
return load_cifar_data_nn(n_batches=3)
elif(which_network == 'cnn'):
return load_cifar_data_cnn()
#Creates 10 element list of 0.0's except with 1.0 at jth index
def digit_to_vector_representation(j):
e = np.zeros((10,1))
e[j] = 1.0
return e
#normalize image data from 0-255 to 0-1 range
def normalize(data):
return data/255.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.