blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a679a5448777fd29b5615ae51eec64711df6d8a4 | flyingsilverfin/SpotMix | /tools/training_data_db.py | 1,127 | 3.671875 | 4 | import sqlite3
class SimilarityBoundsException(Exception):
pass
class TrackSimilarityDb():
def __init__(self, db_file_path):
self._conn = sqlite3.connect(db_file_path)
self._create_tables()
def _create_tables(self):
""" Create a three column table - track id 1 (text), track id ... |
fc2d4a0139ec3a882240d34fa9266ed5fc05f7d6 | mattvenn/python-workshop | /tutorial/quiz.py | 814 | 4.09375 | 4 | total_questions = 2
current_question = 1
score = 0
#introduction
print "welcome to Matt's quiz!"
print "there are", total_questions, "questions in the quiz"
#function to ask the questions and get the answers
def ask_question(question,answer):
print "-" * 20
print "question", current_question, "of", total_ques... |
02731bbd7b58eb575d7c2801654dbff8e6544f78 | Oshini99/python-turtle-graphics | /makingCircleUsingSquaresRapidWay.py | 275 | 3.65625 | 4 | import turtle
my_turtle = turtle.Turtle()
my_turtle.speed(0)
def makingSquare(lenght,angle):
for i in range(4):
my_turtle.forward(lenght)
my_turtle.right(angle)
for i in range(150):
makingSquare(100,90)
my_turtle.right(11)
|
2ef5180201911778dc816fd0ad05288459ace580 | wuhao2/Python_learning | /数据结构及其应用/Python_datastruct_implement/queue.py | 1,281 | 4.0625 | 4 | # _*_ coding: utf-8 _*_
__author__ = 'bobby'
__data__ = '2017/6/4 15:41 '
# 队列的实现
class Queue(object):
def __init__(qu, size):
qu.queue = []
qu.size = size
qu.head = -1
qu.tail = -1
def Empty(qu):
if qu.head == qu.tail:
return True
else:
... |
fcf734b6ae7b329acecb8237ffd3a796d0133162 | kayvera/python_practice | /array/hashtable.py | 398 | 3.8125 | 4 | # hash table should always be top of mind for a possible solution
dict = {}
dict['a'] = 1
dict['b'] = 2
dict['c'] = 3
print(dict)
print(dict['a'])
for k in dict.keys():
print(dict[k])
for k, v in dict.items():
print(k, ' :', v)
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {k: v for k, v in zip(keys,... |
88f86cc3ad6edab68be2677052309c495932aab0 | nicaibuzhao/day05 | /06-字典的使用.py | 231 | 4.40625 | 4 | # 练习1:定义一个字典类型的变量,输出及查看类型
dic = {"name":"张三","age":123,"sex":"男"}
# 练习2:根据key(age) 使用中括号和get方式字典中的value值
print(dic["name"])
print(dic.get("age")) |
d4b3ec7c4609d35042b8452f11b58329e262643a | petervel/Euler | /problems_026-050/problem30.py | 394 | 3.71875 | 4 | #!/usr/bin/python
__author__ = 'peter.vel'
def digits(number):
number = str(number)
list = []
for i in number:
list.append(int(i))
return list
def is_sum_of_fifths(number):
sum = 0
for i in digits(number):
sum += pow(i, 5)
return number == sum
def main():
sum = 0
for i in range(10, 1000000):
if is_sum... |
171d30a31f5008e5d7cb727b19d0a0f5d43c7a30 | billkd24/python | /conditions.py | 185 | 4.03125 | 4 | age = int (input("Please enter your age:"))
if age >= 18:
print ("Elgible to Drive")
else:
print ("Not elgible to Drive")
print (f"Please come back after {18-age} years.")
|
dec5d647b9225b0a2863702d69e45118cd17e4cf | w1033834071/qz2 | /oldboy/day04/homework.py | 709 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding -*-
#列出商品 选商品
# li = ['手机','电脑','鼠标垫','游艇']
# for i,j in enumerate(li):
# print(i+1,j)
# num = int(input("num:"))
# if num > 0 and num <= len(li):
# good = li[num-1]
# print(good)
# else:
# print('商品不存在')
dic = {
"河北":{
"石家庄":["鹿泉","真诚","元氏"],
"邯郸... |
bf9c33fed299a2db57b9729f82624aa3ca5cb6d9 | vidyasagarr7/DataStructures-Algos | /Karumanchi/Trees/DeepestNode.py | 1,022 | 3.859375 | 4 | import queue
from BinaryTree import BinaryTree
def deepest_node(root):
if root is None:
return
else:
que = queue.Queue()
que.put(root)
node = None
while not que.empty():
node = que.get()
if node.get_left():
que.put(node.get_left())... |
aba41e2227f1e73dff66cf5266477c443932f607 | yaelBrown/pythonSandbox | /usefulPythonFiles/mathHomework.py | 122 | 3.6875 | 4 | import math
def func(a):
return math.pow(a,2) - (6 * a) + 5
for x in range(-2,6):
aa = func(x)
print(f"{x} {aa}") |
c0c7f66a0d9ee3566934c0801f4a0d33f9c735cb | korwil/lessons | /python/p_lesson_6/task2.py | 1,288 | 3.734375 | 4 | # Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
# Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
# Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
# Использовать фор... |
c5b9670f2f8ea047289d554c524f97dfd9bb2031 | twsq/car-velocity-estimation | /recurrent_cnn_polished_yury.py | 11,485 | 3.78125 | 4 | from scipy import misc
import json
import numpy as np
import sys
'''
Implementation of recurrent CNN for predicting velocity. The network first computes
features by applying a CNN to every frame that is put in as input (currently last 5 frames
of each sequence) and then uses these features as input into a recurrent ne... |
57e1d8dd720a11286d178e660c3d61cf9e0e5933 | mgbrouli/Controle.Estoque | /main.py | 2,891 | 3.8125 | 4 | #não esta totalmente funcional, falta realmente criar alguns comandos e no futuro aprender a criar bancos de dados externos para salvar os arquivos
bebidas = []
pereciveis = []
naoPereciveis = []
def cadastro():
while True:
lista = {}
lista.clear()
lista['produto'] = str(input('D... |
558c9fd9aed5fc8ce6d7bed02344e7dcea6e43ce | thezaza101/Python-Code-Snippets | /other/p/SIT742A1/A1P1.py | 5,516 | 3.828125 | 4 | import pandas as pd
'''The first task is to read the json file as a Pandas DataFrame and delete the rows
which contain invalid values in the attributes of “points” and “price”.'''
df = pd.read_json('datasets//wine.json')
df = df.dropna(subset=['points', 'price'])
'''what are the 10 varieties of wine which receives th... |
925512bdd8868822aa354e61f13a70e76a252e43 | tramxme/CodeEval | /Medium/PredictTheNumber.py | 542 | 3.53125 | 4 | import sys, re
def doStuff(num):
seq = [0,1]
while(num > len(seq)):
addSeq = seq[len(seq)//2:]
for n in seq[:len(seq)//2]:
if n == 0: addSeq.append(1)
elif n == 1: addSeq.append(2)
elif n == 2: addSeq.append(0)
seq.extend(addSeq)
print(seq[num])
... |
438aad130f2b87a3faa16391282f9ece3fdc4c35 | wtripp/udacity-cs215-intro-algorithms | /final/final-3_weighted_graph.py | 1,984 | 4.15625 | 4 | #
# In lecture, we took the bipartite Marvel graph,
# where edges went between characters and the comics
# books they appeared in, and created a weighted graph
# with edges between characters where the weight was the
# number of comic books in which they both appeared.
#
# In this assignment, determine the weights betw... |
e80853e568d3b11e2fe6ab68fa0a0fff3728e396 | goncalossantos/Algorithms | /Challenges/CCI/Chapter 01/rotate_matrix_inplace.py | 1,970 | 3.96875 | 4 | class Rotation():
def rotate(self, i, j):
return (j, self.N - i -1)
def __init__(self, i, j, N):
self.N = N
self.get_coordinates_to_rotate(i, j)
def get_coordinates_to_rotate(self, i, j):
self.top = (i,j)
self.right = self.rotate(i,j)
self.bottom = self.ro... |
91e830c34984c65e3e6b19dffbad9fcc16d56669 | Deeklogu/Codek | /fact.py | 70 | 3.5625 | 4 | import math
s=int(input("enter any number"))
print(math.factorial(s))
|
75fc2b455bd9dd48d7b20fa2981fee1f2a49706a | anthonynolan/coding-for-schools | /grades.py | 331 | 4.03125 | 4 | # Get the input
english = input("What grade did you get in English?")
maths = input("What grade did you get in Maths?")
computers = input("What grade did you get in Computers?")
# Change them all to integers
a = int(english)
b = int(maths)
c = int(computers)
print("Your average grade is " + str((int(a) + int(b) + int... |
e321a91b066fc6ee8367ebf7fcef27925284d184 | scobbyy2k3/python-challenge | /pyPoll/main.py | 2,104 | 3.875 | 4 | #import modules
import os
import csv
election_data = "Resources/election_data.csv"
# list names of candidates
candidates = []
# number of votes for each candidate
num_votes = []
# total number of votes
total_votes = 0
# percentage of total votes for each candidate
percent_votes = []
with open(election_data, ne... |
4de807dc7ea0381d03bd98d0c77d4b3a24933b33 | gaurav-dwivedi/mypracticecodes | /Fibonacci 4 methods.py | 692 | 3.65625 | 4 | def fib1(n):
a, b = 0, 1
for i in range(n):
print(a)
a, b = b, a + b
def fib2(n):
if n == 0:
return 0
if n == 1:
return 1
return fib2(n - 1) + fib2(n - 2)
def fib3(n):
c = 0
a, b = 0, 1
while True:
if c > n: return
yield a
a, b ... |
eb6cec76feb86c1601ba06c931c67b268127ee4c | ChetnaRajput/Python-Basics-Day1-2 | /2-factorials.py | 377 | 4.25 | 4 | """
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
"""
n = int(input("Enter a number to calculate factorial:"))
fact =... |
bd828f4715855be2470be81b9d7fd53e48867f3e | Datatu/datascience | /datascience/assignment3/multiply.py | 966 | 3.90625 | 4 | import MapReduce
import sys
"""
Implementation of Matrix multiplication in MapReduce
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
value = record
if(value[0]=='a'):
for i in range(0,5):
mr.emit_intermediate(str(val... |
8813fb2506743db415d641b129ed3c7cc3464d38 | ybillchen/Simple-Examples-Keras | /Keras_linear_fitting.py | 1,406 | 3.578125 | 4 | # 'Keras_linear_fitting' is used to fit linear data with one layer
# created by Bill
from tensorflow import keras as kr
import numpy as np
import matplotlib.pyplot as plt
# generate data and add random noise
x = np.linspace(-1, 1, 200)
np.random.shuffle(x)
y = 0.5 * x + 2 + np.random.normal(0, 0.05, (200, )... |
942a2cab78d72c9dd2b8e58d7f035a0d54370dfd | mahiradayal/foundations | /homework_2/homework-2-part1-dayal.py | 1,315 | 4.15625 | 4 | # Mahira Dayal
# Oct 30, 2020
# Homework 2, Part 1
# Part One: Lists
Numbers = [22, 90, 0, -10, 3, 22, 48]
print(len (Numbers))
print(Numbers[3])
print(Numbers[1]+Numbers[3])
print(sorted(Numbers, reverse=True) [1])
print(Numbers [-1])
print((sum (Numbers))/2)
import statistics
# I didn't want to add and divide, thou... |
7e52cf50f97a380fd642400ed77ac5c0e6e9706a | LukeBrazil/fs-imm-2021 | /python_week_1/day1/fizzBuzz.py | 324 | 4.15625 | 4 | number = int(input('Please enter a number: '))
def fizzBuzz(number):
if number % 3 == 0 and number % 5 == 0:
print('FizzBuzz')
elif number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
print('Buzz')
else:
print(f'Number does not fit requirements: {number}')
fizzBuzz(num... |
88871276907ca035324a4bfb0e4f06cb2064c79a | sakshigoyal58/Python | /PythonDictionary.py | 321 | 3.90625 | 4 | dictionary = {"name" :"sakshi", "name" : "varnit"}
print(dictionary) #wont give error but will take the last one only
dic1 = {"name" : "sakshi", "age" : 23}
for i in dic1:
print(dic1[i])
tuple= (1,2,1,1)
print(sorted(tuple))
x=10
y=x
y=12
z=12
if id(z) == id(y):
print("yes")
else:
print("No")
#pull reques... |
a7a0128e77c0b50df320cc4e38977228e8d8c997 | Shisan-xd/testPy | /python_work/day3_三目运算符.py | 415 | 3.71875 | 4 | """
语法:
条件成立执行表达式 if 条件 else 条件不成立执行表达式
"""
a = 8
b = 2
c = a if a > b else b # 判断a是否大于b,a大于b则执行a变量赋值给c,否则执行b赋值给c
print(c)
# 需求:有两个变量,比较大小 如果变量1 大于 变量2 执行 变量1 - 变量2 否则 变量2 - 变量1
aa = 91
bb = 90
cc = aa - bb if aa > bb else bb - aa
print(cc)
|
9dccb72e337bcc49f565112437d2ac3b37f0ce77 | traviswu0910/Intern_Project | /News_try_and_delete_redundant.py | 609 | 3.578125 | 4 | #抓贅字用,修正清洗資料用
#也可看時間序列變化
import pickle
import pandas as pd
with open('top_news_keys','rb')as f:
data = pickle.load(f)
def show_key_words_with_score():
total_date = pd.date_range('20180101','20200708',freq='d')
total_date = total_date.strftime('%Y%m%d')
for date in total_date:
try:
print(date)
print(data[d... |
fad1ab671b20db6e864fcb4901309182543fc4bf | XuJunhao-jiaojiao/Time | /2级python资料/Python部分/上机练习/2/2.2.py | 97 | 3.578125 | 4 | N=input("请输入一段文字:")
i=0
for l in range(len(N)):
print(N[i])
i=i+1
|
1bcede79f3cf143f12089e1b6987aea4be497fc2 | Aiyane/aiyane-LeetCode | /1-50/搜索旋转排序数组.py | 1,556 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 搜索旋转排序数组.py
"""
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], ta... |
4e3e9e8d4cd97f98eedbf41beb1c653245f87669 | crab-a/hw02 | /statistics.py | 673 | 4.28125 | 4 | def mean(values):
"""
calculate the mean of all values in the iterable 'values'
:param values: iterable containing numbers(int/float/double)
:return: the mean
"""
total = sum(values)
length = len(values)
return total / length
def median(values):
"""
calculate the median of all ... |
c891f30f12fc1e48b967817380b5b2cae4338e27 | pascal19821003/python | /study/tutorial/runoob/7.py | 1,234 | 4.3125 | 4 | #Python 列表(List)
#https://www.runoob.com/python/python-lists.html
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
print("============================")
#list = [] ## 空列表
#list.append('Google') ## 使用 append() 添加元素... |
d86868b1c56b0028c414efb13f74ade56c5ddb99 | Hassan-Sher/DS-Labs | /Quick Sort.py | 485 | 3.921875 | 4 | def quicksort(A,low,high):
if low < high:
p = partition(A,low,high)
quicksort(A,low,p-1)
quicksort(A,p+1,high)
def partition(A,low,high):
i = low-1
pivot = A[high]
for j in range(low,high):
if A[j] <= pivot:
i = i+1
A[i],A[j] = A[j],A[... |
2d06b1366e0745be87a9ad997f745d6235ea5b3f | jbelo-pro/CoffeeMachine | /Problems/Game over/task.py | 229 | 3.671875 | 4 | scores = input().split()
# put your python code here
i = 0
c = 0
for score in scores:
if score == 'C':
c += 1
else:
i += 1
if i == 3:
break
print('You won' if i < 3 else 'Game over')
print(c)
|
e342707bbb1ff14024589b2a8944cdf8df57124c | kumbhani/pingpong | /solution_bitmapXOR2.py | 1,170 | 4.0625 | 4 | '''
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexit... |
619ec1b6a2c44dceffe8f2c9497f6e6193dd1686 | dinabseiso/HW10 | /seventeen2.py | 4,812 | 3.671875 | 4 | #! usr/bin/env python
# seventeen2.py
### Import here
from random import randint
### Body
def draws(file):
with open(file) as fin1:
future_draws = fin1.readlines()
return future_draws
def play_game(file):
"""This function initiates the game. For this particular game, there will be
17 marbles in a jar. Turns... |
e25aa025141e8d1fabd276df4054e0bd7a348f1c | jaychan09070339/Python_Basic | /practice_1/ABCD_Z.py | 132 | 3.828125 | 4 | #!/usr/bin/python
word="A"
num=ord(word)
count=0
while count<=25:
print(word,end="")
num+=1
word=chr(num)
count+=1
|
402794a866d092d623be988b2358ed1285e7c26b | aambrioso1/Effective_Python | /Item42.py | 5,410 | 3.875 | 4 | #!/usr/bin/env PYTHONHASHSEED=1234 python3
"""
Item 42: Prefer Public Attributes Over Private Ones
"""
# Reproduce book environment
import random
random.seed(1234)
import logging # Used for exception handling
from pprint import pprint
from sys import stdout as STDOUT
# Write all output to a temporary directory
imp... |
46c3db3ca5a7bc31051b203406aaaabb3fd1eca0 | NoGroceries/python2021 | /tutorial/numbers.py | 457 | 4.09375 | 4 | # Division (/) always returns a float
print(17 / 3)
print(17 // 3) # 商
print(17 % 3) # 余数
print(4 * 3.75 - 1) # 混合类型时,会将int转换为float
# In interactive mode, the last printed expression is assigned to the variable _
# >>> 8/5
# 1.6
# >>> print(_)
# 1.6
# Python strings cannot be changed — they are immutable.
language ... |
f2f47058972d2b0616d9ddec2133bd5efc334d46 | NiuNiu-jupiter/Leetcode | /137. Single NumberII.py | 1,965 | 3.75 | 4 | """
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2... |
1a0b2059b961d67244c732ea18fbc0c2102e22c0 | trevornagaba/titanic_spyder | /app.py | 7,373 | 3.5625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
# %matplotlib inline
# Import train data
train_df=pd.read_csv("data/train.csv")
train_df.head()
# Determine percentage of missing data
def missingdata(data):
total = ... |
535e4bea1b336ba5c31d7a5e1930601de1e8a519 | prakash4531/Python_basics2 | /11_Text_Alignments.py | 1,003 | 4.3125 | 4 |
# -*- coding: utf-8 -*-
"""
Problem No: 11 (Text Alignments)
"User enter the text (0 < len < 20) and alignment (left, center, right).
print the aligned out put and by adding - to make alignment"
Formula:
-Left:
>>> print 'Praveen'.ljust(width,'-')
Praveen----------
-Right
>>> print 'Praveen'.rjust(w... |
a882d4466d05b55b925e04735602dc860ba6787a | harinisridhar1310/Guvi | /fibonnaic.py | 124 | 3.671875 | 4 | #harini
a=int(input())
first=0
second=1
for i in range(0,a):
print(second)
third=first+second
first=second
second=third
|
19576cdb776a951310d6625b07473defb0d5e77e | JaredLGillespie/OpenKattis | /Python/boundingrobots.py | 755 | 3.828125 | 4 | # https://open.kattis.com/problems/boundingrobots
def walk_think(x, y, c, v):
if c == 'u':
return x, y + v
if c == 'r':
return x + v, y
if c == 'd':
return x, y - v
return x - v, y
def walk_actual(w, l, x, y, c, v):
x, y = walk_think(x, y, c, v)
return min(max(0, x), ... |
5c9a63b08723cad8c03ef299631ae75942f60b4e | hdjsjyl/LeetcodeFB | /29.py | 1,324 | 3.78125 | 4 | """
29. Divide Two Integers
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.34... |
8d1239b00f976c1bf180daf2d41b4a5186703eba | blue0712/blue | /demo25.py | 553 | 3.78125 | 4 | day_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
lengthArray = []
for d in day_of_week:
lengthArray.append(len(d))
print(lengthArray)
print([len(d) for d in day_of_week])
print([d for d in day_of_week if len(d) > 6])
x1, x2, x3, x4, x5, x6, x7 = day_of_week
print(x1, x3,... |
13d9c525a9785751ba2978c7cf6ef943e4fab247 | sethdeane16/projecteuler | /027.py | 665 | 3.5 | 4 | import resources.pef as pef
import time
"""
https://projecteuler.net/problem=27
8.877437829971313
"""
def main():
maxn = 0
answer = 0
for a in range(-1000,1001):
for b in range(-1000,1000):
streak = 0
for n in range(80):
if pef.is_prime(n**2 + (n*a) + b):
... |
7d9f770c4c89d81a98cd3af70b8811948e573a8a | sreeharisreddy/MachineLearning | /RandomForestClassificationExample.py | 2,059 | 3.53125 | 4 | # Loading the library with the iris dataset
from sklearn.datasets import load_iris
# Loading scikit's randomforest classifier library
from sklearn.ensemble import RandomForestClassifier
#loading pandas
import pandas as pd
#loading numpy
import numpy as np
#seeting random seed
np.random.seed(0)
#creating an ob... |
9beea0207e8a6961b8c014f83e6dbeac51ba0388 | adjmunro/origin-srs | /data/scripts/AddEntry.py | 3,160 | 3.71875 | 4 | class WordList:
def __init__(self, filename, n_cols):
self.filename = filename + '.txt' if '.txt' not in filename else filename
self.n_cols = n_cols
self.elements = {}
self.other_files = {}
self.other_keys = []
self.read()
self.add()
def add(self):
... |
9afc83208c7522872bda29d23ca1cd6e1d848b98 | Zerpha-Rova/draw | /line1.py | 333 | 3.65625 | 4 | import turtle as td
from turtle import Turtle as turt
z = -1
wn = td.Screen()
bob = turt()
def line(a,b): ###a=(x1, y1) b=(x2,y2)
bob.penup()
bob.goto(a)
bob.pendown()
bob.goto(b)
bob.penup()
line((70,-50),(110,55))
q = 66
w = (q, q*z)
v = (q*z, q)
line(w,v)
'''u = (((10,100*z),bob.ycor()), (w))
line(u)'''
... |
d5dcc719a6146820a70050797f69c02416abb223 | simonada/AI-Projects | /ANN/Networks.py | 14,787 | 3.546875 | 4 | import numpy as np
import random
verbose = False
monitor_test = True
l1_regularization = False
class Network(object):
def __init__(self, sizes, activationFcns, test_data):
"""
:param: sizes: a list containing the number of neurons in the respective layers of the network.
See proj... |
da721234e24fc476a24ac93d5216948697ba03fe | arfsufpe/scheduler | /scheduler.py | 6,438 | 3.640625 | 4 | '''
Created on 12 de jan de 2020
@author: Rodrigo
'''
from __future__ import print_function
from ortools.sat.python import cp_model
# Each volunteer has a predefined job to do and also predefined is his total number of shifts during the whole month
# for example John is a volunteer (John is a senior) and he's ... |
c78718b0e1afcb6f9d8b11bfe4f905f606135bb8 | V-Plum/ITEA | /lesson_2/homework_2.py | 310 | 3.71875 | 4 | def main():
# Get number
n = int(input("Enter number: "))
# Calculate result
n1 = n + 1
n2 = n - 1
result = n1 ** 2 - n2 ** 2
# display result
print(f"Різниця добутків чисел n+1 та n-1 дорівнює: {result}")
if __name__ == "__main__":
main()
|
b8e176885d95a609f35beb603c8159c22c0f0045 | archerckk/PyTest | /Ar_Script/ar_286_循环分支练习.py | 1,432 | 3.8125 | 4 | """
今天习题:
习题一:
1 用while语句的2种方法输出数字:1到10
2 用for语句和continue 输出结果:1 3 5 7 9
习题二:假设有列表
a = [1,2,3,4,5,6]
1 用for if else 的方法查找数字8是否在列表a里,如果在的话,输出字符串'find',如果不存在的话,
输出字符串'not find'
2 用while语句操作上面的列表a,输出下面结果:
[2,3,4,5,6,7]
"""
# 练习1 用while语句的2种方法输出数字:1到10
print('练习1方法1结果展示:')
x = 1
while True:
print(x)
x... |
ec0ea09be5bc48eca7c73a2736fc813c0245b554 | jpieczar/Euler | /Python/twelve.py | 458 | 3.8125 | 4 | from itertools import accumulate, count
from math import sqrt
def count_factors(num):
sum_ = 2 * sum(num % i == 0 for i in range(1, int(sqrt(num)) + 1))
return sum_
def triangular_numbers():
yield from accumulate(count())
def main():
for triangle_nr in triangular_numbers():
if count_facto... |
c39c9220965bcbb75f947043243cf7d6c21bdd5a | bhanurangani/code-days-ml-code100 | /code/day-2/4.Loops/WhileLoop/WhileLoop.py | 74 | 3.875 | 4 | #this is how while loop is used
i=1
while i < 6 :
print(i)
i += 1 |
d2356e0091cc32fc97af06942f69e653d3753640 | MatthewC221/Algorithms | /license_format.py | 964 | 3.703125 | 4 | # Leetcode: https://leetcode.com/problems/license-key-formatting/description/
# Some of these questions are hella weird to be honest. Quite straight forward, be careful of edge cases.
# Realise there's an elegant way to find out the length of the first group. If you have 8 chars and groups of 3, your first group
# is l... |
a2f38fe8698ad7ded399dbf26dc8dfd1bd8f46bd | jardellx/arcade | /base/181/solver.py | 142 | 3.578125 | 4 | words = input().split(" ")
cont = 0
for w in words:
try:
value = int(w)
cont += value
except:
pass
print(cont) |
e0aaab68845ea2081e62013339c84e4b37d9cb0a | DandyCV/LITS | /Lesson05.py | 720 | 3.625 | 4 | def check_float(s):
if '.' in s:
return True
else:
return False
s = '5.8'
print (check_float(s))
def decor(func):
def inner(*args, **kw):
print('\n')
func()
print('\n')
return inner
@decor
def smart_input():
numbers = input('Введіть кілька чисел через пробіл... |
cfd1602fc6dbc6fc1adfd299bbfeb8db31bc3f34 | Nicolaks/prime-number | /prime-number-master/programm/prime-0.1.py | 930 | 3.96875 | 4 | import os
from math import *
# Function return true if a number is prime.
def is_prime(n):
for i in range(2, int(sqrt(n)+1)):
if n%i == 0:
return False
return True
# Create a while, with a top number, and check if the number
# is prime ans after put him in file.
def launch():
n = int(input("What number shoul... |
2c2423a260c44bfb8c3583863789811a4682cd14 | brookslybrand/CS303E | /CodingBat/Logic-1/in1to10.py | 261 | 3.625 | 4 |
# coding: utf-8
# In[129]:
def in1to10(n, outside_mode):
'''
return True if between 1 and 10 inclusive, or
outside those numbers if outside_mode = True
'''
return ( (not outside_mode and 1 <= n <= 10) or (outside_mode and (n <= 1 or n >= 10) ) )
|
f9f6e29dd029f32c0c80e1c53aba796e2a62e90c | efficacy/aoc2020 | /day14/day14.py | 3,680 | 3.59375 | 4 | import re
import math
BITS = 36
MAX = 0b111111111111111111111111111111111111
def invert(x):
return MAX - x
def double(values, bit):
# print("double:",values,bit)
ret = []
for value in values:
# print("considering:",value)
zero = value & invert(bit)
one = zero | bit
ret... |
0ee18bd49d1d04a1eb865bee71c7d6963d7f6117 | kawaiiblitz/Introduction-to-Computer-Science-Python | /IteracionRecursion.py | 1,859 | 4.03125 | 4 | ###################################### Iteración y Recursión ######################################
# Solución Iterativa - Multiplicación #
def mult_iter(a,b):
result = 0
while b > 0:
result += a
b -= 1
return result # Cuando salga del while manda el resultado #
mult... |
131b39c139ee96c367634e002383b8c4ccd0d220 | davorgraj/SluzbenaVozila | /main.py | 1,453 | 3.78125 | 4 | # -*- coding: utf-8 -*-
from Vehicles import Vehicle, add_new_vehicle, list_all_vehicles, edit_number_of_kilometers_or_date_service, delete_vehicle, save_vehicles_in_txt
def main():
print "Dobrodošl v programu za urejanje vaših avtomobilov"
print ""
vehicles = []
while True:
print ""
p... |
6e2f2468dd4f5dffa7392d34d3860f943a8924e2 | florije1988/manman | /learn/005.py | 226 | 3.515625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'manman'
"""
求 2/1+3/2+5/3+8/5+13/8.....前20项之和?
"""
a = 1.0
b = 2.0
sum = 0
c = 0
for i in range(0, 20):
sum = sum + b/a
c = a + b
a = b
b = c
print(sum)
|
22cd43a4045dd296910b52e4485660aafa89ba53 | irenatrend/Data_Analyst_Nanodegree_Udacity | /Data_Wrangling_With_Mongo_DB/Final Project/AdditionalDataExploration.py | 2,689 | 3.5625 | 4 | #!/usr/bin/env python
import pprint
def get_db(db_name):
from pymongo import MongoClient
client = MongoClient('localhost:27017')
database = client[db_name]
return database
if __name__ == '__main__':
db = get_db('cities')
# Count different Amenities
print "Count different Amenities:"
... |
9221e4f9d26162f25cb37cd9f20045ea35170084 | Charleso19/Python3-Text-Adventure-ex45 | /ex45m.py | 12,242 | 3.78125 | 4 | # As well as built-in modules, I have imported two self-made modules,
# mainly to shorten the current python file and improve readabiltiy
from sys import exit
from random import randint, randrange, choice
from math import sqrt
from textwrap import dedent
from entity_module import CreateEntity
from attack_mod... |
d54e601375118780dfd2572e3618c119d25188f1 | gitter-badger/pymanopt | /pymanopt/solvers/steepest_descent.py | 3,161 | 3.609375 | 4 | """
Module containing steepest descent (gradient descent) algorithm based on
steepestdescent.m from the manopt MATLAB package.
"""
import time
from pymanopt.solvers import linesearch
from pymanopt.solvers.solver import Solver
class SteepestDescent(Solver):
def __init__(self, ownlinesearch=None, *args, **kwargs):... |
025faad9007cb7b8db2ee7234749047d501320f8 | kMatejak/recruitment-tasks-gdansk | /ZADANIE_2_missing_numbers.py | 612 | 3.828125 | 4 | def missing_numbers(m: list, n: int) -> list:
data = {number: None for number in range(1, n + 1)}
missing_numbers = list()
for x in m:
data.update({x: 1})
for number in data:
if data[number]:
continue
else:
missing_numbers.append(number)
return missin... |
fcbfd8faaad28f4bc7f554d8f1e3fe0b409e8a8d | rafaelperazzo/programacao-web | /moodledata/vpl_data/34/usersdata/83/13869/submittedfiles/moedas.py | 403 | 3.859375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a=input('Digite o valor de a: ')
b=input('Digite o valor de b: ')
c=input('Digite o valor de c: ')
if a>=b :
w=c//a
r=(c%a)//b
if (c%a)%b==0 :
print (w)
print (r)
else :
print ('N')
else :
r=c//b
w=(c%b)//a
... |
9c4292fd7559a9ef782a9f1cc52cfe5dbcda8716 | elrion018/CS_study | /beakjoon_PS/no1874.py | 769 | 3.546875 | 4 | n = int(input())
stack = [0]
num = 0
arr_1 = []
arr_2 = []
for _ in range(n):
_input = int(input())
if stack[-1] < _input and _input not in arr_1:
while stack[-1] < _input:
num += 1
if num not in arr_1:
stack.append(num)
arr_2.append("+")
a... |
90a31b9be41e4ba7eef5244f99ab8b5c327e6b25 | adylshanov/Home_Work_Adylshanov | /number_system.py | 2,605 | 3.65625 | 4 | '''
Модуль перевода в разные системы исчисления
'''
__all__ = [
'dec2bin',
'dec2oct',
'dec2hex',
'bin2dec',
'oct2dec',
'hex2dec'
]
def dec2bin(number):
"""Переводит из десятиричной системы в двоичную"""
return code(number, 2)
def dec2oct(number):
"""Переводит из десятиричной системы в восьмеричную"""
return... |
087f25ccdae50bc5d7ecb2ec9acfeac082026593 | James-Lee1/Unit_5-02 | /unit_5-02-1.py | 662 | 4.4375 | 4 | # Created by : James Lee
# Created on : 13 Nov. 2017
# Created for : ICS3UR
# This program shows the largest number in an array
def find_highest_value(arrays = []):
# Finds the highst value in am array
value_number_in_array = 0
for value in arrays:
if value_number_in_array < value:
v... |
b72f97f2746a06e18c4f6faf1838fc68de46e853 | kurund/edx-mit-compscience-python | /bsearch.py | 778 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 2 22:45:31 2017
@author: kurund
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
if len(aStr) == 0:
return False
elif... |
b36580b261d1a705b3e1c32bc3eb543ca2f51631 | blackmoses67/programming-portfolio | /programming/percentcalc.py | 2,347 | 3.53125 | 4 | def main():
#all variables
pts = 0
shotsMade = 0
shotsTaken = 0
reb = 0
ast = 0
stl = 0
blk = 0
mins = 0
games = 1
#start the loop
while games <= 82:
print "\n"
#points per game
p = float(raw_input("Enter Points: "))
pts += p
PPG = pts / games
print "Player scored", p, "Points in this game"
p... |
b589cd6ab904a0883979716a31cc1578731bdf66 | younkyounghwan/python_class | /lab5_2.py | 847 | 3.8125 | 4 | """
쳅터: day 5
주제: 함수
문제:
문자열의 듀플을 매개변수로 받아서, 해당 문자열들을 ','로 한 줄에 연결하여 출력하는 함수 print_sting을 정의한다.
소프트웨어공학과, 정보통신공학과, 글로컬it학과, 컴퓨터공학과를요소로 가지는 튜플을 매개변수로 해서 print_string을 호출한다.
작성자:윤경환
작성일: 18 10 02
"""
def print_string(a): #함수 정의
# 연결된 문자열을 반환
for i in range(0,len(a)): #반복문
print(a[i], end="") #출력
i... |
220e861d868f7d01123ef0416133df59901a1c34 | jknsware/python-crash-course | /chapter_6/person.py | 597 | 4.03125 | 4 | people = []
person = {
'first_name': 'jason',
'last_name': 'ware',
'age': '42',
'city': 'cedar park',
}
people.append(person)
person = {
'first_name': 'stuart',
'last_name': 'ware',
'age': '39',
'city': 'liberty hill',
}
people.append(person)
person = {
'first_name': 'chad',
'last_nam... |
1c241fbc085dcb4ff4df6a7d090f3bac75f69b3f | RobertEJohnson/python-intro | /conditionals.py | 175 | 3.546875 | 4 |
if 3 > 2:
print('The rules of the universe still apply')
elif 2 > 3:
print('I am a 47 foot tall purple platypus bear')
else:
print('How did you even get here?')
|
46c5f93235e2d3f9da0efccab452d7ab29a4e060 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_118/2790.py | 481 | 3.671875 | 4 | from numpy import sqrt,ceil,floor
def palind(n):
if ceil(n)!=floor(n):
return False
n=int(n)
if str(n)==str(n)[::-1]:
return True
return False
def count_palind(a,b):
count=0
for i in range(a,b+1):
if palind(i) and palind(sqrt(i)):
count=count+1
return count
if __name__=='__main__':
fp=open("input.tx... |
9d4969927009e8492c75ef3c9e088cb2910b4c42 | HankDa/UCD_S1_Python_Assignment | /p6_19209435_08Oct/p6p5.py | 1,081 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 15:47:46 2020
@author: Hank.Da
"""
"""
#pseudocode
if enter password == correct password:
print('You have successfully logged in')
else:
print('password incorrect')
print('Plz enter correct passwaord three times')
for loop 3 ti... |
7b80c75808d3a73e75db0dfeaa0e7cbd0f6e4671 | Rishika1983/Python-code-practice | /mumber.py | 223 | 4.1875 | 4 | #The program takes a number n and computes n+nn+nnn
n = int( input('enter your number'))
num = ''
total = 0
for i in range(0,n+1):
num = num + str(n)
print (num)
total = total + int(num)
print(total) |
37879554ca69ceec2c2b1e5c49b2ad93e0e5788a | jdee77/100DaysOfPython | /Day-02/codes/leapyear.py | 427 | 4.28125 | 4 | print("LEAP YEAR")
year = int(input("Enter the year :"))
leapYear = False
# a year is leap year if its evenly divisible by 4
# except evenly divisible by 100
# unless not divisible by 400
if year % 100 == 0:
if year % 400 == 0:
leapYear = True
else:
if year % 4 == 0:
leapYear ... |
06b43121f55062f22988a5b9411f16234b2dd4c9 | pankajdahilkar/python_codes | /gender.py | 402 | 3.921875 | 4 | import csv
name = input("Enter your name ")
with open("Female.csv",'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader :
for field in row :
if field == name:
print(name,"is girl")
... |
ddc06a5b1e493fa6a87bf83aeb93ca25e6784a80 | bespontoff/checkio | /solutions/Blizzard/palindromic_palindrome.py | 780 | 3.828125 | 4 | #!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run palindromic-palindrome
# Write a palindromic program with acheckio(s)function that checks whethers(a string) is a palindrome.
#
# For this task, using "#" is forbidden.
#
# You can use other methods for the function's definition (for example... |
03e98da48b534616b82afb084c7016ff9d225af6 | RAVE-V/python-programs | /matrix and transpose.py | 486 | 3.953125 | 4 | list1=[[1,1,1],[2,2,2],[1,1,1]]
list2=[[1,1,1],[1,1,1],[1,1,1]]
#list3=[[0,0,0],[0,0,0],[0,0,0]]
for k in range(3):
print '|',
for l in range(3):
print list1[k][l],
print '|\n'
print'*********'
f=0
for i in range(3):
for j in range(3):
list2[i]... |
59a1e376ae8bf470a623070f71eca6ea2d2791e4 | InesTeudjio/FirstPythonProgram | /ex3.py | 238 | 4.40625 | 4 | # 3. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
new_string = string [:2] + string[-2:]
print(new_string) |
94c8681ed44e9da010bedd0d54c9d219e0fc6a2e | the-nans/py_repo_4gb | /lesson_4/lesson4_cw6.py | 2,974 | 3.53125 | 4 | """
Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
б) итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл не должен
быть бесконечным. Необходи... |
a2b465ed58bee8e0c11fe4697d7ee694ac3670a6 | guardeivid/aiuta | /Lenguajes/Python/Curso/90-Geolocalizacion.py | 1,291 | 3.625 | 4 | #!/usr/bin/env python 3
# -*- coding: utf-8 -*-
# instalar
# pip install geopy
#
"""
from geopy.geocoders import Nominatim
punto = "22.1577057, -102.2731303"
geolocation = Nominatim()
result = geolocation.reverse(punto)
print result.address # direccion
print(result.latitude, result.longitude)
print result.raw # js... |
99a4f752e7924393936cb57d4a38153024c9089d | johanqr/python_basico_2_2019 | /Tarea5/Ejemplo.py | 1,258 | 3.8125 | 4 | # Misc classes
class misc:
def __repr__(self):
# return the clase name
return self.__class__.__name__
def __str__(self):
# return the clase name
return self.__class__.__name__
class Animal(misc):
def __init__(self, especie):
self.especie = especie
... |
244244432e2911b854fb56d9e5f4acf33a39d2f6 | preetha-mani/IBMLabs | /Calculator.py | 292 | 4 | 4 | first=int(input("enter a first number:"))
second=int(input("enter a second number:"))
add=(first+second)
sub=(first-second)
div=(first/second)
mul=(first*second)
print("The addition is",add)
print("The Subtraction is",sub)
print("The multiplication is",mul)
print("The division",div) |
fc9c76f8a4106e82a687adbabf688476306a179f | wasp-lahis/PED-1s2020 | /lab_06/lab06.py | 1,011 | 3.609375 | 4 | percurso = 33
qtd_nivel_0 = 0
qtd_nivel_1 = 0
qtd_nivel_2 = 0
tempo = 0
tempo_medio = 0.
max_velocidade = 0.
min_velocidade = 1000
soma_tempo = 0
cont = 0
tempo = float(input())
while tempo != -1:
if tempo < 180:
qtd_nivel_0 +=1
elif tempo >= 180 and tempo < 240:
qtd_nivel... |
1b2d60ddb87afd52191b3a699003657830bde59d | jannekai/project-euler | /061.py | 741 | 3.53125 | 4 | from collections import OrderedDict
import time
import math
from euler import *
start = time.time()
def triangle(n): return int(n*(n+1)/2)
def square(n): return int(n*n)
def pentagonal(n): return int(n*(3*n-1)/2)
def hexagonal(n): return int(n*(2*n-1))
def heptagonal(n): return int(n*(5*n-3)/2)
... |
cf68801c5aae8c1e5a2182f226e583b0966a36d9 | jaeminjung/algoexpert | /productSum.py | 476 | 3.78125 | 4 | def helpf(array, depth):
ans = 0
while array:
first = array.pop(0)
if type(first) != list:
ans += first * depth
else:
ans += helpf(first, depth + 1)
return ans
def productSum(array):
# Write your code here.
ans = 0
depth = 1
while array:
first = array.pop(0)
if type(first) != ... |
1eb3bede29decc9d40711569f48172c5a9702489 | BharathiSundaravadivel/Practise_Python | /cal_age.py | 1,692 | 4.25 | 4 | '''
-Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
-
-Extras:
-
-Add on to the previous program by asking the user for another number and printing out that many copies of the pr... |
8f308473e75c57c93ee878ee2466277507ae2e79 | Hidayattullah/first_repo | /Example1.py | 141 | 4.0625 | 4 | #Simple example
a = 10
b = 50
if a > b:
print("A more than B")
print(a-b)
else:
print("B more or equal A")
print(b-a)
print("The End") |
1413ee82b38c2178cc0429cd9e755ec8fd3ca370 | DeepaShrinidhiPandurangi/Problem_Solving | /Rosalind/Formatting_FASTA_files/Remove_empty_lines.py | 454 | 3.734375 | 4 | # Remove empty lines from the file
openfile = open("L3_char.txt")
contents = openfile.read()
#print(read)
new_contents = []
for line in contents:
# Strip whitespace, should leave nothing if empty line was just "\n"
if not line.strip():
continue
# We got something, save it
else:
... |
e59fafae44068ba3e52fc104e26454939c334833 | arsummers/python-data-structures-and-algorithms | /data-structures/graph/graph.py | 791 | 3.671875 | 4 | class Graph:
def __init__(self):
self._vertices = []
def add_vertex(self, value):
vert = Vertex(value)
self._vertices.append(vert)
return vert
def get_vertices(self):
return self._vertices or None
def add_edge(self, vert1, vert2, weight=0):
if vert1 in ... |
4aff5328f4d32d46d8fb0273caee126b40bbb844 | andrewrosss/rake-spacy | /rake_spacy/aggregators.py | 1,247 | 3.546875 | 4 | from abc import ABC
from abc import abstractmethod
from typing import List
import numpy as np
class BaseAggregator(ABC):
@abstractmethod
def __call__(self, scores: List[float]) -> float:
"""Reduces a list of numbers to a single number.
Args:
scores (List[float]): The numbers over... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.