blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
6957f81ef3a3c9400eeeaade57cced0bbfa97fd9 | kallel-mahdi/MVA-Master | /ALTEGRAD/LAB7_Influence_max/code/part1/models.py | 1,290 | 3.609375 | 4 | """
Learning on Sets - ALTEGRAD - Jan 2021
"""
import torch
import torch.nn as nn
class DeepSets(nn.Module):
def __init__(self, input_dim, embedding_dim, hidden_dim):
super(DeepSets, self).__init__()
self.embedding = nn.Embedding(input_dim, embedding_dim)
self.fc1 = nn.Linear(embedding_dim... |
da3150794177b49b2e2aed55d8c20e3c3f09c103 | Daviderose/Whiteboard-excercises | /ArrayIndex/ArrayIndex.py | 236 | 4.0625 | 4 |
arr = [-1,0,3,5,2,5,2]
def find_max_index (arr):
max_index = 0
for i in range(len(arr)):
if arr[i] > max_index:
max_index = i
return max_index
if __name__ == '__main__':
print(find_max_index(arr))
|
1acd4e7e7f4c9353ac6be02d55c2feae3a47b27b | ingmar12345/trafficsim | /controller/algorythms/test.py | 1,506 | 3.6875 | 4 | from controller.controller import Controller
from controller.controller import Algorithm
class Test( Algorithm ):
"""
Algorithm that iteratively toggles each traffic light from red to green to orange to red again.
"""
def __init__( self ):
super().__init__()
self.counter = 0
self.lightIndex = 0
self.colou... |
bb58c2ea50f9a5010bca2e2b8462d42b6d1413fb | Lilitt21/homework | /shiftDict.py | 444 | 3.609375 | 4 | '''input: abcd
key = 3
output: defg'''
a = dict()
#key = 3
shift = dict(zip(
['a', 'b', 'c', 'd', 'e', 'f', 'g','h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'],
['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',... |
6ac1e150cc67cb73d6a6847b0e03d510db4f9ff1 | JuanJoseSenit/subir_github | /bucles/continue_else_en_ciclos.py | 871 | 3.8125 | 4 | #USO DEL CONTINUE
frase="juanjo es pro"
contador=0
for i in range(len(frase)):
if frase[i]==" ": #va a ir el ciclo leyendo letra por letra. si encuentra un espacio no hace nada, es decir, no entra en ningun if mas y no hace nada
continue
else:
contador=contador+1
print("hola")
print("La frase: " + frase + " c... |
c328f75f3d0278660d4d544563b5d953af5b7041 | jjti/euler | /Done/81.py | 2,016 | 4.21875 | 4 | def path_sum_two_ways(test_matrix=None):
"""
read in the input file, and find the sum of the minimum path
from the top left position to the top right position
Notes:
1. Looks like a dynamic programming problem. Ie, start bottom
right and find the sum of the minimum path from the current... |
b3cca4d969aa2be4ad517aad8d903ae2826da02d | jjti/euler | /Done/65.py | 2,141 | 4.1875 | 4 | import utils
"""
The square root of 2 can be written as an infinite continued fraction.
The infinite continued fraction can be written, 2**0.5 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, 23**0.5 = [4;(1,3,1,8)].
It turns out that the sequence of partial values of continued fractions for squ... |
a30a1d86721b5ca62407334b865b8883342a744e | jjti/euler | /Done/63.py | 398 | 3.796875 | 4 | import utils
"""Powerful digit counts
Problem 63
The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit number, 134217728=8^9, is a ninth power.
How many n-digit positive integers exist which are also an nth power?
"""
count = 0
for i in range(1, 100): # base
for j in range(1, 100): # power... |
d6a3a1abfac543f817434f9b903515db63993c02 | jjti/euler | /Done/57.py | 1,511 | 4.125 | 4 | import utils
"""
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
2 ** 1/2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = ... |
8e06a87cabb0912f5dee47b9251b02eee31edd83 | jjti/euler | /Done/112.py | 2,029 | 4.03125 | 4 | from utils import split, join
def bouncy_and_increment(n):
"""
n {int} number to test for bounciness
return a tuple with a boolean for whether it was bouncy and,
if it's false, a number for how much to increment the current number by
"""
digs = split(n)
# direction can be -1: ... |
e40a069013123d3f020531c26c65672f4990efb4 | tjhlp/numpytest | /numpytest/data structure/structure_tjh_select_sort.py | 379 | 3.5 | 4 | def select_sort(alist):
count = len(alist)
for i in range(count):
min_index = i
for j in range(i+1, count):
if alist[j] < alist[min_index]:
min_index = j
if min_index != i:
alist[i], alist[min_index] = alist[min_index], alist[i]
li = [10, 44, 20... |
58d92c903974f75a0fa661be90d212ccbd8a56b2 | hallba/UnicornWrightFisher | /numpyReplace.py | 810 | 3.515625 | 4 | """Substitute for numpy.
A set of functions that (partially) replicate numpy
functions so that code can run on pico.
"""
import random as rnd
print("Using pure python alternatives to numpy")
def zeros(number, dtype=float):
if dtype == int:
return([0 for _ in range(number)])
elif dtype == float:
... |
2d7eb20c2f6eb18f3a8e7524df6decdceafb3cd7 | 1505069266/python- | /面向对象/公有,私有成员.py | 1,202 | 4.125 | 4 | class Student:
name = ''
age = 0
# 一个班级里所有学生的总数
sum1 = 0
__score = 0
# 实例方法
def __init__(self, name, age):
# 构造函数 实例化的时候会运行这里的代码
self.name = name
self.age = age
self.__class__.sum1 += 1
print("当前班级人数:" + str(self.__class__.sum1))
# print('我是:'... |
b98a369267893116b8f196287ad84983a9b08dac | 1505069266/python- | /函数式编程匿名函数,高阶函数,装饰器/reduce.py | 186 | 3.625 | 4 | # reduce
from functools import reduce
# 连续计算,连续调用lambda
list_x = [2, 5, 6, 4]
r = reduce(lambda x, y: x*y, list_x) # 求和
# ((2*5)*6)*4
print(r)
print(sum(list_x)) |
42694749ea37e9c48aa5f11c8e4eeb76dd8fba91 | 1505069266/python- | /函数/参数.py | 143 | 3.625 | 4 | # 必须参数
def add(x, y):
# x y为必须参数,也叫形参
return x + y
def add2(x=1, y=1):
return x + y
print(add2())
|
f3efcbf3c69c0f5c17058214546ec2450d43bd15 | 1505069266/python- | /变量与运算符/list.py | 108 | 3.6875 | 4 | a = [1, 2, 3, 4]
a.append(22)
print(a)
tuple1 = (1, 2, 3, [1, 2, 4])
tuple1[3][2] = "ddd"
print(tuple1) |
7ac0ace8b17c80af072aa80be36b1831684c91da | 1505069266/python- | /面向对象/静态方法.py | 1,015 | 4.125 | 4 | class Student:
name = ''
age = 0
# 一个班级里所有学生的总数
sum1 = 0
# 实例方法
def __init__(self, name, age):
# 构造函数 实例化的时候会运行这里的代码
self.name = name
self.age = age
self.__class__.sum1 += 1
print("当前班级人数:" + str(self.__class__.sum1))
# print('我是:' + name)
... |
817cc56c7be9c6f89a4a1c5f87b370dfc0a29d70 | kshimauchi/ProblemSolvingTechniques | /python_workspaces/PrimitiveTypes/count_bits.py | 551 | 3.671875 | 4 | # Python 3.8
# Everything in python is a object:
from functools import lru_cache
def count_bits(x: int) -> int:
"""
Args:
x (object):
"""
num_bits = 0
while x:
num_bits += x & 1
x >>= 1
return num_bits
print(count_bits(12))
@lru_cache(maxsize=1028)
def ... |
5ff753d7ac3265f5e88dfa88ee11742f85499e8d | ArtZubkov/pyDev | /lab1.py | 2,463 | 4.28125 | 4 | '''
Программа, вычисляющая уравнение прямой, которая пересекает
заданную окружность и расстояние между точками пересечения
которой минимальны.
'''
#Ввод данных и инициализация
print('Уравнение окружности: (x-x0)^2+(y-y0)^2=r^2 ')
x0=float(input('Введите x0 для уравнения окружности: '))
y0=flo... |
4c28efd8124035ef404c5cdabf8279a25ffdead2 | nasingfaund/Yeppp-Mirror | /codegen/common/Argument.py | 1,926 | 4.4375 | 4 | class Argument:
"""
Represents an argument to a function.
Used to generate declarations and default implementations
"""
def __init__(self, arg_type, name, is_pointer, is_const):
self.arg_type = arg_type
self.name = name
self.is_pointer = is_pointer
self.is_const = is... |
cc238905a40057f32dfe99bf04989327e5403ec8 | ShangC/PY4E | /Course3/Chapter13Assignment/13_week6_1.py | 1,089 | 3.515625 | 4 | '''
Use the below information to test the code:
URL: http://py4e-data.dr-chuck.net/comments_42.json
Retrieved: 2733
Count: 50
Sum: 2553
URL: http://py4e-data.dr-chuck.net/comments_44137.json
Retrieved:
Count: 50
Sum:
'''
import json
import urll... |
594357bf9d2669370a5a10bd8eba7e1d5606bfc4 | Pkoiralap/python-tutorials | /map.py | 295 | 3.71875 | 4 | items = ['Ram', 'Shyam', 'Hari']
def custom_map(func, lst):
result = []
for item in lst:
mapped_result = func(item)
result.append(mapped_result)
return result
def mapFunc(item):
return item*2
mapped_items = custom_map(mapFunc, [1,2,3,4,5])
print(mapped_items) |
e3ddcf3c2bc69e2c48fb492b84233df731285048 | Pkoiralap/python-tutorials | /list_comprehention.py | 598 | 3.6875 | 4 | lst = [
{
'name': 'Nished',
'occupation': 'Doctor',
'number': 123123,
'salary': 500000,
},
{
'name': 'Suyog',
'occupation': 'Engineer',
'number': 1123143123,
'salary': 400000,
},
{
'name': 'Kedar',
'occupation': 'Enginee... |
8fe211a3abf680823dabe7fd7f31104b320b1177 | Pkoiralap/python-tutorials | /conditionals.py | 189 | 3.8125 | 4 | a = 5
less_than_five = lambda x: 'my aunt\'s daughter' if x < 5 else "not less than 5"
print(less_than_five(4))
print(less_than_five(5))
print(less_than_five(3))
print(less_than_five(10)) |
ab442067a0764d35a2db46d2802901f5a2a67ca9 | mattpaletta/coloured-graph-traversal | /test/test_blog_examples.py | 4,012 | 3.6875 | 4 | from unittest import TestCase
from colouring.traversal import traverse_graph, Node, Colour
from typing import List, Dict
# Helper function, takes a list of nodes, and a graph of their indices, returns the nodes at those indices
# Ex:
# nodes = [Node(1), Node(2), Node(3)]
# graph = {
# 0 : [1],
# 1 : [2],
... |
16d052be3d99339cd00bcb88a2cb076f12c4124c | xiaomin418/leetcode_all | /717.py | 1,308 | 3.703125 | 4 |
class Solution(object):
def isOneBitCharacter2(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
if len(bits)==1:
if bits[0]==0:
return True
else:
return False
elif len(bits)==2:
if bits[0]==0 ... |
ee48583be1cb6d3af6ff0b126276e001d6c8576a | techabhishekg/practice | /DetectLoop.py | 2,313 | 3.921875 | 4 | class Node:
def __init__(self):
self.next= None
self.data= 0
def push(head_ref, newdata):
newnode = Node()
newnode.data = newdata
if head_ref is None:
head_ref = newnode
else:
cur = head_ref
while cur.next:
cur = cur.next
cur.next = newn... |
9cdbc37de8e01d3b490478d2e10e8d5e95fe68bd | techabhishekg/practice | /abstract_test.py | 281 | 3.640625 | 4 | class Employee:
__cprt = 0
_count = 0
def __init__(self):
Employee._count = Employee._count + 1
def display(self):
print('number of employee', Employee._count)
emp = Employee()
emp1 = Employee()
emp.display()
print(emp._count)
print(emp._cprt)
|
10e7273af6940e0ba861ddcfddc743947f431510 | Dggz/pybook | /sda/testingtdd/blog.py | 776 | 3.65625 | 4 | class BlogPostHistory:
FILENAME = 'posts.txt'
SEPARATOR = ','
def __init__(self, title, desc):
self._title = title
self._desc = desc
def save(self):
with open(self.FILENAME, 'a+') as f:
data = f'{self._title}{self.SEPARATOR}{self._desc}\n'
f.write(data)... |
b379ae31d3d04c67732b5819adca9061c541a21a | Dggz/pybook | /cripto/rsa.py | 3,203 | 3.5625 | 4 | from random import randint, choice
from math import gcd
from collections import defaultdict
def check_space(a):
if a == ' ':
return 0
if ord(a) - 64 < 0 or ord(a) - 64 > 26 or a == '@':
return -(27 ** 3)
return ord(a) - 64
def is_prime(num):
if num % 2 == 0 and num != 2 or num <= 1:
... |
b2a17694c824af410828e0911300a5f1641dfe3b | Dggz/pybook | /new_formatting.py | 1,851 | 4 | 4 |
# Old % way
print('\n%\n')
age = 74
name = "Eric"
print("Hello, %s. You are %s." % (name, age))
age = 74
first_name = "Eric"
last_name = "Idle"
profession = "comedian"
affiliation = "Monty Python"
print("Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (
first_name, last_name, age, profession,... |
b6ba1625a5f257c77ac966dffbe12bee96f21d30 | Dggz/pybook | /prezentare/ch5.py | 1,421 | 3.796875 | 4 |
#### printing with diff separators/endlines
# print('ACME', 50, 91.5)
# print('ACME', 50, 91.5, sep=',')
# print('ACME', 50, 91.5, sep=',', end='!!\n')
# end= can be used to suppress \n when printing
for i in range(5):
print(i, end=' ')
print(','.join(('ACME', '50', '91.5')))
row = ('ACME', 50, 91.5)
# print(... |
66053ba518e59e9c6fb21d7710959500f9f4cd8e | Dggz/pybook | /cripto/rsa2.py | 3,153 | 3.5625 | 4 | from random import randint, choice
from math import gcd
def get_index(a):
if a == ' ':
return 0
return ord(a) - 64
def is_prime(num):
if num % 2 == 0 and num != 2 or num <= 1:
return False
for i in range(3, int(num // 2) + 1, 2):
if num % i == 0:
return False
... |
bd2507a40c65bcfab1bf237d875b8bde6cebae4e | itziar/python-learning | /EXAM/problema8.py | 1,779 | 3.921875 | 4 | '''
Problem 8
Write a Python function called satisfiesF that has the specification below. Then make the function call run_satisfiesF(L, satisfiesF). Your code should look like:
def satisfiesF(L):
"""
Assumes L is a list of strings
Assume function f is already defined for you and it maps a string to a Bool... |
5bddf893638891cf843b1cb6b3353cbdea532c0b | laegsgaardTroels/chess | /chess/pieces.py | 5,650 | 4.15625 | 4 | class Piece:
"""An abstract class for a piece on the board."""
def __init__(self, color=None, board=None, position=None):
self.color = color
self.board = board
self.position = position
def is_opponent(self, other):
"""Return the color of the opponent."""
if other.co... |
156737faaa85ebcca7fef8c8f7b8644068e8e427 | YangChemE/Udacity_DataStructure_Algorithm | /Knapsack_Problem.py | 1,379 | 3.90625 | 4 | #### Naive approach based on Recursion (exponential time) ###
def knapsack_max_value(knapsack_max_weight, items):
lastIndex = len(items) - 1
return knapsack_recursive(knapsack_max_weight, items, lastIndex)
def knapsack_recursive(capacity, items, lastIndex):
# Base case
if (capacity <= 0) or (lastIndex... |
dc7fdc3f6d9ef44579d0b30669214b7c356fd9dd | alokofficial/Python-Training | /guess_game.py | 370 | 3.8125 | 4 | import random
jackpot=random.randint(1,100)
#print(jackpot)
guess=int(input("chal guess kar"))
counter=1
while guess!=jackpot:
counter+=1
if guess>jackpot:
print("guess lower")
guess=int(input("chal dubaara guess kar"))
else:
print("guess higher")
guess=int(input("chal dubaa... |
8870fcb5a782ca19f56ed97c49eb6fd9cfb4c1e0 | MareAustrale/hangman | /hangman.py | 3,304 | 4.03125 | 4 | #!/usr/bin/python
import sys
import random
import string
# Asks player if they would like to begin a new game
def newGame():
while True:
try:
response = str(raw_input("Would you like to begin a new game of Hangman (Y or N)? ")).upper().strip()
if response[0] == 'Y':
return True
if response[0] == 'N':
... |
c3bab4b5f9876c6e0492d63ccb8e14dcf18dac08 | LelandoSupreme/DATA608 | /Module5_Project5/Module5_LelandRandles.py | 1,351 | 3.515625 | 4 | # Module 5, DATA 608
# Leland Randles
import pandas as pd
from flask import Flask
app = Flask(__name__)
# This Flask API lets you enter any borough / species combination and
# then returns a json blob of the tree_id, boroname, spc_common, health
# and steward columns of the NYC tree census data set for t... |
6e86f4588a125d340d8a267f1768d84e6c770fab | kashyapsanchit/Python_DSA | /two_sum_problem.py | 236 | 3.609375 | 4 | def two_sum(A, target):
i = 0
j = len(A) - 1
while i <= j:
if A[i] + A[j] == target:
return True
else:
i += 1
return False
A = [1, 2, 5, 6]
target = 10
print(two_sum(A, target)) |
cefd1eefb6fba9323fe0bc403b0d50bc7cdbcae6 | kashyapsanchit/Python_DSA | /integer_to_binary.py | 289 | 3.828125 | 4 | from Stack import Stack
def divide_by_2(num):
s = Stack()
while num > 0:
remainder = num % 2
s.push(remainder)
num = num // 2
binary = ""
while not s.is_empty():
binary += str(s.pop())
print(binary)
return binary
divide_by_2(669) |
1b9802019e7d0dab98c27d1a8a58e91911e65cb4 | gongchengshi/python_common | /string_utils.py | 1,640 | 3.671875 | 4 | def lstrip_string(string, unwanted_string):
if string.startswith(unwanted_string):
string = string[len(unwanted_string):]
return string, True
return string, False
def lstrip_strings(string, unwanted_strings):
removed = True
while removed:
removed = False
for unwanted_st... |
a89bcae6b2c3c7bcc1438fae95e063a5135e3dc7 | ai-msceteers/assignment2 | /Simulated_Annealing_Folder/Simulated_Annealing_V1.1.py | 6,755 | 4.03125 | 4 | #/**
# *\file Simulated_Annealing.py
# *\brief This code contains the simulated annealing algorithm implemented
# * to solve the Assignment 2, group project, rubix cube problem
# * - Solves both n=2, n=3 cubes
# * - Utilises calculate_cost() function based on number of missplaced ... |
02654e2225a8c91c6d349027ed8e0d5aa5d1492a | Sunwait-nsk/resume | /My portfolio/portfolio/Python/happy_farm/main.py | 1,706 | 3.796875 | 4 | class Potato:
stage_potato = ['семя', 'росток', 'зреет', 'созрела']
def __init__(self, name):
self.name = name
self.stage = 'семя'
def info(self):
print('Картофель {} находится на стадии {}'.format(self.name, self.stage))
def grow(self):
self.stage = self.st... |
7432e574d515aadac24d93b6aa1568d3add65fc6 | johnpospisil/LearningPython | /try_except.py | 873 | 4.21875 | 4 | # A Try-Except block can help prevent crashes by
# catching errors/exceptions
# types of exceptions: https://docs.python.org/3/library/exceptions.html
try:
num = int(input("Enter an integer: "))
print(num)
except ValueError as err:
print("Error: " + str(err))
else: # runs if there are no errors
print('... |
d78585044147f77090dc54494e1a3c24b36c5b37 | johnpospisil/LearningPython | /while_loops.py | 592 | 4.21875 | 4 | # Use While Loops when you want to repeat an action until a certain condition is met
i = 1
while i <= 10:
print(i, end=' ')
i += 1
print("\nDone with loop")
# Guessing Game
secret_word = "forge"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
print("\nGUESSING GAME")
while guess != secret_... |
7a1bae5b1b9bedf34e6b2f2623024b98a6c25348 | johnpospisil/LearningPython | /variables.py | 420 | 4.3125 | 4 | char_name = "John"
char_age = 50
is_male = True
print("There once was a man named " + char_name + ".")
print("He was " + str(char_age) + " years old.")
print("He liked the name " + char_name + ".")
print("But he did not like being " + str(char_age) + " years old.")
print("Is " + char_name + " male? " + str(is_male))
p... |
fe50ac9d19e9cf5bfb07fbe12fde007bc62e77c4 | nkyriako/misc | /distances.py | 563 | 4 | 4 | #Nicole Kyriakopoulos
#nkyriako@ucsc.edu
#programming assignment 0
#This program converts kilometers to miles
def convert(): #define function
kil = eval(input('What is the distance in kilometers?: ')) #stores kilometer value in variable kil
mil = kil * .... |
a1cfbbbb68a211a8068748abebce57bfb408dd3b | nkyriako/misc | /hw4/hw4test.py | 3,598 | 3.71875 | 4 | """
Unit tests for Homework 4, CMPS101 Spring16
How do you test?
================
1) Copy this file to the folder where you saved hw4.py, rename this file to "hw4test.py"
2) Just run this on terminal (you can also click green button in Spyder)
python3 hw2test.py
3) If the output is similar to
... |
b31046b02ab61ab18907cad6146fab7fb957afdc | fengfengcloud/learning_spider | /example/0_Basic_usage_of_the_library/openCV/11-2超大图像二值化.py | 1,834 | 3.546875 | 4 | #!/user/bin/env python3
#!-*- coding:utf-8 -*-
'''
Created on 2018年3月25日
@author: RecluseXu
'''
import cv2 as cv
import numpy as np
def big_image_binary_threshold_demo(image):#全局
h,w = image.shape[:2]
cw = 256 # 步长
ch = 256
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
for row in range(0,h,ch):
... |
44aa990931bbeb59fbc82d63d6a045d6e2aaa3ff | pgurazada/fast-fast-ai | /code/np-forward-prop.py | 785 | 3.578125 | 4 | import numpy as np
def neural_network(inputs, weights):
'''
return a single output using pretrained weights and an array of input
feature values
'''
return inputs.dot(weights)
def ele_mult(number, vector):
output = np.zeros_like(vector)
assert(len(output) == len(vector))
for i in ... |
0a0cfb26245808219c8515e6edf656721054195e | torbenm/neuralnets_for_python | /demo.py | 651 | 3.65625 | 4 | from neuralnet.neuralnet import NeuralNet
import numpy as np
from util.numpyextensions import NumpyExtensions
np.random.seed(1)
X = np.array([[0, 1], [0, 0], [1, 0], [1, 1]])
y = np.array([[1, 0, 1, 0]]).T
CORRECT = 0
FAILED = 0
def run_neural_net(iter, X, y):
print("Running iteration number",iter)
nn = Neur... |
10536d2c00b2c6e4443e61daa2fa3fc9e0a09bdb | olegtrygub/ETChallenge | /battleship.py | 2,092 | 3.859375 | 4 | import sys
from field import Field
from field import Result
def read_map_from_file(path):
"""
Reads map from its representation in file
"""
input_file = open(path, 'r')
battlemap = []
size = int(input_file.readline())
for i in range(size):
battlemap.append(map(lambda c: 0 if int(c) ... |
a1c24c4bbd6ba57ebad7447a9d012cbb3ebcdbec | catauggie/solve1 | /index power.py | 251 | 3.703125 | 4 | import random
x=int(input())
def set_args():
return [random.randint(-10, 10) for i in range(x)], random.randint(0, 20)
def power(elements, n):
return -1 if n >= len(elements) else elements[n]**n
print(power(*set_args()))
|
5ae37a8f6530b55db61a626953bca43d955991fe | catauggie/solve1 | /axy.py | 195 | 3.53125 | 4 | import math
def axy(x, y):
z, q global
return z=(x+(2+x)*x**(-2))/(y+(x**2+10)**(-1/2)) and q=2.8*math.sin(x)+abs(y)
print(z, q)
x=int(input())
y=int(input())
print(axy(x,y))
|
a473e901e1a8e4b9671e2a45678c6df3f5059635 | hao6699/sort_python | /无重复最长字串.py | 579 | 3.53125 | 4 | def lengthOfLongestSubstring(s):
dic = {} #定义可查询的字典,当新来的字符进来的时候,会推入字典中并更新里面的值
max_length = 0
start = 0 #start是不重复字串的开头,遇到跟前面字符相同时,会跳到下个字符
for i in range(len(s)):
if s[i] in dic and start <= dic[s[i]]:
start = dic[s[i]]+1 ... |
1035849206cc0e7d431629de49c2aa0fa3cd575c | avivko/pythonWS1819 | /stackTask.py | 698 | 4.09375 | 4 | class Stack:
def __init__(self):
self._stack = []
def is_empty(self):
if not self._stack:
return True
return False
def push(self, item):
self._stack.append(item)
def pop(self):
self._stack.pop()
def peek(self):
if not self.is_empty():
... |
41c3a1a500e769e302d957387386e44235c9d823 | bavneetsingh16/Python | /Funnystring.py | 434 | 3.796875 | 4 |
def funnyString(s):
s1=s[::-1]
n=len(s)
for i in range(1,n):
a=ord(s[i])
b=ord(s[i-1])
c=ord(s1[i])
d=ord(s1[i-1])
if(abs(a-b) == abs(c-d)):
temp=1;
else:
return "Not Funny"
if(temp==1):
return "Funny"
q = ... |
3148035a21aba62fd1dac326e084d9b41fcf0db4 | bavneetsingh16/Python | /Dictionary.py | 386 | 3.65625 | 4 | from statistics import mean
StudentGrades = {
'Ivan': [4.32, 3, 2],
'Martin': [3.45, 5, 6],
'Stoyan': [2, 5.67, 4],
'Vladimir': [5.63, 4.67, 6]
}
avgDict = {}
for k,v in StudentGrades.items():
avgDict[k] = mean(v)
print(avgDict)
print(max(avgDict.values()))
print(min(avgDict.values()))
... |
58c3aac8c38968207bab986039506edcaf4d22c9 | tonylimcs/Coding-Exercise | /ex_2.py | 1,025 | 3.765625 | 4 | """
Given a set of single digits (up to 7),
find the number of prime numbers you can find from this input.
Assume positive values and greater than zero.
Example:
Input: {1, 7}
Expected: 3
Note: 7, 17, 71
"""
from itertools import combinations, permutations
def parse(in_):
ls_ = []
for ch in in_:
if... |
7e6595fd6055ee67e1e6d45a8c33c38f704a7a14 | m-piechatzek/phishing_url_detector | /src/data_preprocessing/malicious_analysis.py | 1,717 | 3.5625 | 4 |
# implement the Levenshtein (edit distance) algorithm
# taken from: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
def edit_distance(s1, s2):
if len(s1) < len(s2):
return edit_distance(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)... |
16d9aca7e7daeb8a43ca2db0f84f5c8ad1951d10 | hansrajdas/random | /missing_word.py | 444 | 3.609375 | 4 | # Fractal Analytics
def missingWords(s, t):
missing = []
a = s. split(' ')
b = t.split(' ')
i = 0
j = 0
while i < len(a):
if j == len(b):
missing.append(a[i])
else:
if a[i] != b[j]:
missing.append(a[i])
else:
j += 1
i += 1
return missing
print missingWo... |
9e4369eb4f8577b139e00748654ac1cd20055e8d | hansrajdas/random | /a.py | 1,326 | 3.703125 | 4 | def _find_quote_char_in_part(part):
if '"' not in part and "'" not in part:
return
quote_char = None
double_quote = part.find('"')
single_quote = part.find("'")
if double_quote >= 0 and single_quote == -1:
quote_char = '"'
elif single_quote >= 0 and double_quote == -1:
qu... |
51f7d3efada010da0f9d5d58d9825ed0c6d22418 | hansrajdas/random | /practice/max_product_cutting.py | 571 | 3.59375 | 4 | def getMaxProduct(n, d):
if n == 1 or n == 2:
return 1
if n == 3:
return 2
if n in d:
return d[n]
_max = 1
for i in range(2, n):
_max = max(_max, i * (n - i), i * getMaxProduct(n - i, d))
d[n] = _max
return _max
# Main
print(getMaxProduct(2, {})) # 1 -> ... |
4e63fc78f6d613cb782028dd09f6ad14f365161c | hansrajdas/random | /practice/delete_node_from_linked_list.py | 913 | 3.9375 | 4 | class Node:
def __init__(self, k):
self.k = k
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_begin(self, k):
if self.head is None:
self.head = Node(k)
return
n = Node(k)
n.next = self.head
s... |
59fae312cef33158e2074a6d6dc9880f8ed73d30 | hansrajdas/random | /practice/s.py | 604 | 3.78125 | 4 | s1 = [1,1,100,3]
s2 = [200,2,3,1]
s3 = [10,1,4]
def find_max_sum(s_arr, n):
if n == 0:
return 0
if len(s_arr) == 1:
return sum(s_arr[0][-n:])
# Assume no term is picked form the first stack
max_sum = find_max_sum(s_arr[1:], n)
first_stack = s_arr[0]
for i in range... |
c0520b4031b569268c84a81d38616af2b39b8d26 | hansrajdas/random | /practice/loop_starting_in_linked_list.py | 2,003 | 4.15625 | 4 | class Node:
def __init__(self, k):
self.k = k
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_begin(self, k):
if self.head is None:
self.head = Node(k)
return
n = Node(k)
n.next = self.head
s... |
42e68cf6fc2f585b99515f598c3e86dcda9da99f | hansrajdas/random | /practice/flip_a_bit_to_get_seq_of_1s.py | 376 | 3.703125 | 4 | def max_ones(A):
right = 0
left = 0
_max = 0
while A:
if A & 1:
right += 1
else:
left = right
right = 0
_max = max(_max, right + left + 1) # +1 for mid 0 to be swapped
A >>= 1
return _max
# 1101 1101 111
print(max_ones(1775))
prin... |
dca62658df9a3fc81e5652ac148ff078119667c5 | Plasmar/batch-rename-tool | /batch-rename.py | 542 | 3.625 | 4 | # Cameron M Merrick
# 2.13.2018
# filenameParser.py
# Script to rename a batch selection of files in a directory
import os
import sys
targetDir = sys.argv[1]
os.chdir(str(targetDir))
for f in os.listdir():
# Split off the extension from the filename
file_name, file_ext = os.path.splitext(f)
# Select the ... |
6c45f39f4196aa592011481cc47842cfa937ed23 | Svetlanamsv/NOD | /main.py | 192 | 4 | 4 | print("Input the first number: ")
a = int(input())
print("Input the second number: ")
b = int(input())
while a != 0 and b != 0:
if a>b:
a = a%b
else:
b = b%a
nod = a+b
print(nod)
|
c8c21b41e80c4def3a9d1f26d4bbb839fb30eeac | scaverod/GamblingMarkovChain | /transition_matrix.py | 1,314 | 3.953125 | 4 | import numpy as np
"""
This function create a transition matrix based on:
- min: Minimum value of chips that the player can reach. When the player reaches this amount, he withdraws.
- max: Maximun value of chips that the player can reach. When the player reaches this amount, he withdraws.
- bets: Array of... |
85450dcaae78c04a7da53374318f94828f22e909 | mabog3/2021-Fall | /ps0/ps0.py | 2,139 | 3.984375 | 4 | #################
# #
# Problem Set 0 #
# #
#################
#
# Setup
#
class BinaryTree:
# left : BinaryTree
# right : BinaryTree
# key : string
# temp : int
def __init__(self, key):
self.left = None
self.right = None
self.key = key
... |
a9286b6aa0e4185915bebea4888bc79d7c27bc3b | yeasellllllllll/bioinfo-lecture-2021-07 | /basic_python/210701_70_.py | 763 | 4.25 | 4 | #! /usr/bin/env python
print(list(range(5)))
# [0, 1, 2, 3, 4]
print('hello'[::-1])
# olleh
print('0123456789'[0:5:1])
#위의 숫자 위치 찾는 것은 원하는 위치를 설정할수없다.
print(list(range(2, 5, 1)))
# [2, 3, 4] 2~5사이의 1차이나게끔 올려서 리스트 보여줘
totalSum = 0
for i in range(3):
totalSum += i
print(i)
print('totalSum:', totalSum)
'''
... |
480bf914b7170421e64799b9496ba0be3e42b317 | yeasellllllllll/bioinfo-lecture-2021-07 | /src/184page.py | 390 | 3.609375 | 4 | import sys
n_pivo = sys.argv[1]
l_pivo = [0, 1]
def pivo(n):
for i in range(n- len(l_pivo))
l_pivo.append(l_pivo[-1] + l_pivo[-2])
print(l_pivo[-1])
print(l_pivo)
pivo(n_pivo)
# import sys
# def fib(n):
# if n == 0:
# return 0
# elif n == 1:
# return 1
# else:
# ... |
3aa6561930c6ee098685626c7e92dfb7116236dd | yeasellllllllll/bioinfo-lecture-2021-07 | /basic_python/210704_96.py | 1,212 | 3.953125 | 4 | #! /usr/bin/env python
class Account:
account_count = 0
def __init__(self, balance, password):
self.__balance = balance
self.__password = password
self.bank = 'SC은행'
num1 = random.randint(0, 999)
num2 = random.randint(0, 99)
num3 = random.randint(0, 999999)
... |
5dd205aa92471bbb8c2f578baa2f77dd858cf698 | yeasellllllllll/bioinfo-lecture-2021-07 | /basic_python/210701_73.py | 630 | 3.765625 | 4 | #! /usr/bin/env python
'''
#강사님 방법
total = 0
for i in range(101, 200, 2):
total =+ i
print(total)
# 방법 2
myList = []
for i in range (100, 200, 2):
if i % 2 == 1:
myList.append(i)
print(sum(myList))
# 방법 3
print(sum(range(101, 200, 2)))
'''
'''
#내가 풀고싶은 방법 + 강사님 설명
inStr = input('a(space)b:')
a, b =... |
1774cdc97415daad7da927c6e84e900f96604def | yeasellllllllll/bioinfo-lecture-2021-07 | /rosalind/210703_141.py | 1,091 | 3.609375 | 4 | #! /usr/bin/env python
'''
#141
l_d = [100, 200, 300]
for i in l_d:
print(i + 10)
#142
l_d = ['김밥', '라면', '튀김']
for i in l_d:
print("오늘의 메뉴: ", i)
#143
l_d = ['SK하이닉스', '삼성전자', 'LG전자']
for i in l_d:
print(len(i))
# count(i)는 i가 몇개 있는 지 세어줘, len은 몇글자인지 알려줘
#144
l_d = ['dog', 'cat', 'parrot']
for i ... |
79e26bd800561248b90acf4bbe85386ba1b2fc7e | yeasellllllllll/bioinfo-lecture-2021-07 | /rosalind/210703_111.py | 1,430 | 3.71875 | 4 | #! /usr/bin/env python
'''
#111
h = "안녕하세요"
print(h * 2)
#112
h = 30
print(h + 10)
#113
h = input("num: ")
if int(h) % 2 == 0:
print("짝수")
else:
print("홀수")
#114
h = input("입력값: ")
if int(h) > 234:
print("출력값: ",255)
else:
print("출력값: ",int(h) + 20)
#115
h = input("입력값: ")
if int(h) < 20:
print(... |
9fc9df1a3b6028dffaae5efdfacc2b5577929ce2 | lihaoyang411/My-projects | /Encryption-Bros-master/Main.py | 1,947 | 4.15625 | 4 |
import sys
typeChosen = 0
def choose(choice):
while True:
if choice.find(".") >= 0 or choice.find("-") >= 0:
choice = input("You didn't type in a positive integer. Please try again: ")
else:
try:
choice = int(choice)
dummyNum = 2/choice
... |
da36f23c824c1486886db2295f6fa99c9726f52e | lihaoyang411/My-projects | /Festival_Bros-master/festival_scheduler.py | 4,288 | 3.78125 | 4 | import random.randint
import datetime
#Function that, given a location and genre, makes a list of possible festivals that the user would want to attend (including time conflicts, they will be accounted for in the scheduler)
def select_festival(location, genre, global_festivals_list):
possible_festivals = []
#Iterat... |
23334bd9745a107a337460c8cd4a2b8dcfa6a52d | Shiliangwu/python_work | /hello_world.py | 1,037 | 4.21875 | 4 | # this is comment text
# string operation examples
message="hello python world"
print(message)
message="hello python crash course world!"
print(message)
message='this is a string'
message2="this is also a string"
print(message)
print(message2)
longString='I told my friend, "Python is my favorite language!"'
pri... |
503e6699780112a8fea597e677cff4e7489a5524 | sn-ritika/python-problems | /Patterns.py | 568 | 3.953125 | 4 |
# coding: utf-8
# In[15]:
print('Given String: \n')
# In[16]:
str='abcdefghijklmnop'
# In[17]:
print(str)
# In[18]:
print('Required Pattern \n')
# In[19]:
for i in range(0,16,3):
j=i+4
print(str[i:j])
if i>=12: #to prevent 6th iteration
break
# In[20]:
input("... |
2cb5f89a49ec312fbc966dc23747cbdf7cd146c6 | Matthias-Rev/Avalam_IA | /tree_search.py | 8,247 | 3.734375 | 4 | import copy
from random import choice
import math
import time
liste_possible=[]
N=0
Path=[]
Moi=None
#permet de savoir quelle pion on est
def tour(num):
if num == False:
return 1
else:
return 0
#determine si qqun sait encore jouer
def winner(board, turn, number=0):
if len(verification(boa... |
bde6d52ed8e8578510e2e3ed47ca03fd13172c33 | anindo78/Udacity_Python | /Lesson 3 Q2.py | 698 | 4.15625 | 4 | # Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
def greatest(list_of_numbers):
if len(list_of_numbers) == 0:
return 0
else:
maximum = list_of_numbers[0]... |
376a28cf50efef77943dc3bfe75650de010bdb2a | TrellixVulnTeam/Python-Development_PSHU | /Day14/mycode.py | 1,451 | 3.78125 | 4 | from art import logo
import random
from game_data import data
from art import vs
print(logo)
def format_data(account):
account_name = account["name"]
account_title = account["description"]
account_place = account["country"]
return f"{account_name} a {account_title} from {account_place}"
def checker... |
7b88353d94cb47d4359ed903d6f5c1c28a68f9e4 | TrellixVulnTeam/Python-Development_PSHU | /Day 12/Guess the number.py | 1,200 | 4.0625 | 4 | import random
numbers = [25, 36, 47, 52, 65, 79, 88, 92]
Secret_number = random.choice(numbers)
print(Secret_number)
print('welcome to number guessing game')
print("i'm thinking of a number between 1 and 100")
level = input("choose difficulty level 'easy' or 'hard'").lower()
global find_number
def guess_number(count... |
76a212297eba0df0c6543cde7f58db7180c2cba1 | TrellixVulnTeam/Python-Development_PSHU | /Day5/FindMaxScore.py | 538 | 3.96875 | 4 | # 🚨 Don't change the code below 👇
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
print(max(student_scores))
print('*'* ... |
3b1f91648c76e30619c09fc543cc57b3914bc5a7 | TrellixVulnTeam/Python-Development_PSHU | /Day27/argsprog.py | 100 | 3.53125 | 4 |
def add(*args):
sum = 0
for n in args:
sum += n
print(sum)
add(1, 2, 3, 4, 5) |
0fc6e1ae13fecbc47013ddecc2b29ef71f13b8c6 | hamsemare/sqlpractice | /291projectReview.py | 2,985 | 4.28125 | 4 | import sqlite3
connection = None
cursor = None
name= None
# Connect to the database
def connect(path):
global connection, cursor
connection=sqlite3.connect(path)
cursor=connection.cursor()
def quit():
exit(0)
def findName():
global name
studentName= input("Enter Student Name: ")
if(studentName=="q" or stud... |
c2a93a6b2f178eccb56e89462cd62af169db32ed | Matijazajc/TicTacToe | /prvi.py | 941 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 11:31:01 2019
@author: MatijaZajc
"""
"""
How to play the game: enter which space you want
to put the X or 0 at (depending whos turn it is)
available places: top-L, top-M, top-R, mid-L, mid-M, mid-R, low-L, low-M,low-R
"""
theBoard = {'top-L': ' ', 'top-... |
3f30bad898e7fbaa90495f3f609f6f6c3d43ba78 | HunterOreair/Portflio | /RollDie.py | 942 | 4.1875 | 4 | #A simple python program that rolls die and returns the number that has been rolled. Made by Hunter Oreair.
from random import randint # imports randint. duh.
min = 1 #sets the minimum value on the dice that you can roll
max = 6 #sets the maximum value
def die(): # Creates a method called die
rollDie = r... |
e0a747bada81b1e1b1f1d5ad661149c278b1f7b1 | imu56473/cssi | /random.py | 193 | 3.734375 | 4 | import random
roll1 = random.randint (1,6)
roll2 = random.randint (1,6)
while (roll1 != roll2):
print ("roll # 1:",roll1)
print ("roll # 2:",roll2)
print("the total is:",roll1 + roll2)
|
6fd22bccc6c183790f2a45cfa314ec465ea1a8a2 | edanurtosun/super | /super.py | 344 | 3.71875 | 4 | class Kume(list):
def append(self,value):
if value in self:
return
super().append(value) #zaten sinifta var olan append #metodunu ezmek icin super() metodunu kullaniyoruz
a_kumesi = Kume([10, 10, 20, 30])
a_kumesi.append(100)
a_kumesi.append(200)
a_kumesi.append(100)
a_kumesi.appe... |
e677accb7b9d3f161a028ee950c247c0c66786d6 | jyongforever/ceshi09 | /try.py | 3,620 | 3.515625 | 4 | # -*- coding:utf-8 -*-
import time
# start1 = time.time()
# for i in range(100000):
# print('hello')
# end1 = time.time()
# print(end1-start1)
#
# start2 = time.time()
# i = 0
# while i < 100000:
# print('hello')
# i += 1
# end2 = time.time()
# print(end2-start2)
# print(end1-start1)
# i = 1
# n = int(inpu... |
4f6684fba945036624432b2dcfbbecd97d078bf3 | Kwon-YoungSun/python | /source/day01.py | 669 | 3.765625 | 4 | """
print("IDLE에서 파이썬 코드를")
print("작성해서 출력해보는")
print("예제입니다")
print("Hello!" * 3)
print("Hello Python")
# print()
print("출력", "출력")
"""
# 하나만 출력
print("# 하나만 출력합니다.")
print("Hello Python Programming...!")
print()
# 여러 개 출력
print("# 여러 개를 출력합니다.")
print(10, 20, 30, 40, 50)
print("안녕하세요", "저의", "이름은", "윤인성입니다!")
pri... |
ef550b06501f7d1af533b16b15a06435c5e4eef5 | amitaabhang/RutgersClass | /cw/03-Python/3/Activities/03-Stu_HobbyBook-Dictionaries/Unsolved/HobbyBook_Unsolved.py | 501 | 4.0625 | 4 | # Dictionary full of info
my_info = {
"Name":"Arisha",
"Age":4,
"Hobbies":["Drawing","Playing","Jumping","Running"],
"WakeUpTimes":{"Monday":7,"Tuesday":7,"Weekend":8.29}
}
# Print out results are stored in the dictionary
print(f'I am {my_info["Name"]} and I am {my_info["Age"]} years old')
print(f'I lo... |
99b6c5f996234adde17f7290b6492f5d7e8cbffc | PKatarina/UMCG-Microbiome | /PathwayTable_class.py | 1,277 | 3.59375 | 4 | import csv
class PathwayTable:
"""
A class for opening pathway files
"""
def __init__(self, table_name):
self.table = table_name
self.rows = []
self.total_abundance = 0
with open(self.table) as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t')
... |
2135d9d7648fb5e33f8b7ef891964dec8654b6e5 | li195111/DSNeRF | /utils/generate_html.py | 10,145 | 3.671875 | 4 | import dominate
from dominate.tags import *
import os
class HTML:
"""This HTML class allows us to save images and write texts into a single HTML file.
It consists of functions such as <add_header> (add a text header to the HTML file),
<add_images> (add a row of images to the HTML file), and <save> (sav... |
109d4aa9c58d4b6f98ca9ec3942cbc635bd5f485 | suyogrk/iw-python-assignment3 | /ds/quicksort.py | 1,060 | 3.90625 | 4 | # A3 - quick sort
def quick_sort(input_list):
quick_sort_helper(input_list, 0, len(input_list) - 1)
def quick_sort_helper(input_list, first, last):
if first < last:
split = partition(input_list, first, last)
quick_sort_helper(input_list, first, split - 1)
quick_sort_helper(input_list, s... |
d37effba012bfead25618794e61b25356ffd7ac0 | suyogrk/iw-python-assignment3 | /ds/linearsearch.py | 290 | 3.71875 | 4 | # a5 - linear search
def linear_search(input_list, item):
for i in range(len(input_list)):
if input_list[i] == item:
return i
return -1
input_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(linear_search(input_list, 93))
print(linear_search(input_list, 100))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.