blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
69bf85d0d2f29fdcee99c20093a66ade204792a1 | alexgarces98/Pythonprogramas | /EXTRA 4.py | 849 | 3.875 | 4 | def sumar(n1, n2, n3):
'''int,int,int --> int
OBJ: Suma 3 numeros y si 2 de ellos o mas son iguales devuelve 0
PRE: si n1==n2 or n1 == n3 or n2 == n3 return 0'''
if (n1 != n2) and (n1 != n3) and (n2 != n3):
suma = n1 + n2 + n3
else:
suma = 0
return suma
##PRUEBA:
pri... |
f67a4321751080a428dfc5df1647a3e82601ca8c | alexgarces98/Pythonprogramas | /comerciales.py | 2,374 | 4.0625 | 4 | '''Una empresa almacena los datos de sus comerciales en una estructura de datos que contiene los siguientes campos:
nombre, apellidos, provincia que tiene asignada y ventas realizadas para el mes. Las ventas del mes es un array para
cada comercial, donde se almacenan día por día las ventas de esa persona. Com... |
2a40c11b484c0974d8c9825c6a854bca4d851115 | alexgarces98/Pythonprogramas | /mcd3numeros.py | 378 | 3.6875 | 4 | def maximo_comun_divisor(x, y, z):
"""int, int, int -> int
OBJ: maximo común divisor de x, y, z
"""
div = 0
top = min(abs(x), abs(y), abs(z))
for i in range(1, top + 1):
if x % i == 0 and y % i == 0 and z % i == 0:
div = i
return div
print(maximo_comun_divisor(25, -25, 2... |
21836d10efaea0d13e567b72f34dece6f08ec3ff | alexgarces98/Pythonprogramas | /acertarNumero.py | 451 | 3.953125 | 4 | n = int(input("Introduce el número adivinar: "))
num = int(input("Pide a alguien que trate de adivinarlo. Apuesta: "))
a= 0
while(num!=n):
a += 1
if(num<n):
print("Casi! El que me has dado es más pequeño que el que buscas")
else:
print("Casi! El que me has dado es más grande que el que buscas")... |
fd1cb37fe41b24e85d3d98c442fc53fee16cfe6a | alexgarces98/Pythonprogramas | /EXTRA 2.py | 1,090 | 3.859375 | 4 | def obtenerPrecio(tipo,peso):
'''string, float --> float
OBJ: Da precios, introduciendo su precio y nombre
PRE: tipo: platanos,peras,mandarinas o caquis'''
if (tipo == 'Pera'):
precio = 1.5
resultado = precio * peso
elif (tipo == 'Mandarina'):
precio = 2.99
resu... |
d6b5e95ecafd350186884baeb95f1590cea73bf1 | theozornelas/AI-Projects | /8 Puzzle/cs170_ec.py | 3,834 | 3.671875 | 4 | from Graph import puzzle
from Graph import boardNode
from Graph import queueSize
trivial = [[1, 2, 3],
[4, 5, 6],
[7, 8, 0]]
beginner = [[1, 2, 3],
[4, 5, 6],
[7, 0, 8]]
easy = [[1, 2, 0],
[4, 5, 3],
[7, 8, 6]]
medium = [[0, 1, 2],
[4, 5, 3],
[7, 8, 6]]
hard = [[8, 7, 1],
[6, 0, 2],
[5, 4, 3]]
veteran = [[1,... |
cb6fd0437c7d3e7ab3297e9395c16adf914b9363 | jeeHwon/pyPJ | /pj2_conda/pandas18.py | 1,115 | 3.5625 | 4 | import pandas as pd
data = pd.read_csv('data/mov2.csv')
# print(data.head())
# data.info()
# ==과제
# 1) data 데이터프레임의 'Age'열을 활용하여 data['Newage'] 열을 생성
def getAge(x):
if x ==1:
return "Under 18"
elif x ==18:
return "18-24"
elif x ==25:
return "25-34"
elif x ==35:
return ... |
5c7644f62e28c10db72661082cfe2f027a0a1a5e | jeeHwon/pyPJ | /LinearAlgebra/1_basics.py | 1,193 | 3.75 | 4 | import numpy as np
# column vector
c = np.array([1,2,3])
print(c.shape)
# obataining a particular entry
print(c[0])
# row vector
r = np.array([ [1,2,3] ])
print(r.shape)
#obtaining a particular entry
print(r[0,1])
# creating a matrix with all zeros
a = np.zeros((2,2))
print(a)
# creating a matrix with all ones
b ... |
fa1220e339736d77326c0fbe8a3cea104b6238a1 | Paradise98/python | /lintcode/string permutation.py | 148 | 3.78125 | 4 | #-*-coding:utf-8-*-
def Permutation(self,a,b):
m=list(a)
n=list(b)
m.sort()
n.sort()
if m==n:
return True
else:
return False
|
3b3eea599b7c6fc9e3cd9de39026abf61ece8aff | max-s-ua/python-course | /hw1/task2.py | 516 | 3.875 | 4 | # task 2
def main():
print('Hi. Lets calcutale price of cheese...')
try:
price = float(input('price of 1 kg: '))
if price < 0:
raise ValueError('\'value\' must be positive')
print('weight(g)\tPrice(usd)')
for weight in range(50, 1050, 50):
print('{:5... |
2b232ae3fbe5ce275e5e0498b0ef44e5fcb13b98 | alirezakfz/DataSciennce-NanoDegree | /Project 02 (Disaster Response Pipeline)/SubmissionFiles/data/process_data.py | 3,827 | 3.546875 | 4 | import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
"""
Loads data from messages and categories datasets, returns merged dataframe
input:
File path for CSV files.
output:
Merged dataframe
""... |
61ceeba6658d2209a73776ab5dd57a54de3b7e3a | momentum-morehouse/palindrome-PSX4414 | /main.py | 152 | 4.0625 | 4 | name = input('Please enter your name ')
print(name)
if name == name[::-1]:
print(name, 'is a palindrome.')
else:
print(name,'is not a palindrome.') |
ab60bc9ed323d133556fc8da2483e184faae8bcd | gonzaruiz/Assignment_2.1 | /Assigment_2.1.py | 171 | 3.9375 | 4 |
# coding: utf-8
# In[3]:
number = input("enter comma separated numbers: ")
list = str(number).split(",")
tuple = (list)
print('List: ', list)
print('Tuple: ', tuple)
|
9a711a64a492b8ad3c9d56641f099c3a012c838d | Venuram/Udacity-coursework | /Recommendation with IBM/Recommendations_with_IBM.py | 36,327 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Recommendations with IBM
#
# In this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform.
#
#
# You may either submit your notebook through the workspace here, or you may work from your local machine and submit t... |
6c420d89a32b1c0b9ec9cd59353e45909111d2a0 | shunak/python-sandobox | /variance_std.py | 890 | 3.640625 | 4 | import numpy as np
# func for mean
def find_mean(data):
s = sum(data)
N = len(data)
mean = s / N
return mean
a = [1,2,2,5,6]
# print(find_mean(a))
# func for data - mean
def find_diff(data):
mean = find_mean(data)
diff = []
for num in data:
diff.append(num-me... |
cd216317f1f2a1eb116b747abc7b3ef78ae94344 | py1-10-2017/garreth-python1-10-2017 | /lists_to_dict.py | 309 | 3.75 | 4 | name = ["Garreth", "Dax", "Gray", "Brian", "Lauren"]
favorite_animal = ["horse", "cat", "fox", "rhino", "dog"]
def create_dict(arr1, arr2):
new_dict = {}
zipped = zip(arr1, arr2)
new_dict = dict(zipped)
return new_dict
new_dict2 = create_dict(name, favorite_animal)
for x in name:
print new_dict2[x]
|
ee5724c32427607322d5910f713816c1cb160fe1 | 4d4nsoni4/PyLadies_DP | /08/8_3.py | 347 | 3.71875 | 4 | domaci_zvirata = ["pes", "kočka", "králík", "had"]
def je_zvire_v_seznamu(seznam):
""" Zjistí, jestli se dané zvíře nachází v seznamu """
nove_zvire = input("Jaké zvíře se nachází u tebe doma? ")
for zvire in domaci_zvirata:
if nove_zvire == zvire:
return True
else:
... |
0e5c6d966e773b02b6550b654c5a0c734f943dc4 | izumism/algorithms | /strings/coursera/suffix_array.py | 2,980 | 3.734375 | 4 | def suffixes_lexicographic_order(string):
suffixes = []
for i in range(len(string)):
suffixes.append(string[i:])
return sorted(suffixes)
DOLLAR = '$'
def suffix_array(string) -> [int]:
if string[-1] != DOLLAR:
raise RuntimeError(
f"input must ends with '$' character, give... |
45e52f554eee3a9c1153ab1fe29bedac254891a3 | sitati-elsis/teaching-python-demo | /inheritance.py | 760 | 4.1875 | 4 | class Parent():
def __init__(self,last_name,eye_color):
print ("Parent constructor called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print "%s %s" %(self.last_name,self.eye_color)
billy_cyrus = Parent("Cyrus","blue")
billy_cyrus.show_info()
class Child(Parent):
def __ini... |
77ae0f97ced719947b86ae4e39b19f692997cd07 | pavithranainar/python-programming | /sum of natural numbers upto n.py | 120 | 4.09375 | 4 | n=int(input('enter a number:"))
sum1=0
while(n>0):
sum1=sum1+n
n=n-1
print("the sum of first n natural number is",sum1)
|
3195a8daed4e33ec1b06d5bd705b00f3b023fef5 | pavithranainar/python-programming | /powe of number 2.py | 143 | 4.0625 | 4 | print("calculate the power of numbers")
a=int (input("enter the numbers"))
b=int(input("enter the numbers"))
print(a)
print(b)
c=a**b
print(c)
|
e166976253dd21272cb1966afdc2eb61d675b137 | pavithranainar/python-programming | /number is pallindrome.py | 185 | 3.921875 | 4 | print("chek whether a number is pallidrome or not")
n=int(input("n=1"))
if(n<=1000):
x=n
rev=0
while n>0:
re=n%10
rev=rev*10+re
n=n//10
if(x==rev);
print("yes")
else:
print("not")
|
09b3b41b385e1c03e16538dc6bffb644c92ee629 | pavithranainar/python-programming | /armstrong.py | 196 | 4.0625 | 4 | print("TO CHECK WHETHER A NUMBER IS ARMSTRONG")
n=int(input("enter the number"))
t=n
s=0
a=0
while n>0:
re=n%10
a=re**3
s=s+a
n=n//0
if(t==s)
print("armstrong"
else:
print("not armstrong")
|
f0b65003ca37c7a4696fae6b810ace5f585bd705 | LogicJake/code-for-interview | /leetcode-cn/Python/896.单调数列.py | 417 | 3.5 | 4 | #
# @lc app=leetcode.cn id=896 lang=python3
#
# [896] 单调数列
#
# @lc code=start
from typing import List
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
inc = True
des = True
for i in range(1, len(A)):
if A[i] > A[i - 1]:
des = False
if ... |
378349f5f9f3bea75c4d2a8e05b81b5b08ecf4e6 | LogicJake/code-for-interview | /leetcode-cn/Python/218.天际线问题.py | 1,011 | 3.5 | 4 | #
# @lc app=leetcode.cn id=218 lang=python3
#
# [218] 天际线问题
#
# @lc code=start
from typing import List
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
all_points = []
for building in buildings:
all_points.append((building[0], -building[2]))
... |
6e9f72764cbbeacfff5d3846859bf455b9436a9f | LogicJake/code-for-interview | /leetcode-cn/Python/1203.项目管理.py | 2,627 | 3.5625 | 4 | #
# @lc app=leetcode.cn id=1203 lang=python3
#
# [1203] 项目管理
#
# @lc code=start
from typing import List
import collections
class Solution:
def topological_sort(self, items, indegree, neighbors):
# 建立队列和访问顺序
queue = collections.deque()
res = []
# 初始化队列
for item in items:
... |
49e7293565af5a17613df123c68858a204ac2d0c | LogicJake/code-for-interview | /剑指offer/59.2.队列的最大值.py | 607 | 3.765625 | 4 | class MaxQueue:
def __init__(self):
self.que = []
self.maxque = []
def max_value(self) -> int:
if self.maxque:
return self.maxque[0]
else:
return -1
def push_back(self, value: int) -> None:
while self.maxque and self.maxque[-1] < value:
... |
7018a0d493e296146624153d4f6418a6fbac1c39 | LogicJake/code-for-interview | /剑指offer/56.1.数组中数字出现的次数.py | 418 | 3.671875 | 4 | from typing import List
class Solution:
def singleNumbers(self, nums: List[int]) -> List[int]:
ret = 0
for num in nums:
ret = ret ^ num
div = 1
while div & ret == 0:
div <<= 1
a = 0
b = 0
for num in nums:
if num & div:... |
303fe3c4572f5e8eba22b5299c7f1ee74cab5ed3 | LogicJake/code-for-interview | /leetcode-cn/Python/111.二叉树的最小深度.py | 792 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=111 lang=python3
#
# [111] 二叉树的最小深度
#
# @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 minDepth(self, root: TreeNode) -> int:
if not root... |
6b4999640cd3fc8a7cabf11733360704dcd04c3b | LogicJake/code-for-interview | /leetcode-cn/Python/114.二叉树展开为链表.py | 837 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=114 lang=python3
#
# [114] 二叉树展开为链表
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: TreeNode... |
ed86c415ebe1a45eb8ea5bcd7860de1201802adf | LogicJake/code-for-interview | /剑指offer/33.二叉搜索树的后序遍历序列.py | 463 | 3.515625 | 4 | from typing import List
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def help(i, j):
if i >= j:
return True
p = i
while postorder[p] < postorder[j]:
p += 1
m = p
while postorder[p] > po... |
5a1fdc7c470b57bae88fb00bf78ed74e04f1b3ec | LogicJake/code-for-interview | /程序员面试金典/1.1.判定字符是否唯一 .py | 385 | 3.578125 | 4 | class Solution:
def isUnique(self, astr: str) -> bool:
mask = 0
for c in astr:
num = ord(c) - ord('a')
if mask & (1 << num) != 0:
return False
else:
mask = mask | (1 << num)
return True
if __name__ == "__main__":
solu... |
7b0cd3faea77fd1d474ec875138dc4e314db3b08 | LogicJake/code-for-interview | /leetcode-cn/Python/287.寻找重复数.py | 733 | 3.5 | 4 | #
# @lc app=leetcode.cn id=287 lang=python3
#
# [287] 寻找重复数
#
# @lc code=start
from typing import List
class Solution:
# def findDuplicate(self, nums: List[int]) -> int:
# exist = set()
# for num in nums:
# if num in exist:
# return num
# else:
# ... |
87d5612ae65c538316bf3e5986798df1435d28da | LogicJake/code-for-interview | /leetcode-cn/Python/355.设计推特.py | 1,874 | 3.953125 | 4 | #
# @lc app=leetcode.cn id=355 lang=python3
#
# [355] 设计推特
#
# @lc code=start
from typing import List
from collections import defaultdict
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.post = []
self.follows = defaultdict(list)
... |
433977df6f91cde1f1ff8e126a1698253e33702c | LogicJake/code-for-interview | /程序员面试金典/3.1.三合一.py | 1,205 | 3.625 | 4 | class TripleInOne:
def __init__(self, stackSize: int):
self.stack = [0] * (3 * stackSize)
self.top = [-1, -1, -1]
self.cap = stackSize
def push(self, stackNum: int, value: int) -> None:
if self.top[stackNum] < self.cap - 1:
self.top[stackNum] += 1
self.st... |
8fc6172afe1ca16c69aab94ebe5ce47a33ca076f | LogicJake/code-for-interview | /leetcode-cn/Python/290.单词规律.py | 791 | 3.515625 | 4 | #
# @lc app=leetcode.cn id=290 lang=python3
#
# [290] 单词规律
#
# @lc code=start
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
pattern_map = {}
str_map = {}
if len(str.split(' ')) != len(pattern):
return False
for i, s in enumerate(str.split(' ')... |
dccf82c7ebd3844805b455beab8a90eddef566e2 | littlepriyank/guvi_rep | /bs1-4.py | 101 | 3.984375 | 4 | r = input()
if((r>='a' and r<='z')or(r>='A' and r<='Z')):
print("Alphabet")
else:
print("No")
|
ad496e781661d6ab0631c54ec098b885e8e5aa1f | littlepriyank/guvi_rep | /bs1-9.py | 319 | 3.5 | 4 | N,K = [int(x) for x in input("enter value of N and K").split()]
a = [0]*50;s=0
print("enter the integers of array")
t = input().split()
if(len(t)==N):
for i in range(N):
a[i] = int(t[i])
for i in range(0,K):
s+=a[i]
print(s)
else:
print("number of integer not equal to N")
|
1648719a2857ffa8a988678eb728ab1be0c07b8f | littlepriyank/guvi_rep | /ps2-1.py | 324 | 3.765625 | 4 | s = input()
if(s in ["Saturday","saturday","Sunday","sunday","SATURDAY","SUNDAY"]):
print("yes")
elif(s in ["Monday","Tuesday","Wednesday","Thursday","Friday","monday","tuesday","wednesday","thursday","friday","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY"]):
print("no")
else:
print("Invalid Input... |
1c5e17fa901955261dc301b0b064f1c4b8421e26 | josephmisiti/chase-cc-filter | /clean.py | 3,217 | 3.5 | 4 | #!/usr/bin/python
#
# By @josephmisiti 2-18-2013
#
"""
Filter credit cards statements from Chase.com.
Usage:
./clean <command-separated-tags> [case-insensitive]
Example usage:
./clean.py attm <--- filters all of my AT&T wireless charges
./clean.py mcdonald <--- filter all of my purchases at McDonald's
... |
f6e818634ba21f80b3bcfe4fb2d8c58100fb1847 | yiyada77/algorithm | /Python/102-levelOrder.py | 634 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
def recursion(root, length, res):
... |
0d6cb0aa82d93626ca20162f67c4a0e0bf4aae29 | ksang/leetcode-solutions | /verify_preorder_serialization_of_a_binary_tree.py | 604 | 3.625 | 4 | class Solution(object):
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
nodes = preorder.split(",")
if len(nodes) % 2 == 0:
return False
if nodes[-1] != "#":
return False
if nodes[0] == "#":
if len(nodes) == 1:
return True
else:
return False
stac... |
08630bf3c448069793e8ea062eaa451d2a35d5f0 | ksang/leetcode-solutions | /word_pattern.py | 768 | 3.59375 | 4 | class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
check1 = {}
check2 = {}
def check(a, b):
if check1.has_key(a) and check2.has_key(b):
if check1[a] == b and check2[b]... |
0621f619071f9572676f89703c05d6962fa77aa6 | ksang/leetcode-solutions | /bulls_and_cows.py | 910 | 3.65625 | 4 | import sys
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
bull = cow = 0
rest = ""
secret_dict = {}
for i,s in enumerate(secret):
if s == guess[i]:
b... |
a467d3f19c34e16a228401b524aa00cfc1fccb2d | Swxer/advent-of-code-2020 | /day2/day2.py | 575 | 3.96875 | 4 |
f = open("input.txt", "r")
valid_count = 0
# loop through the text file
for line in f:
# separate the line into 3 different components
component = line.split()
# separate the range value
size = component[0].split('-')
# separate the subject value
letter = component[1].replace(':','')
... |
eed57f18efebaa9f265986322624413489d7d958 | anapschuch/RunITA | /CodeSource/RandomEnemy.py | 1,152 | 3.578125 | 4 | from CodeSource.Enemy import*
from random import randint
class RandomEnemy(Enemy):
""" Inimigo que anda numa mesma direção até não ser mais possível se mover.
A partir daí, uma nova direção é escolhida aleatoriamente."""
def __init__(self, img_path, x_init, y_init):
super().__init__(img_path, x_in... |
c2afe91722c540f66d79cc7f5730f65212096de7 | pyomeca/bioptim | /bioptim/examples/getting_started/example_joints_acceleration_driven.py | 3,927 | 3.578125 | 4 | """
A simple optimal control program consisting of a double pendulum starting downward and ending upward while requiring the
minimum of generalized forces. The solver is only allowed to apply an angular acceleration the joint linking the second
pendulum to the first one.
During the optimization process, the graphs a... |
99f3ae50e2a4edfaed5dc693569d34463f084277 | Parvez6084/Easy-to-Python-Learning | /GasseGame.py | 321 | 4 | 4 | import random
n = 5
while 1 <= n:
user = int(input("Enter Your Guess Number 1 to 5 : "))
guessNamber = random.randint(1, 5)
if user == guessNamber:
print("You are win. The number is ", guessNamber)
break
else:
print("you are lose. The number is ", guessNamber)
n = n + 1... |
e6487b1e3d5f9230e18d572620749106b70f7160 | MateuVieira/Advent-of-Code | /Day 2 Inventory Management System/Day_2_Inventory_Mnagement_System_part_2.py | 1,573 | 3.75 | 4 | """
Function receive a list of strings.
create a list to receive the 'result' of the function.
'len_word' -> receive the length of the string from the list.
|
-> Only is right if the length of all strings of the list are equals.
First to run the entire list, the second will run the next item in the
list (i + 1) until ... |
6a5cf8114ec69529075e4f94bcdce115e61c902d | natalieagus/test_mp | /app/static/library.py | 2,677 | 3.96875 | 4 | from org.transcrypt.stubs.browser import *
import random
array = []
def gen_random_int(number, seed):
a = []
for i in range(0,number):
a.append(i)
random.shuffle(a,random.seed(seed))
return a
def generate():
global array
number = 10
seed = 200
# call gen_random_int() with the given number and seed
# sto... |
6492d2dd64db05f8f5f7cc54a4ab82a359101feb | vigneshkalai/implementation-of-decision-tree-with-bagging-and-boosting | /decisionTree/impurity.py | 2,896 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
import pandas as pd
import data_process
def entropy_calc(df, ensemble = None, weights = None):
"""
This function helps to calculate the
entropy information of the features
and returns them.
Arguments:
... |
7d1991f4ef0f6e6cdf2703ade562606088046166 | agshing/algorithms-sedgewick | /bst/tests.py | 1,000 | 3.546875 | 4 | #!/usr/bin/env python3
import unittest
from bst import *
class BSTTests(unittest.TestCase):
def test_bst(self):
# create list of char: ascii_code tuples
key_val_lst = [(c, ord(c)) for c in "PSEUDOMYTHICAL"]
bst = BST()
for key, val in key_val_lst:
bst.put(key, val)
... |
522bd9df3c8679a12b08f71bae3cdb686b998e71 | stodola/tasks | /battle2_poprawione.py | 770 | 3.671875 | 4 | def battle(soldier_list):
sum_even = 0
sum_odd = 0
for i in soldier_list:
if i == 0:
pass
elif i%2 == 0:
if i < 0:
sum_even -= bin(i)[3:].count('0')
else:
sum_even += bin(i)[2:].count('0')
else:
if i < ... |
b4ff9dcf5c6e5da9770ae6a6be6e36fd0fbd3d2c | Piachonkin-Alex/EarleyAlgo | /app/main.py | 3,751 | 3.515625 | 4 | # terminals - a-z
# non-terminals A-Z
# start - non-terminal S
# empty symbol is an empty string
class Rule:
def __init__(self, left_side: str, right_side: str):
self.lhs = left_side
self.rhs = right_side
class Situation:
def __init__(self, left_side: str, right_side: str, point_cord: int, off... |
5ec779d06f2cbfbb9b23862c57d6c3638747bde5 | iam-sundar/learn_python | /data_types/string_package/str_demo.py | 1,802 | 3.921875 | 4 | # single line initialization
name:str = 'Sundar'
# multiple line initialization
about_me:str = ''' I am software developer with 7+ years experience in enterprise application development.
I have good knowledge in Core Java, Java8, Spring Framework, RESTful service, maven, GIT verison control,
Sonar integration, Cassan... |
78386991f94af5455aa6e33cacf7b7f48a73d7f9 | cafe-mignon/algorithm-study | /programmers/algo/Array/leetcode_array4_rotatearray.py | 401 | 3.78125 | 4 | #https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/646/
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
for i in range(0,k)... |
07607971c685c6c5e86303d270a01c8900ec24f5 | cafe-mignon/algorithm-study | /programmers/algo/Array/leetcode_array1_removedups.py | 512 | 3.6875 | 4 | # https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/
import sys
def removeDuplicates(nums) -> int:
num= -sys.maxsize - 1
for i in nums[:]:
if num == i:
nums.remove(i)
continue
else:
num= i
return nums
def removeDuplicate... |
d12769e07d0d18970df9ba1fa54b8c5d8cc13bd8 | Mryangwenming/tools_set | /class.py | 265 | 3.640625 | 4 | class A:
def __getattr__(self, item):
if item not in dir(self):
return getattr(self, "get_name")
def get_name(self):
return "name"
a = A()
a.f1() # 当调用A类中没有的方法时, 会自动调用get_name方法
a.f2()
|
690602e61f84367e3b04fdcf44d3e75ad22bfd05 | aaronrrh/learning-python | /loop.py | 2,761 | 3.921875 | 4 | haveKey=False
doorLocked=True
doorClosed=True
gameOver=False
describeRoom=True
lightOn=False
print('You are in a room. ',end='')
while not gameOver:
if describeRoom:
if lightOn:
print('There is a door that is ',end='')
if doorClosed and doorLocked:
print('closed and ... |
8c9d133d88c404962d09ac6d0f139e6e607c8268 | yashraj077/Codevita | /mockvita/prime fibonacci.py | 1,390 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 13:05:51 2020
@author: yash
"""
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
retur... |
ccee5191571859b55e46f3e94557d0db573f2456 | professor123409/Python_Basics | /String/alphabetical arangement of string.py | 107 | 4.03125 | 4 | x=input("Enter string: ")
words=x.split(' ')
for i in words.sort():
print("the sortest words are:",i)
|
19253d4c04a06c5a9b703c0a1c5bb659995c38a9 | professor123409/Python_Basics | /Recursion/recursion sum of even first n.py | 111 | 3.765625 | 4 | def sum(n):
if n==0:
return n
else:
return 2*n-2+sum(n-1)
x=sum(10)
print(x)
|
2d260d963087025fe1923569336c51dcacca85db | professor123409/Python_Basics | /Dictionary/print key and value user input key.py | 276 | 3.984375 | 4 | words={}
l=[]
x=int(input("Enter size of key"))
for i in range(0,x):
num=int(input("Enter key "))
l.append(num)
for i in l:
print("Enter the values")
words[i]=input()
print("Dictonary is: ",words)
for i in words:
print("KEy is: ",i,"Value is :",words[i])
|
a16f659af4d10f7a1f33197d3f42c1d44d5f0a74 | professor123409/Python_Basics | /Maths/Square Of a Number.py | 76 | 4.03125 | 4 | x=eval(input("Enter a Number: "))
sqr=x*x
print("square of number is:",sqr)
|
0d54f9b9f8b7c428ac9eb30c06683df78aaae0c6 | professor123409/Python_Basics | /Maths/Simple intrest.py | 144 | 3.734375 | 4 | p=int(input("Enter Principle:- "))
r=float(input("Enter Rate:- "))
t=int(input("Enter Time:- "))
si= p*r*t/100
print("Simple Intrest is:- ",si)
|
bba29077d2d4ea5e85e4eb44abe2917b417112e8 | BoSott/random_walk | /vector_walker.py | 6,821 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Vectorized Walker"""
import random
import math as m
import matplotlib.pyplot as plt
import numpy as np
def next_step(x_arr, y_arr, pos, direction, step_size):
"""
Returns the next step for a random walker
:param x_arr: numpy array of the walker's path – x-... |
b7661d157d2de440681bb1edc71a46d99389651e | gitlobodapavel/minesweeper | /results.py | 1,174 | 3.578125 | 4 | from tkinter import *
import menu
import sqlite3_connect_db
import game
def show(username=''):
def display_menu():
root.destroy()
menu.display()
def print_stat():
if username =='':
sqlite3_connect_db.cursor.execute("SELECT * FROM results ")
rows = sqlite3_conn... |
833ec048fa20797d24a70d06d3821edd0ecb54b7 | alicejuan1208/sc-projects | /stanCode_Projects/5_boggle_game_solver/sierpinski.py | 2,132 | 3.859375 | 4 | """
File: sierpinski.py
Name: Alice
---------------------------
This file recursively prints the Sierpinski triangle on GWindow.
The Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski.
It is a self similar structure that occurs at different levels of iterations.
"""
from campy.graphics.gwindow imp... |
b11f179a2d34d105d5f1594f7410bfa0e2b60dec | alicejuan1208/sc-projects | /stanCode_Projects/2_break_out_game/breakout_extension.py | 5,386 | 3.640625 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
YOUR DESCRIPTION HERE
"""
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
from campy.graphics.gobjects import GLabel
FRAME_RATE = 1000 / 120 # 120 fram... |
1715e784d1614edae62ce5918e286ec187997c34 | doctorOb/euler | /P9-pythagoreanTriplet.py | 720 | 4.1875 | 4 | """There exists exactly one Pythagorean triplet for which a + b + c = 1000
Find the product abc."""
import math
def isPythagoreanTriplet(a,b,c):
"""determine if a < b < c and a^2 + b^2 = c^2
formally, a Pythagorean triplet"""
if a < b and b < c:
return (a**2 + b**2) == c**2
else:
return False
def solve(n)... |
3495988a97b0bf0a664811a1643c45fa036f0845 | 5agado/intro-ai | /src/test/mazeOfPacman.py | 6,740 | 3.515625 | 4 | import os
import random
import pygame
import sys
from util import utils
from time import sleep
square_l = 10
pacman_r, pacman_c = None, None
food_r, food_c = None, None
r,c = None, None
visited = []
fPath = []
def dfs(grid, start, end, path = []):
#print(start)
global visited
global fPath... |
7bca1c56a21603cf6e9daa4cd55642861b068ef3 | phungj/MSOE_Comp_Prog_Py | /src/Kattis/2021/MSOE_Comp_Prog/Week_7/B/biggest.py | 1,242 | 3.625 | 4 | from itertools import tee
from math import pi
# From https://stackoverflow.com/a/34562305
def pairwise(iterable):
"""
s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
out = []
# There are 360 * 60 * 60 = 360 * 3600 seconds in a circle
for _ in ra... |
f46bbcd394a2200f9bf78553740c5ac3f8a6d874 | phungj/MSOE_Comp_Prog_Py | /src/Kattis/2021/MSOE_Comp_Prog/Week_7/E/goldbach2.py | 761 | 3.734375 | 4 | # Functions found from https://gist.github.com/paulhankin/c471b24c9a4717010681f0c5e33d6be9
def primes(n):
x = [False] * (n + 1)
for i in range(2, n + 1):
if x[i]: continue
yield i
for j in range(2 * i, n + 1, i):
x[j] = True
def prime_pairs(n):
ps = list(primes(n))
... |
3c95c53643f758013bf74dd541312a7f6d0f8ffc | phungj/MSOE_Comp_Prog_Py | /src/Kattis/2021/MSOE_Comp_Prog/Week_6/B/B_Grille.py | 1,007 | 3.53125 | 4 | from itertools import chain
def apply_grille(plaintext, ciphertext):
for r in range(len(grille)):
for c in range(len(grille[0])):
if grille[r][c] == ".":
plaintext[r][c] = ciphertext[:1]
ciphertext = ciphertext[1:]
return plaintext, ciphertext
def rotate_... |
40547b2b358d427284b510eb4fe5965aaba50885 | prog-bob/Homework4 | /core/rectangle.py | 1,086 | 4 | 4 | from .base import Base
class Rectangle(Base):
def __init__(self, name):
super().__init__(name, 4)
def perimeter(self, *args):
if len(args) != 2:
print("Не заданы значения сторон прямоугольника")
return None
self.perimeter_val = sum(args) * 2.0
print(f"... |
12a3efbf2fd89d0464f2aa46bb69e3ca3aa2ca05 | varunnair735/Computational-Physics | /Final Project/Other Scripts/channel_flow_test.py | 7,472 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def channel_flow(tend, N, L, obstacle=None):
"""Will solve a 2-d channel flow system according
to Navier-Stokes equations for an NxN grid in
a channel of length L, height L/2, iterating
for <tend> seconds"""
# physical parameters of fl... |
f5ef0c8bc854f89c4169b9939a57d48444ba0e29 | asbroad/eecs-337-nlp | /project_01/src/match_options.py | 7,215 | 3.65625 | 4 | import nltk
from nltk.tag import pos_tag
from collections import defaultdict
import re
'''
The 'ignore_list' is a list of words and names to ignore when analyzing the twitter data,
of note, will ferrell and kristen wiig became a trending topic on google and yahoo during the 2013 golden globes
as suggestions of hosts f... |
c80710428c0baf81e67e6aeb7cc70fc03abcba18 | jordanfaure/checkers-2016-miele_t | /draughts/commons.py | 914 | 3.53125 | 4 | #!/usr/bin/env python
#regex
import re
"""Define Color enum and Type enum"""
Ether = "Ether"
Black = "Black"
White = "White"
Human = "Human"
CPU = "CPU"
# Stone State enum
Pawn = "Pawn"
Lady = "Lady"
# Cell of Board State
Empty = "Empty"
Fill = "Fill"
class Hit:
"""Class for separate entry from user to inter... |
3d31e7c1c2393e299baf0165fb568185c05f3029 | kritiguptasjsu/tictactoe | /tictactoe.py | 2,591 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 4 19:19:38 2019
@author: Kriti Gupta
"""
import random
choices=[1,2,3,4,5,6,7,8,9]
def printmatrix():
"Function to print the tictactoe matrix"
print(choices[0],'|',choices[1],'|',choices[2])
print('----------')
print(choices[3],'|',choices[4],... |
a4b285a2878edf37110901666176346844464177 | GavinDN/python_work | /format_2().py | 1,236 | 3.59375 | 4 | # coding=gbk
# format()ʵʹ
N = 'Gavin'
print(format(N, '10')) # ûб־ַĬ룬ȲĬÿո
print(format(81.23, '10')) # ûб־ĬҶ룬ȲĬÿո
print(format(N, '0>10')) # Ҷ룬ָȲ0
print(format(N, '0>4')) # Ҷ룬ַʵʿȴָ4
print(format(N, '*>10')) # Ҷ룬㲿á*
print(format(N, '>010')) # Ҷ룬㲿0
print(format(N, '>10')) ... |
f5eae5ae7113c585d6547622bc49e26b0ae116ec | GavinDN/python_work | /abs_5().py | 348 | 3.765625 | 4 | # coding=gbk
# 利用绝对值比较大小并输出较大者
# 编写程序,输入两个负数并比较它们的大小,同时输出较大者,代码如下:
a = int(input('请您输入一个负数:'))
b = int(input('请再输入一个负数:'))
# 绝对值大的负数反而小
if abs(a)>abs(b):
print(b)
else:
print(a)
|
1e5ddc99148c03415ac5f1a5d4fa8cc9a61bda2a | GavinDN/python_work | /format_1().py | 488 | 3.515625 | 4 | # coding=gbk
# ʽٷ
print(format(0.1623445,'%')) # СʽΪٷ
print(format(0.1623445,'.2%')) # ʽΪ2λСİٷ
print(format(0.01623445,'.6%')) # ʽΪ6λСİٷ
print(format(2/16,'.2%')) # ʽΪ2λСİٷ
print(format(0.1623445,'.0%')) # ʽΪİٷ
print(format(0.1623445,'8.6%')) # ʽΪ6λСİλٷ
|
2245c07a64384e77a44b9540fcd551f245492289 | ShimaSama/Python | /email.py | 344 | 4.3125 | 4 | #program to know if the email format is correct or not
email=input("Introduce an email address: ")
count=email.count('@')
count2=email.count('.')
end=email.rfind('@') #final
start=email.find("@")
if(count!=1 or count2<1 or end==(len(email)-1) or start==0):
print("Wrong email address")
else:
print(... |
c225736d28347912c84fbb8e7913e3887609f386 | menezesbrindon/2sem | /assw/assw/fact.py | 95 | 3.734375 | 4 | a=int(input('enter the num'))
x=1
while a!=0:
x=x*a
a=a-1
print(x,end=' ')
|
192a570977ed87a92c93f5ddba1473cd567f7dc4 | menezesbrindon/2sem | /assw/assw/list.py | 110 | 3.5 | 4 | a=[8,9,10]
a[1]=17
a.append(4)
a.append(5)
a.append(6)
a.remove(a[0])
a.sort()
a=a*2
a.insert(3,25)
print(a)
|
8604924bc54c4a61897f2b310d94d35f16de31e2 | GitGaoCo/PythonDailyWhiteBoard | /havefunhere.py | 1,286 | 3.890625 | 4 |
##### Questions comes from intenet resources #########
## start to use pycharm
## this is a test
#2019-09-06
#This is how to convert from string exppression to equation
#it is very simple just use eval() function and python will return numerical result
def eval_ (expressions):
return eval(expressions)
print eval... |
5fc28ab298c14b482825b23bb6320ca32e50b514 | sudiptasharif/python | /python_crash_course/chapter9/fraction.py | 1,763 | 4.4375 | 4 | class Fraction(object):
"""
A number represented as a fraction
"""
def __init__(self, num, denom):
"""
:param num: integer numerator
:param denom: integer denominator
"""
assert type(num) == int and type(denom) == int, "ints not used"
self.num = num
... |
36df6a6be2706949450d5491633460ce982a1d35 | sudiptasharif/python | /python_crash_course/ps1/ps1a.py | 765 | 4.09375 | 4 | down_payment_rate = 0.25
total_months = 12
r = 0.04
n = 0
current_savings = 0
annual_salary_prompt = "Enter your annual salary: "
portion_saved_prompt = "Enter the percent of your salary to save, as a decimal: "
total_home_cost_prompt = "Enter the cost of your dream home: "
annual_salary = float(input(annual_salary_p... |
31469ef24734f92c84f4540bbba9a8580a810554 | sudiptasharif/python | /LearningPythonBasics/LearningBasics/LearningBasics.py | 434 | 3.640625 | 4 | '''
Created on Jun 14, 2018
@author: sudiptas
'''
myvar = "Hello Python";
print(myvar);
x = 100;
pi = 3.14;
empname = "python is great";
a = b = c = 100;
print(x);
print(pi);
print(empname);
x = 1;
y = 2;
print("x = "+str(x));
print("y = "+str(y));
y,x = x,y;
print("x = "+str(x));
print... |
cf3ff8f98e8574da1462624a0363d82794350c90 | dpauk/turtle_game | /race.py | 1,937 | 3.546875 | 4 | """An actual race"""
from turtle_has_no_energy_error import TurtleHasNoEnergyError
class Race:
def get_time_for_turtle_over_next_metre(self, speed):
speed_per_minute = 0.1 * speed # i.e. turtle covers this over 1 minute
return round((1 / speed_per_minute) * 60)
def get_energy_for_turtle_aft... |
a78f4a0162e21e33ca71939072d442093a45f0a8 | zht198484/PythonBasic | /com/zht/collection/PrintListRecursively.py | 617 | 3.578125 | 4 | seq = ['a', 'b', 'c']
print seq
# not recommend to insert different type
seq.insert(1, 1)
print seq
seq.append('d')
for i in seq:
print i
print type(seq[0])
print type(seq[1])
seq.insert(1, ['a1', ['b2','c2']])
print seq
for i in seq:
print i
print isinstance(seq, list)
def print_seq(the_seq, indent=Fal... |
c24de5e6b864266c450d38eff7ca8eeb42b661f3 | Tosa95/pypiet | /printStr.py | 2,341 | 3.90625 | 4 | # -*- coding: utf-8 -*-
import commands
def _biggerPowOfTwo (num):
if (num < 2):
return 0
acc = 2
exp = 1
while acc<num:
acc *= 2
exp += 1
return exp-1
class StringPrinter:
#Sequence è una lista di coppie (colore,dimensione), dove dimensione è la dimensione del blocco e colore è una coppia (y,x) di c... |
ff46ca27a5b2aede113956579b626b9f03c8292a | oddrune/dotfiles | /bin/prefix | 373 | 3.546875 | 4 | #!/usr/bin/env python3
import os
import sys
import glob
files_to_rename = sys.argv[2:]
if not files_to_rename:
files_to_rename = glob.glob("*")
for a in files_to_rename:
# if os.path.isfile(a):
newname = "%s-%s" % (sys.argv[1], a)
if os.path.isdir(a):
continue
os.rename(a, ... |
1eb8b6492caff5c21188ebcf8f520e9479c80e2a | matanjos/ProjetoFinalEngSoftware3 | /códigos/fibonacci.py | 247 | 3.921875 | 4 | def fib(n): #Definição da Funçõa de Fibonacci
if n==0: #Critério de parada da função de Fibonacci
return 0
elif n==1: #Critério de parada da função de Fibonacci
return 1
else: #Recursividade.
return (fib(n-1)+fib(n-2))
|
a453b2a8f0e51c57d43f0894e0d99664ca68f866 | LGiave/TPSIT | /Python/Es_vari/es_04 copy.py | 463 | 3.84375 | 4 | myList = []
mySecondList = []
cond = True
while cond:
x = input("inserire un valore:")
myList.append(x)
r = input("vuoi inserire un altro valore? y/n\n")
if r == "y" or r == "Y":
continue
else:
cond = False
n = int(input("len: "))
print(n)
for word in myList:
print(wor... |
d122e3ade1a5c5d88541f94bc31576f61059139c | jdfrancop/probando | /encriptar.py | 1,584 | 4.09375 | 4 | #version 1
#def encriptar(frase):
# encriptada = ""
# for letra in frase:
# if letra in "AEIOUaeiou":
# encriptada = encriptada + "x"
# else:
# encriptada = encriptada + letra
# return encriptada
#print(encriptar(input("Ingresa una frase: \n>>> ")))
print("---------------... |
3b7d96436710c8e7c543258e99bbe45e24659196 | jdfrancop/probando | /clases_y_objetos.py | 344 | 3.6875 | 4 | class Estudiante:
def __init__(self, nombre, edad, curso_inicial):
self.nombre = nombre
self.edad = edad
self.curso_inicial = curso_inicial
self.estado_activo = True
self.cursos = [curso_inicial]
estudiante1 = Estudiante("Juan", 34, "Python")
estudiante1.edad = 45
print(e... |
0134992829955935825b8a5c66af4225139c8cc9 | jdfrancop/probando | /rangos.py | 1,006 | 3.921875 | 4 | import re
cadena = "abceef ghi" \
"0123456789-" \
"los buenos dias de hola con hola que bien"
print(re.findall("[a-d]", cadena))
print("--------------------------------")
print(re.findall("[a-d2-5]", cadena))
print("--------------------------------")
print(re.findall("[^a-d2-5]", cadena))
print("---... |
253e80b1f9ae499d49eb0d79c34b821e0c8dfb6d | waditya/HackerRank_Linked_List | /09_Merge_Sorted_LinkList.py | 2,952 | 4.28125 | 4 | """
Merge two linked lists
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def MergeLists(headA, headB):
... |
6647f2a03e8d08ca8807c5dad2c2a0694d264713 | SethGoss/notes1 | /notes1.py | 363 | 4.28125 | 4 | # this is a comment, use them vary often
print(4 + 6) # addition
print(-4 -5) #subtraction
print(6 * 3) #multiplication
print(8 / 3) #division
print(3 ** 3) #exponents - 3 to the 3rd power
print(10 % 3) #modulo gives the remainder
print(15%5)
print(9%4)
# to make variable, think of a name
name = input("Wh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.