blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
769c3c101971e5db5cf6937dea786070cfcea123 | wesenu/cs699-Software_lab | /Lab8/code8/binsearch.py | 673 | 3.96875 | 4 | import sys
import math
def binsearch (inputlist,number):
result = -1
low=0
high=len(inputlist)-1
while(low <= high):
mid=int(math.floor((low+high)/2))
if(number == int(inputlist[mid])):
return mid
elif(number < int(inputlist[mid])):
high=mid-1
else:
low=mid+1
return result
#Read file
f = op... |
9c5adf76ece604769986d60b7aea574d910b58f0 | NamibiaTorres/GameZetaSpecial | /IfElseExample.py | 176 | 3.984375 | 4 | while True:
x = int(input('Please input a number: '))
if x == 1:
print("You Sexy")
if x == 2:
print("You so so Saucy")
print("Thank You")
|
4bf944b07d68fcd57304280f2700daf52262e092 | cccui0815/dataStructure | /SegmentTree_2.py | 2,645 | 3.609375 | 4 | # 节点区间定义
# [start, end] 代表节点的区间范围
# max 是节点在(start,end)区间上的最大值
# left , right 是当前节点区间划分之后的左右节点区间
class SegmentTreeNode:
def __init__(self, start, end, x, left=None, right=None):
self.start = start
self.end = end
self.max = x
self.left = left
self.right = right
def __str__... |
79f2c5d2138e9cddcb638d1c2d49d8d6b6f9f4d1 | zepetto7065/study | /알고리즘&자료구조/dongbin_code/6-10.py | 129 | 3.65625 | 4 | n = int(input())
array = []
for i in range(n):
array.append(int(input()))
array = sorted(array, reverse=True)
print(array) |
d183c04cb0c60a9a4130518eb82563d4c119b35f | madebr/ncurses_programs | /python/basics/mouse_menu.py | 2,948 | 3.59375 | 4 | #!/usr/bin/env python
import curses
WIDTH = 30
HEIGHT = 10
startx = 0
starty = 0
CHOICES = [
"Choice 1",
"Choice 2",
"Choice 3",
"Choice 4",
"Exit",
]
def main():
# Initialize curses
stdscr = curses.initscr()
curses.curs_set(False)
stdscr.clear()
curses.noecho()
# Line ... |
792fc61aa7d15b5b5b50661819cc41727d4b5462 | GeorgeRobson/Functions_Parameters-Global_Variables | /diceRoller.py | 1,194 | 3.859375 | 4 | die roll program
#Describe the purpose of this program here.
import random,time
#dice face
s1 = "- - - - -\n| |\n| O |\n| |\n- - - - -\n"
s2 = "- - - - -\n| O |\n| |\n| O |\n- - - - -\n"
s3 = "- - - - -\n| O |\n| O |\n| O |\n- - - - -\n"
s4 = "- - - - -\n| O O |\n| |\n... |
f925b07efb1e6cfa19148218019223137da8a72c | user12986714/SpamSoup | /utils/learn_ms/joinline.py | 5,583 | 3.875 | 4 | #!/usr/bin/env python3
# coding=utf-8
import re
import sys
import pickle
def at_index(string, element_index):
""" Get the string at the specified index of a list seperated by ',' """
len_string = len(string)
current_index = 0
current_ptr = 0
is_in_quote = False
is_escaped = False
while... |
3004bd79405e9ae0ee1b9cf969937564782e2f7d | baris5d/Space-Cakes | /Challenges/Hard/Game-of-Life/gameoflife.py | 2,493 | 3.71875 | 4 | ## Baris Dede
# Conway's Game of Life
line = input().split()
iteration = int(line[2])
matrix = []
width = int(line[1])
height = int(line[0])
for i in range(height):
matrix.append(list(input()))
# Hücrede yaşam var mı?
def isPopulated(ver,hor):
return matrix[ver][hor]=="*"
# Komşu sayısını h... |
ad3cd8084d54ba7302c97d490b060ef4ff93b16d | Viibur/Hour-Counter | /hours.py | 5,694 | 3.984375 | 4 | import csv
from tkinter import *
import os
fieldnames = ['Date','Time','Description']
#function that reads in the csv file
def readable(name):
allrows = []
with open(str(name)+'.csv','r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
... |
d5d404faef12c2549ac70c61f98e03276b9fe6f8 | WeberLiu94/Data-Structure-and-Algorithms-for-Python-1 | /剑指offer/孩子们的游戏.py | 562 | 3.5 | 4 | def LastRemaining_Solution(n, m):
# write code here
number_list = list(range(n))
index = -1 #从0开始循环
count = 1
length = n
while (length != 0):
index += 1
if index == n:
index = 0
if number_list[index] == -1:
continue
if count % m == 0:
... |
545cafb1ca44f3485a4f6bfd11ef05a53e684ac2 | WeberLiu94/Data-Structure-and-Algorithms-for-Python-1 | /Recursion/reverse_string.py | 265 | 4.09375 | 4 | #思路:两两交换,到中间就停下
def string_reverse(s, n, m):
if n == m // 2:
return str(s)
else:
s[n], s[m-n-1] = s[m-n-1], s[n]
return string_reverse(s, n+1, m)
s = 'hel'
x = string_reverse(list(s), 0, len(s))
print(x) |
29095e099a444b200b81a901c639798fde578e13 | WeberLiu94/Data-Structure-and-Algorithms-for-Python-1 | /剑指offer/字符串的排列.py | 211 | 3.6875 | 4 | def fun(a):
b = a[:]
c= []
for i in range(len(a)-1):
a[i], a[i+1] = a[i+1], a[i]
c.append(a)
a = b[:]
print("a", a)
print("b", b)
print("c", c)
a = [1,2,3]
fun(a) |
e313addde3a09f4482cf907bf077360942014898 | WeberLiu94/Data-Structure-and-Algorithms-for-Python-1 | /剑指offer/第一个不重复的字符.py | 547 | 3.515625 | 4 | def FirstNotRepeatingChar(s):
# write code here
str_list = list(s)
temp = str_list[:]
temp.sort()
uiniqe = []
if temp[0] != temp[1]:
uiniqe.append(temp[0])
for i in range(1, len(temp) - 1):
if temp[i] != temp[i + 1] and temp[i] != temp[i - 1]:
uiniqe.append(temp[i... |
8e79b99c17a11c7ffe47f034e32891c2906ba707 | WeberLiu94/Data-Structure-and-Algorithms-for-Python-1 | /sort/冒泡排序.py | 1,050 | 4.03125 | 4 | #原始的冒泡排序 不断的两两比较,将最小的值传到数组的首位,然后减少比较的范围,知道最后一个树
def BubbleSort(array):
length = len(array)
for i in range(length):
for j in range(length-1, i, -1):
if array[j] < array[j-1]:
array[j], array[j-1] = array[j-1], array[j]
return array
#改进版本,增加一个标志位来判断是否需要数据交换,若Flag为False,则... |
0a99c40e1222125be150dd7957fce4b318358486 | gracehaza/AdventofCode2020 | /day01/day02b.py | 1,017 | 3.546875 | 4 | import math
filepath = 'day01input.txt'
with open(filepath,"r") as filenow:
lineslist = filenow.readlines()
for i in range(0,len(lineslist)):
numberstring=lineslist[i]
number = float(numberstring)
sum = 0
for j in range (1,len(lineslist)):
numberstring2 = lineslist[... |
cb7a3578cbc67a33e70bd70f1aa662e8d3433ee6 | kostcher/algorithmsPython | /hw_7/task_1.py | 1,094 | 3.953125 | 4 | # Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив,
# заданный случайными числами на промежутке [-100; 100).
# Выведите на экран исходный и отсортированный массивы.
# Сортировка должна быть реализована в виде функции. По возможности доработайте алгоритм (сделайте его умнее).
import random
... |
26b99c56ad463df8fb29ace9262a1ed2493c8bb9 | kostcher/algorithmsPython | /hw_6/task_1.py | 1,924 | 3.546875 | 4 | # 1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех
# уроков. Проанализировать результат и определить программы с наиболее эффективным использованием памяти.
import sys
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
num... |
4d055de5d26e2eee1e88e34758622bd0a18a9d25 | vickymzheng/601_cse_data_mining | /proj2/map_reduce/mapReduceExamples/test.py | 253 | 3.53125 | 4 | def add1(x): return x+1
print map(add1, [1,2,3])
def isOdd(x): return x%2 == 1
print filter(isOdd, [1,2,3,4])
def add(x,y): return x+y
print reduce(add, range(5))
print reduce(lambda x,y: x+y, filter(isOdd, map(lambda t: t[0], [(1,2),(2,4),(5,3)]))) |
54ccb45fc9052907c7b1b57b6ccd44bd04343454 | gham-khaled/MinMax | /Exercice1/game.py | 2,747 | 3.875 | 4 | import copy
def possible_split(stack):
"""
Get the possible division of 1 stack
:param stack: Number of stack to divide into two stacks
:return: Example 7 --> [[6,1], [5,2], [4,3]]
"""
return [[stack - x, x] for x in range(1, int(stack / 2) + 1)]
class Game:
visited_node = 0
def __i... |
abb1190d5b778f109b877d4c8d0d6caf02c67635 | kkirsanov/articles | /2009-keldysh-Python-robot/simple_program.py | 128 | 3.875 | 4 | a=1
b=2
c=a+b
c+=2
a="123"
b=a+"'asd'"
if a == "123":
print a
else:
pass
a = "1"+2 #cannot concatenate 'str' and 'int' |
5e973a0ae7d65558145901f3b529d23c3abffc98 | caitlingbailey/complementor | /Algorithm test.py | 1,145 | 3.578125 | 4 | import pandas as pd
from Subroutines import scorecalculator,matching, differencescore
'''testing mentor matching algorithm using a sample of 11,000 individuals answers to personality quiz. Sample is split into 1000 'mentees' and 10000 'mentors' '''
#read in the score csv
samplescores=pd.read_csv('data.csv',usecols=ra... |
08db32fe40ef74f1fc9c5b2ed43caeb11b9de6cd | oneoffcoder/nextgencoders | /2020-08-21-python-no-tears/code/04-conditionals.py | 530 | 4.3125 | 4 | # conditionals are if/else statements
# conditionals are how computers make decisions
# lhs < rhs : less than
# lhs > rhs : greater than
# lhs <= rhs : less than or equal to
# lhs >= rhs : greater than or equal to
# lhs == rhs : is equal to
age = 19
if age < 18:
print('minor')
elif age < 25:
print('young adu... |
f9c43d207d9f660b54984a6cb1ef5ef0700efef7 | oneoffcoder/nextgencoders | /2020-08-21-python-no-tears/code/07-fstring.py | 117 | 3.671875 | 4 | # advanced f-string
num_1 = 20
num_2 = 3
print(f'I like {num_1} and {num_2}. {num_1} + {num_2} = {num_1 + num_2}')
|
a600e50c5f290b81831cb798abd79204aa2c3d6c | SonjaAits/thesis-code | /bilstm/BC5CDR-chem/measure_data.py | 174 | 3.5625 | 4 | import json
with open("parsed_data.txt", "r") as f:
data = json.loads(f.read())
count = 0
for item in data:
count +=1
print("Count: " + str(count)) |
b0a70d60bfc8a46e36874bd6d4bde1ff7eb84afc | MS-DDOS/leetcode | /algorithms/146_LRU_Cache/LRU_Cache_OrderedDict.py | 876 | 3.6875 | 4 | from collections import OrderedDict
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
"""
:rtype: int
"""
try:
value = sel... |
3a63e4319ea45c7c2b3804902f261957cb7e51b9 | CodePointer/Generate_Bibtex_From_Csv | /ExtractTitleFromWord.py | 1,231 | 3.9375 | 4 | def get_word_list(file_name):
"""Extract titles from the word list
:param file_name: The input .txt file.
:return: A word list with titles
"""
# Read data from file
word_list = []
word_set = set()
file = open(file_name, 'r')
data = file.read()
file.close()
# Process
data... |
fb0e77ca915c91fb1f894a502190eb824b2d327c | Tapan-24/python | /sum_of_numbers_+series.py | 118 | 3.5625 | 4 | x = int(input("Insert No of elements in series: "))
su_m=0
i = 0
while i<=x:
su_m +=i
i += 1
print(su_m) |
d0613c2e06ba61734f6315fb44555cb2fd92c95a | Tapan-24/python | /divisible.py | 170 | 4.125 | 4 | x=int(input("Insert the numerator"))
y=int(input("Insert the Denomiator"))
if x%y == 0:
print(x,"is Divisible by",y)
else:
print(x,"is Not Divisible by",y)
|
78366af4a9df2e5806e26e164495f852128e07eb | Tapan-24/python | /binnary_search_of_number_of_array.py | 467 | 3.90625 | 4 | from random import random
N=20
array=[]
for x in range(N):
array.append(int(random()*10))
array.sort()
print(array)
number = int(input("search for any number in array: "))
mini = 0
maxi = N-1
while mini<=maxi:
mid = (mini+maxi)//2
if number < array[mid]:
maxi = mid-1
elif number > ... |
b6bd7184fa765b575c8e8be3ee68319af6092fb0 | Tapan-24/python | /sum_row_column.py | 426 | 3.59375 | 4 | from random import randint
col=6
row=6
matrix=[]
sum_col=[0]*col
sum_row=[0]*row
for i in range(row):
myrow=[]
for j in range(col):
myrow.append(randint(0,3))
matrix.append(myrow)
for i in range (row):
for j in range(col):
sum_row[i]+=matrix[i][j]
sum_col[j]+=matri... |
39cb162f430735fbd146e553ce9dadba88c7ae97 | Tapan-24/python | /positive_negative.py | 167 | 4.15625 | 4 | x=float(input("Insert Number"))
if x>0:
print("This Is a POSITIVE number")
elif x<0:
print("This Is a NEGATIVE Number")
else:
print("This Is ZERO")
|
6d4ef8eb8ea0fd56a6124728dba130ceeef8a7e6 | Tapan-24/python | /recycle_item_list.py | 378 | 3.71875 | 4 | def rimg_shift(first,next):
if next<0:
next=abs(next)
for i in range(next):
first.append(first.pop(0))
else:
for i in range(next):
first.insert(0,first.pop())
values=[9,8,7,6,5,4,3,2,1,0]
print(values)
rimg_shift(values,-2)
print(values)
rimg_shift(val... |
56d4913091f1e666277c64072826bd1f04099fa3 | Tapan-24/python | /sum_of_product_of_digit.py | 220 | 3.984375 | 4 | x=abs(int(input("Insert Integer values only : ")))
su_m =0
mu_l =1
while x!=0:
digit = x%10
su_m += digit
mu_l *= digit
x = x//10
print("Sum of Digit is ",su_m)
print("Product of Digit is ",mu_l) |
46c36ec1f859634f5009f0a44b9c8beeb8c6692a | Tapan-24/python | /even_odd_in_digit.py | 223 | 4 | 4 | x= int(input("Enter few numbers without space: "))
eve = 0
odd = 0
while x>0:
if x%2==0:
eve += 1
else:
odd += 1
x = x//10
print("Even numbers are %d and odd numbers are %d"%(eve,odd))
|
7c63fe5a67ef892a3987040721b090de8215c1d1 | mikeharling/HCI4_twitter_emotion_analysis | /emotion_analysis.py | 2,732 | 3.5625 | 4 | """
Analyses the processed tweet tokens and tries to match them
to each emotion dictionary
"""
anger_file = open("dictionary/anger.txt", "r")
disgust_file = open("dictionary/disgust.txt", "r")
joy_file = open("dictionary/joy.txt", "r")
surprise_file = open("dictionary/surprise.txt", "r")
anticipation_file = open("dict... |
4023f8682d86bd5894eb188e4875dab028d00fea | michaelfromyeg/course-compare | /backend/controllers/reader.py | 3,783 | 3.515625 | 4 | import requests
from ics import Calendar
from controllers.course import Course
class Reader:
'''
Course reader to build a course object (friendly for this module) from a .ics file
'''
def __init__(self, url: str, filename: str):
self.cal = None
self.reader_courses = []
self.url... |
42c760f6e1ca563f9142dac18016098160d3a080 | coDeguZo/Learning_Python.py | /Tuples.py | 361 | 3.96875 | 4 | #Strucutre where we can store multiple picses of information.
coordinates = (4, 5) #Tuples with coordinates in it. #Are immutable - cant be changed or modified.
coordinates[1] = 10 #Cannot change the tuple assignment.
print(coordinates[1])
#list are doing the same thing, but Tuples are immutable as you cannot modify ... |
81f45b487b7621e0d65192a4086781244cf1757a | KiaraRaynS/second_day_homework | /computer_guessing.py | 1,472 | 3.90625 | 4 | import random
def computer_guesses():
game_mode = str(input('Mode: Easy or Hard? '))
if game_mode.lower() == str('hard'):
boundary_y = 100
boundary_b = 100
else:
boundary_y = 10
boundary_b = 10
boundary_x = 1
boundary_a = 1
guesses_count = 0
random_number = ... |
a385d9c4b38d3fd74adc28c37e93d8344bdc4140 | freieslabor/FrozenBottle | /UDP_clients_py2/mazegen2d.py | 1,227 | 3.953125 | 4 | #!/bin/false
""" Python module to generate a 2D grid maze. """
class mazecell(object):
__slots__ = ("x","y","mz","tmp","wf","neigh")
/// called from maze(). Init only maze().
def __init__(self,maze,x,y):
self.x=int(x)
self.y=int(y)
self.tmp = None
self.wf=0x0F # wall-flags. UDLR
if not isinstance(mz,ma... |
c5e915ba71af5a3a0b29ad528c6e6ac2e0fd6124 | mdkdoc15/trial-with-vs-code | /TicTacToe/GUI/practice_gui.py | 166 | 3.75 | 4 | import tkinter as tk
#Creates a window
win = tk.Tk()
#Lables the window
win.title("TicTacToe")
#Will keep the window displayed till it is exited out
win.mainloop() |
13d1b8b837af77e7b51226808b55cdf1a046dac9 | jogurdia/python-course-repository | /variables.py | 449 | 4.0625 | 4 | # name of variable = data type
name = "Johan"
print(name)
x = 100
book = "Dracula"
print(x)
print(book)
# Variable names cannot start with numbers
# Variables names should be something easy to understand
# Name conventions
book_name = "Dracula" #Snake Case
bookName = "Dracula" #Camel Case
BookName = "Dracula" ... |
9b100f55274485f5359815455214c54e948683c8 | Aldoil/ProjectToSchool | /ProjectEX4.py | 3,602 | 3.921875 | 4 | """
ZADANIE 4. (10 punktów)
Gra losowa polega na zgadnięciu 6 liczb z przedziału od 1-10, wygrana następuję gdy mamy co najmniej 5 trafień. Kolejność podania liczb jest nieistotna.
Napisz program, który ma celu sprawdzenie prawdopodobieństwa sukcesu w pewnej grze losowej.
Masz przeprowadzić symulację 1000 krotnej próby... |
ca9d8d538cc6bdb42af61da8161b005cc3a10623 | esmeraldastan/Weapon-inventory | /Weapons.py | 3,091 | 3.609375 | 4 | #class start
class Item(object):
def __init__(self, name):
self.name = name
#WEAPONS AT USE
#SUPERCLASS
class Weapons(Item):
def __init__(self, name, damage, weight):
super(Weapons, self).__init__(name)
self.damage = damage
self.weight = weight
... |
02ec795ce72d30b0180220fd868ce782d85f6da6 | jugal404/alpha-q | /rps.py | 867 | 3.953125 | 4 | import random as rd
import time
print ("welcome")
print ("rock,paper,sissor?")
print("please enter r,p,s")
n=(input())
cc=['r','p','s']
co=rd.choice(cc)
if n!='r' and n!='s' and n!='p':
print("invalid input")
else:
time.sleep(1)
print("computer choise is",co)
def op():
if (co=='p' and n=='r') :
... |
a07a5e58705333faa47c0a61c67ebe7b5cae8b8e | xuzhanliang/-Interview-code-python | /剑指offer/04.二维数组中的查找.py | 339 | 3.5625 | 4 | from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
i, j = len(matrix) - 1,0
while i>=0 and j < len(matrix[0]):
if matrix[i][j] > target: i-=1
elif matrix[i][j] < target : j += 1
else:return True
... |
b6c68a98155c8884aa5a8fc586389ee25f358747 | vivianig/exercises-in-programming-style | /07-infinite-mirror/#my-tf-07.py# | 2,295 | 3.71875 | 4 | #!/usr/bin/env python
import re, sys, operator
# Mileage may vary. If this crashes, make it lower
RECURSION_LIMIT = 9500
# We add a few more, because, contrary to the name,
# this doesn't just rule recursion: it rules the
# depth of the call stack
sys.setrecursionlimit(RECURSION_LIMIT+10)
def count(word_list, stopwo... |
8e3b1fdad3ce6976b1017188fcd2e51b38848874 | LenaVolkova/python-project-lvl1 | /brain_games/games/prime.py | 527 | 3.703125 | 4 | import random
RULES = 'Answer "yes" if the number is prime. Otherwise answer "no".'
MIN_NUMBER = 1
MAX_NUMBER = 4000
def is_prime(num):
if num <= 1:
return False
else:
for divider in range(2, num // 2):
if num % divider == 0:
return False
return True
def... |
f4ed33f7177cdce45c2934de0b1a623fbd10acd8 | ysnannaimi8200/ATELIER-PYTHON | /TP PYTHON/atelier.2/AT2.Q4.py | 445 | 3.578125 | 4 | '''la fct commun est pour afficher les nbrs repeter dans les
deux set et de suprimer les nombre non repeter au 1er set '''
def commun(set1, set2):
x = set((""))
for i in set1:
for j in set2:
if i == j: x.add(i)
y = set1.copy()
for i in set1:
if i in x: y.remove(i)
print... |
22d6b4792468dc13f456e9cfdeb9fb1125c91096 | SuyashMishra-dev/cohort_2 | /submissions/sp_002_amit-93/week_12/day_3/session_1/helo_1.py | 105 | 4.09375 | 4 | '''name = input("what is your name? ")
print(name)'''
name = "masai School"
for i in name:
print(i) |
7f4ae1271a3704d5b311bf03e0b9e3e6a5b5a885 | sjayster/python_reads | /decorator_practical.py | 2,427 | 3.96875 | 4 | """
To use multiple decorators on top of the same function, we need to use the functools module and import wraps
Then on top of every wrapper, we need to include @wraps(argument_present_in_the_decorator_function)
"""
from functools import wraps
import time
import logging
def deco_logger(original_fun):
# original... |
9de64df7e9760707c096316213c5fd824ea169d4 | sjayster/python_reads | /graphs.py | 2,510 | 3.921875 | 4 | class Graph(object):
def __init__(self, graph_dict=None):
if not graph_dict:
graph_dict = {}
self.graph_dict = graph_dict
def vertices(self):
return self.graph_dict.keys()
def edges(self):
return self.getEdge()
def addVertex(self, vertex):
if verte... |
d5da63f03175fdcec82f8fe5710553d0e411bac3 | sjayster/python_reads | /stacks.py | 2,250 | 3.921875 | 4 | #!/usr/bin/python
"""
Stack is a LIFO data structure. Meaning, the element that was added towards the end will be removed first.
The elements are added in a sequential fashion.
If elt1 is added to stack[0], elt2 will be added to stack[1]
Higher the index, newer the element. And the newest element will be popped first.... |
c43b1ed9c370ba1b6f00c37c887e2bff2d9ebd38 | sjayster/python_reads | /queues.py | 2,452 | 4.34375 | 4 | #!/usr/bin/python
"""
Queue is a FIFO data structure. Meaning, the element that was added first will be removed first.
If elt1 is added to queue[0], elt2 will be added to queue[0] and elt1 will move to queue[1]
Lower the index, newer the element. And the oldest element will be dequeued first.
Queue order:
_________... |
59db2db10495ec0efa0c6d361dcaa07297ea841e | ireneyaejinnam/intro-to-python-2017 | /problem3.py | 656 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 7 18:25:39 2017
@author: ireneyaejinnam
"""
series = []
series.append([1])
rows = int(input("Enter the number of rows:"))
if rows > 1:
series.append([1,1])
for n in range(2,rows):
row_above = series[n-1]
row_now = [1]
... |
7274e0ec3bae37dc044fe026a5f528c981f2e609 | duncankmckinnon/SyntheticDataGenerator | /SyntheticGenerator/Distribution/Distribution.py | 4,079 | 3.84375 | 4 | import numpy as np
class Distribution:
"""
Distribution class - generates values to be used when weighting
attribute prevalence
Properties:
- name (str) - the object name (Distribution)
- type (str) - the type of distribution (constant, uniform, etc.)
- weights (n... |
04bf581e63397b5281b2d02f11aaf587cb1e5880 | Xx220xX/UFU_Programas | /programas/excel/exc.py | 1,601 | 3.78125 | 4 | #https://realpython.com/openpyxl-excel-spreadsheets-python/#reading-excel-spreadsheets-with-openpyxl
from openpyxl import * # importar tds os modulos
planilha = load_workbook(filename="PYTHON.xlsx") # abre uma planilha ja existente
print(planilha.sheetnames) # mostra os SHEETs existentes
space = planilha.active # she... |
633ce72ac1ba0962690b42980960d83fc436d1a6 | AntonHub00/arabic-and-roman-numeral-conversion | /arabic_to_roman.py | 1,183 | 4.09375 | 4 | import sys
def arabic_to_roman(user_input):
try:
int(user_input)
except Exception:
sys.exit('Enter just numbers')
if int(user_input) > 3999:
sys.exit('Number most be less than 4000')
arabic_num = list(user_input)
# To directly convert arabic digit to roman char depending... |
ab732110904875c9a7e61d7ce66917f670072c18 | PaulFlambard/Python_MaxLinder | /cours_2nde_if&for.py | 1,188 | 3.515625 | 4 | 2 == 1 + 1
14 < 13
12 <= 6 + 6
9 == 3**2 and 12 - 3 != 9
9 == 3**2 or 12 - 3 != 9
if True:
print('bidibix')
if 2 == 4:
print('problème') #ne sera pas affiché car le test est faux#
if 4 < 5:
print('zêta')
k = int(input('Rentrer une valeur :')) #permet à l'utilisateur de choisir la... |
82751b6fc51784024109fd380de6e0dd79c2c1b2 | leohanwww/deep-learning | /误差反向传播法.py | 10,526 | 3.71875 | 4 | 计算损失函数关于权重参数的梯度,使用数组微分在计算上比较费时
根据计算图从左到右传播为正向传播
可以通过反向传播高效计算导数
计算图的反向传播
链式法则
z = t**2
t = x + y
aZ/aX = aZ/aZ * aZ/aT * aT/aX 其实就是 az / aX = az/aT * aT/aX
反向传播即z关于x的导数aZ/aX
这样的好处就是只要关心局部计算,可以计算出x有微小变化时z做出何种变化
加法节点的反向传播
aL/aZ ......aL/az * 1
......aL/aZ * 1
加法节点反向传播原封不动地将右边的值传递到左边,两个加数各获得一份
乘法节点的反向传播
乘法的反向... |
c47713ecee317525008ca3f760db65a5145e9064 | leohanwww/deep-learning | /子类化ndarray.py | 3,732 | 3.75 | 4 | 子类化ndarray
视图投影
视图投影是标准的ndarray机制,通过它你可以获取任何子类的ndarray,并将该数组的视图作为另一个(指定的)子类返回
>>> import numpy as np
>>> class C(np.ndarray): pass
>>> arr = np.zeros((3,))
>>> c_arr = arr.view(C)
>>> type(c_arr)
<class 'C'>
从模版创建
当numpy发现它需要从模板实例创建新实例时,ndarray子类的新实例也可以通过与视图转换非常相似的机制来实现。 这个情况的最明显的时候是你正为子类阵列切片的时候。
>>> v = c_arr[1:]
>>... |
f320b07973c235964109a5dae589b172a17cb72a | bongcoy/Konversi_Bilangan | /konversi.py | 3,255 | 3.984375 | 4 | '''
Kekurangan program :
1. Harus convert bentuk Hexa (yang ada hurufnya) dengan manual, contoh : ketika ada A, maka harus menuliskan 10
2. Tida bisa merubah KE Hexa berbentuk huruf (khusus untuk sisa berangka 10 - 16),
jadi yang tertampil adalah angka 10 - 16 bukan A - G
created by Muhammad Pascal Dewantara, In... |
60f366ce45d158945598dd11ba60bb259f851dcc | tprice2/chapter_progress | /ch_9_practice/ch_9_practice.py | 2,768 | 4.375 | 4 | """
Complete all of the TODO directions
The number next to the TODO represents the chapter
and section that explain the required code
Your file should compile error free
Submit your completed file
"""
import pickle
print("----------Chapter 9.1----------")
# TODO 9.1 Dictionaries
# Finish creating th... |
f320f1e5114cc3e499f4ff0c4eeadc664fe548b0 | yashar-sb-sb/my-codeforces-submissions | /0-99/66/(17817981)[OK]A[ b'Petya and Java' ].py | 303 | 3.640625 | 4 | def f():
a = int(input())
if a <= 127 and a >= -128:
print('byte')
elif a <= 32767 and a >= -32768:
print('short')
elif a <= 2147483647 and a >= -2147483648:
print('int')
elif a <= 9223372036854775807 and a >= -9223372036854775808:
print('long')
else:
print('BigInteger')
f() |
cc1e9d8f5b5aafa006aa295cd7a834953b06956e | yashar-sb-sb/my-codeforces-submissions | /500-599/592/(13981729)[RUNTIME_ERROR]C[ b'The Big Race' ].py | 261 | 3.515625 | 4 | s = input()
s = s.split(' ')
t = int(s[0])
a = int(s[1])
b = int(s[2])
def gcd(a,b):
if(b==0):return a
if(a<b):a,b=b,a
return gcd(b,a%b)
g = a*b//gcd(a,b)
s = t//g*min(a,b)-1
s = s + min(t%g,a,b)
g = gcd(s,t)
print(str(s//g)+"/"+str(t//g))
|
675e5a9fccd470aeadff476e8800989e7576d45a | yashar-sb-sb/my-codeforces-submissions | /500-599/526/(29821015)[OK]A[ b'King of Thieves' ].py | 230 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
n = int(input())
s = input()
for i in range(n):
for j in range(1, n):
t = s[i::j]
if t.find('*'*5) != -1:
print('yes')
exit()
print('no')
|
18942761fec09f3229de425440ba54d98599c6df | KKubala/3-Cups-Game | /kulka.py | 691 | 3.515625 | 4 | def monit_kulki(silnik, kulka):
'''
Funkcja monit_kulki monitoruje pozycję kulki
(stirng, int) -> int
Argumenty:
silnik - nazwa silnika, który zostanie obrócony, w praktyce może być to
tylko "B" lub "B"
kulka - pozycja kulki przed obróceniem silnika czyli int [1, 2, 3]
Wynik:... |
0a4d123b4a5588bcc34124f3dc9f0e864e43d06d | frank-qcd-qk/EECS397-Python | /Assignment3/assignment3.py | 5,946 | 4.15625 | 4 | """
Author: "Frank" Chude Qian
Email: CXQ41@case.edu
"""
import time #! Not used for active writing code, but just for evaluation
import random #! Not used for active writing code, but just for evaluation
import string #! Not used for active writing code, but just for evaluation
#! Control Tag for debug and testing
... |
56cddd96546e853c7894f43cfb73e4e6f16e691d | i23SebasRam/AprendiendoTensorFlow | /DetectorNumerosRobotica/number_detection.py | 1,407 | 3.515625 | 4 |
import tensorflow as tf # Se requiere instalar tensorflow
import cv2
import numpy as np
import matplotlib.pyplot as plt
# La siguiente función permite ingresar una imagen RGB de cualquier tamaño como primer parámetro, y el
# segundo paraámetro corresponde al modelo de clasificación.
# La función retorna el número q... |
c2b7fa078e54a969f316f9ece89c4ff2198729e5 | FernandoMarcon/NLP | /clustering/clustering_basics.py | 1,283 | 3.59375 | 4 | # Clustering Basics
import pandas as pd
data = pd.read_csv('data/Course-Hashtags.csv')
data.head()
# Separate Hashtags and title to lists
hash_list = data['HashTags'].tolist()
title_list = data['Course'].tolist()
# Do TF-IDF conversion of hashtags
from sklearn.feature_extraction.text import TfidfVectorizer
vectoriz... |
ea4187377bb99bb5734c7e8b413d9b8cb5e6c9fe | LogicStarDust/cnn-text-classification-tf | /wgd/dnn_mnist_test.py | 599 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
# Load the MNIST dataset from the official website.
# 加载MNIST数据集合
mnist = input_data.read_data_sets("mnist/", one_hot=True)
num_train, num_feats = mnist.train.images.shape
num_test = mnist.test.images.shape[0... |
64d089030c0d8d3a4a6beeefddbc8d332aeb26df | Shafin-A/adventofcode2019 | /day6/day6.py | 1,566 | 3.890625 | 4 | f = open("input.txt","r")
lines = f.readlines()
orbits = {}
planets = set()
graph = {}
for line in lines:
split = line.rstrip().split(")")
planets.add(split[0])
planets.add(split[1])
orbits.setdefault(split[0], set())
orbits[split[0]].add(split[1])
graph.setdefault(split[0], set())
... |
ecf8c3ba20077cd468c95c43adecbf988b59b83b | pawelpopielarski/prefix-calc | /PrefixCalculator_test.py | 1,826 | 3.515625 | 4 | import unittest
import PrefixCalculator, calcerrors
class TestPrefixCalculator(unittest.TestCase):
def setUp(self):
self.target = PrefixCalculator.PrefixCalculator()
def test_init(self):
self.assertEqual(0, len(self.target.stack))
def test_calculate_negative(self):
with... |
b319beb8351046a3fae475e729e16409bacb47d9 | codecell/pythonAlgos | /arrays/arrayIntersection.py | 1,353 | 3.734375 | 4 | # Que https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/674/
'''
Time complexity i think is O(n * m)
space complexity = I am not sure,
About my code, when I used same symbols to replace traversed index, I was getting results like [4, 9, '#'],
So I decided to change the ... |
6690390d2ea6c92825deb7b67adbd648cd9062e2 | codecell/pythonAlgos | /linkedlist/deleteNthNode.py | 543 | 3.75 | 4 | # Q.) https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/603/
'''
space complexity - O(1)
Time complexity - O(n)
'''
def removeNthFromEnd(head, n: int):
holderList = head
lent = 1
# To get the length
while head.next:
head = head.next
lent +... |
05dc7ecb5dd33d535f683ecb4b76a5cedfbeb01c | codecell/pythonAlgos | /strings/reverseStr.py | 915 | 4.03125 | 4 | # Q) https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/
'''
space complexity => O(1)
time complexity O(n)
for e.g ['h', 'e', 'l', 'l', 'o,] => ['o', 'l', 'l', 'e', 'h']
each item eventually takes d position from i to len - i - 1, this should take n/2 iterations to... |
380f810d0bb2f6f2c58fc827ec36eded20b851cd | codecell/pythonAlgos | /trees/arrayToBst.py | 481 | 3.75 | 4 | # Q. https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/631/
def sortedArrayToBST(nums):
# TreeNode(val) => to instantiate a new Tree node
def plant(arr):
if arr is None:
return
mid_index = len(nums) // 2
leftSide = arr[0:mid_index]
rightSide = arr[mid_index ... |
809c976770c6111204d8368916c1a8351574de64 | Gavr59222/Lesson2 | /Task2.py | 450 | 3.59375 | 4 | var_list = []
while True:
item = input('Пожалуйста введите элемент списка: ')
var_list.append(item)
q = input('Формирование списка завершено? (y/N)) ')
if q.lower() == 'y':
break
last_idx = len(var_list) - 1
for idx, _ in enumerate(var_list):
if idx % 2 == 0 and idx < last_idx:
v... |
f61ce34e5a69b24b611300b1441c8b97aaf0127c | mnabu55/CarND-Advanced-Lane-Lines | /thresholding.py | 6,356 | 3.84375 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def gradient_threshold(image, orient='x', thresh_min=0, thresh_max=255):
"""
This function applies threshold to x, y gradient to detect the lane line
"""
# Convert to grayscale
gray = cv2.cvtColor(image, ... |
754e3b3f842926a28531b8eff5c98e2c4058f793 | Jotkanwal/Capstone | /Local_Test_Scripts/DHT11_HumidityAndTempTester.py | 691 | 3.75 | 4 | #if python doesn't recognize this do sudo pip3 install Adafruit_DHT
import Adafruit_DHT
import time
#variable assignments for the data pin and sensor data stream
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN=23
#the loop waits 3 seconds every pass, then reads the data streamed
#from the gpio pins to the pi and displays tem... |
477eb15ac4f584cc2758e70bfa4ea662191d0de9 | proffillipesilva/aulasdelogicaprogramacao | /revisao_p2_parte_1.py | 1,553 | 4.09375 | 4 | # inicio
def exercicio1():
nota1 = float(input("Digite a nota1: "))
nota2 = float(input("Digite a nota2: "))
soma = nota1 + nota2
if soma < 10:
return(f"Falhou com soma de notas igual a {soma}")
else:
return(f"Passou com soma de notas iguais a {soma}")
# fim
#inicio
def exercicio2():
num_entrada... |
e9193fbb321b81cf8d342e2f8daf2519ee1479ef | proffillipesilva/aulasdelogicaprogramacao | /aula3004/media_alunos.py | 527 | 3.6875 | 4 | with open('../aluninhos.csv', 'r') as file:
# file.read() --> le o arquivo inteiro
# file.readlines() --> converte cada linha em uma posição de uma lista
dicionario = {}
linhas = file.readlines()
for linha in linhas:
linha = linha.strip('\n').strip()
lista = linha.split(',')
... |
d4b15a30d9aaf219d7eac2fe65b46459246b10fb | proffillipesilva/aulasdelogicaprogramacao | /aula3004/excecoes.py | 345 | 4.15625 | 4 | # exemplo1
numerador = 10
denominador = 1
resultado = numerador/denominador # zero division error --> divisão por zero
print(resultado)
#exemplo2
posicao = 5
lista = [7,9,0,1,3]
print(lista[posicao]) # index error --> posição invalida
#exemplo3
print("a" + "b" + 2) # type error --> quando você junta de forma err... |
29adb27c9660aff0a3572329359ba4d4036aaa29 | Xiaokeai18/Leetcode-solutions-python3 | /LeetCode1-99/53_Maximum_Subarray_DP.py | 363 | 3.5625 | 4 | class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum,max = 0,nums[0]
for number in nums:
if sum > 0:
sum += number
else:
sum = number
if sum > max:
... |
5597a3b0606081477764712c7509d2371e520ce2 | Xiaokeai18/Leetcode-solutions-python3 | /LeetCode100-199/107_Binary Tree Level Order Traversal II.py | 943 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
1fcff1b5785620e0a1b3bbad5c7dd0ff1d336a9c | Xiaokeai18/Leetcode-solutions-python3 | /LeetCode100-199/101_Symmetric_Tree_Iterative.py | 886 | 4 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
r... |
72f918001ac60f6b382181556bc9bc174331d726 | ademerdzhiev/aipnd_project | /aipnd_command_line/input_args.py | 3,539 | 3.734375 | 4 | # PROGRAMMER: Angel
# DATE CREATED: 24.05.2020
# REVISED DATE: 26.05.2020
# PURPOSE: Create a function that retrieves command line inputs from the user using
# the Argparse Python module.
import argparse
import torch
def args_input():
"""
Retrieves and parses command line arguments provided by th... |
d60af3162b3e4db845270e3daf0cce3bf6ebf4fb | VivekUdupa/DataStructure | /Midterm/singlyLL.py | 2,158 | 4.1875 | 4 | class Node :
"""Node class"""
def __init__(self, data = None, next = None):
"""Initializing Parameters"""
self.data = data
self.next = next
def getNextNode(self):
"""Returns the Next Node"""
return self.next
def setNextNode(self, newNext):
"""Sets the current node pointer to next node"""
self.next ... |
b02fabba4624a626b12128668ce6f9fd5624813c | sohumsen/silver-disco | /chess engine.py | 1,952 | 3.84375 | 4 | ##Chess Engine##
########################################################
black_king=u"\u2654"
black_queen=u"\u2655"
black_rook=u"\u2656"
black_bishop=u"\u2657"
black_knight=u"\u2658"
black_pawn=u"\u2659"
white_king=u"\u265A"
white_queen=u"\u265B"
white_rook=u"\u265C"
white_bishop=u"\u2... |
3ecad63dbb45bba8742b63c37e07de16e2b6c7e5 | PolopTechnology/Algorithms | /Python/Dynamic Programming/Pynamic_Programming.py | 144 | 3.5625 | 4 | ids = [1, 1, 1, 1, 1]
f = 0
i = 0
while i < len(ids):
f += ids[i]
i += 1
ids.insert(0, 2)
print(f)
f += ids[0]
print(f)
|
bd83e980ce1fe7ef935ac940722d004747bca898 | LucySargent/she-codes-python | /Lists/q1 lists_exercises.py | 1,078 | 4.40625 | 4 | # Given the list of foods below, output:
# 1. The first item in the list.
# 2. The third item in the list.
# 3. The last item in the list.
# 4. The first three items in the list.
# 5. The last three items in the list.
# 6. The last item in the sublist.
foods = [
"orange",
"apple",
"banana",
"strawberr... |
788d32377cb61cbf48b319158e5bea0ac7e30715 | LucySargent/she-codes-python | /Lists/q3 lists_exercises.py | 224 | 4.25 | 4 | n = 3
namelist = []
for i in range(n):
name = input('Enter a name: ')
namelist.append(name)
print(namelist)
# OUTPUT
# Enter a name: izzy
# Enter a name: archie
# Enter a name: boston
# ['izzy', 'archie', 'boston']
|
5fdf6efb99bb85c13b5643876343bbbd875f710b | LucySargent/she-codes-python | /Loops/for_loops_playground.py | 2,864 | 4.40625 | 4 | #Loops - repetitive tasks
#Loop - for loops, while loops
#For loops - know how many times to repeat
#while loops - don't know how many times to repeat
#For Loops - sequence, strings, lists, dictionaries
# a = [1,2,3,4]
# print(a[1:4])
# #in this ex we are iterating through a sequence of numbers - our range is a range... |
819ad24c51b780578a9ca733ea741712e5fdd089 | mostafa4adel/Some-Sorting-Algorithms-with-Python | /SortingO_N2/InsertionSort.py | 289 | 3.703125 | 4 | def sortArray(theList: list):
n = len(theList)
for i in range(1, n):
key = theList[i]
hole = i
while hole > 0 and theList[hole - 1] > key:
theList[hole] = theList[hole - 1]
hole = hole - 1
theList[hole] = key
return None
|
a5a04849f14f71041cb9594fdd5af4f74e39daae | hezron-hezron/latihanpy | /day02/hw02.py | 702 | 3.6875 | 4 | # P1 (20%) :
# Panjang = 6
# Lebar = 3
#
# * * * * * *
# * * * * * *
# * * * * * *
# * * * * * *
# p2 (80%)
# # diagonal = 1 diagonal = 2 diagonal = 3
# *
# * * * *
# * * * * *
# *... |
eca7fbf9b3487a652a2f863c34a3d76044a54649 | aviadfi2016/python_mix | /Exercise 11.py | 455 | 3.765625 | 4 | ##Exercise 11_1
def sum_of_list(given_list):
return sum(given_list)
##test
list= [1, 2, 3, 4]
print(sum_of_list(list))
##Exercise 11_2
def multiply(given_list):
my_new_list = [i * 2 for i in given_list]
print(my_new_list)
##test
list= [1, 2, 3, 4]
multiply(list)
##Exercise 11_3
def n... |
2b98daecfcd7dde11724b0ed88ebb9decf1b69ee | cmf3673/CS_313E_Projects | /Boxes.py | 4,727 | 4.21875 | 4 | ## Problem: Imagine a room full of boxes. Each box has a length, width, and height.
# Since the boxes can be rotated those terms are inter- changeable. The dimensions
# are integral values in a consistent system of units. The boxes have rectangular
# surfaces and can be nested inside each other. A box can nest insid... |
fd5e999f8c7ad3b2ebc9313c984d3f08edb7b8f4 | cmf3673/CS_313E_Projects | /Interval.py | 5,700 | 4.3125 | 4 | ## Problem: An interval on the number line is denoted by a pair of values like so: (3, 8).
# Our intervals are closed. So this interval represents all numbers between 3 and 8 inclusive.
# The first number is always going to be strictly less than the second number.
# Normally in mathematics we represent a closed inte... |
dd429245b1616d9d0618fd6f580e9697c0605c4c | cmf3673/CS_313E_Projects | /Chess.py | 3,190 | 3.96875 | 4 | ## Problem: The Eight Queens Problem is a fairly old problem that has been well
# discussed and researched. The first published reference to this problem was
# in a German Chess magazine in 1848 by Max Bezzel. In 1850, Franz Nauck published
# all 92 solutions of the problem for an 8x8 board. S. Gunther in 1874 sugge... |
ede1d7ab27d9d72b189156605cbd85231db2c0e9 | deeppunster/curio_demo | /Curio_demo_pkg/curio_demo_11.py | 3,360 | 3.84375 | 4 | """
curio_demo_11.py - Curio tutorial.
(from https://curio.readthedocs.io/en/latest/tutorial.html)
Kid uses Fibonacci numbers for building the Minecraft game.
"""
import curio
import signal
# an event object for tracking permission from the parent
start_evt = curio.Event()
async def countdown(n):
"""
A si... |
c951007d05a849342fb210e9a4911063746df6cb | Ishwarya510/Python-Practice | /while/while.py | 224 | 3.890625 | 4 | i=int(input("How much do you have:"))
while i>5:
print("you are rich")
i-=1
print("now you have")
print(i)
else:
print("now you are poor")
print("I have taken your money,Goodbye!") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.