blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3778d1779d42cd18e94218babea4582cd4259b93 | simamumu/python_library | /数学/素因数分解.py | 780 | 3.5625 | 4 |
# 先にふるってprimesを作る
def hurui(N):
koho = list(range(2,N))
prime = []
limit = math.sqrt(koho[-1])
while True:
p = koho[0]
if limit <= p:
prime = prime + koho
break
else:
prime.append(p)
koho = [e for e in koho if e%p != 0]
return... |
8db2c5b49559d9b3e9d47e21a0181948f987c6f5 | carlosvcerqueira/Projetos-Python | /ex032.py | 463 | 3.65625 | 4 | from datetime import date
ano = int(input('Que ano quer analisar? Coloque 0 para analisar o ano atual: '))
cores = {'limpa': '\033[m', 'Vermelho': '\033[1:34:31m', 'Roxo': '\033[35:45m', 'amarelo': '\033[33:33m'}
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
pr... |
59185a63ac67ccf751b061c314f744c1f628dd6b | danylagacione/Codility | /Lesson2/CyclicRotation.py | 1,616 | 4.28125 | 4 | # CyclicRotation
#
# Uma matriz A consistindo de N inteiros é fornecida.
# A rotação da lista significa que cada elemento é deslocado para a direita por um índice,
# e o último elemento da lista é movido para o primeiro lugar.
# Por exemplo, a rotação da lista A = [3, 8, 9, 7, 6] é [6, 3, 8, 9, 7]
# (os elementos são d... |
13e56e329d324199f27814f9669f4ba7b88c96fd | connormullett/PythonPacman | /pacman.py | 882 | 3.53125 | 4 |
class Pacman:
def __init__(self):
self.total_points = 5000
self.points = 5000
self.lives = 3
self.ghost_multiplier = 200
self.lives_gained = 0
def add_points(self, points):
self.points += points
self.total_points += points
if self.points >= 1000... |
c3050b32fdc495a20d31a07266e070fafcd074d0 | optimus-kart/python-multithreading | /examples.py | 12,887 | 3.53125 | 4 | class Test:
def __init__(self):
self.tests = {}
def add(self, fn, tests):
self.tests[fn] = tests
def run(self):
for fn, tests in self.tests.items():
for test in tests:
self.run_test(fn, test)
def run_test(self, fn, test):
test.setdefault("ar... |
d4149e54be8afa247dae476fd8cc5f242cff77f6 | sebanazarian/itedes | /modulo1/segmento3/examenFinal/autosABM.py | 2,895 | 3.703125 | 4 | def agregarAutos(autos):
auto={}
patente = input("Ingrese patente del Auto: ")
patenteDuplicada = verificarPatente(patente)
while patenteDuplicada=="si":
print("Patente Existente ingrese nuevamente")
patente = input("Ingrese patente del Auto: ")
patenteDuplicada=verificarPatente(patente)
auto['patente']= pa... |
5b3179b3ae4405bb75a8f7ab5728ff1629a0b717 | SingleMaltose/DSP_Optimizing_With_Python | /Loop_Bound_Calc.py | 3,801 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 14:18:53 2019
This is the straight-forward implementation of algorithms in Chaptr 2,
"Iteration Bound" of "VLSI Digital Signal Processing Systems".
The class 'Graph' contains 2 algorithm for calculating iteration bound of dsp
graph, named "Longest Path Matrix(... |
3305512104f41a73ce7a94a26c13a232c575bed7 | alexganwd/coderdojo | /projects/2019-2020/week2/askforuserinput.py | 405 | 4.3125 | 4 | #Ask user for information
operator = input("Introduce an operation\n")
number1 = int(input("Introduce your first number\n"))
number2 = int(input("Introduce your second number\n"))
#Present information back to the user
print("The operation selected is " + operator)
if operator == '+':
result = number1 + number2
... |
392c88b63a163b7bc2a569599facfa62f40da343 | humachine/AlgoLearning | /leetcode/Done/500_KeyboardRow.py | 1,382 | 4.125 | 4 | #https://leetcode.com/problems/keyboard-row/
'''Given a List of words, return the words that can be typed using letters of alphabet on only one row's of the Qwerty keyboard.
Inp: ["Hello", "Alaska", "Dad", "Peace"]
Out: ["Alaska", "Dad"]
'''
class Solution(object):
def findWords(self, words):
result = []
... |
7f1bcfa1aee24dd1c195ea05af9c9c3667b497fc | aifulislam/Demo_First_Python_Coding | /program11.py | 1,945 | 4.4375 | 4 | #Inner If Statement--------
if 6>4:
if 6>3:
if 7>2:
print('Hi')
if 6<9:
if 4<6:
if 5<6:
if 9<8:
print('Hi')
else:
print('hello')
#Lage number find of three numbers-----
num1 = 90
num2 = 80
num3 = 50
if num1>nu... |
0c0cbea05af8a9f6ba575e74fe9c9aad540d774f | jcroskrey/csc121 | /lab6/chapter9.py | 2,806 | 3.828125 | 4 | # Problem 1
def prob_1():
for i in range(10):
print("*", end=" ")
# Problem 2
def prob_2():
for i in range(10):
print("*", end=" ")
print()
for i in range(5):
print("*", end=" ")
print()
for i in range(20):
print("*", end=" ")
print()
# Problem 3
def prob_3(... |
7c7386287f6763affff9ee436cd8af213178f160 | applutree/Python-Repo | /practicepython_practice1.py | 436 | 4.15625 | 4 | from datetime import date
name = input("What is your name? ")
age = int(input("what is your age? "))
current_date = date.today()
year_to_100 = (current_date.year - age) + 100
print("Hello " + name + ", you will turn 100 years old in ", year_to_100, " years." )
iter_num = int(input("Enter number of iteration: "))
f... |
9ff04bf2695a433287aecb4736e27e2d0d3dc216 | zerghua/leetcode-python | /N1323_Maximum69Number.py | 1,130 | 4.0625 | 4 | #
# Create by Hua on 4/16/22.
#
"""
You are given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing ... |
25d68d2472cac4d36be00e2d9217465f17f55196 | filipbartek6417/RegexEngine | /Regex Engine/task/regex/regex.py | 260 | 3.84375 | 4 | pair = input().split('|')
match = 'True'
for index, item in enumerate(pair[0]):
try:
if item != pair[1][index] and item != '.':
match = 'False'
break
except IndexError:
match = 'False'
break
print(match)
|
2d041e4fde674f00c30e90ca3c8571de3e7047d2 | Graunarmin/Krypto_SS18 | /handy_python_stuff/my_lib.py | 2,918 | 3.640625 | 4 | '''
Sammlung von nützlichen Funktionen
import my_lib
'''
def ggT(s,e):
'''
ggT von s und e mit dem euklidschen Algorithmus bestimmen
'''
tmp = 0
if s < e:
tmp = e
e = s
s = tmp
while True:
r = s % e
if r == 0:
break
s = e
e = ... |
3415154c7002758264b5680b732b61fff43523b7 | clouds16/intro-python | /week7/test_roll.py | 866 | 3.875 | 4 | import random as r
class Dice:
def __init__(self):
self.numdice = 2 # number of dice
self.numfaces = 6
def rollDice(self):
diceRolls = []
for i in range(self.numdice):
roll = r.randint[1, self.numfaces]
return diceRolls
def main():
count = 0
dic... |
9f022b590c08cb293c7369dcfd4cd7bca9fed85b | amrithajayadev/misc | /dp/trapping_rain_water.py | 889 | 3.765625 | 4 | def greatest_element_right(nums):
output = [nums[-1],]
for i in range(len(nums) - 2, -1, -1):
output.append(max(nums[i], output[-1]))
print(output[::-1])
return output[::-1]
def greatest_element_left(nums):
output = []
for i in range(len(nums)):
if not output:
outp... |
02eb0671b97df8276f876ff814827f595ae072b0 | jorinvo/r | /substitution_cipher/encrypt.py | 730 | 3.65625 | 4 | import argparse
import sys
default_abc = 'abcdefghijklmnopqrstuvwxyz '
def main():
# Parse ars
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'abc',
type=str,
help=''
)
a... |
5a67eb8cc78796e1ce82b64c8f08647e1f9857ea | ColeDavis99/BST | /TESTING_creation_insertion_deletion.py | 2,767 | 3.734375 | 4 | import random
#File 1 generates a C++ program to test BST values (insertion and deletion)
#File 2 generates a listing of numbers I can put into visualgo.com and
#See what the BST I just made looks like
file1 = open("test1.txt","w")
file2 = open("test2.txt","w")
file1.write("#include \"header.h\"\n")
file1.write("... |
91d7bea7bca7643d173d2f94bde593b13f3687b6 | Lujinjian-hunan/python_study | /课堂笔记/day4/文件操作2.py | 805 | 3.65625 | 4 |
# f = open('user.txt')
# f.close()
# with open('user.txt',encoding='utf-8') as f: #文件对象,文件句柄
# for line in f:
# print(line)
# line = line.strip()
# if line:
# print(line)
#1、读取到文件所有内容
#2、替换 new_str
#3、清空原来的文件
#4、写进去新的
#新的
import os
# 打开a文件,再以只写的方式新建一个新文件
with open('words.txt... |
21660b9a8b185b249efbbabbc41ee99c4dd65da9 | trgeiger/algorithms | /hackerrank/2d-array-ds.py | 1,879 | 3.671875 | 4 | """
Context
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation:
a b c
d
e f g
There are hourglasses in , and an hourglass sum is the sum of an hourglass... |
fe25dbd68bb8d7d25e650bee1341dd87c7288902 | yaoyawei/Python-Learn | /Higher_order_function.py | 2,933 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
print("----函数名----")
f = abs
print("f=abs,f(-10)=%d)"%f(-10))
#abs = 10 #abs(-10)会报错
#print("abs=10,abs(-10)=%d"%abs(-10))
f = abs
def add(x, y, f):
return f(x) + f(y)
#add(5,-6,abs)=abs(5)+abs(-6)=11
print("add(5,-6,abs)=%d"%add(5,-6,abs))
# map() & reduce()
print(... |
36c573882bf494deda08fd1a108581afc85e87fc | rkbrian/AirBnB_clone | /models/engine/file_storage.py | 1,671 | 3.5 | 4 | #!/usr/bin/python3
"""Module defines a class ``FileStorage`` used to serialize/deserialize
python data to/from a JSON file"""
import json
from models.base_model import BaseModel
from models.user import User
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.revi... |
ae3a1c03f4ec1d0911ba3bb0802f067f33632360 | XIG-DATA/IPO | /ex.py | 247 | 3.71875 | 4 | class Question :
answer = None
text = None
class Add(Question):
def __init__(self, num1, num2):
self.text = '{} + {}'.format(num1, num2)
self.answer = num1 + num2
from ex import Add
add1 = Add(1,2)
print(add1.text)
# print(add1.answer) |
79b5eae90926db59af2cde5982f495e7eab1d3d6 | aniGevorgyan/python | /homework.py | 2,689 | 3.75 | 4 | #!/usr/bin/python 3.7.2
from math_util import myFactorial
# 1. Գրել ֆունկցիա, որը կընդունի 1 պարամետր՝ n, և կվերադարձնի բառարան, որի key-երն են 1-ից մինչև n֊ը, իսկ value֊ները
# դրանց համապատասխան ֆակտորիալները։
def getFactorial(n):
md = {}
for i in range(1, n + 1):
md[i] = myFactorial(i)
return md
# 2. Կա... |
a4df27d70b1ead5f05ab470fbda720679b7f1d13 | Frederick-S/Introduction-to-Algorithms-Notes | /src/chapter_07/stack_optimized_tail_recursive_quick_sort.py | 598 | 3.59375 | 4 | from .quick_sort import partition
def stack_optimized_tail_recursive_quick_sort(numbers):
stack_optimized_tail_recursive_quick_sort_internal(
numbers, 0, len(numbers) - 1)
def stack_optimized_tail_recursive_quick_sort_internal(numbers, p, r):
while p < r:
q = partition(numbers, p, r)
... |
3752b08ff2472a5373393bee0a268e968dde0133 | vidgit/FAQ | /Maths/DuplicatesXOR.py | 283 | 3.59375 | 4 | def repeatedNumber(A):
k=1
i=2
A=list(A)
n=len(A)
while(i<=n-1):
k=k^i
i+=1
temp=A[0]
for j in range(1,n):
temp=temp^A[j]
return temp^k
A=[1,1,3,4,5]
print repeatedNumber(A) |
f2ab002d34be50716c362ee13e0453bb1d824bff | 1290259791/Python | /leetcode/book/2.4.2.py | 634 | 3.609375 | 4 | def MaxSum(array, n):
"""
连续子数组的最大乘积
动态规划 Max=Max{a[i],Max[i-1]*a[i],Min[i-1]*a[i]}Min=Min
创建一维数组
:param array:
:param n:
:return:
"""
maxA = [0 for i in range(n)]
minA = [0 for i in range(n)]
maxA[0] = array[0]
minA[0] = array[0]
value = maxA[0]
for i in range... |
59e99feed18c04c2caff685907f85e119f143844 | kanthuc/game-of-life | /golengine.py | 1,734 | 3.53125 | 4 | class Cell:
neighbors = ((-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1))
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "(%i, %i)"%(self.x,self.y)
def __eq__(self, other):
... |
70e1c716e8a2a52cee4270d1baa06fede0c2707a | liucng/python-2020-study | /第三周/凯撒密码.py | 229 | 3.578125 | 4 | i = str(input())
a = ""
for t in i :
if "a"<= t <="z":
a+=chr(ord("a")+(ord(t)-ord("a")+3)%26)
elif "A"<= t <="Z":
a+= chr(ord("A") + (ord(t) - ord("A") + 3) % 26)
else:
a=a+t
print(a) |
701fab841832779fa67b30f20d72e065cd2ebdd7 | HeartFu/LeetCode | /109. Convert Sorted List to Binary Search Tree/Solution.py | 1,373 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 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 = r... |
487aa13f4c25a5923263d4aeb5cd2c79e39f42d0 | shen-huang/selfteaching-python-camp | /19100203/AustinJiangg/d3_exercise_calculator.py | 463 | 3.90625 | 4 | operator = input("请输入需要进行的运算(加,减,乘,除):")
number_one = float(input("请输入第一个参数:"))
number_two = float(input("请输入第二个参数:"))
if operator == "加":
a = number_one + number_two
print(a)
if operator == "减":
b = number_one - number_two
print(b)
if operator == "乘":
c = number_one * number_two
print(c)
if ope... |
57e82995e134b2c7eefe378172c95b7b1e644051 | ppyy-hub/bbbb | /py_ws/day2/e1.py | 2,087 | 3.953125 | 4 | # 从键盘输入一个成绩,根据成绩输出对应的等级
# 90(包含)---100(包含) A
# 70(包含)---90(不包含) B
# 60(包含)---70(不包含) C
# 0(包含)--60(不包含) D
# 其它情况,输出“无效的成绩”
# score=input("请输入你的成绩")
# scores=int(score)
#
# if scores>=90 and scores<=100:
# print('A')
# elif scores>=70 and scores<90:
# print('B')
# elif scores>=60 and scores<70:
# prin... |
64608e47e768e3d4a26070a157f5c805c22f63dd | azegun/python_study | /chap07/module_study/module_with.py | 1,081 | 3.53125 | 4 | #파일을 생성하고 + 파일 이름을 변경합니다.
import os
with open("original.txt", "w") as file:
file.write("hello")
os.rename("original.txt", "new.txt")
#파일을 제거합니다
os.remove("new.txt")
std_list = [["1", "김상건", 90, 80, 70],
["2", "이나연", 80, 80, 60]]
if not os.path.exists("../std_list.txt"):
# if os.path.isfile("st... |
9129d1802695e6d8ef1db2fbff28a6a0cb29e203 | JasonCheng1/Sudoku-Game | /Past Versions/PreSudoku.py | 2,498 | 3.890625 | 4 |
board = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4,... |
0ccc50990d10f40e5695365ea19a643a7af14540 | Zhenye-Na/leetcode | /python/917.reverse-only-letters.py | 1,589 | 3.8125 | 4 | #
# @lc app=leetcode id=917 lang=python3
#
# [917] Reverse Only Letters
#
# https://leetcode.com/problems/reverse-only-letters/description/
#
# algorithms
# Easy (59.56%)
# Likes: 1163
# Dislikes: 47
# Total Accepted: 112.6K
# Total Submissions: 185.9K
# Testcase Example: '"ab-cd"'
#
# Given a string s, reverse ... |
ada59bc04c4ce2767ae2fed7501a66fb7ab579fd | MiroslavPK/Python-OOP | /01 - Defining classes/Exercise/06 - Pokemon/project/trainer.py | 1,001 | 3.703125 | 4 | from project.pokemon import Pokemon
class Trainer:
def __init__(self, name: str):
self.name = name
self.pokemon = []
def add_pokemon(self, pokemon: Pokemon):
if pokemon in self.pokemon:
return 'This pokemon is already caught'
self.pokemon.append(pokemon)
r... |
c0f609852171585583e3c7474350aaf8a42f1f52 | MKDevil/Python | /学习/6、第六部分 - 类和OOP/26、类的编写基础/1、类的编写基础.py | 2,045 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 示例一、定义类--------------------------------------------------------
class FirstClass():
def setdata(self, value):
self.data = value
def display(self):
print(self.data)
x = FirstClass()
x.setdata(99)
y = FirstClass()
y.setdata(88)
x.display()
y.disp... |
ab90c5a180f4a49bbf5c64062f7049add4b3da8f | MakarVS/GeekBrains_Algorithms_Python | /Lesson_3/Check/hw_nekrasov_lesson_3/les_3_task_4_nek.py | 1,216 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 4 12:01:37 2020
@author: Nekad
"""
# =============================================================================
# 4. Определить, какое число в массиве встречается чаще всего.
#Если искомый элемент(ы) встречается в массиве несколько раз, используйте один любой по ваше... |
195df4d2de4aa76a02cbb6f6ace83861e818527c | frankier/apertium | /apertium-tools/scrapers-misc/kkitapNameFixer.py | 887 | 3.65625 | 4 | #!/usr/bin/env python3
import sys
import fileinput
import sys
if len(sys.argv) < 2:
files="kaz.bible.kkitap.txt"
else:
files=sys.argv[1]
for line in fileinput.input(files, inplace=True):
# for line in lines:
#print(lines)
i=0
j=0
line=line.strip()
if "Патшалықтар 1" in line or "Патшалы... |
7037f4717a933499345a69f09222e799bd612ab1 | alex-moffat/Python-Projects | /Snippets/SQLITE_assignment.py | 8,426 | 4.09375 | 4 | # PYTHON: 3.8.2
# AUTHOR: Alex Moffat
# PURPOSE: The Tech Academy Bootcamp - SQLITE ASSIGNMENT
#=============================================================================
"""
TAGS:
SQL, sqlite3.version, error handling, connect, cursor, execute, CREATE, INSERT, SELECT
slice, upper, fetchall, executescript, 'with' s... |
487ba07c41449c775970653e3fb4d03f6720caf9 | GaneshDesk/Python-Programs | /.history/Python_Basic_Programs/Sum_of_Digits_20200821205105.py | 378 | 4.28125 | 4 |
# program to calculate sum of digit of given number.
def SumFunction(n):
tot = 0
while(n > 0):
dig = n % 10
tot = tot+dig
n = n//10
return tot
if __name__ == '__main__':
print("Program for sum of digit of given number")
n = int(input("Enter a number:"))
ret = SumF... |
f28b0653287a74c0dafea59e344c35ba59b054d8 | no4job/WER | /SRC/wer.py | 14,202 | 3.609375 | 4 | # import numpy
import time
import Levenshtein
import re
import os
from io import StringIO
# import csv
import csv_tools
# import editdistance
import collections
def wer(r, h):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time ans space com... |
265458e9a36ae2ac1ebb2189e2573d3ab9e4db48 | deepaksinghcv/self_training_MNIST | /model.py | 1,426 | 3.59375 | 4 | '''contains a NN model for training MNIST'''
import torch
import torch.nn as nn
class MNIST_Model(nn.Module):
'''define a custom NN for MNIST'''
def __init__(self, num_of_input_channels, num_of_output_channels):
'''initialize the model with given channels'''
super(MNIST_Model, self).__init__()
... |
41c488b8ff926e02cc567ad7d9ed6724a672782b | Suoivy/RBF-Neural-Network | /RBFModel.py | 25,086 | 3.59375 | 4 | """"
Date:2017.4.27
Neural Network design homework
Using 3-phases-RBF NN to regression
author:Suo Chuanzhe
email: suo_ivy@foxmail.com
"""
import numpy as np
import time
from sklearn.cluster import KMeans
from scipy.spatial import distance
import matplotlib.pyplot as plt
class RBFModel():
# config model value
... |
955f9fb338854949f7862d18ef9e5a071988d9f2 | rafaelperazzo/programacao-web | /moodledata/vpl_data/82/usersdata/233/42998/submittedfiles/decimal2bin.py | 119 | 3.71875 | 4 | # -*- coding: utf-8 -*
binario=int(input('Digite um número binário: '))
soma=0
while
soma=soma+n*2**i
n=binario%10
|
85be9a41f124a4f914124a1c7bc447eb1812db0d | Yakobo-UG/Python-by-example-challenges | /challenge 48.py | 705 | 4.25 | 4 | #Ask for the name of somebody the user wants to invite to a party. After this, display the message “[name] has now been invited” and add 1 to the count. Then ask if they want to invite somebody else. Keep repeating this until they no longer want to invite anyone else to the party and then display how many people they h... |
fe52f47a23d6a7422475453e86cf9a467ece99c0 | hlcr/Leetcode | /48. Rotate Image.py | 770 | 3.765625 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix)):
for j in range(i, len(matrix)):
matrix[i][j], matrix[j][i] = m... |
f70c05721a5d5569d4d229eff43c7046311a1301 | jashidsany/Learning-Python | /Codecademy Lesson 5 Loops/L5.3_Infinite_Loops.py | 353 | 3.90625 | 4 | students_period_A = ["Alex", "Briana", "Cheri", "Daniele"]
students_period_B = ["Dora", "Minerva", "Alexa", "Obie"]
for students in students_period_A:
students_period_B.append(students) # if you change students_period_B to students_period_A, it will cause an infinite loop
print(students)
# temp variable re... |
f5a6000e29ca7b9c6cb8f2ced47a8899f4871faa | rramosp/20182.python.sols | /utils/student_function/student_PS1_SYNTAX_4.py | 212 | 3.84375 | 4 | ## Ejercicio del estudiante
def fibonacci(n):
f_1=1
f_2=1
suma=0
if(n<3):
return 1
for i in xrange(3,n+1):
suma=f_1+f_2
f_1=f_2
f_2=suma
return suma
|
3ee568a4bee32affc4766cab773e212fe5a25e8c | EEsparaquia/Python_project | /script31_2.py | 960 | 3.75 | 4 | #! Python3
# Programming tutorial:
# Urllib Module import urllib.request
# Basicaly go to
# 'http://pythonprogramming.net'
# and serch basics and filter the
# <p></p> tags to extract thr content
import urllib.request
import urllib.parse
import re
print('''
#####################
# ... |
9e30b8d24b2b2d73ce039cab05d315a108b8b418 | Nep-DC-Exercises/day-7 | /frequency_pattern_1.py | 785 | 4.1875 | 4 | # Given two arrays write a function to find out if two arrays have the same frequency of digits.
array_1 = [1, 2, 3, 4]
array_2 = [1, 2, 3, 4]
frequency_1 = {}
frequency_2 = {}
# populate two dictionaries with key of the number in the array and the value is how frequent it shows up
def frequency(arr1, arr2, dict1, ... |
0e3ef14db7711323ea905ba2a031960d7ac21c22 | vega28/code_challenges | /codewars/mumbling.py | 1,438 | 3.90625 | 4 | # Mumbling
# https://www.codewars.com/kata/5667e8f4e3f572a8f2000039
# Challenge:
# Transform any input string by the given pattern:
# for each character, multiply by the place in the string,
# then capitalize the first one of that character,
# then string them together by dashes.
# Constraints:
# the... |
fe1178387fe03b627620f201c82f27396045ead2 | JMH201810/Labs | /Python/p01310a.py | 771 | 4.625 | 5 | ##Buffet: A buffet-style restaurant offers only five basic foods.
##Think of five simple foods, and store them in a tuple.
##• Use a for loop to print each food the restaurant offers.
##• Try to modify one of the items, and make sure that Python rejects the change.
##• The restaurant changes its menu, replacing two... |
9a0cc1ea58eb6b69cd7544588defd5c48b2325b9 | MATEO19M/ESPE202011-FP-GEO-3285 | /workshops/unit1/WS01HelloWorld/Hello World.py | 430 | 4 | 4 | print("Hello World from Mateo Martinez \n ESPE \n GEO")
# input variables
addend1 = input(" Enter the first number --> ")
addend2 = input(" Enter the second number --> ")
# add two numbers
sum = float(addend1) + float(addend2)
# displaying the sum
print("The sum of {0} and {1} is {2}".format(addend1,addend2... |
2bd3d4fce2853e4196a63ee869aae1a8a9198123 | alcal3/CSS-301-Portfolio | /problem3.4.5.py | 387 | 4.0625 | 4 | #aleks calderon
#5.2.2019
#creating a class w/method that prints greeting and students name
class Student:
def __init__(self, name, major):
self.name = name
self.major = major
def myfunc(self):
print("Good morning, " + self.name)
p1 = Student("Aleks", "Communications")
p1... |
8819849347dbc7f6e0eaada57b02a979637d31b8 | seansliu/Escape-the-Zombies | /ZombieGame.py | 7,410 | 3.5 | 4 | # Zombie Game GUI
#
# Michelle Lee, Sean Liu, Sophie Lucy
from zombie import *
import Tkinter as Tk
from PIL import Image, ImageTk
class ZombieGame:
"""Escape the Zombie Game"""
def __init__(self):
"""define the GUI window"""
self.main_window = Tk.Tk()
self.main_window.title('Escape the Zombies!')
# creat... |
cf9e14be615e4920ace467037c8087728ecb0e6f | arifaulakh/Competitive-Programming | /DMOJ/ship/ship.py | 435 | 3.59375 | 4 | parts = input()
full = "BFLTC"
if parts == full:
print("NO MISSING PARTS")
if parts.count("B") >=1 and parts.count("F") >=1 and parts.count("L")>= 1 and parts.count("T") >= 1 and parts.count("C"):
print("NO MISSING PARTS")
if parts.count("B") == 0:
print("B")
if parts.count("F") == 0:
print("F")
if part... |
0ffcc2caf7a8e3989abe8d03085f67b10d089744 | homutovan/HomeWork2.3 | /main.py | 5,209 | 3.6875 | 4 | valid_symbol = {'(': [1],
')': [0],
'+': [2, lambda oper1, oper2: oper1 + oper2],
'-': [2, lambda oper1, oper2: oper1 - oper2],
'*': [3, lambda oper1, oper2: oper1 * oper2],
'/': [3, lambda oper1, oper2: oper1 / oper2]}
def two_operand... |
ca497649868b45efab43b9bec158d420fa82276d | jlaframboise/StockPrediction | /util_functions.py | 11,393 | 3.515625 | 4 | import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
def apply_rolling(stock, trail_size, predict_length, predict_change=False, trend_classify=False):
"""
A function that takes in a timeseries for a ... |
7cb1e76c1cb95f4e34014dd2b5e0f225fcb6e798 | JagadeeshMandala/python | /python programms/sum of natural numbers.py | 210 | 4.125 | 4 | num=int(input("enter the number"))
if num<0:
print("enter the postive numbers only")
else:
sum=0
while(num>0):
sum+=num
num-=1
print("The sum is",sum)
|
e6fdfe1837a9128e853e867bfb6158b7df12361a | DandyCV/SoftServeITAcademy | /L11/L11_HW1_2.py | 838 | 3.890625 | 4 | #Визначте атрибути fullname та email в класі Employee. При заданих first та last names:
#- В конструкторі сформуйте fullname звичайним з’єднанням через пробіл first та last name.
#В конструкторі сформуйте email з’єднанням first та last name через ‘.’ між ними та приєднуючи
# ‘@company.com’ наприкінці.
class Employee():... |
e4e87e57536067268168f5db77064b21fc26b1d5 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4311/codes/1635_1055.py | 389 | 3.703125 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
from math import*
vi = float(input("Velocidade inicial: "))
an = radians(float(input("angulo: ")))
d = float(input("distancia horizontal: "))
g = 9.8
R = ((vi**2)*s... |
6559fafc1963ca91871f8eb37e1a883bf37a8327 | millenagena/Python-Scripts | /aula06 - desafio 003 soma.py | 148 | 3.890625 | 4 | n1 = int(input('Informe um número: '))
n2 = int(input('Informe mais um número: '))
print('A soma resultante desses números é {}'.format(n1+n2)) |
417f6ecaf27ae5b969e5e22a46270f52165e0aed | IceHilda/HallOfGrandmasters | /coding 1.2.3.py | 686 | 3.921875 | 4 |
# Create a function that takes in a list of numbers
def pwn(numbers=None, art=None):
# default set to none
# If no list provided, ask the user
if numbers == None:
numbers = input("What are your numbers (without spaces)? ")
#numbers = list(numbers)
numbers = [int(x) for x in numbers]... |
3e5237e2d1f3998ad3b42302e8f11fdcf3e6c13a | michaelverano/PracticeWithPython | /renameDates.py | 1,322 | 3.578125 | 4 | #! python3
# renameDates.py - renames filenames with American MM-DD-YY date formats
# to European DD-MM-YY.
import shutil, os, re
# Create a regex that matches files with the American date format.
datePattern = re.compile(r"""(.*?) # all text before the date.
((0|1)?\d)- # one or two digits for month
((0|1... |
10dc1dd13ed43ece05c4d777de720a35e1f1244d | CoderGustavo/ExerciciosPython | /65.py | 628 | 4.0625 | 4 | vezes = soma = maior = menor = 0
continuar = 'S'
while continuar in 'S':
valor = int(input('Digite um valor: '))
continuar = str(input('Deseja continuar? [S/N] ')).strip().upper()[0]
vezes += 1
soma += valor
if vezes == 1:
maior = menor = valor
else:
if valor > maior:
... |
031d71300bba616925c70adad8e63007e625f47c | samrap/algebrasolver | /config/alg.py | 10,915 | 3.953125 | 4 | from __future__ import division
from fractions import Fraction, gcd
import math
"""Algebra calculation module
This module takes user input from the algebra.py module and
processes calculations based on the function called by the user.
Functions in this module should never be called explicitly in
this script, aside fr... |
038d6011227a6cfe626473dd89323a9e4d9bc555 | Kamik423/advent-of-code-2020 | /12.py | 3,009 | 3.828125 | 4 | #!/usr/bin/env python3
from math import cos, radians, sin
from typing import List
import aoc
class Ship:
"""
▲y N 90
│ W ● E 180 ● 0
└──▶x S 270
"""
x: int
y: int
orientation: int
waypoint_x: int
waypoint_y: int
commands: List[str]
d... |
8e878e698cc603c45fc8f59fc3cdce95de5f271e | huangde/Project_Euler-and-Python-Challenge | /Project_Euler/P27.py | 458 | 3.5625 | 4 | import Primelist
from P3 import IsPrime
listb=Primelist.primes(1000)
lista=range(-999,1000,2)
def f1(a,b):
return lambda n:n**2+a*n+b
def Nprime(c):
n=0
nprime=0
while c(n)>0:
if IsPrime(c(n)):
n+=1
nprime+=1
else:
break
return nprime
res=[]
f... |
e032b3741971024ab77674a3b95686fb87d94697 | KIMSIYOUNG/Algorithm-study | /programmers-1/DivideArray.py | 610 | 3.65625 | 4 | '''
파이썬에서 문자열, 튜플, 리스트가 비어있는 경우 False를 반환한다.
return문에서도 and | or 를 사용하면 boolean 유무를 판단하여 리턴한다.
둘을 합치면 return answer or -1 이 가능하다.
- answer가 빈 리스트가 아니면 true이기에 그냥 리턴하고,
빈 리스트라면 false를 리턴하여 or 뒤의 구문이 실행된다.
'''
def solution(arr, divisor):
answer = sorted([v for v in arr if v % divisor == 0])
return answer or ... |
6731f1d1568d941135d74cdbcef070371cb6cc55 | Born-S1nner/simpleCalc | /tablet.py | 1,667 | 4.03125 | 4 | from tkinter import *
window = Tk()
expression = ""
def input_number(number, equation):
global expression
expression = expression + str(number)
equation.set(expression)
def clear_input_field(equation):
global expression
expression = ""
equation.set("Enter the Expression")
def evaluate(equati... |
7f2b7ba2657636a731f522c10d6694510849a9bd | sontekliu/python-note | /python-02/python-04.py | 827 | 4.0625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# 递归函数,如果一个函数在函数内部调用了自身,那么这个函数就是递归函数
def fact(n):
if 1 == n:
return 1
return n * fact(n-1)
print fact(10)
print fact(100)
# 栈溢出
print fact(1000)
# 尾递归是指,在函数返回的时候,调用自身本身,并且return语句不能包含表达式。
# 这样,编译器或者解释器就可已把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会溢出
# 遗憾的是,大多数语言没有针对尾递归做优化,Python也没有... |
0126f30d5acbb541fe7f5c9b09deaac116a6d096 | jethrodaniel/exercism | /python/acronym/acronym.py | 159 | 3.6875 | 4 | import re
def abbreviate(words):
words = re.compile(r'[^a-zA-Z\'?!]').sub(' ', ''.join(words)).split()
return ''.join([x[0] for x in words]).upper()
|
c14b764a3ea115112b347021d4ef66f7fc43c19a | pzfrenchy/SortingMethods | /InsertionSort/InsertionSort/InsertionSort.py | 508 | 3.90625 | 4 | list = [3,2,5,8,4]
for i in range(1, len(list)):
currentValue = list[i] #copy current value to temp location
while i > 0 and list[i-1] > currentValue: #check if index greater than 0 and preceeding value greater than current
list[i] = list[i-1] #shift higher va... |
3919e12eae9de47329e665a8f238bf8a5505bb4d | DavidNovo/ExplorationsWithPython | /ftpExperiments.py | 797 | 3.640625 | 4 | __author__ = 'davidnovogrodsky_wrk'
from ftplib import FTP
ftp = FTP('domainname.com')
ftp.login(user='username', passwd='password')
ftp.cwd('/specific domain or location/location of files/')
# getting a file
def grabFile:
#name off file we want to grab
fileName= 'fileName.txt'
# opening a local file
... |
40107a49deb5b3f2ad8d4c1e79d4769189c924f5 | Widdershin/CodeEval | /challenges/024-simplesorting.py | 1,111 | 4.375 | 4 | """
https://www.codeeval.com/browse/91/
Simple Sorting
Challenge Description:
Write a program which sorts numbers.
Input Sample:
Your program should accept as its first argument a path to a filename. Input example is the following
70.920 -38.797 14.354 99.323 90.374 7.581
-37.507 -3.263 40.079 27... |
82c732e4cb902a915572437ac165ae1c1d1230bf | ChrisLiu95/Leetcode | /easy/Balanced_Binary_Tree.py | 1,169 | 4.125 | 4 | """
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
1... |
d09ac79c0c81eb6c6520483d9db5faaff60bd078 | harishramuk/python-handson-exercises | /193. Important Methods and Functions for Dict keys,values,items1.py | 306 | 3.9375 | 4 | #KEYS & VALUES
d = {100:'A',200:'B',300:'C'}
print(d.keys())
for key in d.keys():
print(key)
print(d.values())
for valu in d.values():
print(valu)
#item method
print(d.items())
for item in d.items():
print(item)
for k,v in d.items():
print(k,'---------',v) |
3de071389f50099ea8bb39632bb4bdb8caae030a | yuvika22/hackerrank-python | /basic/FindingThePercentage.py | 496 | 3.609375 | 4 | # Solution to https://www.hackerrank.com/challenges/finding-the-percentage/problem?h_r=next-challenge&h_v=zen
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
... |
fe48adf7a36ff5dc7dd0d6a30743c6214c6d2db5 | EddieHandford/Speed-Pong | /pong.py | 4,997 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 12:00:59 2019
@author: Eddie
"""
import turtle
import winsound
wn = turtle.Screen()
wn.title("Pong by Eddie")
wn.bgcolor("blue")
wn.setup(width=800 , height=800)
wn.tracer(0)
#while True:
# wn.update()
#
#creating a padd... |
22a64e103ec232d8d51d2360014391f04dd3febf | Ezward/ai-for-robotics | /python/kalman_filter/gaussian.py | 3,492 | 3.5 | 4 | import sys
import math
#
# \frac{1}{\sqrt{2\pi\sigma^{2}}} \times e^{\frac{1}{2}\frac{(x-\mu)^{2}}{\sigma^{2}}}
#
def gaussian(mean, variance, x):
"""
Calculate the probability at x given a gaussian distribution.
:param mean: mean of the gaussian distribution
:param variance: variance of the gauss... |
e241f56a767c82903d1da8976cf362dc5609a483 | JohnMachado11/100-Projects-Python | /05.1_Avg_Height/avg_height_easier.py | 448 | 4.25 | 4 | # AVERAGE HEIGHT OF ALL STUDENTS
# Example input = 67 82 51 31 21
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# Method 1 - Easy
total_height = sum(student_heights)
number_of_students = len(studen... |
11d076db3b191d1a1dd9514ae3473dc86a0ce05c | leaner2/python | /10.1.1读取整个文件.py | 1,689 | 3.8125 | 4 | with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
#10.1.2 文件路径
#绝对路径:with open('C:\users\other_files\text_files\filename.txt') as file_object:
print('\n\n')
#10.1.3 逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
... |
f7572560f518e1ac5e678c79bbce205ff005f08d | singhwarrior/python | /python_samples/chap5/winner.py | 2,670 | 4.0625 | 4 | """
<Problem Statement>
Read race timings of james,julie,mikey,sarah from corresponding input files.
Print the top three performances of each.
<Working Description>
One line is read from all files which correspond to race-time values of each
player.
Each line is splitted by comma. Since comma separated values are no... |
72a3c78ebc5aa2dda8b123a1f396e580a9aaa1d1 | HussainAther/mathematics | /algebra/neuralnetworks/nesterov.py | 2,109 | 3.71875 | 4 | import numpy as np
"""
Nesterov's (Nesterov nesterov) method for proximal gradient descent.
"""
def grad(f, x, deltax):
"""
Compute the gradient numerically using our function f that takes in x as a variable.
"""
xval = f(x) # evaluate the function f at x.
step = f(x + deltax) # step forward with ... |
ecf2ad1669596a3c7467cfa7f463d7d9225d2cb8 | marojas11/MC | /python/exercises/pyworkbook-10.py | 507 | 4.03125 | 4 | import numpy as np
print "Exercise 10:Arithmetic"
print "Create a program that reads two integers, a and b,from the user.Your program should compute and display"
print "The sum of and b"
a=float(raw_input("Please enter a="))
b=float(raw_input("Please enter b="))
print "La suma es: ", a+b
print "La resta b-a es:", b-a
... |
4a07f78d93fe44d5baa928d7d8c2ee1c7c300e12 | Zihan2Wang/Checkers | /turn.py | 8,342 | 3.9375 | 4 | '''
This module contains one class, Turn, which represents the stages of the
current turn.
'''
from constants import NEW_TURN, VALID_PIECE_SELECTED, CHECK_MULTIPLE_JUMPS, \
MOVE_COMPLETE
import random
class Turn:
'''
Class -- Turn
Represents the stages of a player's turn.
... |
f7cf98e69d24d996f7e061598483a609fe5b348b | DOGANAY06/My-python-project- | /librarytobb4days.py | 4,026 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 13:25:25 2019
@author: Doğan AY
"""
import os
dir(os)
#%%
import speech
import time
response = speech.input("Say something, please.")
speech.say("You said " + response)
def callback(phrase, listener):
if phrase == "goodbye":
listener.sto... |
022fcaba4ab02fab876b5d6cb00a63bb81169f87 | jennerwein/whoami | /app/helper.py | 2,723 | 3.671875 | 4 | import math
##############################################################################
# Prettyprint duration of time
def duration(time):
def norm2(zahl):
return(("00"+str(zahl))[-2:])
gesamtzeit=time
dauer=''
# Tage
days = time // (24 * 3600)
if days == 1:
dauer=dauer+str... |
d428c57ec98d625ca335bec9369bf6567845c0c8 | iofall/War | /war.py | 7,029 | 4.15625 | 4 | # A Simple War Game
from random import shuffle
# Two useful variables for creating Cards.
SUITE = 'H D S C'.split()
RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
class Deck:
"""
Deck Class for creating a deck of 52 cards
"""
def __init__(self):
self.cards = []
for suite... |
ce3022538d7a4b1bba134194493ddb9dcbf63571 | SlaoutiYannis/UDACITY-Hippocampal_Volume_Quantification | /out_section2/source_code/utils/volume_stats.py | 2,670 | 4.09375 | 4 | """
Contains various functions for computing statistics over 3D volumes
"""
import numpy as np
def Dice3d(a, b):
"""
This will compute the Dice Similarity coefficient for two 3-dimensional volumes
Volumes are expected to be of the same size. We are expecting binary masks -
0's are treated as background... |
b1f1e1cdf333359b1892158101c7952cb391bdd8 | harmansehmbi/Project17 | /practice17e.py | 258 | 3.6875 | 4 | import re # re -> Regular Expression
# Regular Expression Symbols
quote = "Search the Candle rather than Cursing the Darkness"
result = re.match("Candle", quote) # Match from starting
print(result)
print(type(result))
|
677a27d08b98f30cdd05ed3dad09f614bc7f1d93 | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /solutions/Session03/slicing_lab.py | 1,059 | 4.125 | 4 | #!/usr/bin/env python3
"""
One solution...
"""
def swap(seq):
"""with the first and last items exchanged"""
return seq[-1:] + seq[1:-1] + seq[:1]
assert swap('something') == 'gomethins'
assert swap(tuple(range(10))) == (9, 1, 2, 3, 4, 5, 6, 7, 8, 0)
def rem(seq):
"""With every other item removed"""
... |
eee25bd963e53cee87a3b2cde57db530897b07d2 | reshamj/DataStructures-Algorithms | /romannumbers.py | 1,261 | 4.1875 | 4 | #1. Verify if an roman number is valid
#2. sort an array of roman numbers
import re
import collections
#is it a valid Roman number
def isRoman(inputRoman):
thousand = r'M{0,3}'
hundred = r'(C[MD]|D?C{0,3})'
ten = r'(X[CL]|L?X{0,3})'
digit = r'(I[VX]|V?I{0,3})'
result = bool(re.match(thousand+ hund... |
d184d0427bad72649228740361dc91ea625f1852 | giovane1-8/aulas-AfroDev | /aula_9_continuação.py | 816 | 4.15625 | 4 | # I/O
import os
os.system("cls")
import pandas as pd
df = pd.read_excel("estudo_io_aula_9.xlsx")
print(df.index)
print(df)
# df1 = df.dropna() remove a linha que tiver algum valor nulo em qualquer coluna
df1 = df.fillna(0) # insere um valor para os campos nulos
print(f"================= \n {df1}")
... |
272af9d5315a5e44621c3de72d7b008ab29d9df9 | anahitahassan/The-Python-Bible | /4_Logic/ifStatements.py | 694 | 4.125 | 4 | # 32: if Statements
# python immediately indents the next line.
# if I wrote False instead of true, it wouldn't print.
if True:
print("it worked!")
num1 = 100
num2 = 150
if num1 > num2:
print("num1 is bigger than num2")
else:
print("num1 is less than num2")
# what happens if num1 = num2?
num3 = 400
nu... |
3f404ba3e1791d0d49730a5943fc868f8ac49a24 | giulicom/coding-exercises | /maxAreaHist.py | 431 | 3.640625 | 4 | def maxArea(height):
"""
:type height: List[int]
:rtype: int
"""
i = 0
j = len(height)-1
area = 0
while i < j:
h = min(height[i], height[j])
currArea = h*(j-i)
area = max(currArea, area)
if height[i] > height[j]:
j -= 1
else:
... |
9add4c13c41e03652cefd80821169c236004d793 | masumndc1/zim | /coding/python/header_masum.py | 2,427 | 3.53125 | 4 | #!/usr/bin/python3.4
import sys
from urllib.request import urlopen
from urllib.request import Request
#res=Request('http://www.debian.org')
"""
... here we will pass the url with formate of like
# ./header_masum.py debian.org
"""
template='http://www.{}'
urlreq=template.format(sys.argv[1])
#template.format(sys.... |
3513114b3ba94e2481ac242c87d4c5488a55cffa | utk09/open-appacademy-io | /1_IntroToProgramming/1_Loops/4_sum_nums.py | 340 | 3.953125 | 4 | # Write a method sum_nums(max) that takes in a number max and returns the sum of all numbers from 1 up to and including max.
def sum_nums(max_val):
count = 0
for i in range(max_val+1):
count = count + i
return count
print(sum_nums(4)) # prints 10
print(sum_nums(5)) # prints 15
print(sum_nums(1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.