blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c9fb8bf999abb5e8ab4d611967e2b7dd45d28ad5 | ralic/Note | /Algorithms/ClouldClass/week2/reversinglinkedlist.py | 635 | 3.734375 | 4 | class Node(object):
def __init__(self, address, data, node=None):
self.data = data
self.address = address
self.next = node
def create_node(self, nodelist):
while nodelist:
result = filter(lambda address: address == self.next.address, nodelist)
def __str__(self)... |
45de0a7e1f53ca3214b1d6533c26938a0e1e2e9a | ChrisAHolland/Kattis-Solutions | /ReverseBinary.py | 103 | 3.59375 | 4 | #!/usr/bin/env python3
x = bin(int(input()))
x = x.strip("0b")
x = x[::-1]
x = int(x,2)
print(x) |
0553c938ad254ebcbc895e347ca33adf7dd85941 | JohnnyDeuss/minesweeper-solver | /minesweeper_solver/policies/selection_methods.py | 3,017 | 3.546875 | 4 | """ This file defines a number of selection methods that can be used in `policies.make_policy`. """
from random import randrange
import numpy as np
from scipy.ndimage.morphology import binary_dilation
def nearest(preferred, prob):
""" Select a square that is nearest, as defined by the Manhattan distance, to an a... |
da240d2c009162d6ec9eccf8b0801dbe3373262e | DanKirby1996/Software-Engineering-Final-Project | /cse416-master/data/scripts/verify_neighbors.py | 843 | 3.90625 | 4 | #!/usr/bin/env python3
#
# Used to verify neighbors file.
# Checks that any given entry should have a returning edge.
import sys
import json
from collections import defaultdict
if len(sys.argv) != 2:
print(f"{sys.argv[0]} [neighbors file to check]")
sys.exit(0)
neighbors_file = sys.argv[1]
neighbors_dict =... |
8f3091c519db1ef737291f844ad1c5a984ca120c | xukangjune/Leetcode | /solved/241. 为运算表达式设计优先级.py | 1,278 | 4.125 | 4 | """
分治算法。就是“分而治之”,将一个大问题分解成小问题,然后解决小问题的后,再解决大问题。这题就是分治算法。首先,如果字符串中含有运算符,那么对于每个
运算符都可以将字符串分成两部分,左边和右边。递归返回的左边和右边都是数字,然后根据运算符的不同,将数字两两运算。递归到最后,如果最后的字符串只含有
数字,那么就直接返回数字。
"""
class Solution:
def diffWaysToCompute(self, input):
if input.isdigit():
return [int(input)]
ret = []
for i i... |
3290cd16f7ef5ff39e9479067c5ec8886ab1443d | Sniperhorus/Python | /Ejercicios_basicos.py | 1,252 | 4.40625 | 4 | """
Los siguientes, son una serie de ejercicios que tienen como
finalidad el que tu practiques los conocimientos adquiridos a
lo largo de este segundo bloque.
"""
# Dado de los valores ingresados por el usuario (base, altura)
# Calcular y mostrar en pantalla el área de un triángulo.
print("+++++++++++++++... |
da032d5c0780a41d86d09dbe0d7f23ecc350a7c1 | XinWei-Yang/algorithms | /algorithms/search/first_occurrence.py | 663 | 4.0625 | 4 | """
Find first occurance of a number in a sorted array (increasing order)
Approach- Binary Search
T(n)- O(log n)
"""
def first_occurrence(array, query):
"""
Returns the index of the first occurance of the given element in an array.
The array has to be sorted in increasing order.
"""
low, high = 0, ... |
96dd434c558242f717dcfa0832727dd73bcf9bd6 | Sashlin-Dean-Moonsamy/FInance-Calculator | /finance_calculators.py | 2,125 | 4.40625 | 4 | import math
#Set boolean values
investment= False
bond= False
#request that user choose which type of calculation they want to do
print("""Chooose either 'Investment' or 'Bond' from the menu below to proceed:
Investment - to calculate the amount of interest you'll earn on an interest
Bond - to calcul... |
a9df2657b8a200508690c173bb6196c91ffae411 | oxhead/CodingYourWay | /src/lt_344.py | 677 | 4.03125 | 4 | """
https://leetcode.com/problems/reverse-string
Related:
- lt_345_reverse-vowels-of-a-string
- lt_541_reverse-string-ii
"""
"""
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
"""
class Solution:
def reverseString(self, s):
... |
583c14ea3b009c8e4b6ffa4aa12920ac073bbfe4 | roger6blog/LeetCode | /SourceCode/Python/Problem/00218.The_Skyline_Problem.py | 4,148 | 3.875 | 4 | '''
Level: Hard
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city
when viewed from a distance.
Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo
(Figure A),
write a program to output the skyline formed by these building... |
0b530a2fc6b9bf0b91f0fbb6dc14b1218fbc758a | sairina/python-practice | /scratch.py | 1,763 | 3.5625 | 4 | import json
import requests
''' All from realpython.com/python-json/'''
response = requests.get("https://jsonplaceholder.typicode.com/todos")
todos = json.loads(response.text)
# json.loads turns the response into a dictionary
todos == response.json()
''' MANIPULATE JSON DATA AS NORMAL PYTHON OBJECT '''
# map of us... |
e3c4d95831d4500ffe64f1e56d29daf9e3ee1b95 | juanma414/ayedd-if | /ejercicio7.py | 547 | 4.03125 | 4 | t = str(input("Ingresar tipo de pieza (a/b): "))
if (t != "a" and t !="b"):
print ("el valor ingresado no es un tipo de pieza válido")
else:
m = int(input("Ingresar la medida: "))
if t=="a":
if m >= 163 and m <= 167:
print("Cumple con las especificaciones")
else:
... |
c5b912b33cefe3bd0401847395bd9767b4ac19ce | RiyaGaur/Python-Programming | /Shape and Reshape/solution.py | 91 | 3.640625 | 4 | import numpy
n=input()
list=(n.split( ))
arr=numpy.array(list,int)
print(arr.reshape(3,3))
|
939693a0da8197861ec5cc1eb10764239e02a131 | panarnold/python-projects | /python-theory/inheritance-and-composition.py | 3,046 | 3.8125 | 4 | # inheritance: dziedziczy, rozszerza, czerpie (derive) np Horse IS Animal
# composition: relacja 'has' CompositeClass HAS a ComponentClass, Horse HAS a Tail
#composition umozliwia reuzywanie kodu przez dodawanie ich do innych obiektów
#wszystko w python jest obiektem: moduły, definicje klas i funkcji są obiektami, o... |
02d11f6137dcb7598db370dfa175157f2b65ab26 | waltman/advent-of-code-2017 | /day23/coprocessor_conflag2.py | 390 | 3.5 | 4 | #!/usr/bin/env python3
MIN = 108100
MAX = 125100
STRIDE = 17
# sieve
isPrime = set()
for i in range(MAX+1):
isPrime.add(i)
for i in range(2, MAX+1):
if i in isPrime:
for j in range(i*2, MAX+1, i):
if j in isPrime:
isPrime.remove(j)
cnt = 0
for i in range(MIN, MAX+1, STRID... |
52b128155e9de0e9808da669d8854534c900d4c9 | TesterCC/Python3Scripts | /mooc_python/programming/practice4_sum_prime_number.py | 1,412 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2019-04-12 16:26'
"""
100以内素数之和
描述
求100以内所有素数之和并输出。
素数指从大于1,且仅能被1和自己整除的整数。... |
660ea6f06891d603654c2d7d9535a41acffd7f86 | yenpinchiu/Eight-Legged-Essay | /LeetCode19_Remove_Nth_Node_From_End_of_List.py | 1,651 | 3.953125 | 4 | '''
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
'''
# Definition f... |
ec0e09f2db2f1e440f07047824f75f56186d521a | bfirner/armada-player-demo | /base_agent.py | 1,312 | 3.625 | 4 | #! /usr/bin/python3
#
# Copyright Bernhard Firner, 2019
#
# The agent must choose which actions to take. An agent takes the form of:
# (world state, current step, active player) -> action
#
# There are quite a few steps in Armada.
class BaseAgent:
"""The base agent. Replace the internal functions to implement... |
1553d2cb3364bbbadcd20e41bd0385448a09865c | Bao-Learning-School/Tutorial | /image_lib.py | 8,654 | 3.515625 | 4 | """Manages pygame images"""
import collections
import os
from typing import List, Optional, Tuple
import pygame
class Animator(object):
"""Animates a sequence of images."""
def __init__(self, owner: Optional[pygame.sprite.Sprite]=None):
"""Creates an image animator.
Args:
owner: Owner of this anima... |
7b52d3a00b7dadb17cad1a2ac047e69a09201402 | rockomatthews/Dojo | /Python/toinCoss.py | 369 | 3.53125 | 4 | import random
def toss(Amount):
heads = 0
tails = 0
for x in range(1, Amount):
new_toss = random.randint(0,1)
if round(new_toss) == 1:
heads += 1
else:
tails += 1
print "There were " + str(heads) + " heads and " + str(tails) + " tails flips. (tails ... |
726cd8906ae7a849b83127d0e08bfac4f177f46b | szabgab/slides | /python/examples/csv/count_csv_rows.py | 1,089 | 3.75 | 4 | import csv
import sys
from collections import defaultdict
def check_rows(filename):
rows = []
widthes = defaultdict(int)
with open(filename) as fh:
rd = csv.reader(fh, delimiter=';')
for row in rd:
width = len(row)
rows.append(width)
widthes[width] += 1
... |
10fa0843d587069d75986bd5eeec3c307ed33efa | chanrl/bettingmodel | /knn.py | 9,970 | 3.921875 | 4 | """
Functions and classes to complete non-parametric-learners individual exercise.
Implementation of kNN algorithm modeled on sci-kit learn functionality.
TODO: Improve '__main__' to allow flexible running of script
(different ks, different number of classes)
"""
import numpy as np
import pandas as pd
from colle... |
49c1984dd1ed9e587758a8d7d248af1e5f11e4e8 | DSR1505/Python-Programming-Basic | /02. For loops/2.03.py | 133 | 3.546875 | 4 | """ Write a program that outputs 100 lines, numbered 1 to 100, each with
your name on it. """
for i in range(100):
print(i+1,'DSR') |
2416bb2ff294f45b1c3fb45633c79de43b251531 | thrishik7/ML-algos | /linear_regression.py | 2,063 | 3.671875 | 4 | import pandas as pd
from pandas import DataFrame
import numpy as np
import matplotlib.pyplot as plt
#LINEAR REGRESSION
def initialize_parameters(lenw, b=0):
w= np.random.randn(1,lenw)
return w,b
def forward_prop(X,w,b):
z=np.dot(w,X) +b #hypothesis
return z
def cost_function(z,y):
m= y.shape[0]
... |
5870ceb75f5842badd837fed1931aadcfd18ff92 | skellykiernan/pylearn | /VI/ch29/specialize.py | 924 | 3.734375 | 4 | class Super(object):
"""Top class"""
def method(self):
"""example method"""
print("in Super.method")
def delegate(self):
"""call a action if defined in subclass"""
self.action()
class Inheritor(Super):
"""all methods in Super"""
pass
class Replacer(Super):
"""... |
9494ac43f651c653f97ed0337427d2b6cc4edd5b | PJHalvors/Learning_Python | /ZedEx5to8.py | 3,462 | 4.1875 | 4 | #!/bin/env/python
#This program contains exercises Num5 to Num8 from Zed's Book
#Exercise5:Printing with variables
#Set variables to numeric or characters
name = "PJ"
age = 25 #arbitrary number
ht = 68.125 #also arbitrary
wt = 125 #also also arbitrary
eyes = 'Almond'
teeth = 'White'
hair = 'Purple-Undercut' #I total... |
5142a2061f67f69daa9329dffe5abf27025dd2d8 | wfwf1990/python | /Day2/zuoye.py | 281 | 3.6875 | 4 |
#打印出所有三位数中的水鲜花数
num = 100
while num <= 999:
num1 = num // 100
num2 = num // 10 % 10
num3 = num % 10
if num == num1 ** 3 + num2 ** 3 + num3 ** 3:
print(num)
num += 1
ge = " "
str1 = input("str:")
print(str1.count(" "))
|
97216740dd0b98638ad62846afee34bac659a97f | innalesun/repetition-of-the-material | /функции/les10.07.py | 896 | 3.875 | 4 | '''
p = lambda x=1,y=2:x**y
s = p
print(s(5))
'''
def f_func():
print('test func1')
def sec_func():
print('test func2')
def sim_func(fn):
print('start')
fn()
print('stop')
a = sim_func(f_func())
b = sec_func(sec_func())
'''
def simple_decore(fn):
print('start function')
fn(... |
65b5caa728844dec3dd6d38fa7b1242b6d365bb8 | tillderoquefeuil-42-ai/bootcamp-ml | /day04/ex12/polynomial_model.py | 946 | 4.1875 | 4 | import numpy as np
def add_polynomial_features(x, power):
"""
Add polynomial features to vector x by raising its values up to the power given in argument.
Args:
x: has to be an numpy.ndarray, a vector of dimension m * 1.
power: has to be an int, the power up to which the components of vect... |
556e3c6a72cc8bcee51baa8a8afa17eb2f90bbad | pjedur/python | /Verkefni1/palindrome.py | 252 | 3.703125 | 4 | def palindrome(n,b):
if n < b:
x = format(n)
return x == x[::-1]
if b == 10:
x = format(n)
return x == x[::-1]
if b == 2:
X = bin(n)[2:]
return X == X[::-1]
return False
|
b10d24079c9637043111c3a74837e10ebe156e1e | Quelklef/gin-bots | /bots/simple/simple_gin.py | 1,007 | 3.71875 | 4 | """ A simple gin bot """
import random
import sys
sys.path.append('../..')
import gin
import client
def choose_draw(hand, history, derivables):
""" choose where to draw a card from """
discard = derivables['discard']
their_hand = derivables['other_hand']
current_points = gin.points_leftover(hand, their_han... |
e36ba285d16f0676270d3833d1aa0880e54c8a17 | Llontop-Atencio08/t07_Llontop.Rufasto | /Rufasto_Torres/Bucles.Mientras.py | 1,427 | 3.96875 | 4 | Ejercicio01
#Pedir edad de ingreso a la escuela PNP
edad=10
edad_invalida=(edad<16 or edad >25)
while(edad_invalida):
edad=int(input("ingrese edad:"))
edad_invalida=(edad<16 or edad >25)
#fin_while
print("edad valida:",edad)
#Ejercicio02
#Pedir nota de sustentacion de tesis
nota=0
nota_desaprobada=(nota<12 or... |
16a5025f389caa8761f4fd198ddce941d3d6a42c | akarshvs/LOGIC-BUILDING-PYTHON | /reversesent.py | 212 | 3.65625 | 4 | sent = input()
sent = sent[:-1]
count = 0
word_lis = sent.split(' ')
for word in word_lis:
count +=1
print(f'LENGTH : {count}')
print('REARRANGED SENTENCE')
print(*sorted(word_lis),sep=' ',end='.')
|
6123e4f75ef3ab051b9d47c9ca17dcbc566a3e91 | godarderik/projecteuler | /Solved/Problem62.py | 486 | 3.515625 | 4 | cubes = {}
for z in range(10000):
sort = list(str(z**3))
for x,y in enumerate(sort):
sort[x] = int(y)
sort = sorted(sort)
for x,y in enumerate(sort):
sort[x] = str(y)
sort = "".join(sort)
if sort in cubes:
cubes[sort][0] += 1
cubes[sort][1].append(z**3)
i... |
3dc0655e7b208b9fd45777a4a4125a712f588eae | erjan/coding_exercises | /subsets_ii.py | 562 | 3.765625 | 4 | '''
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
'''
class Solution(object):
def subsetsWithDup(self, nums):
ret = []
self.dfs(sorted(nums), [], ret)
... |
c07feb81c09c8a5b4e5d73ed3f4df146413acbde | purnesh42H/algorithms-in-python | /python_modules_and_structures/python_modules_basic.py | 2,210 | 4 | 4 | '''
Note that functions are also treated as objects in python. When def is
executed, a function object is created together with its object reference.
If we do not define a return value, Python automatically returns None
An activation record happens every time we invoke a method: information
is put in the stack to sup... |
d9763ecec0aa411ba014d6fb25e29b0f0273fcb7 | ITlearning/ROKA_Python | /2021_03/03_07/input_error.py | 133 | 3.671875 | 4 | string = input("입력 > ")
print("입력 + 100 : ", string + 100)
# input 함수의 입력은 무조건 문자열 자료형이다. |
5a6647baedeb215e44f993773b29a4aae4c231f7 | rezavai92/leetcode-solution | /24. Swap Nodes in Pairs/python-solution.py | 711 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swap(self,head):
current = head
fakeHead = ListNode()
fakeHead.next=head
prev=fakeHead
while(current... |
b0f86b213d708b9b91f8d096f83f60853882b08e | ft25/Python-Programming | /codekata/count_no_of_digits.py | 43 | 3.5 | 4 | num=(input("enter a no:"))
print(len(num))
|
94bde5490afe3cbe2205576585ff509d7bc37d00 | wuqunfei/algopycode | /leetcode/editor/en/[1114]Print in Order.py | 2,109 | 4.15625 | 4 | # Suppose we have a class:
#
#
# public class Foo {
# public void first() { print("first"); }
# public void second() { print("second"); }
# public void third() { print("third"); }
# }
#
#
# The same instance of Foo will be passed to three different threads. Thread A
# will call first(), thread B will cal... |
51f87001e2bf858026345886206cc5489af01f9c | Utugoed/SimpleBankingSystem | /banking.py | 4,837 | 3.640625 | 4 | import random
import sqlite3
def luhn(number):
sum = 0
for i in range(15):
if i % 2 == 0:
k = int(number[i]) * 2
if k > 9:
k -= 9
sum += k
else:
sum += int(number[i])
sum = (10 - sum % 10) % 10
return str(sum)
def create_a... |
0a32ad2ce7f63f6a610530b4b65d277b45ca8aeb | zmatteson/clrs-algorithm | /chapter_2/exercices/2_1_4.py | 718 | 4.03125 | 4 | #Add 2 n bit binary integers, stored in two n-element arrays
#The sum should be stored in binary form in an (n + 1) array C
#Input 2 Arrays of size n representing binary ints
#Output one array of their sum with size n+1
def add_binary_ints(A,B):
C = []
carry = 0
for i in range(len(A)-1, -1, -1):
s ... |
9e5b35dcbef3b32d31df04981e4e1673ca3c7fe0 | angelosuporte/PythonLearning | /app_pyLearning/ClassExample2.py | 542 | 3.8125 | 4 | class Calculadora:
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplicacao(self, valor_a, valor_b):
return valor_a * valor_b
def divisao(self, valor_a, valor_b):
return valor_a / val... |
864459b88c5b38c5119e8ef0ef0f4dedf057203d | fengye-lu/python_fullstack_oldboy | /week/day27/threading_test.py | 1,323 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/2/29 15:35
# @Author : Jackey-lu
# @File : threading_test.py
import threading
from time import ctime, sleep
# def music(func):
# for i in range(2):
# print('I was listening to %s. %s'%(func,ctime()))
# sleep(1)
#
# def move(func):
# for i in range(... |
aa945ff2466efdb5c73300c1c60f4a844ebac4bb | mrdotb/computor_v1 | /main.py | 461 | 4.09375 | 4 | #!/usr/bin/env python3
import sys
from Equation import Equation
argc = len(sys.argv)
if argc < 2:
sys.exit("Missing argument")
elif argc > 2:
sys.exit("Too much arguments")
e = Equation(sys.argv[1])
print("Input form: ", e.format())
e.simplify()
print("Reduced form: ", e.format())
print("Polynomial degree... |
7383a4bd0d840e2f1aba926361538461e4e182ad | chachout/Python-petits-programmes | /Conversion des degrés en radians.py | 93 | 3.921875 | 4 | d=float(input("angle en degré : "))
r=(d*2.*pi)/360.
print (d,"degrés font",r, "radians") |
22a8a7e7165d12252e040f2632c6fad41ced8727 | aryan-jain/ping-pong-leaderboard | /matchups.py | 1,599 | 3.625 | 4 | import argparse
import itertools
def main():
matchups = []
if args.type == "singles":
for player in itertools.combinations(args.players, 2):
sit_out = tuple([p for p in args.players if p not in player])
matchups.append((player[0], player[1], sit_out))
elif args.type == "do... |
f6dd03a1c32adcd21f71856c1c51840d0ad1b6d9 | RafaelMri/boolean | /monotone.py | 12,707 | 3.640625 | 4 | """
This code supports functions that are of the form {0,1} ** n ==> {+1, -1}
This has two reasons:
* {0, 1} ** n allows us to use the binary representation which is convenient
* {+1, -1} is better when we want to work with fourier. Note that "+1 < -1" for that matter!
"""
import numpy
import itertools
import random
f... |
b1662b04a4b1b8d3ffd1e018abd69f4efcdce832 | colephalen/SP_2019_210A_classroom | /students/TylerRay/session3/mailroom.py | 2,796 | 4.15625 | 4 | #!/usr/bin/env python3
donors = [("Alpha Beta", [1000.21, 250.80]),
("Tucker Jones", [800.33]),
("Vladmir Putin", [500000.12, 250000.55, 750000]),
("Kim Jong Il", [200.80]),
("Tony Robinson", [500000, 1000000, 750000])]
donor = donors[0]
donations = donors[1]
def main_menu():... |
04817964cab3a318856299d0422111afe7d53a2c | Darssh/Codewars | /Python-Solutions/first_non_repeating_character.py | 833 | 4.25 | 4 | """
Write a function named firstNonRepeatingCharacter that takes a string input,
and returns the first character that is not repeated anywhere in the string.
For example, if given the input 'stress', the function should return 't',
since the letter t only occurs once in the string, and occurs first in the string.
As... |
fc78c8787652766fe6aedad0f9c14214b3865397 | atyndall/cits4211 | /tools/helper.py | 1,143 | 3.703125 | 4 | import collections
UNICODE = True # Unicode support is present in system
# The print_multi_board function prints out a representation of the [0..inf]
# 2D-array as a set of HEIGHT*WIDTH capital letters (or # if nothing is there).
def print_multi_board(a):
for row in a:
print(''.join(['#' if e == 0 else ch... |
907355b5dd8f493e23dbb249fab31856e78ddf8e | aanchal-jain/ProjectEuler | /euler_12.py | 222 | 3.53125 | 4 | def countDivisors(n):
res=[1,n]
for i in range(2,n//2+1):
if(n%i==0):
res.append(i)
return(len(res))
countDivisors(28)
x = 55
y = 11
while(countDivisors(x)<=500):
x+=y
y+=1
print(x)
|
aa78c514be6b7101575c85689c11b5e13d1cc1c1 | TrellixVulnTeam/pythonProgramming_YW7W | /Chapter10/quiz_4_19.py | 1,542 | 3.8125 | 4 | class Student(object):
def __init__(self, s_name):
self.name = s_name
self.totalQuizScore = 0
self.quizScoreList = []
self.numQuizes = 0
self.classes = []
self.grades = []
self.totalgpa = 0
def getName(self):
return self.name
def getNumQuize... |
4fb3dbc508059d9074042cc185e0512da11aa3c5 | CMetzkes/exercise | /scripts/python_ersteschritte.py | 998 | 3.5625 | 4 | 1
type(1)
1.
type(1.)
1+1.
x = 1.
x
x == 1.
x < 1.
x + 1.
x += 1. # X wird verändert, Ergebnis x=2
x
# Funktionen definieren
def addiere(x, y):
return x+y # einrücken
addiere
addiere(1.,1.)
addiere('a','b')
addiere(1. ,'b')# Fehlermeldung: Lösung: str(1.)
# Klassen: beschreiben, welche Attribute und Methoden Ob... |
9999e25883b00195d522aecef1b9dd3e835547c7 | nicohervith/Python | /Test_Funciones.py | 542 | 3.765625 | 4 |
def input_con_confirmacion(pregunta):
confirmacion = False
dato_usuario = ""
while not confirmacion:
dato_usuario = input(pregunta)
seguro = input("Dijiste {}, ¿Estás seguro? [ si / no ]".format(dato_usuario))
if seguro == "si":
confirmacion = True
return dato_usuar... |
a366043bb5e6902c35d10a0d2a4c4f20f7c00e59 | kuba332211/gitrepo | /gitrepo/python/potega.py | 700 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# potega.py
# obliczanie potęgi podstawy podniesionej do wykładnika
def potega_it(a, n):
wynik = 1
for i in range(n):
wynik = wynik * a
#print(wynik)
return wynik
def main(args):
#a =int(input("Podaj podstawę: "))
#... |
7b367a7c664a0da65d56656d613253b6e2483f90 | licaoyuan123/HackerRank | /MaxArraySum.py | 1,190 | 3.84375 | 4 | '''
To address with DP, work through the array, keeping track of the max at each position until you get to the last value of the array. You should start with the base cases defined before iterating through the remainder of the array.
max @ position 0: value @ 0
max @ position 1: either:
value @ 0
value @ 1
from that... |
0355384daee309ee35b9450eebc69ba185803b99 | MaximeMoutet13/Stage_2020 | /tbs/graph/_graph.py | 5,304 | 3.5 | 4 | import json
from ._mixed_graph import MixedGraph, UNDIRECTED_EDGE
class Graph(MixedGraph):
"""Generic undirected Graph class."""
def __init__(self, vertices=tuple(), edges=tuple()):
"""An undirected graph.
Args:
vertices (iterable): each vertex must be *hashable*.
ed... |
a1ca6b3f1d873b015d392ea8e699d1ceaef23c40 | pranavgokhale95/alpha_full | /A4/final.py | 1,736 | 3.5625 | 4 | '''
This code works!
I have no idea what is expected in assignment
it writes current state of philosopher and time to mongodb
you should have mongodb server running
follows similar solution : https://www.youtube.com/watch?v=_ruovgwXyYs
'''
import threading
import time
from pymongo import MongoClient
class Philosoph... |
b0adea411997f2032147b728ccccdf68770b141a | SylphDev/Actividades_Algoritmos | /prepas_ejercicios/2_semana/prepa2.2.py | 1,233 | 3.9375 | 4 | #Ejercicio 2.2: Diseña un programa que determine si un número o palabra ingresados por teclado, son palíndromos o no.
class Word:
def __init__(self):
self.word = ''
def get_input(self):
'''
Obtiene del usuario una palabra o secuencia de numeros
y verifica si es valido
... |
f6ab372bf0cad0f433798a838529de4622c7221b | PiyushChaturvedii/My-Leetcode-Solutions-Python- | /Leetcode 2/Intersection of Two Linked Lists.py | 1,294 | 3.671875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not... |
fb11af4abd0a65bf50bc4712a2f5f265b9663aa5 | EldanGS/patterns | /src/creational_patterns/singleton/singleton_metaclass.py | 943 | 4.15625 | 4 | """ Intent:
Singleton is a creational design pattern that lets you ensure that a class has
only one instance, while providing a global access point to this instance.
"""
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance ... |
fa80d16432ff770487ed942e410e1567e0065bbd | SandeepKumarShaw/python_tutorial | /new folder/nested_if_else.py | 291 | 3.984375 | 4 | winning_number = 4
user = int(input("enter any number between 1 and 10 :-"))
if user == winning_number:
print("you selected a right number")
else:
if user > winning_number:
print("you enter number is too heigh")
else:
print("you enter number is too low")
|
b9f83171f60dd37c145e705eb3f77156a6178538 | kazice/Python-Algorithm | /SortAlgorithm/orientBubbleSort.py | 665 | 3.890625 | 4 | #!/usr/bin/python
# -*- coding:utf8 -*-
# 定向冒泡排序,又叫鸡尾酒排序
# 此算法与冒泡排序的不同处在于从低到高然后从高到低
def orientBubbleSort(num):
length = len(num)
left, right = 0, length-1
while left < right:
i = left
while i < right:
if num[i] > num[i+1]:
num[i],num[i+1] = num[i+1],num[i]
... |
b4a3618f3b9a6cb852c496b19735b62194e71456 | shankarapailoor/Project-Euler | /Project Euler/p10-20/p13.py | 1,018 | 3.6875 | 4 | from copy import deepcopy
def findCollatzSequence(x):
y = deepcopy(x)
collatzsequence = [y]
if x == 1:
return 1
while x > 1:
if x % 2 == 0:
x = x/2
t = 0
t = deepcopy(x)
collatzsequence.append(t)
else:
x = 3*x + 1
z = 0
z = deepcopy(x)
collatzsequence.append(z)
return len(collatzsequ... |
b6c51a8ba737f755b4e0facdba897a4b14efdbb7 | JATP98/Listas-de-python-recuperacion | /eje3.py | 719 | 4.09375 | 4 | # Dada una lista de números enteros
# (guarda la lista en una variable) y un entero k,
# escribir un programa que:
#Cree tres listas listas, una con los menores, otra con los
#mayores y otra con los iguales a k.
#Crea otra lista lista con aquellos que son múltiplos de k.
listaenteros=[1,2,3,4,5,6,4,6,4,7,8,9,4]
numer... |
d05e38034338f47dc92e24394c3c5f43f5ef364c | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/grains/1295ac1334f8416a949638880bbf7117.py | 201 | 3.59375 | 4 | __author__ = 'tracyrohlin'
def on_square(n):
return 2 ** (n-1)
def total_after(num):
if num == 1:
return on_square(num)
else:
return on_square(num) + total_after(num - 1)
|
467409fb46e5d80265b787e211c8c6306fae7eb9 | Anil314/HackerEarth-Solutions | /Implementation/Roy's Life Cycle.py | 2,415 | 3.515625 | 4 | '''
Roy is going through the dark times of his life. Recently his girl friend broke up with him and to overcome
the pain of acute misery he decided to restrict himself to Eat-Sleep-Code life cycle. For N days he did
nothing but eat, sleep and code.
A close friend of Roy kept an eye on him for last N days. For every s... |
cbf863520fb8d36ff7eff85b90e0a06f33aec135 | gabrielwallaceBDS/faculdade- | /aula 2 pratica/expressaoAlgebrica.py | 521 | 4.0625 | 4 | """
ESCREVA AS SEGUINTES EXPRESSOES ALGEBRICAS EM LINGUAGEM PYTHON
A)O SOMATORIO DOS 5 PRIMEIROS NUMEROS INTEIROS E POSITIVOS
B) A MEDIA ENTRE 23, 19 E 31
C) O NUMERO DE VEZES QUE 73 CABE EM 403
D) A SOBRA QUANDO 403 É DIVIDIDO POR 73
E) 2 ELEVADO Á DECIMA POTENCIA
F)O VALOR ABSOLUTO DA DIFERENCA ENTRE 54 E 57
G)O ME... |
547af9fb67c9b8719c060dca0d2623911c3819a9 | 1Aanshu/Python01 | /corepython01/my_libs/MyFunctions.py | 494 | 3.84375 | 4 | def f1():
print("Hello from f1 function")
print("My name is Aanshu Dwiwedi")
print("Ktm")
print("Bye")
"""
def f2(num1):
print("Aanshu Sum")
print(num1)
"""
def f3(num1, num2):
num3 = num1 + num2
print("Num1 : ", num1)
print("Num2 : ", num2)
print("Sum :", num3)
def f4():
... |
a579702348c911173956c23180da8dbd5183f34d | Gigio212/Tarea-04 | /Software.py | 1,702 | 4.03125 | 4 | #Encoding: UTF-8
#Autor: Rodrigo Rivera Salinas
#Descripcion: Dependiendo el numero de paquetes que se compro, se aplicara un descuento dependiendo del numero de paquetes y se imprimira el costo total
def descuentoEnPaquetes(paq,precio):
if paq <= 0:
return("Error, ingresar numero de paquetes validos")
... |
8224c2897f460d444e8e6dfc22bae47d8e034d17 | zhangzhenyu13/AudioSegmentation | /AudioSubtitleSegmentation/TextNormailzation/normalize_transcription.py | 7,128 | 3.515625 | 4 | import requests
import time
import random
import string
import json
import unicodedata
import regex as re
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally conside... |
926e88c0edd8d8d3a29f528fba82efc0fd1c838e | jambellops/redxpo | /mitx6.00/creditcode.py | 2,643 | 4.28125 | 4 | ##
## Title: Credit statement
## Author: James Bellagio
## Description: Calculation of Credit Statement assignment for edx mit 6.00 week 2
##
##
##
##
##
##
# def balance_unpaid(balance, payment):
# """ function of remaining balance after payment
# parameter: balance = initial balance
# parameter: pa... |
03a636be3d6264eebd6ba7a29d1b26fb98c3485e | shvekh/Laborator | /Laboratorn 2/Lab2.1(мой).py | 281 | 3.953125 | 4 | my_number=int(input("Задаем число = "))
user_number=int(input('Введите число: '))
while user_number!=my_number:
print("Не совпадает")
user_number=int(input('Введите число повторно: '))
print('Совпадает')
|
c45dd95cb6317c8dcf3724495ad5a1b0f1c59f6d | delete00man/password-generator | /password_generator.py | 7,995 | 3.84375 | 4 | from tkinter import *
from tkinter import Tk
import string
from random import randint,choice
from time import sleep
passwordlogin = ""
usernamelogin = ""
password = ""
def login():
login_infos = open("login.txt", "r")
login_infos = login_infos.read()
list_login_infos = login_infos.split(",")
usernamel... |
bc1d14c731eedf763741e3e61a94ddaa396f81e4 | skinder/Algos | /PythonAlgos/flattenarray.py | 739 | 4.28125 | 4 | '''
Given a nested array of values, write a function to return a flattened array containing only the integer values.
Ex.
Input: [6, 2, [1, [9, 3], [1, 2], [True], 'hello world', [None] ], 2]
Output: [6, 2, 1, 9, 3, 1, 2, 2]
'''
def flatten(arr):
flattened = []
for i in arr:
if type(i) == list:
... |
59521c808d11785066664fcc21a6acb918e8e4f4 | Seowyongtao/turtle-crossing | /car_manager.py | 660 | 3.6875 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager(Turtle):
def __init__(self):
super().__init__()
self.moving_distance = STARTING_MOVE_DISTANCE
self.random_color = random... |
81402bd143d7f66d5a1bbd47b9a40c482c6480fe | hvy/pfi-internship2016 | /assignment1.py | 730 | 4.4375 | 4 | def outer(x, y):
"""Compute the outer product of two one-dimensional lists and return a
two-dimensional list with the shape (length of `x`, length of `y`).
Args:
x (list): First list, treated as a column vector. 1 dimensional.
y (list): Second list, treated as a row vector. 1 dimensional.
... |
36b7eb9438a4edb1eafb53012a3b2a65161fcd73 | ivadimn/py-input | /mthreads/locks/locks2.py | 3,915 | 4.0625 | 4 | import random
from collections import defaultdict
import threading
FISH = (None, 'плотва', 'окунь', 'лещ')
###
# Другая проблема с блокировками: они могут быть взаимными.
# Один поток заблокировал ресурс A и ему нужен ресурс Б, а другой поток наобарот - заблокировал Б и ждет А.
def func_1(n):
global a, b
f... |
51b645e61372ec1d11fff2038286a000dd94684c | mohan1411-qa/TC_PYTHON_1411 | /tic_tac_toe_v1.py | 4,465 | 3.875 | 4 | import random
import emoji
def display_board(board):
print(' ' + board[1] + '||' + board[2] + '||' + board[3])
print('----------')
print(' ' + board[4] + '||' + board[5] + '||' + board[6])
print('----------')
print(' ' + board[7] + '||' + board[8] + '||' + board[9])
print('----------')
def p... |
c367c0fd72392e0e37639897882bb130ea6ad03d | walsh06/sportsanalysis | /premierleague.py | 3,701 | 3.515625 | 4 | headers = ['Pos','Team', 'Pld', 'W', 'D', 'L', 'GF', 'GA', 'GD', 'Pts']
def printHeader(heading):
print "============================"
print heading
print "============================"
def readCSV(filename):
with open(filename) as f:
contents = f.readlines()
seasons = {}
reading = Fals... |
aefbde1daef14b3bd4ebc4b073d444d7d37d5848 | danieltavares1301/alunos_matriculados | /tres.py | 632 | 3.640625 | 4 | class Aluno:
# inicializando com nome do aluno e sua matricula
def __init__(self, nome, matricula):
self.nome = nome
self.matricula = matricula
self.nota1 = 0
self.nota2 = 0
self.trabalho = 0
# adicionando notas e trabalhos
def addNotas(self, nota1, nota2, trabal... |
65ed11c44d0f40c1c7474b0227e65315516c4045 | skulumani/algorithm_practice | /binary_search.py | 1,991 | 4.03125 | 4 | """Binary search of an array in python
Given a sorted array A[] ( 0 based index ) and a key "k" you need to complete
the function bin_search to determine the position of the key if the key is
present in the array. If the key is not present then you have to return -1.
The arguments left and right denotes the left m... |
f6516d5d34bf13f64cc6904a597da004896238f0 | Aasthaengg/IBMdataset | /Python_codes/p02379/s204323871.py | 118 | 3.59375 | 4 | import math
x1,y1,x2,y2=map(float,input().split())
x2=x2-x1
y2=y2-y1
x1,y1=0,0
dis=(x2**2+y2**2)
print(math.sqrt(dis)) |
3279f0cd3a69fc54d618a2dee41034f10e5eddc8 | mallory-jpg/bank | /bank_interface.py | 2,039 | 3.5625 | 4 | """Connect to database & enter into bank simulation"""
import logging
from bank_ops import *
from bank_admin import *
from bank_customers import *
import storage
while __name__ == '__main__':
# configure logs
logging.basicConfig(filename='bank.log', filemode='w',
format=f'%(asctime)s - %(se... |
551240ea9e8bf9c0e6797e4a0e6b038ff56822d8 | lincolnjohnny/py4e | /1 Programming_for_Everybody_(Getting_Started_with_Python)/Week_6/ex_04_06.py | 1,108 | 4.375 | 4 | # Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for
# all hours worked above 40 hours. Put the logic to do the computation of pay in a function
# called computepay() and use t... |
36b63aef140dd8cca027d40fd347da0c0136aa76 | Aasthaengg/IBMdataset | /Python_codes/p03803/s686294267.py | 211 | 3.59375 | 4 | a,b =map(int,input().split())
A,B,C =("Alice","Bob","Draw")
if max(a,b) ==13 and min(a,b) ==1:
print(A) if a < b else print(B)
else:
if a > b:
print(A)
elif a < b:
print(B)
else:
print(C) |
7cbdb3e9d2af76b58da792f27e3aa9391caae715 | jill-liu2017/stockPlot | /runPgm.py | 1,745 | 3.65625 | 4 | ##
# File name: main.py
# - This file is the entry program for starting service on command line
#
# This program retrieves stock history date from yahoo finance
# for the provided stock symbol and data range in month or year.
# It then plots price and generates prediction using polynomial regression.
#
# ... |
3acba645551e37e5fc5e9652856fff08b5427c01 | o-henry-coder/python05_12_2020 | /univer/HW/chapter04/algorithmic trainer/task01.py | 221 | 4.21875 | 4 | max_product = 100
num = int(input('enter any number '))
product = num * 10
while product < max_product:
print(product)
num = int(input('enter any number '))
product = num * 10
print('sorry, this number > 100') |
4ec263c3de49080ee13b72d9cc40bdfcef383377 | bleezmo/projecteuler | /proj5.py | 193 | 3.515625 | 4 | def main():
num = 2520
while True:
isNum = True
for i in range(1,21):
if((num//i)*i != num):
isNum = False
break
if(isNum):
break
num+=10
print("Answer is:",num)
main() |
5020d728d855309f974ffba64e5a0a34e3368742 | osnipezzini/PythonExercicios | /ex027.py | 384 | 4.03125 | 4 | """Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o ultimo nome separadamente .
Ex: Ana Maria de Souza
primeiro = Ana
ultimo = Souza"""
from format import style
nome = str(input('Digite seu nome completo : ')).strip()
n = nome.split()
style()
print('Seu primeiro nome é {}'.... |
a910c343ba6ad76d00574f5cc47c188e78874476 | nirdesh1995/Algorithms | /project2/main.py | 5,555 | 3.75 | 4 | import re
"""Abstract Data Type Edge"""
class edge:
def __init__(self, source, destination, nexts = None):
self._source = node
self._destination = destination
self._next = nexts
def getDest(self):
return self._destination
def getNext(self):
return self._next... |
029028d0d119206315f4acdf5343073024a37561 | jeffersonmca/Knights_Tour_Problem | /main.py | 2,596 | 3.90625 | 4 | #######################################
# The Knight's Tour Problem #
#######################################
# Name: Jefferson Marques Costa Alves #
# March 2021 #
#######################################
#
# Constants
#
# Start point of the tour
START_X, START_Y = 0, 0
# Board height... |
9369a09071545312687c95f3dace06d6fa078ce8 | jennyChing/leetCode | /504_convertToBase7.py | 477 | 3.671875 | 4 | '''
504. Base 7
'''
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
sign = -1 if num < 0 else 1
num = abs(num)
res = ""
while num >= 7:
res += str(num % 7)
num //= 7
res += str(... |
26ada5ffef929ddd47b3cbd4ed58ebdc831975f4 | ramakrishna227/CorePython | /functionPractice.py | 260 | 3.890625 | 4 | def function(n=-5):
if n > 0:
print(n, end=' ')
function(n - 1)
else:
print(n)
function(3)
x = function()
print(x)
# python has a maximum recursion depth of 996
def doubler(y=1):
return y * 2
z = doubler(10)
print(z)
|
67f1fdc8303f647549fda2ce3df7d8ed8321ada5 | gheorghecalancea/AI-LAB | /C-161/Marjina Alexandru/Lab5/Lab5.py | 1,091 | 3.5 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
#incarcam setul de date
iris = pd.read_csv("dataset/iris.csv")
#despărțim datasetul în vector de caracteristici (features) și vectorul clasă
features = ['sepal_length', 'sepal_width', 'petal... |
35d82e829d16b1d29938ba3486796cafb3de4759 | 0xNajmul/exercise | /python/loop.py | 114 | 3.9375 | 4 | # print a[0] to a[2]
for x in range(3):
print(x)
# while loop 1 to 10
x=0
while x<10:
print(x)
x+=1
|
9bde3ca1d54501f76844262f163d057e164f4a34 | rchordiya/Academic-and-Self-motivated-Projects | /Python_Library/main.py | 1,462 | 3.59375 | 4 | from SearchEngine import SearchEngine
from Media import Media
def main():
track=True
results = list()
search_obj=SearchEngine()
while track:
print("Enter your choice\n");
print("-------------------------------------\n");
print("1. Search by call number\n");
print("2. Search by title\n");
print("3. Search... |
db000019cd1b0cbb4541dcb7b67c5d926a106bed | Dhrumil-Zion/Competitive-Programming-Basics | /Codechef/Practice/Chef And Operator.py | 163 | 3.671875 | 4 | for _ in range(int(input())):
n1,n2 =map(int,input().split())
if n1>n2:
print(">")
elif n1==n2:
print("=")
else:
print("<") |
dde00a57523cbcbd125afa05853eca7674be9c54 | abrahampost/adventofcode | /day1/part1.py | 372 | 3.546875 | 4 | TARGET = 2020
# Adds seen numbers to set.
# If the diff between the target and current num is in set, that is the pair
with open("input.dat", "r") as file:
seen = set()
for line in file.readlines():
num = int(line)
diff = TARGET - num
if diff in seen:
print(num * diff)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.