blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
86f2716a81c85cd3a05cd0623c463fae61b97d45 | Gituser275974/Simple-point-counter | /Software releases/en_point_counter.py | 2,312 | 4.15625 | 4 | version = "1.0.1"
add = 1
A_Point = '0'
B_Point = '0'
print("Version:", version)
while True:
input = '0'
del(input)
print('A=', A_Point, 'B=', B_Point)
input = input('> ')
if input == 'help':
print("")
print("Add --[argument]")
print("")
print("Choose the section tha... |
e4f32eefef7d5126b45461fe1ad8b413813e058b | ged1182/splines | /splines/metrics.py | 1,912 | 3.53125 | 4 | import numpy as np
def mse(y, y_hat):
"""
Compute the mean-squared-error between y and y_hat
:param y: array of shape (n,) : the target values
:param y_hat: array of shape (n,) - the predicted values
:return:
"""
loss = np.mean((y - y_hat) ** 2)
return loss
def mse_grad(y, y_hat, d_y... |
c2f4c4547a1cccb9eb7f770e44509a8a09f0afe9 | mqingyn/pyutils | /pyutils/iterutils.py | 10,582 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys ,traceback ,time
from pyutils.storage import storage
class Counter(storage):
"""Keeps count of how many times something is added.
>>> c = counter()
>>> c.add('x')
>>> c.add('x')
>>> c.add('x')
>>> c.add(... |
09fee8e36dec28125a36fac7d83bd8d3bbbfa05b | packetpirate/practice-problems | /factorial/solutions/factorial.py | 175 | 3.546875 | 4 | # This function computes the factorial of the given number.
# ie: fact(7) = 7! = 5040
def fact(n):
prod = 1
for i in range(1,(n+1)):
prod *= i
return prod
|
d82d9f4cf66e670676417cf7109d7cdfd4cda43c | AcerAspireE15/python-exception-handling | /12.py | 744 | 4.125 | 4 | def function1(a, b):
print(a+b)
print(a*b)
print(a-b)
print(a/b)
print(a%b)
function1(20, 3)
print('hello')
try:
a = 20
b = 0
print(a/b)
except ZeroDivisionError:
print('there is a divide by zero error')
try:
a = 20
b = 10
print(a/b)
except ZeroDivis... |
76d139dc9c23610d77ba6747953572b5a8299c09 | ohis/PythonOOP | /Car.py | 757 | 3.875 | 4 | class Car(object):
def __init__(self,price,speed,fuel,mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
self.display_all()
def d... |
34a36712aaa2b6f09d30b4026841b4b0c5d4b438 | chavitag/DAW_Programacion | /Tema 02/Clases Presenciais/NumeroMaior.py | 490 | 4.03125 | 4 | #!/bin/python
# -*- coding: utf-8 -*-
#
# Determiña cal de dous números é o maior
#
# Pedir num1
# Pedir num2
# Si (num1 > num2) Visualizar "O maior é " num1
# SeNon Si (num2 > num1) Visualizar "O maior é " num2
# SeNon Visualizar "Son Iguais"
num1=int(input("Introduce un numero:"))
num2=int(input("Introduce otro nume... |
2a9279f049b4745136d2108b4df0cc251895efb4 | NenadPantelic/HackerRank-Problem-Solving | /Problem Solving - Interview preparation/4.Dictionaries and Hashmaps/CountTriplets.py | 491 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 21:15:30 2020
@author: nenad
"""
def read_file(path):
f = open(path, 'r')
items = list(map(int, f.read().split()))
f.close()
return items
def count_triplets(arr, r):
# Test 1
#print(count_triplets([1,2,2,4],2))
# Test 2
#pr... |
e746d9d9887a5befaeb817262d471989f12ba34c | abhishekra07/Python-openCV | /openCvReadImage.py | 838 | 3.5625 | 4 | import cv2 # importing computer vision module
import numpy as np
img = cv2.imread("Resource/lady.jfif") # reading or loading image
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # converting image to gray color space. openCV follow BGR color pattern
imgBlur = cv2.GaussianBlur(imgGray, (3, 3), 0) # ksize should b... |
06fc21c95037a5b73d0b0635a01c25450348854f | abbiejones/daily-coding | /p8.py | 1,112 | 3.5625 | 4 |
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Tree:
def __init__(self, root=None):
self.root = root
def is_unival(root):
value = root.value
def unival_helper(root, value):
if root == None:... |
114a66672bdf3b53d511ff4ef786c6d449dd60d3 | jhintz24/project-euler | /python/002.py | 544 | 3.65625 | 4 | #
# Copyright (c) Justin Hintz, 2019. All rights reserved.
# Project Euler - Problem 002
#
# Python 3.7.4
#
import time
# Straightforward and simple.
def fibonacci(n):
returnSum = 0
n0 = 0
n1 = 1
for x in range(1, n):
nNext = n0 + n1
if nNext > n:
break
if nNext %... |
3127bb7135690b25eec1416ca207b9d7aa331903 | FlyingBackdoor/Data-Structures-and-Algorithms | /Python/01.1 - Exersie_firstRecurringCharacter.py | 605 | 4.3125 | 4 | ''' //Google Question
//Given an array = [2,5,1,2,3,5,1,2,4]:
//It should return 2
//Given an array = [2,1,1,2,3,5,1,2,4]:
//It should return 1
//Given an array = [2,3,4,5]:
//It should return undefined
function firstRecurringCharacter(input)
}
//Bonus... What if we had this:
// [2,5,5,2,3,5,1,2,4]
// return 5 bec... |
89fd19475ea3dad8f5f5f10780811803bad7dae7 | leonhart8/alpha_zero | /tic_tac_toe/alpha_zero.py | 5,570 | 3.6875 | 4 | """
Module used for training an agent to play a game using self play with the Alpha Zero algorithm
"""
import numpy as np
import tensorflow as tf
from sklearn.model_selection import KFold
from mcts import MCTS
from nnet import TicTacToeNet
from tictactoe import TicTacToe
from tensorflow import keras
from play import Pl... |
61498eb447680048fbc73a3dca2e7745464bf0f6 | andyzhushuai/Mac_Code | /study_python/Magnus/l2_2.py | 276 | 3.6875 | 4 | #/usr/bin/python
# coding=utf-8
#USER: Andy Zhu
#LANG: py
#TASK: l2_2
# 对http://www.something.com形式的URL进行分割
url = raw_input('Please enter the URL: ')
domain01 = url[11:-4]
domain02 = url[7:]
print "Domain name: " + domain01
print "Total name: " + domain02
|
6d8fbf4d91fdf349d13b6b2c96695685746bc20e | Capt-Nemo/course6.00 | /ps1/ps1b.py | 477 | 3.703125 | 4 | #Problem Set 1
#Name: Nemo
from math import *
rank = 3
TestNum = 7
logPrime = log(2) + log(3) + log(5)
n = raw_input('please input a number')
n = int(n)
while rank < n:
Limit = TestNum/2
sign = 0
for i in range(3,Limit,2):
if TestNum % i == 0:
sign = 1
break
if sign == 0:
rank = rank + 1
logPrime = l... |
c69ac60d0de3526ee7bb42880139d8a1beed17b7 | Aasthaengg/IBMdataset | /Python_codes/p03325/s740110881.py | 280 | 3.5 | 4 | def prime2_factorize(N):
cnt = 0
while N % 2 == 0:
cnt += 1
N //= 2
return cnt
def resolve():
N = int(input())
A = [int(i) for i in input().split()]
sumA = 0
for a in A:
sumA += prime2_factorize(a)
print(sumA)
resolve()
|
df8617000b0f07fb5d20148811e0380b7a1b482d | BjornChrisnach/intro_to_python_UTA_Arlington | /def_square.py | 335 | 4.15625 | 4 | # Write a function that accepts a number as argument and returns
# the square of the number. For example if the number passed to
# the function is 5 then your function should return 25.
# def my_square(input_number):
# square = input_number**2
# return int(square)
def my_square(x):
result = x**2
retu... |
ec71fa48874dc3fc90b2499c1b435742967003d1 | shiyu3169/Internet_Protocol_Stack | /project/rawhttpget.py | 1,337 | 3.546875 | 4 | #! /usr/bin/python3
import socket
from urllib.parse import urlparse
import argparse
from HTTP.MyCurl import MyCurl
HTTP_SOCKET=80
def main(args):
domain,path,filename=parse_url(args.url)
try:
Destination = (domain, HTTP_SOCKET)
conn = MyCurl(Destination)
response = conn.get(path)
... |
c302cb30091117aa5a3acab52c40e28e4ccc0213 | lepaguillaume/EDM5240-devoir-1 | /devoir1.py | 596 | 3.640625 | 4 | #coding: utf-8
# Pour tous les matricules entre 1930 et 1999
for annee in range(30000,100000):
print(annee)
# Le bogue de l'an 2000! — code pour les premières possibilités de l'an 2000
for annee in range(0, 10):
print("0000{}" .format(annee))
# Pour tous les matricules après 00000-00009 entre 2000 et 2001
fo... |
2d3baca6e1c61ebb43da487fb5717c409f96411d | marcos1262/X-Invaders | /src/Trajetoria.py | 1,619 | 4.375 | 4 | from abc import ABC, abstractmethod
from math import sin
class Trajetoria(ABC):
"""
Representa uma trajetória baseada em uma função
"""
@abstractmethod
def proximo(self, incremento) -> (float, float):
pass
@abstractmethod
def anterior(self, decremento) -> (float, float):
... |
2efd7ad9bb296c5e416211d40f514dcaf614562f | comeeasy/study | /python/sw-academy-python2/list_tuple/prac16.py | 282 | 4.09375 | 4 | '''
항목 값으로는 0을 갖는 2*3*4 형태의 3차원 배열을 생성하는
리스트 내포 기능을 이용한 프로그램을 작성하십시오.
'''
dim3 = [0 for i in range(0, 4)]
dim2 = [dim3 for i in range(0, 3)]
matrix = [dim2 for dim1 in range(0, 2)]
print(matrix) |
0c9e7ff82d33a4300d173fa99d7dc30cbba5471b | Ananas1/Algorithms_of_sorting | /QuickSort.py | 679 | 3.71875 | 4 | import AlgorithmBase
class QuickSort(AlgorithmBase.AlgorithmBase):
def Sort(self):
self.QSort(0, len(self.items)-1)
def QSort(self, left, right):
if left >= right:
return
pivot = self.Sorting(left, right)
self.QSort(left, pivot-1)
self.QSort(pivot+1, right)
... |
ef5f52f63acb2081e76ee82a91f08d5797cf9bff | codebreaker-00/Learn-python | /input_and_while_loops.py | 287 | 3.828125 | 4 | message = input("okkay now give input : ")
print(message)
message = int(message)
if (message >= 0):
print(message)
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while ('cat' in pets):
pets.remove('cat')
print(pets) #removes all 'cat' from pets |
eb90c6f94cb0017182de096ea91fdf69735c0a34 | khvr/Connected-Devices | /connected-devices-python workspace/iot-device/apps/labs/module02/TempSensorEmulator.py | 2,728 | 3.671875 | 4 | '''
Created on Jan 25, 2019
Emulator class implements a child thread and has a run method
in which if a flag is true prints str representation of class SensorData.
If the threshold condition is satisfied calls the smtpClientConnector to pass
the message to E-mail account
@author: hkalyan
'''
from threading... |
3161e5a1deb289b0b0d8826057336dfd7f9eadcf | gabriel-francischini/ciscato-alp-invasao | /resolucao.py | 389 | 3.609375 | 4 | # Teste
a = [3, 4, 50, 2, 13, 67, 4 , 23, 18]
b = [5, 6, 22, 122, 34, 67, 89, 32, 189,25 ,53 ,67 ,125]
c = [5, 6, 22, 123, 34, 67, 89, 32, 189, 25 ,53 ,67 ,125]
print('''digite um código para obter a data:
a = [3, 4, ...],
b = [5, 6, 22,122, ...] ,
c = [5,6, 22, 123, ...] ''')
x = input(' digite a variável corr... |
1213a6de0fb818e6759a477ff669b6fdc897ea91 | JohnTheodore/project_euler_solutions | /python/02.py | 451 | 3.921875 | 4 | #!/usr/bin/python
def get_fib_array(max_num):
fib_array = [1, 2]
if max_num < 2:
return False
last_num = sum(fib_array[-2:])
while True:
last_num = sum(fib_array[-2:])
if last_num > max_num:
return fib_array
fib_array.append(last_num)
def sum_evens(array):
summation = 0
for num in ar... |
0a6cc34d35595ac4d125411d9f38eb63d714c95e | eulersformula/Lintcode-LeetCode | /Rat_Jump.py | 3,342 | 4.03125 | 4 | # Lintcode 1861//Hard//Google
# Description
# There is a mouse jumping from the top of a staircase with height n. This mouse can jump 1, 3 or 4 steps in an even number of jumps and 1, 2, or 4 steps in an odd number of times. Some steps have glue,if the mouse jump those steps,it will be directly stuck and cannot contin... |
9d56bb7b98062b824d540a2ac9a6528364027656 | chiragkalal/python_tutorials | /Python Basics/2.int_and_floats.py | 715 | 4.46875 | 4 | # Arithmetic Operators:
# Addition: 3 + 2
# Subtraction: 3 - 2
# Multiplication: 3 * 2
# Division: 3 / 2
# Floor Division: 3 // 2
# Exponent: 3 ** 2
# Modulus: 3 % 2
# Comparisons:
# Equal: 3 == 2
# Not Equal: 3 != 2
# Greater Than: 3 > 2
# Less Than: 3 < 2
# G... |
afef8e889d22fdcf40cc2cba6d824438d35d4da2 | wy89050/numpy_test | /p87.py | 251 | 4.3125 | 4 | #變換陣列的形狀排列與維度
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
a_2d = a.reshape(3,4)
print(a_2d)
print('\n')
a_3d = a.reshape(3,2,2)
print(a_3d)
print('\n')
a_2d_col = a.reshape(3,4, order='F')
print(a_2d_col) |
4469ecd2a30aaa860e27c3b0cd20e167b6366431 | angiebabyleigh/python_aug_2018 | /Python/OOP/bigmathdojo.py | 288 | 3.75 | 4 | class MathDojo:
def __init__(self):
self.total = 0
result = 0
def add(self,num1, *nums):
self.total = num1
# print("****", self.total)
for x in nums:
self.total += x
#print(x)
return self.total
md = MathDojo()
md.add(2)
print(md.add(2))
print(md.add(3,5,8,2))
|
744741f9edce83b1abaae49c2324bf338cf17d11 | srad1292/PythonCrashCourse | /Chapter5/ordinal_numbers.py | 368 | 4.34375 | 4 | #Exercise 5-11
#Ordinal numbers indicate their position in a list
#Such as 1st 2nd 3rd 4th
#Store the numbers 1-9
#loop through and print the ordinal ending for each
numbers = [value for value in range(1,10)]
for number in numbers:
if number == 1:
print("1st")
elif number == 2:
print("2nd")
elif number == 3:
... |
f0d8f16f41d446ff7f8ff70cba063454fabea5a6 | aeltanawy/dealnodeal | /dond_v4.py | 4,942 | 3.609375 | 4 | import random
from enum import Enum
class DNDApp:
def __init__(self):
self.finished_games = []
self.player_list = []
def run(self):
"""The actual game that keeps running till the player exits."""
self.player_list = load_player_list()
while True:
player = s... |
9b21ade356a18a7ded0d77f4f75980858e12bc71 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/dnnlau005/question2.py | 2,228 | 4.09375 | 4 | """reformat a text file so all lines are at most a given length
Lauren Denny
11 May 2014"""
i_file=input("Enter the input filename:\n") #get input filename
o_file=input("Enter the output filename:\n") #get output filename
width=eval(input("Enter the line width:\n")) #get integer value for line width
f=open(i_... |
f10ce4627da3a21c347407e5576812b3187e4818 | codecomfort/python-pallarel | /13_3_multiprocess_02.py | 501 | 3.8125 | 4 | # エキスパートPythonプログラミング 改訂2版 13章
# マルチプロセスその2
# multiprocessing の使い方
from multiprocessing import Process
import os
def work(identifier):
print(f'私はプロセス {identifier}, pid: {os.getpid()} です')
def main():
processes = [Process(target=work, args=(number,)) for number in range(5)]
for p in processes:
... |
5c6ef5fd66abd37b848121e5c3f35170df47c346 | CarlissonMiller/WebScrapping_UFC | /Khabib/webscrapping_wiki_khabib.py | 2,064 | 3.640625 | 4 | from urllib.request import urlopen
import requests
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
name = input('Please write Khabib_Nurmagomedov? ')
def get_rows(name):
# Catch the HTML content from URL
wiki_url = "https://pt.wikipedia.org/wiki/"+name
response = requests... |
a2c39bbe4e19d1e9bb6b89052c3b0a4d341d5833 | ralevn/Python_scripts | /PyCharm_projects_2020/Advanced/Comprtehensions/app_ternary_operator.py | 326 | 4.3125 | 4 | # print 'even' if the number is even,
# and 'odd' if the number is odd
x = int(input())
even_message = 'The number is even'
odd_message = 'The number is odd'
if x % 2 == 0:
print(even_message)
else:
print(odd_message)
result = even_message \
if x % 2 == 0 \
else odd_message
print(r... |
ccb7eed9581a2c704ae7bfd3cacaf1ad340501d6 | pyro-bot/AI_2 | /Отчеты/1162 1/PanchishinIR/2/test.py | 2,805 | 4 | 4 | import numpy as np
# создание массива из списка
list_1 = [0,1,2,3,4]
arr_1d = np.array(list_1)
# прибавление и вычитание числа
def minus_plus(minus: bool):
global list_1, arr_1d
for i in range(len(list_1)):
list_1[i] += -1 if minus else 1
arr_1d += -1 if minus else 1
print(list_1)
print(ar... |
9c13264cc94d71678ceb67b1f11db8bf7f5f34a4 | oreogee/python | /python_basic/chapter02_02.py | 1,851 | 3.5 | 4 | # 파이썬 변수
# 기본 선언
n = 700 #컴퓨터 내부에 n이 생성된 주소에 700이란 값이 할당
print(n)
print(type(n))
# 동시 선언
x = y = z = 700
print(x, y, z)
# 선언하고 재선언. 재할당됨. 덮어쓰기
var = 75
var = "Change Value"
print(var)
print(type(var))
print()
# Object References
# 변수 값 할당 상태
print(300) #편리성을 위해 int명시하지 않아도 되는 것
print(int(300)) #1>2>3의 과정을 통해... |
4a2c02a904d4085ea99a7095576c5c06bafb5f02 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/anagram/fecadc62662e4bdbbc1a8252611426b3.py | 409 | 3.828125 | 4 | def count_letters(string):
counts = {}
for a in string.lower():
counts[a] = counts.get(a, 0) + 1
return counts
def detect_anagrams(word, word_list):
word_counts = count_letters(word)
anagrams = []
for w in word_list:
if word_counts == count_letters(w) an... |
4c08ed3d93f156aaea6e7a0b4c101f7b89bf5834 | ktrzcin/list-distance | /list_distance.py | 1,548 | 3.96875 | 4 | import itertools
import sys
from typing import Generator, Iterable, Set, Union
def get_ints_from_input(count: int) -> Generator[int, None, None]:
"""
Read a single line from input and map it to int. Expects a
space seperated list of values. Raise ValueError if count
does not equal number of values to ... |
ebc708926af11bf4de8c03fce3c4ac03ddcd5376 | Akagi201/learning-python | /lpthw/ex44.py | 662 | 4.34375 | 4 | #!/usr/bin/env python
# Exercise 44: Inheritance Versus Composition
class Other(object):
def override(self):
print("OTHER override()")
def implicit(self):
print("OTHER implicit()")
def altered(self):
print("OTHER altered()")
class Child(object):
def __init__(self):
... |
80aad3656021d34d9a17cb08a45e325dc0ce9bb3 | oliverwy/populardesignpattern | /ch17adapterpattern/adapterpatternnormal.py | 403 | 3.734375 | 4 | from abc import *
class Target:
@abstractmethod
def request(self):
print("普通请求!")
class Adaptee:
def specificRequest(self):
print("特殊请求!")
class Adapter(Target):
def __init__(self):
self.__adaptee=Adaptee()
def request(self):
self.__adaptee.specificRequest();
if ... |
6e736a078a9f288c6bd5a96cb70044a17097239e | Rokuto/cmsc128-ay2015-16-assign002-py | /libZ.py | 2,719 | 3.828125 | 4 | def getHammingDistance( str1, str2 ):
# Catch input annomalies
if len( str1 ) != len( str2 ) or len( str1 ) <= 0 or len( str2 ) <= 0:
return -1
# count the character/s that differ from str1
inversion = 0
for x in xrange( 0, len( str1 ) ):
if str1[x] != str2[x]:
inversion += 1
# return answer
return in... |
ab2a9a8db43b34ac66a9a9e6d75cfaee5c1dc615 | xuechuancong/ppt_book | /PycharmProjects/python201/list_squared.py | 497 | 3.65625 | 4 | from math import sqrt
def get_div(x):
s = []
for i in range(1,x):
if x%i == 0:
# print i, x/i
s.append(i)
s.append(x/i)
h = sum(i**2 for i in set(s))
return sqrt(h)
def list_squared(m, n):
p = []
for i in range(m,n):
if i == 1:
p.a... |
31aaada2289d05435794fcc2a27ffe856aad4908 | MSafariyan/Python-practice | /Prime number/PrimeNums.py | 489 | 4.03125 | 4 | # Author: Mahdi Safarian
# Date: 04/20/20
# Subject: Finde Prime Numbers.
import math
def is_prime(number):
if number < 2 :
return False
if number % 2 == 0 :
return number == 2
root = (int)(math.sqrt(number))+1
for i in range (3,root,2) :
if number % i == 0 :
... |
1b7249df0e5c0075d473f2f6b06a9bfcc32f3886 | gabrielreiss/URI | /1176.py | 208 | 3.609375 | 4 | n = int(input())
for i in range(0, n):
fib = [0, 1]
x = int(input())
if x > 1:
for j in range(2, x+1):
fib.append(fib[j-2]+fib[j-1])
print('Fib({}) = {}'.format(x,fib[x])) |
68ad658e71987bb64b79290f2b5057ba7240721f | kagurazakayashi/CodeNotebook | /Python/数组.py | 1,294 | 3.890625 | 4 | book = ['xiao zhu pei qi','xiao ji qiu qiu','tang shi san bai shou'] # 定义book数组
book.insert(0,'bu yi yang de ka mei la') #.insert(x,'xx') 在指定位置添加,x/第几位 , 'xx'/添加的内容
book.append('e ma ma tong yao') #.append('') 在末尾添加
book[2]='pei qi going swimming' #修改第二个位置为'pei qi going swimming'
book.pop() #删除末尾
book.pop(0) #删除指... |
4ec083a5be34bbf2e049b92536826f79c9e11770 | hayeonk/leetcode | /sols/remove_nth_node_from_end_of_list.py | 541 | 3.578125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
dummy = ListNode(0)
dummy.next = head
prev = dummy
runner = dummy
... |
4e52dee410a43521168b5c82cc752162e0722dc8 | zhweiliu/learn_leetcode | /Top Interview Questions Easy Collection/Strings/Implement strStr/solution.py | 759 | 4.09375 | 4 | from typing import Dict, List
'''
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, w... |
428210cea039f846bffecd4ecfa0a04345dcb378 | sumanthgunda/hacktoberfest2020 | /guess_the_num.py | 1,673 | 4.125 | 4 | import random
choice=random.choice(range(21))
def print_pause(msg_to_print):
print(msg_to_print)
time.sleep(2)
def intro(choice):
print("the computer choose a number within the range 20" )
intro(choice)
def try1():
c1=input("i guess the number is ")
if choice == c1:
print("your gues... |
141aa448565efae07bf411fad06bd29413b79583 | liliumka/py_basics | /Ivanova_Tatiana_dz_4/my_tools.py | 1,654 | 3.671875 | 4 | def my_range(start_n, end_n=0):
"""
Генератор на основе итератора count.
Отсчет начинается с переданного параметра start_n. Если указан второй параметр end_n (> start_n),
то выполняется end_n итераций цикла, иначе только 10.
:param int start_n:
:param int end_n:
:return:
"""
from i... |
74976efc8d34950d9a32f359eccaa19a5eb38ace | IsThatYou/Competitive-Programming | /Hackerrank/women's_codesprint3.py | 1,749 | 3.6875 | 4 | ##!/bin/python3
#https://www.hackerrank.com/contests/womens-codesprint-3/challenges/hackathon-shirts
#https://www.hackerrank.com/contests/womens-codesprint-3/challenges/choosing-recipes
import math
import sys
#sys.stdin = open("in","r")
def hackathon_shirts():
t = int(input())
for case in range(t):
n = int(inpu... |
2e7142c62e70a27efc23d2320b895315ca0ba07b | johnardavies/Networks-code | /mergejsondict.py | 488 | 3.609375 | 4 | import json
#merges the two dictionaries that are in json format
def merge(x, y):
#parses the json
dat1=open(x)
dat2=open(y)
data1 =json.load(dat1)
data2 =json.load(dat2)
z = data1.copy()
z.update(data2)
return z
#Reads in the two datasets
fir='filepath1.json'
rem='filepath2.json'
#a... |
a838dd204f9aa065a886e4743e613de1b4b65cf1 | pandeyank/LearningPython | /pythonProject/palindrome.py | 295 | 3.8125 | 4 | n='ABCBA'
def palindrome(n,start,end):
for i in n:
if n[start]==n[end]:
start=start+1
end=end-1
return('Yes')
else:
return('No')
start=0
end=len(n)-1
x=palindrome(n,0,4)
print("The given is string is plindrome Yes or No",x)
|
a195ba85362ab32eed6a071b23bce0ed0fcb37ad | thamo190685/Pythonsamples | /recursive.py | 279 | 4.0625 | 4 | def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
result = 6 + 15
result = 5 + 10
result = 4 + 6
result = 3 + 3
result = 2 + 1
result = 1 + 0 |
971d7a8652f6c1eafc9f4687d8ea5d73b3e8c8c4 | michaelconnolly/coursera | /algorithmic-thinking/test.py | 5,085 | 3.921875 | 4 | EX_GRAPH0 = dict()
EX_GRAPH1 = dict()
EX_GRAPH2 = dict()
def init_graph(num_nodes):
"""
internal function used to create a graph with the inputed amount of nodes.
"""
# Init graph structure.
graph = dict()
# Handle the error case case num_nodes is bogus.
if (num_nodes > 0):
... |
11c72dff5166ac52704c750f1fd1638594567dc4 | Telurt/python-fundamentos | /comprehension.py | 475 | 4.15625 | 4 | """
List Comprehension (compreensão de lista)
É uma construção sintática para criação de uma lista baseada em listas existentes.
"""
lista = [10,20,30]
# Usada como Map
# nova_lista = [item* 2 for item in lista]
# print(nova_lista)
# Usada como Filter
#nova_lista = [item for item in lista if item >= 20 if item < 30... |
283be2db0521ba331e8847974f07ab2bdca14a16 | RishabhArya/Coursera-Data-Structures-and-Algorithms-by-University-of-California-San-Diego- | /4.Algorithms on Strings/Week 1/Trie.py | 658 | 3.609375 | 4 | import sys
def build_tree(patterns):
tree = dict()
tree[0] = {}
index = 1
for pattern in patterns:
current = tree[0]
for letter in pattern:
if letter in current.keys():
current = tree[current[letter]]
else:
current[letter] = index
... |
2393abea126f73bfa450e5ac94e5c1645afdebac | AngelRawencraw/competitive-programming | /DMOJ/dmopc14c5p1.py | 76 | 3.8125 | 4 | import math
r = int(input())
h = int(input())
print(math.pi*(r**2)*h/3) |
e1bd95e6c5ae0682b87d456c0714566529df73d2 | ParsonsRD/SciPy-CookBook | /ipython/Watershed.py | 2,393 | 3.984375 | 4 | # <markdowncell>
# The watershed algorithm (see
# [1](http://en.wikipedia.org/wiki/Watershed_(algorithm))) is used to
# split an image into distinct components.
#
# Suppose that we have the following image, composed of three whites disks
# (pixels of value 1) and a black background (pixels of value 0). We want
# to o... |
5c19ed72268434db322c55c74a289918bc062d16 | tanlangqie/coding | /排序/归并排序.py | 715 | 3.84375 | 4 | # -*- coding: utf-8 -*-#
# Name: 归并排序.py
# Description:
# Author: tangzhuang
# Date: 2021/2/28
# desc: 先递归拆分,再两两合并
def merge(a,b):
#
res = []
i = 0
j = 0
while i<len(a) and j<len(b):
if a[i] <= b[j]:
res.append(a[i])
i += 1
else... |
f592c4c0e437779f75af30c11f43a883e520e590 | IainMcl/Quantum-Computing-Project | /QCP-example/Examples/grover.py | 3,250 | 3.734375 | 4 | """
University of Edinburgh, Shool of Physics and Astronomy
Quantum Computing Project
Implementation of Grover's algoritm.
"""
from qc_simulator.qc import *
from qc_simulator.functions import *
import numpy as np
import math
from matplotlib import pyplot as plt
def grover(oracle, k=1, plot = False):
... |
7d4c1c710a4f30c82a66dd3abf32b30de458772c | Uthaeus/w3_python | /06.py | 264 | 4.1875 | 4 | # Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
nums = input("Enter some numbers:\n")
num_list = nums.split()
num_tuple = tuple(num_list)
print(num_list)
print(num_tuple) |
9f213d9d6723614c22cdf5616f2af5d9a0add0f1 | dinspi3/Python_web | /data.py | 711 | 3.5 | 4 | import requests
from bs4 import BeautifulSoup
import csv
def get_html(url):
r = requests.get(url)
return r.text
def write_csv(data):
with open('test3.csv','a') as f:
writer = csv.writer(f)
writer.writerow((data['url'], data['name']))
def get_data(html):
soup = Beauti... |
5c16357f3df8b05ebf3e89295c3e9c2161aa3f41 | mijantck/pythonCoffeeMachinProgramming | /main.py | 1,604 | 4.34375 | 4 | water = 300
milk = 65
coffee_beans = 100
cups = 0
one_cup_make_coffee_water = 200
one_cup_make_coffee_milk = 50
one_cup_make_coffee_coffee_beans = 15
available_water = 0
available_milk = 0
available_coffee_beans = 0
availale_list = [0 , 0 , 0]
available_cups = 0
current_available_cups = 0
print("write how many ... |
b6d607ad9952f371085cfda2cda4cf63640ea5f6 | revanthavs/morningproblems | /Downloads/palindrome/soln/palindrome.py | 308 | 3.5625 | 4 | string = input()
llength = []
for i in range(len(string)):
for j in range(len(string)):
string1 = ""
string2 = ""
if string[i] == string[j]:
string1 = string[i:j+1]
if len(string1)%2 != 0:
string2 = string1[::-1]
if string1 == string2:
llength.append(len(string2))
print(max(llength)) |
1de6d45b402235a27401381dcceb98415b953fd7 | tejasbirsingh/CodingQuestionsPython | /pascalTriangle.py | 402 | 3.703125 | 4 | def generate( numRows):
triangle =[]
for i in range(numRows):
row =[None for _ in range(i+1)]
row[0],row[-1] =1,1
for j in range(1,len(row)-1):
row[j]=triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(... |
fdd047eb101a774fc05a92ce830c587cdfe299cf | qwjaskzxl/For-OJ | /python-leetcode/剑指offer/线性表 数组_链表_队列_栈/剑指 Offer 25. 合并两个排序的链表.py | 1,777 | 4 | 4 | '''
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:
0 <= 链表长度 <= 1000
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution_wrong: # 题目理解错了,我以为要去重,不过我这个代码写的也不对,那里TLE了
def mergeTw... |
e72a918c1bb05101884f023ffde937d32dc2430f | wrm163/store | /day11/demo.py | 501 | 4.09375 | 4 | '''
继承:
被继承的类:父类。超类
继承的类:子类
在继承中如何使用父类的代码,super就是父类
'''
class Animal: # 动物:父类
name = None
age = None
# 让狗、猫来继承动物
class Dog(Animal): # 子类
def lookgeat(self): # 看大门
print(self.name,"看大门","看了",self.age)
class Cat(Animal):
def catchMouse(self):
print(self.name,"正在抓老鼠")
dog = Dog()
dog.na... |
73787c2e5245a8196921993f1ef370fedbaa545f | dmendelsohn/project_euler | /solutions/problem_099.py | 451 | 3.625 | 4 | import math
import utils
# Determine which of the given a^b values is biggest
def compute(verbose=False):
text = open(utils.INPUT_PATH + 'p099_base_exp.txt').read().split('\n')
pairs = map(lambda line: list(map(int, line.split(','))), text)
logs = list(map(lambda pair: pair[1]*math.log(pair[0]), pairs)) #... |
dd9b21742bdc0bb23be5297d408ac2a0e7e936a0 | SulabhAgarwal007/Python_Machine_Learning | /EDA/Chap_1_EDA.py | 3,501 | 3.84375 | 4 | """
EDA: Exploratory Data Analysis, which means before we do any hypothesis tests we should understand our data first
by creating simple informative plots.
"""
from sklearn.datasets import load_iris
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
data = ... |
8e21b6bf69d9dbbe05032fa39ad28db62f9aceba | Anjalibhardwaj1/Hackerrank-Solutions-Python | /Basics/Aritmetic_Operators.py | 877 | 4.25 | 4 | #Task
#The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
# 1) The first line contains the sum of the two numbers.
# 2) The second line contains the difference of the two numbers (first - second).
# 3) third line contains the product of the two numbers.
# Const... |
cb5d51427fd51561cb627f3feda1dc215d9f7c6f | aaditya79/Sorting-Algorithm-Visualizer | /shellsort.py | 1,007 | 4 | 4 | import time
'''
The main of this function is to sort the
randomized data using the Shell Sort
algorithm.
'''
def shellSort(setData, Data, clock):
lenArr = len(setData)
if (lenArr == 1):
return setData
diff = lenArr // 2
while (diff > 0):
for i in range(diff, lenArr):
c... |
bdf2fdebbf819b96a807986c7f0ac7e5537351c9 | logancrocker/interview-toolkit | /code/dfs/dfs.py | 1,156 | 3.890625 | 4 | class Node:
def __init__(self, label):
self.label = label
self.marked = False
self.neighbors = []
def add_neighbor(self, node):
self.neighbors.append(node)
def visit(self):
print(self.label)
def mark(self):
self.marked = True
class Graph:
def __init__(self, nodes):
... |
824258e0ead8b872fe7caf3b2578f3334b389e11 | Heisenberg1111/P4V | /python_institute/bubbleSort_Lists.py | 1,199 | 4.25 | 4 | # Sorting a list using the traditional bubble sort
#
# Bubble sort as in having the values bubble or float upwards depending on the sorting condition
#
myList=[10,99,45,123,89,69,55]
print("\nInitial List: ",myList)
print(
"""
+=============================+
| |
| Bubble Sort ... |
a2a4bd4c36dcc0b2ed8cf0f03f6de08093c306fb | Elektra-2/python_crash_course_2nd | /python_work/Chapter5/toppings.py | 628 | 4 | 4 | # requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
# for requested_topping in requested_toppings:
# if requested_topping == 'green peppers':
# print("Sorry, we're out of green peppers")
# else:
# print(f'Adding requested toppings {requested_topping}')
# print('\nYou finished making ... |
6d5b02a18d47e8db9179d62d69dbe232c69ab92a | SpyrosChouliaras/SnakifyPython | /Conditions,if,the,else/King move.py | 186 | 3.84375 | 4 | x1 = int(input())
x2 = int(input())
y1 = int(input())
y2 = int(input())
if((y1==x1 or y1 ==x1+1 or y1==x1-1) and (y2==x2 or y2==x2+1 or y2==x2-1)):
print("YES")
else:
print("NO") |
42efd8a8349c87659ab63d0bb750983b30e48381 | dhx1994/cekaizhilu | /practice.py | 451 | 3.6875 | 4 | class Student():
def __init__(self, name, age, **address):
self.name = name
self.age = age
self.address = address
def get_message(self):
print("{}{}{}{}".format(self.address["city"], self.address["street"], self.address["floor"],
self.address["num... |
251d26c59b6b91680362459d3c3be80c3993f1c1 | Byliguel/python1-exo7 | /binaire/binaire_I.py | 3,166 | 3.5625 | 4 |
##############################
# Binaire - partie I
##############################
##############################
# Activité 1 - Decimale vers entier
##############################
## Question 1 ##
def decimale_vers_entier_1(liste_decimale):
nombre = 0
p = len(liste_decimale)
for i in range(p):
... |
47e9a81d6f11a776c21a0212c1ca562c77fd2eae | gujunwuxichina/python_basic | /com/gujun/变量和简单类型/number/float.py | 323 | 4.1875 | 4 | # 浮点型
# 浮点型数值表示带有小数点的数值
# 两种表示形式:
# 1.十进制,浮点数必须包含一个小数点,否则会被当成整型;
# 2.科学计数法,3.14e12,只有浮点型才能使用科学计数法;
a=1.
print(type(a)) # <class 'float'>
b=100e5
print(type(b)) # <class 'float'> |
c36f903e0cc25536b8b9b83b9a7665ebc6ba93cc | gauravtatke/codetinkering | /leetcode/next-greater-elem-i.py | 3,922 | 4 | 4 | #!/usr/bin/env python3
# You are given two arrays (without duplicates) nums1 and nums2 where nums1’s
# elements are subset of nums2. Find all the next greater numbers for nums1's
# elements in the corresponding places of nums2.
#
# The Next Greater Number of a number x in nums1 is the first greater number to
# its rig... |
d35fb64f3d081c9c599c42ec77a290cb23c8d8ff | shirriff/ibm-system-360-50-simulator | /misc/cvb2.py | 889 | 3.578125 | 4 | # Test convert to binary algorithm
import sys
def convert(d): # D is binary coded decimal
r = 0
bit = 1
diff = 0
while d:
print '%x - %x = %x shifted = (%x)' % (d, diff, d-diff, (d-diff) / 2)
d -= diff
diff = 0
if d & 0x20:
diff += 0x6
if d & 0x200:
diff += 0x60
if d & 0x200... |
a0b5cd474ad5b104d30f90377279345d0f32bdd1 | pipjiang/Python-CommonCode | /python算法/6.6如何判断1024!末尾有多少个0.py | 488 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 09:30:27 2020
@author: Administrator
"""
"""
如何判断1024!末尾有多少个0.
有点像脑筋急转弯,一般来说根本想不到.
"""
def method(N):
k = 1
while 5 ** k < N:
k += 1
k -= 1
count = 0
for i in range(k):
tmp = int(N / (5 ** (i+1)))
count ... |
ce2bdc11ede0e591bb67946de041e34595dde592 | PedroCamaRgoz/teste_python | /teste.py | 223 | 3.921875 | 4 | # temp = input("qual é o seu nome ?")
#print("seu nome é %s, bem legal" %(temp))
def teste (*nome):
print ("um teste : ")
for nome in nome:
print(nome)
teste("pedro", "ana","lucio","italo","beatriz")
|
0d6882db632d71c635effe303ea006d805a2aa96 | GForrow/PythonBasics | /Programs/Day2/Functions.py | 686 | 3.890625 | 4 | import random
def examScore():
name = str(input("What is your name?: "))
hwScore = int(input("What was your homework score?: "))
assScore = int(input("What was your assessment score?: "))
examScore = int(input("What was your exam score?: "))
totalScore = ((hwScore + assScore + examScore) / 175) * ... |
0e911530a8164d24d487739883b1708fe0ee885e | KamrulSh/Data-Structure-Practice | /linked list/swapLinkedList.py | 1,763 | 4.15625 | 4 | # Pairwise swap elements of a given linked list
# Move last element to front of a given Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def appendAtHead(self, value):
newNode = N... |
a065c4d638dddc55e1e4479076bbcde682e6395e | nerdjerry/python-programming | /quick_union.py | 870 | 3.796875 | 4 | class unionFind(object):
def __init__(self):
self.id = [0,1,2,3,4,5,6,7,8,9]
self.size = [1] * 10
def root(self,node):
if self.id[node]!= node:
self.id[node] = self.root(self.id[node])
return self.id[node]
def isConnected(self,p,q):
return self.root(... |
c4db7791dcac87d51b3563b4d9c0a31b6836dd22 | vijaykjangid/swapping | /swap.py | 142 | 3.875 | 4 | a=input('Enter first no')
b=input('Enter second no')
print('before swaping a=',a,'b=',b)
a=a+b
b=a-b
a=a-b
print('after swaping a=',a,'b=',b)
|
c9f64db3c20901038086b42356d88ab0e4afe52a | taoyan/python | /Python学习/day08/练习 (6).py | 1,131 | 3.9375 | 4 | # 练习1:
# 现有如下代码, 会输出什么:
# class People(object):
# __name = "luffy"
# __age = 18
#
# p1 = People()
# print(p1.__name, p1.__age)
#练习2:
#编写程序, A 继承了 B, 俩个类都实现了 handle 方法, 在 A 中的 handle 方法中调用 B 的 handle 方法
#练习3:
#模仿王者荣耀定义两个英雄类
#要求:
#
#英雄需要有昵称、攻击力、生命值等属性;
#实例化出两个英雄对象;
#英雄之间可以互殴,被殴打的一方掉血,血量小于0则判定为死亡(提示:这里是... |
f98ad250b152d4a698577937d2fdd8a59daf8eeb | IvayloValkov/Python_Fundamentals | /Lists Basic/08_seize_fire_v3.py | 760 | 3.859375 | 4 | strings = input().split("#")
water = int(input())
cells = []
total_fire = 0
effort = 0
for element in strings:
element_str = element.split()
word = element_str[0]
level = int(element_str[2])
is_valid = False
if water < level:
continue
if word == "High" and 81 <= level <... |
2696abfa5d7801c5a479fe6e28b8e173cf1ecfa6 | Aakancha/Python-Workshop | /Jan26/Assignment/Q11.py | 292 | 3.875 | 4 | def generate_dic(name):
dict_ = {}
f = open(name, 'r')
for a in f:
list_ = a.split()
for each in list_:
dict_[each] = len(each)
list_ = []
return dict_
filename = input("Enter file name: ")
print(f"{generate_dic(filename)}")
|
e48de8b26b4e2acc3585ebb634e5b6ba318e40cc | sonushahuji4/hackerearth_solved_problem_solutions | /Jadoo_vs_Koba.py | 192 | 3.53125 | 4 | #problem link
#https://www.hackerearth.com/practice/python/getting-started/input-and-output/practice-problems/golf/jadoo-vs-koba/
for i in range(int(ord('F')),int(ord('Q'))):
print(i) |
393edde23c34a59f770fb85e58cc50ca6caf016e | lafabo/i-love-tutorials | /a_bite_of_python/24-modul-from-import.py | 540 | 3.9375 | 4 | from math import *
n = int(input('Enter the rage: -'))
p = [2, 3]
count = 2
a = 5
while count < n:
b = 0
for i in range(2, a):
if i <= sqrt(a):
if a % i == 0:
print(a, ' is a complex number')
b = 1
else:
pass
if b != 1:
... |
3667185702d605dc55fb331b134adf7f9ebef5b6 | ant-shiv/IP | /area_shape.py | 682 | 4.1875 | 4 | def circle(r):
return 3.14*r*r
def square(a):
return a*a
def rectangle(l,b):
return l*b
print("1 to calculate Area of circle [A=πr2]")
print("2 to calculate Area of square [A=a*a]")
print("3 to calculate Area of rectangle [A=l*b]")
n=int(input("Enter your Choice(1,2,3): "))
if n==1:
r=float(input(... |
56c6fc069619af193c350c0cb14874470bf57493 | PullBack993/Python-Fundamentals | /05. Lists Advanced - Exercise/10.Inventory.py | 1,255 | 3.953125 | 4 | def is_items_in_list(d, i):
if i in collecting_items:
return True
return False
def collect_items(d, i):
if not is_items_in_list(d, i):
collecting_items.append(i)
return collecting_items
def drop_items(d, i):
if is_items_in_list(d, i):
collecting_items.remove(i)
re... |
dd44717c7a8d9148a3a093258074d975929909d6 | IgorPereira1997/Python-SQL-Basics | /lista_exercicios_2/ex4.py | 951 | 4.28125 | 4 | # -*- coding: utf-8 -*-
op = 0
while(op != 3):
print("\n-----------MENU DE OPÇÕES------------\n")
print("-----------1 - Ler arquivo-----------")
print("-2 - Imprimir conteudo de um arquivo-")
print("--------------3 - Sair---------------")
aux = input("Opção: ")
print("-------------------------... |
52f3081ab9b1abfb8c8e5990a9b2f21d5d83c0e5 | majormunky/advent_of_code | /2017/python/day1.py | 1,249 | 3.703125 | 4 | import sys
import common
def get_filename():
filename = sys.argv[0]
filename = filename.split("/")[-1]
filename = filename.split(".")[0]
return filename
data = common.get_file_contents("data/{}_input.txt".format(get_filename()), single_line=True)
def part1():
answer = 0
for index, character... |
6dac36136200a476499e33082376cf1cd59ce76d | steven-mcmaster/python | /stocks/stocks.py | 762 | 3.65625 | 4 | class Stock:
def __init__(self, ticker, cost, name):
self.ticker = ticker
self.cost = int(cost)
self.name = name
def __str__(self):
return self.ticker + " " + self.name + " " + str(self.cost)
with open('file', 'r') as file:
for line in file:
try:
s1 = S... |
fd20915db85b3f84dcd2a9c63c44757c1a5325f7 | tebeco/MyDemos | /Python/Demos/PythonClass/SupperAndBase/inheritDemo1.py | 579 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
https://stackoverflow.com/questions/21639788/difference-between-super-and-calling-superclass-directly
"""
class A (object):
def __init__ (self):
super(A, self).__init__()
print('A')
class B (A):
def __init__ (self):
super(B, self).__init__()
print('... |
a23d4a974fccd985625bc09821bb14004ae5d567 | Rictus/advent_of_code_2020 | /day7/main.py | 1,858 | 3.6875 | 4 | def parse_containing_bag(_str):
count = int(_str[0])
if _str[-1] == 's':
_str = _str[:-1] # remove plurial
_str = _str.strip()[2:-4] # remove the beginning integer and the end " bag"
return count, _str
def get_rules():
_rules = {}
for line in tuple(open('input', 'r')):
color... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.