blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
4ccb729ebdb80510424aa920666f6b4f0acb5a2a | ErenEla/PythonSearchEngine | /Unit_1/Unit1_Hw3.py | 1,060 | 4.1875 | 4 | # IMPORTANT BEFORE SUBMITTING:
# You should only have one print command in your function
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to ... |
4ed0dc77c6784f2006ca437568f80a73a8d51438 | ErenEla/PythonSearchEngine | /Unit_3/Unit3_Quiz1.py | 504 | 4.15625 | 4 | # Define a procedure, replace_spy,
# that takes as its input a list of
# three numbers, and modifies the
# value of the third element in the
# input list to be one more than its
# previous value.
spy = [1,2,2]
def replace_spy(x):
x[0] = x[0]
x[1] = x[1]
x[2] = x[2]+1
return x
# In the test below, ... |
e431cde89928917d65fb9a3338a6fe947ae03ffa | anhpt1993/leap_year | /leap_year.py | 719 | 3.75 | 4 | # leap year
def check_year(year):
if year % 400 == 0:
return True
elif (year % 4 == 0) and (year % 100 != 0):
return True
else:
return False
def input_data():
while True:
try:
year = int(input("Nhập một năm bất kỳ đi nhé: "))
return year
... |
c3dd07ea8a873b0fbb1efa7c180217cee2520b0d | Surajsah9/my_new-_js_code | /SAI_K/lists/nlist1.py | 314 | 3.6875 | 4 | names=["sai","roshan","vishal","ranjan","ankit","shabid"]
ages=[23,23,20,22,21,22]
lenn=len(names)
lena=len(ages)
print(len(names))
print(len(ages))
n_a=[names,ages]
print(n_a)
print(len(n_a))
index=0
if lenn==lena:
while index<lenn or lena:
print(names[index],":",ages[index])
index+=1
print() |
fb8e8a39f39b53a33de931f8eafe93e2e5b9080d | Surajsah9/my_new-_js_code | /SAI_K/lists/listqn.py | 205 | 3.578125 | 4 | numbers=[50, 40, 23, 70, 56, 12, 5, 10, 7]
index=count=0
while index<len(numbers):
if numbers[index]>20 and numbers[index]<40:
count+=1
else:
pass
index+=1
print(count)
print() |
1b351721aa8fc9cbd1356e9319f64c73063b72d8 | Surajsah9/my_new-_js_code | /SAI_K/lists/count.py | 412 | 3.65625 | 4 | a=[1,1,2,2,3,3,4,5,5,6,6,6,7,7,8,8,9]
b=[i for i in a if a.count(i)>1]
print(b)
print()
a=[1,1,2,2,3,3,4,5,5,6,6,6,7,7,8,8,9]
b=[]
for i in a:
if a.count(i)>1:
b.append(i)
print(b)
print()
a=[1,1,2,2,3,3,4,5,5,6,6,6,7,7,8,8,9]
b=[i for i in a if a.count(i)<2]
print(b)
print()
a=[1,1,2,2,3,3,4,5,5,6,... |
45fe88aef87d198e7ab30abff86ba2f190a20852 | wraikes/cakeday | /src/cakeday/cakeday.py | 422 | 3.71875 | 4 | #! /usr/bin/env python3
from operations import create, delete
def main():
print("Please type an option from the following:")
print("'create' or 'delete' records, or 'get' all records: ")
option = input("create, delete or get: ")
if option == "create":
create()
elif option == 'delete':
... |
206639d10f12c413214c5cf545c5dd4133ec73ff | Dmarcano/Kmeans | /.vscode/kmeans.py | 16,597 | 3.6875 | 4 | #%% [markdown]
## K means algorithm
# The following code implements the k-means algorithm
# for a set of given n-vectors belonging to the kth cluster denoted by x_i,
# we try to find some representative z vectors z_k such that
# J_cluster_distance is as small as can be
# for each vector x_i ... |
3a56f2a71a1e853008cea39c6362b2cebd8480be | Institute-for-Risk-and-Uncertainty/battleships | /BattleshipABM.py | 4,621 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
@title: You sank my battleship!
@date: 22 Jan 2021
@author: ferson
"""
import numpy as np
from numpy.random import *
import matplotlib.pyplot as plt
from time import sleep
#seed(0) # comment out to randomize
n = 102 # length of each ... |
9f2df8df4efc0763760edc6623cc5ad156c38770 | mlaky88/BinaryReal | /binary/binarydeold.py | 4,477 | 3.5 | 4 | import random as rnd
import copy
class SolutionDE:
'''Defines particle for population'''
def __init__(self, D):
self.D = D
self.Solution = []
self.numActiveFeatures = 0
self.F = 1.0
self.Cr = 0.9
self.Fitness = float('inf')
self.gene... |
2261cf64e1f6fb2903701c9d31528e38e68cbea9 | MacHu-GWU/six-demon-bag | /02_Python_Cookbook/object_oriented_programming/magic_attributes/_note___dict__.py | 1,105 | 3.8125 | 4 | ##################################
#encoding=utf8 #
#version =py27, py33 #
#author =sanhe #
#date =2014-10-29 #
# #
# (\ (\ #
# ( -.-)o I am a Rabbit! #
# o_(")(") #
# ... |
55310e89425a96189660dafc0e30c19e6f79ce13 | MacHu-GWU/six-demon-bag | /03_Standard_Library/json_and_pickle[Variable_IO]/_note_pickle.py | 1,988 | 3.671875 | 4 | ##################################
#encoding=utf8 #
#version =py27, py33 #
#author =sanhe #
#date =2014-11-15 #
# #
# (\ (\ #
# ( -.-)o I am a Rabbit! #
# o_(")(") #
# ... |
44bc9366ca09d20c777ac54c78a147a522101b10 | MacHu-GWU/six-demon-bag | /02_Python_Cookbook/encode_decode_in_py2_py3/solve_everything.py | 2,684 | 3.828125 | 4 | ##encoding=UTF8
"""
encode, 编码, 即将str按照一定规则编为bytes
decode, 解码, 即按一定规则bytes解释为str
"""
from __future__ import print_function
from __future__ import unicode_literals
def python3_example():
"""在python3中你定义 s = "something" 的时候, 默认是utf-8编码的str
而如果直接写入文本的时候, 如果使用w
"""
s = "中文" # 是str
b = s.encode("utf8"... |
977bdfb9a8f88aacffab638647e767a55835b47c | jsz1/algorithms-and-data-structures | /binarytree_impl.py | 372 | 3.53125 | 4 | from trees.binarytree import BinaryTree
r = BinaryTree('a')
print r.get_root_value()
print r.get_left_child()
r.insert_left('b')
print r.get_left_child()
print r.get_left_child().get_root_value()
r.insert_right('c')
print r.get_right_child()
print r.get_right_child().get_root_value()
r.get_right_child().set_root_value... |
3b75037c47bcd83aa29d920f93626ee0246e5290 | jack456054/codewars | /tic-tac-toe_checker.py | 1,575 | 3.875 | 4 | def isSolved(board):
finish_or_not = True
# Check row:
for line in board:
winner, finish_or_not = check_line(line, finish_or_not)
if winner == 1 or winner == 2:
return winner
# Check column:
for col in range(0, 3):
winner, finish_or_not = check_line([board[0][co... |
11456d67382ae767d9f58ce5521f4884228f98a4 | larsga/py-snippets | /tic-tac-toe/plot.py | 516 | 3.515625 | 4 |
scores = {'x\n' : -1, 'o\n' : 1, '\n' : 0}
def summarize(file):
summary = []
total = 0
count = 0
for line in open(file):
count += 1
total += scores[line]
if count == 1000:
summary.append(total / float(count))
total = 0
count = 0
return s... |
681dfca9e8ffcc2f788a33ea8953ab5f5e034496 | KelsiAnderson/melon.raffle | /version2/raffle.py | 521 | 3.53125 | 4 | """Randomly pick customer and print customer info"""
# Add code starting here
# Hint: remember to import any functions you need from
# other files or libraries
import Random
def randomly_pick_winner(customers):
winner = random.choice(customers)
print(f'reach out to {name} at {email} and tell them they won!'.... |
1721d0a49792536136f29c48bddcc58ed38f878e | wang-sy/cqu_proj_uiserver | /src/test/phone_number.py | 567 | 3.515625 | 4 | import random
def random_phone_number():
# 第二位数字
second = [3, 4, 5, 7, 8][random.randint(0, 4)]
# 第三位数字
third = {
3: random.randint(0, 9),
4: [5, 7, 9][random.randint(0, 2)],
5: [i for i in range(10) if i != 4][random.randint(0, 8)],
7: [i for i in range(10) if i not i... |
f2bd7bcc6e1efeabea39b2df01587288be36f70f | sirk390/shamir | /src/shamir/extended_gcd.py | 402 | 3.5 | 4 |
def extended_gcd(n1, n2):
"""Return (bezout_a, bezout_b, gcd) using the extended euclidean algorithm."""
x, lastx = 0, 1
y, lasty = 1, 0
while n2 != 0:
quotient = n1 // n2
n1, n2 = n2, n1 % n2
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
bezout_a... |
d70c4d9d84a901939f8c8ae2271f5f1d4311564d | SarpongAbasimi/CodeWarPython | /CodeWordReverseString.py | 265 | 3.53125 | 4 | def spin_words(sentence):
index=1
my_array=[]
while index < (len(sentence) + 1):
my_array.append(sentence[(len(sentence)- index)])
index += 1
my_array="".join(my_array)
return my_array
print(spin_words('sroirraw wollef yeH'))
|
497dd74253a1bb16bcabb3e7a179e72ba0bc2276 | SarpongAbasimi/CodeWarPython | /Findtheuniquenumber6kyu.py | 613 | 3.59375 | 4 | a= [ 0, 0, 0.55, 0, 0 ]
def findUniq(arr):
newarray=[]
mydic = dict()
for numbers in arr:
mydic[numbers]=arr.count(numbers)
if mydic[numbers] <= 1:
newarray.append(numbers)
return newarray[0]
print findUniq([ 1, 1, 1, 2, 1, 1])
#second Solution
def find_uniq(arr):
# y... |
d89a924ced1c99c8b25b4bb37c96fad57abdd2a2 | Sundin/advent-of-code-2019 | /day9/intc_comp.py | 8,644 | 3.703125 | 4 |
def run_intcode_computer(program, input):
return run_program(program, 0, input, [])
def get_intcode_computer_ouput(program, input):
result = run_program(program, 0, input, [])
return result[1]
def get_intcode_computer_finished_program(program, input):
result = run_program(program, 0, input, [])
... |
faaee24ebcc0e6ca6b6c744a4f80eb14db894fc1 | Sundin/advent-of-code-2019 | /day4/day4.py | 1,691 | 3.84375 | 4 |
def split_into_digits(number):
digits = []
while number:
digit = number % 10
digits.append(digit)
# remove last digit from number (as integer):
number //= 10
digits.reverse()
return digits
def is_matching(digits):
found_twins = False
for d in range(1, 6):
... |
46be65808951bce8637699a868fc99ba6c1458bf | Sundin/advent-of-code-2019 | /day3/day3.py | 2,996 | 3.78125 | 4 | import math
grid_size = 10000
def combined_distance_to_first_crossing(lines):
line1 = draw_line(lines[0])
line2 = draw_line(lines[1])
crossings = find_all_crossings(line1, line2)
distances = []
for crossing in crossings:
combined_distance = distance_til_crossing(line1, crossing) + distanc... |
98cfbcfa344a246d259992498168448547f378f5 | muskangoyal267/Rock-Paper-Scissor | /rock paper scissors.py | 1,750 | 3.890625 | 4 | array = ["rock", "scissor", "paper"]
player_1 = input("Player-1, Enter your name: ")
player_2 = input("Player-2, Enter your name: ")
def game():
while True:
shoot_1 , shoot_2 = input(player_1 + " and " + player_2 + " shoot-- ").lower().split(',')
if shoot_1 and shoot_2 in array:
... |
8ce3b07ffa0c8609d4dd0eec50415f534f154ab3 | gerssonmg/mineracao_de_dados | /plotando_3D_bar.py | 1,241 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 23:59:02 2018
@author: Gerson
"""
"""
========================================
Create 2D bar graphs in different planes
========================================
Demonstrates making a 3D plot which has 2D bar graphs projected onto
planes y=0, y=1, etc.
"""
from mpl_t... |
3a665583661f22d2d946cd69f66affe74032b887 | Bower312/Tasks | /task3/task3-1.py | 405 | 3.953125 | 4 | name=input("введите слова через пробел? ")
name=name.split(" ") #сплит считает нам слова через пробел
name.sort(key=len) #сорт делает сортировку , лен считает по символом и выставляет по порядку.
print(name)
#ответ получился такой
#['son', 'kraska', 'mashina', 'devochka'] |
f56d342d0c73af9f3d24b8b8171ea22e02539327 | Bower312/Tasks | /task1/task6.py | 315 | 3.90625 | 4 | kb=("Карабалта")
print("1: "+kb[2])
print("2: "+kb[-2])
print("3: "+kb[0:5])
print("4: "+kb[:-2])
print("5: "+kb[::2])
print("6: "+kb[1::2])
print("7: "+kb[::-1])
print("8: "+kb[::-2])
print("9: "+kb[0::]) #- Выводить буквы по счету или в обратном порядке |
c2d3e85a587c11b9bae19348149545584de22a49 | Bower312/Tasks | /task4/4.py | 791 | 4.28125 | 4 | # 4) Напишите калькулятор с возможностью находить сумму, разницу, так
# же делить и умножать. (используйте функции).А так же добавьте
# проверку не собирается ли пользователь делить на ноль, если так, то
# укажите на ошибку.
def calc(a,b,z):
if z == "+":
print(a+b)
elif z == "-":
print(a-b)
... |
539f5aa5d2a41a1928decd0413939a6ac3878a73 | luisestrellar/curso-Introduccion-a-la-programacion | /Casting.py | 291 | 3.921875 | 4 | print("Ingresa el primer valor:")
Num1 = int(input())
print("Ingresa el segundo valor:")
Num2 = int(input())
Suma = Num1 + Num2
Resta = Num1 - Num2
Multiplicacion = Num1 * Num2
Division = Num1 / Num2
print("El resultado es:" * Suma)
# print(Resta)
# print(Multiplicacion)
# print(Division) |
f8615997bf18e666d51c58f6e20f4d9783a7a1aa | lershat/lab | /Lab_Alg/Lab3/Sureken.py | 463 | 3.53125 | 4 | import turtle
def sur_draw(size, n):
if n == 0:
turtle.forward(size)
else:
sur_draw(size / 3, n - 1)
turtle.right(75)
sur_draw(size / 3, n - 1)
turtle.left(120)
sur_draw(size / 3, n - 1)
turtle.right(75)
sur_draw(size / 3, n - 1)
... |
a6a8a3c87fe930c93693cb273ff7968047f05f31 | YolieQQQ/AtCoder | /abc174/c.py | 326 | 3.609375 | 4 | def sevens():
num = 7
while True:
num = num*10+7
yield num
if __name__ == '__main__':
K = int(input())
for i, sv in enumerate(sevens()):
if sv%K==0:
print(sv)
print(i+2)
quit()
if K<=i:
print(-1)
quit()
... |
440d948350d2b66218a97d682dbd5786532fb6f0 | will8595/PILED | /city.py | 1,462 | 3.609375 | 4 | #!/usr/bin/env/ python
import time
import effects
when = input("Current 24 hr time: ")
hr = int(str(when)[:2])
min = int(str(when)[-2:])
hr *= 3600
min *= 60
when = hr + min
print(hr, min, when)
length = input("How long in minutes? ")
length *= 60
start = time.time()
end = time.time()
firstRun = True
diff1 = time.time(... |
5f2b9bc9b1e08b0c6b1fe9d1ad497006827ddb00 | NicolasDemangeat/AlgoInvest-and-Trade | /optimized.py | 2,811 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import sys
def get_actions_list(data_doc):
"""Load CSV and format data.
Args:
data_doc ([.CSV]): [.csv file with invest data]
Returns:
[list]: [name, price, profit]
"""
with open(data_doc) as csv_file:
csv_list = l... |
58dfc49363c201deaa55ca538f50131ef536fac1 | adeelbhatti88/LeetCode-Practice | /Decompress Run-Length Encoded List.py | 233 | 3.640625 | 4 | print("hello world")
nums = [1,2,3,4]
answerList = []
def DecompressRLElist(list):
lengthOfList = len(nums)
for i in enumerate(nums):
counter = nums[i]
while counter != 0:
an
print (len(nums)) |
3226de0d005befae715a4f4e6315fced25d09173 | adeelbhatti88/LeetCode-Practice | /TwoSum.py | 1,212 | 4.09375 | 4 | # Input: candies = [2,3,5,1,3], extraCandies = 3
# Output: [true,true,true,false,true]
# Explanation:
# Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids.
# Kid 2 has 3 candies and if he or she receives at least 2 extra candies will... |
66c4d00e9ce49d8570cd7a703d04aef1b6b4d3f6 | iSabbuGiri/Control-Structures-Python- | /qs_17.py | 962 | 4.21875 | 4 | #Python program that serves as a basic calculator
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input... |
8bd69d5c6077386a9e79557a3d1ff83ffe464c1b | iSabbuGiri/Control-Structures-Python- | /qs_2.py | 341 | 4.15625 | 4 | #Leap year is defined as year which is exactly divisible by 4 except for century year i.e years ending with 00.
#Century year is a year which is divisible by 400
year = int(input("Enter a leap year:"))
if (year%4 == 0 and year%100 !=0 or year%400==0 ):
print("The year is a leap year")
else:
print("The year ... |
9f02f87f3c5ba51a028c2884b681e4c69098702b | nicoleta23-bot/string | /probl 2 str.py | 390 | 3.921875 | 4 | s=str(input("dati sirul: "))
import string
sm=0
smic=0
sp=0
special_chars=string.punctuation
for i in s:
if i in string.ascii_uppercase:
sm=sm+1
elif ((ord(i)<=57) and (ord(i)>=48)):
smic=smic+1
if i in special_chars:
sp=sp+1
print("Nr de majuscule este ",sm)
print("... |
58ca1bdd5344031b40618a344400b653b721a26c | richardrcw/python | /treegen.py | 1,424 | 3.515625 | 4 | import math
import random
class tree:
def _insert(self, root, num):
if num < root[1]:
if root[0]:
return 1 + _insert(root[0], num)
else:
root[0] = [None, num, None]
return 1
else:
if root[2]:
return... |
3ba2ea80dcc916bf8e245a2ab518042b9ee55e3e | richardrcw/python | /guess.py | 270 | 4.1875 | 4 | import random
highest = 10
num = random.randint(1, highest)
guess = -1
while guess != num:
guess = int(input("Guess number between 1 and {}: ".format(highest)))
if guess > num:
print("Lower...")
elif guess < num:
print("Higher....")
else:
print("Got it!")
|
9b75d94496342a72f91bd00aae6c65e99e42d2c0 | GramescuDan/JB_Guessing_Game | /Game.py | 3,435 | 3.65625 | 4 | import random
def word_check(wch):
word_list = list(wch)
new_word = ""
for i in word_list:
if i in ['0', '1']:
new_word += i
return new_word
def triad_check(word):
word_list = list(word)
for i in range(3, len(word)):
tri = word_list[i - 3] + word_list[i - 2] + wor... |
de9adc79b613075317aa41d4a1abbf09f81e5c4f | CAANASUUCRE/BachelorDIM-Lectures-Algorithms-2020 | /assignements/Session_1/S1_algotools.py | 4,589 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 15:26:05 2020
@author: vanhouta
"""
import numpy as np
import random
Tab = [10,10,19]
## Documentation for average_above_zero
# @param _table table with number above zero
def average_above_zero(table:list):
Som = 0
## @var _Som
# Sum of all number
... |
39a8ded0fe2865097c6c386cc7105c6c643061d6 | justhonor/Data-Structures | /剑指offter/FindContinuousSequence_41.py | 1,229 | 3.578125 | 4 | #!/usr/bin/python
# coding:utf-8
##
# Filename: FindContinuousSequence_41.py
# Author : aiapple
# Date : 2017-08-17
# Describe: 剑指offter NO.41
#
# 和为S的两个数字 VS 和为S的连续正数序列
##
################################################
def FindContinuousSequence(tsum):
# write code here
if tsum < 3:
return ... |
a7d7a38ce3172132a07cc9f4069fd8b37f782770 | justhonor/Data-Structures | /Sort/HeapSort.py | 2,099 | 3.890625 | 4 | #!/usr/bin/python
# coding:utf-8
##
# Filename: HeapSort.py
# Author : aiapple
# Date : 2017-07-28
# Describe: 堆排序
##
#############################################
#coding: utf-8
#!/usr/bin/python
import random
import math
#随机生成0~100之间的数值
def get_andomNumber(num):
lists=[]
i=0
while i<num:
... |
4c33a43d27dede9366a759d3a40bccffcba92d3a | justhonor/Data-Structures | /Sort/BubbleSort.py | 532 | 4.15625 | 4 | #!/usr/bin/python
# coding:utf-8
##
# Filename: BubbleSort.py
# Author : aiapple
# Date : 2017-07-05
# Describe:
##
#############################################
def BubbleSort(a):
length = len(a)
while(length):
for j in range(length-1):
if a[j] > a[j+1]:
temp = a[j]
... |
4d320542af021e08030eda59e2252a870c8efc14 | justhonor/Data-Structures | /String/Replacement.py | 676 | 3.625 | 4 | #!/usr/bin/python
# coding:utf-8
##
# Filename: Replacement.py
# Author : aiapple
# Date : 2017-07-12
# Describe: 空格替换
## 将字符串中的所有的空格替换成%20
# "l am a student." --> l%20am%20a%20students.
#
#########################################################
def replacement(string):
nString = ""
... |
13ba8da5334bb8db33a3b51dd66aab9a6ab153fa | TyagiAnuj/Coursera---Learn-Python-to-access-web-data | /week4/web-crawer-follow-links.py | 3,117 | 4 | 4 | '''
In this assignment you will write a Python program that expands on http://www.pythonlearn.com/code/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position relative to the first name in the list... |
abca76cf467a4ac1326e35ea91f262bfddd13d53 | axemanz/Labs | /lab1.py | 2,892 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 29 15:28:51 2019
@author: amanz
"""
import time
start = time.time()
def read_file_and_make_set(): #while it reads the file, it splits any
file_set = set(open('words_alpha.txt').read().split()) ... |
5fa5b2390ac0e780a3e4ca139bde3c8dc4aea6a3 | zhangyi123/code_test | /answers.py | 1,570 | 3.71875 | 4 |
'''
Is the way you wrote the second program influenced by writing the first?
The two questions are quite similar, so I could've written one answer function for two questions. However,
The entries in the two questions are still different, for example a number might contain a '*' in one file
but not in the other, so I d... |
2a66a15dc6539606f84cdaef2a852425fe393c4c | jakirkham/yail | /yail/core.py | 10,576 | 3.625 | 4 | __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Oct 20, 2016 11:42$"
import itertools
import math
import toolz.itertoolz
from toolz.itertoolz import (
accumulate,
concat,
count,
first,
peek,
sliding_window,
)
from builtins import (
range,
map,
zip,
)
from f... |
ec9c0c4c68d074571efe0946654fae27dd0a104e | tomaszkyc/film_details_searcher | /film_details_searcher/film_details_searcher/models/select_menu.py | 1,048 | 3.6875 | 4 | class SelectMenu:
def __init__(self, items):
self.items = items
def __str__(self):
return '\n'.join(self.get_menu_items())
def get_menu_items(self):
menu_items = []
for index, item in enumerate(self.items, start=1):
menu_items.append(f"{index}. Movie title: {ite... |
39157dc5170a60fd03844cb1acaffda74c5974af | i812/automate-your-page | /html_generator.py | 4,579 | 3.734375 | 4 | def generate_concept_HTML(concept_title, concept_description):
html_text_1 = '''
<div class="concept">
<div class="concept-title">
''' + concept_title
html_text_2 = '''
</div>
<div class="concept-description">
''' + concept_description
html_text_3 = '''
</div>
</di... |
25dfc14b2e8a98218c48fee68eb07ca4c7f02fad | xingkyh/MicroExpressionRecognition | /model.py | 3,737 | 3.6875 | 4 | from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dropout, Flatten, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.layers import PReLU
def CNN(input_shape=(48, 48, 1), n_classes=8):
"""
参考论文实现
A Compact Deep Learning Model for Robust Facial Expression Recognition
... |
89f1f59ec9522e8e50ae92065062a9b0f025578a | bernalde/GDP_Refomulation_NN | /neural_net/architecture_calculation.py | 4,894 | 3.75 | 4 | """
10-701 Introduction to Machine Learning
Final Project
Generalized Disjunctive Programming (GDP)
Reformulation Classification using Neural Network
Neural Network Implementation using TensorFlow
"""
from __future__ import print_function
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
random... |
e68274f23538f2a9d32b3d6dbf255be9b63e274f | Tashveerr/Python | /Chapter1/Exercise page 71.py | 330 | 3.859375 | 4 | message = "Hello Eric, would you like to learn some Python today?"
print(message)
name = "Eric"
print(name.upper())
print(name.lower())
first_name = "Eric"
full_name = f"{first_name} "
message = f'Albert Einsten once said, "A person who never made a mistake never tried anything new.", {full_name.title()}!'
... |
b4528f5ccab9fe85bfa0eb9e60ceef9a70cb4618 | ZephrFish/RandomScripts | /CVEScan.py | 2,291 | 3.578125 | 4 | # CVE Scanner
# The file should contain one operating system per line. For example:
# Example: python scan_cves.py affected_operating_systems.txt
# Copy code
# Windows
# Linux
import argparse
import requests
def scan_cves(affected_operating_systems_file):
# Read the list of affected operating systems from the file
... |
752c706f891b65a86f27e289b667eb6aee82acf5 | prashantahuja/mongodb_pa | /mongo_pa.py | 551 | 3.671875 | 4 | def insert():
try:
employeeid = raw_input("Enter Employee Id:")
employeename = raw_input("Enter employee Name")
db.employees.insert_one(
{
"id": employeeid,
"name": employeename
}
)
except Exception as ex:
print("exc... |
3e2f290c92b01f674c95ece3df8ef28ad7e4e9b7 | Camm66/8-Puzzle-Algorithms | /EightPuzzle_Tests.py | 6,985 | 3.578125 | 4 | from EightPuzzle import *
# initial states
easy = [1, 3, 4, 8, 6, 2, 7, 0, 5]
medium = [2, 8, 1, 0, 4, 3, 7, 6, 5]
hard = [5, 6, 7, 4, 0, 8, 3, 2, 1]
# goal state
goal = [1, 2, 3, 8, 0, 4, 7, 6, 5]
eightPuzzle = EightPuzzle()
strategy = ["Breadth First", "Depth First", "Iterative Deepening",
"Uniform Cos... |
919eab822ad9c985a083d00a8659034db54589dd | CeciliaTPSCosta/atv-construdelas | /lista1/celsius_fahrenheit.py | 196 | 4.0625 | 4 | # Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit.
celsius = float(input('Diga-me uma temperatura em C \n'))
print(f'{9/5 * celsius + 32}°F')
|
4d737f3cdff3065f1c11c03ed8ce14c8c70b9f74 | CeciliaTPSCosta/atv-construdelas | /lista1/temperatura.py | 220 | 4.15625 | 4 | # Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.
fahrenheit = float(input('Diga-me uma temperatura em F \n'))
print(f'{5 * ((fahrenheit-32) / 9)}°C')
|
05c5f350515e2ddf590a0adcae487883a2be483b | lenarother/BeastBar | /beastbar/animals.py | 2,960 | 4.03125 | 4 | from game import JostlingArea
class Animal:
def __init__(self):
self.strength = 0
self.has_recurring_action = False
self.is_new = False
@property
def name(self):
return self.__class__.__name__
def is_animal(self, name):
name = name.lower()
name = name.... |
efabcf8f6f413c833a75c8cc5e57e556c2d12823 | prathamarora10/guessingNumber | /GuessingNumber.py | 561 | 4.21875 | 4 | print('Number Guessing Game')
print('Guess a Number (between 1 and 9):')
import random
number = random.randint(1,9)
print(number)
for i in range(0,5,1):
userInput = int(input('Enter your Guess :- '))
if userInput < 3:
print('Your guess was too low: Guess a number higher than 3')
elif userInput < 5... |
4deb314c5a74ae9b7906786744f526e2e0e46cca | JulioAaron/python | /potencia_n.py | 299 | 4.09375 | 4 | #Calcular la n-esima potencia de x con ciclos repetitivos
x = int(input("Ingrese un numero:"))
exp = int(input("Ingrese su exponente:"))
producto = x
for i in range(exp-1):
print(x, producto, i)
producto = producto*x
print("%s^%s = %s" % (x, exp, producto))
print("Comprobacion", x**exp)
|
5028bdea19a2981a2abf3d9c649a6e784839ff91 | JulioAaron/python | /zodiaco.py | 5,691 | 4 | 4 |
# Signos del Zodiaco, implementación en python para conocer el signo zodiacal con base en al mes y día de nacimiento
# Algoritmos selectivos
'''Signo Fechas Astro Elemento India China
Aries 21 de marzo - 20 de abril Marte / Plutón Fuego Tejas (fuego) Dragón (5) 5.°
Tauro 21 de abril 20 de mayo Venus / Tierra Tierra P... |
fa7b898e1580f2b98357f1edc0bea5e0e6119ea4 | lky9464/DL_TensorFlow | /BasicTF_MNIST_Input.py | 1,042 | 3.59375 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
# 텐서플로우에 기본 내장된 mnist 모듈을 이용하여 데이터를 로드
# 지정한 폴더에 MNIST 데이터가 없는 경우 자동으로 데이터를 다운로드
# one_hot 옵션은 레이블을 one_hot 방식의 데이터로 만들어 준다.
mnist = input_data.read_data_sets("./mnist/data/", one_hot=... |
4c0de2b24c8a45def300f26d79c3b7ed04ac573c | nOctaveLay/Data_Structure | /Data_Structure_python/Queue/Queue.py | 609 | 4.03125 | 4 | from abc import ABCMeta, abstractmethod
class Queue(metaclass = ABCMeta):
#add element e to the back of queue
@abstractmethod
def enqueue(self,data):pass
#Removes and returns the first element from the queue
#(or null if the queue is empty)
@abstractmethod
def dequeue(self):pass
#Returns the first element of... |
93b6c6ac7965d4f0dac5adfd4b6c3ea82e194d8d | zentaijanos/ProjectEuler | /project_euler_08.py | 1,411 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 10:05:22 2019
Project Euler 8: Largest product in series
@author: zentai
Given a list, 1000 long. Multiply the near 4 elements, and determine the biggest value given sequence.
New N is 13 here.
How to loop properly throug of the list with 4 elem... |
b7d5f737b240fd2310408264bb403416007fd5cb | zentaijanos/ProjectEuler | /project_euler_10.py | 748 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 3 16:25:32 2019
Project Euler 10: Summation of primes
@author: zentai
Loop for 2 million, and detect all primes, and during the loop, sum them up.
"""
import math
import time
start = time.time()
def is_prime(number):
if number > 1:
... |
07b952c512879448decf2de0f9c7872d45a81fc0 | ogiovanniruiz/statics_app | /Statics_OOP/rotate.py | 1,965 | 3.609375 | 4 | import pygame
import math
import time
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
displayWidth = 800
displayHeight = 600
myfont = pygame.font.SysFont("arial", 25) # initializes font
clock = pygame.time.Clock()
gameDisplay = pygame.display.set_mode((disp... |
c7d1d525216cda9a270fec92d228c8fed20c32c1 | miread/cryptography | /rail_fence_cipher/rail_fence_cipher.py | 2,888 | 4.03125 | 4 | def encrypt(contents, key):
result = ""
for n in range(1, key + 1):
# First rail follows a simple distance formula
if n == 1:
distance = 2 * key - 3
count = 0
for letter in contents:
if count == 0:
result += letter
... |
3f8da93995fa4e8f5a61fe178ba12a57740b1a04 | TheLogicalNights/Python-Programming | /Assignment-2/Program2.py | 272 | 4.09375 | 4 | # Problem Statement : Accept one number from user and print that number of * on screen.
def Display(iNo):
while(iNo>0):
print("*")
iNo-=1
def main():
iNo = int(input("Enter a number :\n"))
Display(iNo)
if __name__ == '__main__':
main() |
39cebe0780b8532517dadf4fd04517b9ba79f207 | Carterhuang/sql-transpiler | /util.py | 922 | 4.375 | 4 | def standardize_keyword(token):
""" In returned result, all keywords are in upper case."""
return token.upper()
def join_tokens(lst, token):
"""
While joining each element in 'lst' with token,
we want to make sure each word is separated
with space.
"""
_token = token.strip(' ')
if ... |
c78040d8b6c1a3431411fc27b022a4449742ef23 | abhchennagiri/octopaul | /code/backend/add_missing_points.py | 1,504 | 3.59375 | 4 | # Add the missing data points
import datetime
import pandas as pd
import sys
#input_file = "B0010E1M02.csv"
data=pd.read_csv(sys.argv[1])
array=data.values
def print_missing_points(date1,date2,price):
while(date1 > date2):
print str(date2) + ","+ str(price)
date2 = date2 + datetime.timedelta(d... |
01458c3f0df27f7e1e0e68ad62b0ad4cb127a9f1 | aratik711/python-exercise | /function.py | 181 | 3.875 | 4 | """
This script print time in hours
"""
def minutes_to_hours(minutes, seconds):
hours = minutes / 60 + seconds / 3600
return hours
print(minutes_to_hours(70, 300))
|
8c9890c843a63d8b2fa90098b28594ba1e012d99 | justinhohner/python_basics | /datatypes.py | 1,042 | 4.34375 | 4 | #!/usr/local/bin/python3
# https://www.tutorialsteacher.com/python/python-data-types
#
"""
Numeric
Integer: Positive or negative whole numbers (without a fractional part)
Float: Any real number with a floating point representation in which a fractional component is denoted by a decimal symbol or scientifi... |
6f1205cf5d0ad92fb2ef32948f24d85fba6f9bb9 | zlmcdaniel/ConnectFour | /This thingy.py | 1,319 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 14 14:20:42 2019
@author: sullia4
"""
def clear_board():
board= []
for a in range(6):
board.append(['.'] * 7)
return board
def row_num(col, board):
n = int(len(board) - 1)
while True:
if board[n][col] == ".":
... |
d901f305e0896bcb8fd1c6c99dbe49613334d3eb | pedrofrancal/Python | /aprendendo/testes/testes.py | 1,679 | 3.953125 | 4 | def falarNomeEIdade(nome, idade):
# verificar tipo de idade
print(type(idade))
idade=int(idade)
print(f'Seu nome é {nome}')
if idade >= 18:
print('Você é maior de idade')
else:
print('Menor de idade')
# verificar tipos
print(type(idade))
def validarIdade(idade):
if i... |
3b49beb10f3fa3985cbf3ed91187b5bcebdab997 | tsurrdurr/HexChecksumCalc | /hexcalc.py | 1,268 | 3.765625 | 4 | def main():
while(True):
print(">>")
text = str(input("Enter cmd: ")).upper()
text = get_new_hex(text)
print(text)
def add_colon(text):
text = text.strip()
if(text[0] != ':'):
text = ':' + text
return text
def get_new_hex(text):
try:
text = add_colon... |
9acddfa9dc609fbb3aad91d19c4348dda1aee239 | jsanon01/100-days-of-python | /resources/day4/area_circumference_circle.py | 427 | 4.59375 | 5 | """
Fill out the functions to calculate the area and circumference of a circle.
Print the result to the user.
"""
import math
def area(r):
return math.pi * r ** 2
def circumference(r):
return math.pi * 2 * r
radius = float(input("Circle radius: "))
circle_area = area(radius)
circle_circumference = circu... |
a088d621f6118ea17ce1c583df4ca8b3b2b70a8c | sonamg111/logical_question | /kitne_aaadmi_the3.py | 407 | 3.84375 | 4 | elements_list=[23,14,56,12,19,9,15,25,31,42,43]
index=0
elements_len=len(elements_list)
even_sum=0
odd_sum=0
average=0
average1=0
while index<elements_len:
if elements_list[index]%2==0:
even_sum=even_sum+elements_list[index]
else:
odd_sum=odd_sum+elements_list[index]
index=index+1
average=even_sum/elements_len
a... |
3017e1c539fa6552106adc6b1532891c9ad36439 | ssak32/Tutotrials | /Python/Udemy_PythonCoreAdvanced/functions/calc.py | 178 | 3.875 | 4 | def Calc(a,b ):
x = a + b
y = a - b
z = a * b
u = a / b
return (x, y, z, u)
# Multiple return values are stored in Tuple.
result = Calc(10, 5)
print(result) |
fce00cb9a94f79792570574080f46f4ed312767b | ssak32/Tutotrials | /Python/TestingVS/PythonApplication1/PythonApplication1/LoadJsonData.py | 961 | 3.625 | 4 | import json
from urllib.request import urlopen
class LoadJsonData:
data = []
def getData(self):
return self.data
'''Reading json file'''
class ReadJsonFile(LoadJsonData):
def __init__(self, fileName):
self.fileName = fileName
def read(self):
with open(self.fileName, "r", e... |
101e6b6cf13deb9485f5b4042330ca1083b629e9 | ssak32/Tutotrials | /Python/Udemy_PythonCoreAdvanced/multithreading/usingsubclass.py | 303 | 3.625 | 4 | from threading import *
class MyThread(Thread):
def run(self) -> None: # overriding the run method within Thread class
print(current_thread().getName())
i = 0
while (i < 10):
print(i)
i += 1
t = MyThread()
t.start()
print(current_thread().getName()) |
f6d404ee4c2cb7f1f1fc8bf3e68e7ca202b4a1f4 | ssak32/Tutotrials | /Python/Udemy_PythonCoreAdvanced/controlstatements/evenorodd.py | 139 | 4.125 | 4 | num = int(input('Enter a number: '))
if num == 0:
print('Zero')
elif num%2 == 0:
print('Even number')
else:
print('Odd number') |
fdf7fcd23f695cabe1975a0c60c5dc8018dba7a3 | ssak32/Tutotrials | /Python/TestingVS/PythonApplication1/PythonApplication1/JsontoDictionary.py | 863 | 3.5 | 4 | '''Load Json to Dictionary, loads raw Json data into Multivalue dictionary'''
import operator
from functools import reduce
from itertools import chain
from collections import defaultdict
'''Merge two dictionaries'''
def Merge(dict1, dict2):
res = {**dict1, **dict2}
return res
'''Retaining key, and appending ... |
ced45e783342e117779fc90c07ce7591d9552fee | ssak32/Tutotrials | /Python/Udemy_PythonCoreAdvanced/multithreading/threadcommunicationusingwaitandnitify.py | 805 | 3.703125 | 4 | from threading import *
from time import *
class Producer:
def __init__(self):
self.products =[]
self.c = Condition()
def produce(self):
self.c.acquire()
for i in range(1, 5):
self.products.append("Product_" + str(i))
sleep(1)
print("Product ... |
e2ca488af3efc7e4d8f5bc72be4ac0a3f139edd9 | saumyatiwari/Algorithm-of-the-day | /api/FirstAPI.py | 790 | 4.125 | 4 | import flask
app=flask.Flask(__name__) #function name is app
# use to create the flask app and intilize it
@app.route("/", methods =['GET']) #Defining route and calling methods. GET will be in caps intalized as an arrya
# if giving the giving any configuration then function name will proceed with @ else it will use n... |
4ae8272922c1c18a4497fdfe13ced1d1b85c82ba | saumyatiwari/Algorithm-of-the-day | /LinkedList/Finding middle element in a linked list _ Practice _ GeeksforGeeks.py | 1,404 | 3.5 | 4 | # your task is to complete this function
# function should return index to the any valid peak element
def findMid(head):
# Code here
slow = head
fast = head
# print(head.data)
while( temp_fast.next &temp_fast.next.next):
# print(temp_slow.data,temp_fast.data)
temp_slow = temp_slow.n... |
c1a842c69baa720f09c8245cce9e69e5e64814ea | saumyatiwari/Algorithm-of-the-day | /Stack&Queue/BalancedParanthesis.py | 1,176 | 3.609375 | 4 | def checkBalanced(str):
s=[]
res= True
top=-1
for e in str:
if top==-1:
s.append(e)
top+=1
else:
if e == "{" or e=="[" or e=="(":
s.append(e)
top+=1
else:
if (e=="... |
04ec402e9424060cba7dfca22ebbedaf13235469 | saumyatiwari/Algorithm-of-the-day | /Tree/IterativeHeight.py | 583 | 3.828125 | 4 | class tree:
def __init__(self,val):
self.data=val
self.left=None
self.right=None
def height(self,root):
if root:
q=[]
h=1
q.append(root)
while q:
count= q.len()
h+=1
while count>0:
temp=q.pop[0]
if temp.left is not None:
q.append(temp.left)
if right.temp is not No... |
4c247474c3e2c042cd044e151f5ede0dcdd740b3 | Swagat-Kumar/Competitive_Code_LeetCode | /construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.py | 611 | 3.859375 | 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 buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
def build(pS,pE,iS,iE):
... |
cc7b0eec72d8b2f3c39b4b2ea7c25c480d295cd0 | harineem/Euler | /prob3.py | 567 | 3.640625 | 4 | __author__ = 'harineem'
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
import math
def isPrime(n) :
if(n==2 or n==3 or n==5 or n==7 or n==11): return True
if(n%2==0 or n%3==0 or n%5==0 or n%7==0 or n%10==0): return False
x = int(n/2);
for... |
19f47a5bbd7fcaa57fc36566780840abf7d9aa80 | kolypto/py-mongosql | /mongosql/query.py | 34,449 | 3.609375 | 4 | """
### Creating a MongoQuery
`MongoQuery` is the main tool that lets you execute JSON Query Objects against an SqlAlchemy-handled database.
There are two ways to use it:
1. Construct `MongoQuery` manually, giving it your model:
```python
from mongosql import MongoQuery
from .models import User # Your m... |
b14b54bd3ccff2224304a92ae045164f8c1649a9 | fair-classification-with-perturbations/fair-classification-with-adversarial-perturbations | /robust-fairness-code/naive_training.py | 22,626 | 3.671875 | 4 | """ Functions for training using the naive approach."""
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import tensorflow as tf
import time
import data
import losses
import optimization
import model
import rbc_utils
class NaiveModel(model.Model):
"""Linear model fo... |
1544a910a16011cc302ba6bcb449c0c8887c05ee | msvrk/frequency_dict | /build/lib/frequency_dict/frequency_dict_from_collection.py | 557 | 4.53125 | 5 | def frequency_dict_from_collection(collection):
"""
This is a useful function to convert a collection of items into a dictionary depicting the frequency of each of
the items. :param collection: Takes a collection of items as input :return: dict
"""
assert len(collection) > 0, "Cannot perform the ope... |
f4e554737c17844546f5ec999776e617a90c2be1 | amal-meer/Naive-Bayes-and-KNN-Classifiers | /Naïve Bayes and KNN Classifiers.py | 11,203 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Problem2: naïve Bayes Classifiers
# In[1]:
import pandas as pd
import matplotlib.pyplot as plt
import math
import statistics
from pandas.plotting import scatter_matrix
from sklearn.model_selection import train_test_split
import seaborn as sb
import operator
# ### 1- Load ... |
97188acfb28d75619af4317f30553746d56fcac2 | sjogleka/Illegal_Activity_Recognition | /Illegal_Activity_Detection/class_kalman.py | 1,390 | 3.640625 | 4 | from numpy import *
class Kalman(object):
"""The standard implementtation of the object tracking using Kalman filters"""
def __init__(self):
"""Initialising constants required for calculations"""
self.F = matrix([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],dtype = 'float')
self.H = matrix([[1,0,0,0],[0,1,0,0]... |
3adeaef019c9c3dcd2e767b45d0631cdc4b5a22a | dianaanakman/BasicPython | /example.py | 495 | 4.0625 | 4 | #def greeting(name):
# print('hello',name)
#main program
#input_name= input('enter your name:\n')
#greeting(input_name)
def get order(menu):
orders = []
order = input("what would you like to order? (Q to Quit)")
while (order.uppe() !='Q'):
#find the order
found = menu.get(order)
... |
db9643636c4aec316a6a42db411e91b344d1037d | dianaanakman/BasicPython | /temperature.py | 189 | 3.859375 | 4 | print("hello im your doctor")
temperature = input("Temperature = \n" )
if int(temperature) >= 38:
print("Got COVID!")
else:
print("Demam biasa2")
print("Thanks For Coming To Our Clinic") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.