blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e5ee7a96bf4a82a2da1c5b73fd44323915423908 | namnv4/python | /recommendation-system/utils/manhattan.py | 6,632 | 4.125 | 4 | from collections import Counter
import matplotlib.pyplot as plt
import csv
def manhattan(rating1, rating2):
"""Computes the Manhattan distance. Both rating1 and rating2 are
dictionaries of the form
{'The Strokes': 3.0, 'Blue Streak': 2.5 ...}"""
distance = 0
for key in rating1:
if ... |
30cb2152ba61fdc70e20fde9f9b71daa05ffafa1 | divyachandramouli/Data_structures_and_algorithms | /4_Searching_and_sorting/Bubble_sort/bubble_sort_v1.py | 555 | 4.21875 | 4 | # Implementation of bubble sort
def bubble_sorter(arr):
n=len(arr)
i=0
for j in range(0,n):
for i in range(0,n-j-1):
#In the jth iteration, last j elements have bubbled up so leave them
if (arr[i]>arr[i+1]):
arr[i],arr[i+1]=arr[i+1],arr[i]
return arr
array1=[21,4,1,3,9,20,25,6,21,14]
prin... |
3f3205aea8dd64a69b9ed91f6aab600d63da9475 | divyachandramouli/Data_structures_and_algorithms | /3_Queue/Queue_builtin.py | 384 | 4.21875 | 4 | # Queue using Python's built in functions
# Append adds an element to the tail (newest element) :Enqueue
# Popleft removes and returns the head (oldest element) : Dequeue
from collections import deque
queue=deque(["muffin","cake","pastry"])
print(queue.popleft())
# No operation called popright - you dequeue the head w... |
da3083ae44778e0fbe6177756a4c4736d62d11f8 | divyachandramouli/Data_structures_and_algorithms | /4_Searching_and_sorting/Recursion/fib_val_iterative.py | 274 | 3.53125 | 4 | #Return the value of fib seq given the pos - iterative
def get_fib_val(pos):
if (pos==0):
return 0
if (pos==1):
return 1
first=0
second=1
next=first+second
for i in range(2,pos):
first=second
second=next
next=first+second
return next
print(get_fib_val(6)) |
c9c45ba67a057a5ff79e95737ff7e2e8799d622e | johan-wendelind/on-learning | /basics.py | 169 | 3.859375 | 4 | numbers = {"Johan": 10.0, "Hojt": 2.1, "Peter": 5.0}
mysum = sum(numbers.values())
length = len(numbers)
avg = mysum / length
print(avg)
hej = "Hej"
print(hej.lower())
|
6111c6ba0af45cb83eb7254b7a01c9aabba24421 | Egor93/Climate_dynamics_and_statistics | /ex1/ex1_part_2.py | 3,668 | 3.5 | 4 |
import numpy.linalg as LA
import numpy as np
import matplotlib.pyplot as plt
class PDF:
# DESCRIPTION
# Class containing all methods necessary to generate
# two arrays of samples which have user-defined standart deviation,mean;
# correlate/do not correlate with each other according to user... |
90fdca302f36aabd3a9e68b74401cc81b4b37339 | jamesilloyd/robot_lab_inspection | /classification.py | 6,753 | 3.59375 | 4 | import numpy as np
from cv2 import cv2
from matplotlib import pyplot as plt
import thresholding
import part
from mpl_toolkits.mplot3d import Axes3D
'''
partClassification is used to classify all the parts within a cropped image.
It's inputs are:
-img_bgr = the cropped image to be classified
-show = whether to show re... |
351c73d47838d5e027952f2bcfad6e5f3b439fcc | safa-6/DSCGaziOdevSenligi | /problemset4safaözer.py | 211 | 3.796875 | 4 | #Safa Özer
x= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x)
for i in x:
if(i % 2) == 0:
i= False # print(i, "Cift Sayidir.")
elif(i % 2) == 1:
i= False
else:
print(max(x))
|
1f265b5316c3cd5fd6f103c8cac60a75584e01b3 | Lee8150951/Python-Learning | /day05/01-OperateDictionary.py | 575 | 4.375 | 4 | # P88练习
# 练习6-1
man = {
'first_name': 'Jacob',
'last_name': 'Lee',
'age': 22,
'city': 'Shanghai'
}
print(man)
# 练习6-2 略
# 练习6-3
python = {
'dictionary': 'it can store many Key/value pairs',
'list': 'it can store many data, but they can be changed',
'tuple': 'it can store many data, and they ... |
9ad344b78580699941bee4bf63239492d1b69d85 | Lee8150951/Python-Learning | /day07/03-Return.py | 835 | 4.15625 | 4 | # P127练习
# 练习8-6
def city_country(city, country):
conclusion = f"{city.title()}, {country.title()}"
return conclusion
info = city_country("Santiago", "Chie")
print(info)
info = city_country("Shanghai", "China")
print(info)
info = city_country("Tokyo", "Japan")
print(info)
# 练习8-7
def make_album(singer_name, alb... |
09c6efc1ed4e0d774b72dd47d4df3f95a72d2287 | s444427/Algorithms---Tasks-from-sites | /DONE/Dywan.py | 299 | 3.546875 | 4 | # https://adjule.pl/groups/ogolny/problems/mwpz2014y
# solution by Paweł Lewicki
if __name__ == '__main__':
count = input();
for i in range(0,int(count)):
mylist = input()
newlist = mylist.split(' ')
mytuple = tuple(newlist)
print(int(mytuple[0]) * int(mytuple[1])) |
301f738c7aa181ac3535e21f24f2609dd69bc152 | s444427/Algorithms---Tasks-from-sites | /DONE/Liczby pierwsze.py | 509 | 3.75 | 4 | # https://pl.spoj.com/problems/PRIME_T/
# solution by Paweł Lewicki
import math
if __name__ == '__main__':
x = int(input())
for j in range(0, x):
n = int(input())
isPrime = 0
if n == 1:
isPrime = 1
elif n == 2:
isPrime = 0
else:
for... |
40f3e8dd0591c6fd6209b9ce1e52a8407f009047 | will-jac/sl_arrhythmia | /neuron.py | 2,600 | 3.546875 | 4 | import numpy as np
# Ideas for development / different options:
#
# Type of NN:
# - Recurrent
# - Feedforward
#
# Type of activation
# - ReLU
#
# Loss function
# - MSE
#
# Type of backpropogation
# - ?
#
# Meta-parameters
# - Input / output layer sizes
#
# basic code
def sigmoid(z):
return 1 / (1 + np.exp(-z))
... |
584f92c81ac9f745e10411691a455dbc3a1e2aef | rpytel1/clickbait-challenge | /feature_extraction/services/slang_service.py | 1,489 | 3.671875 | 4 | import nltk
from nltk import word_tokenize
with open("../feature_extraction/resources/slang_words.txt", encoding="utf-8") as f:
content = f.readlines()
slang_list = [x.strip() for x in content]
# function checking for presence of slang words in a text
def calculate_num_slang_words(text):
if text == "":
... |
a18409893d7bf522e91091be92bbc46dbe4af198 | zhanghui0228/study | /python_Basics/basics/day09--tuple.py | 2,782 | 4.09375 | 4 | #元组(tuple)
'''
元组是"不可变"的列表(list)
元组使用小括号来进行表示
元组书写格式:
格式一: tup1 = ('abc', 'bcd', 123, 456)
格式二: tup2 = 'abc', 'bcd', 1, 2, 3
'''
#元组的读写
'''
元组的读取方式与列表读取的方式是相同的
元组创建完元素后,元素不允许修改,如果元组内持有列表,则元组内的列表可以被修改
元组允许使用"元组运算符"来进行创建新的元组 元组运算符同样适用于列表
'''
t1 = (['张三', 20, 2000], ['李四... |
3bed81d65c30f440ee3abd6106801608f9f7e72c | zhanghui0228/study | /python_Basics/memory/mem.py | 1,145 | 4.21875 | 4 | #内存管理机制 ----赋值语句内存分析
'''
使用id()方法访问内存地址
'''
def extend_list(val, l=[]):
print('----------------')
print(l, id(l))
l.append(val)
print(l, id(l))
return l
list1 = extend_list(10)
list2 = extend_list(12, [])
list3 = extend_list('a')
print(list1)
print(list2)
print(list3)
"""
垃圾回收机制:
... |
9f90663477c36ddaff0bf19c432e0445a739f77d | zhanghui0228/study | /python_Basics/Association协程/asyncio_queue.py | 1,558 | 3.84375 | 4 | # 协程之间的数据通信
'''
嵌套调用 拿到另一个协程函数中的结果
'''
import asyncio
# async def compute(x, y):
# ''' 定义一个计算协程函数 '''
# print(' start compute {0} + {1} '.format(x, y))
# await asyncio.sleep(5)
# return x + y
#
#
# async def get_sum(x, y):
# ''' 获取compute协程函数中返回的结果 '''
# result = await compute(x, y)
#... |
86374990275c081632ef916b8c338c50611141c6 | zhanghui0228/study | /python_Basics/process进程/process_pool.py | 1,187 | 3.5625 | 4 | #进程池
'''
#now_process = current_process() #当前进程
'''
import time
from multiprocessing import current_process, Pool
def run(file_name, i):
'''
多线程执行的代码 ---写入文件
:param file_name: str 文件名称
:param i: int 写入的数字
:return:
'''
now_process = current_process()
with open(file_name, ... |
31918b42c7390832e1cfa859445bcb16c3a56d80 | sdbaronc/LaboratorioFuncionesRemoto | /a_power_b.py | 331 | 4.03125 | 4 |
while True:
a = int(input("ingrese la base del numero:"))
if a==0:
print("final del programa")
break
b = int(input("ingrese el exponente del numero: "))
def a_power_b(a, b):
prod = 1
for x in range(1, b + 1):
prod = prod * a
print(prod)
a_powe... |
50903c1ea22fd9f91f8afd8d5b804b9ddc457e69 | brianna219c/cssi-labs | /python/labs/functions-cardio/functionsCalculator.py | 274 | 3.828125 | 4 | print("Welcome to bri's calculator!")
num1 =int(raw_input("Give me a numnber:"))
num2 =int(raw_input("Give me another numnber:"))
def myAddFunction(add1, add2):
sum = add1 + add2
return sum
print(myAddFunction("Here is the sum:" + str(myAddFunction(num1, num2)))
|
137defbc2fbc8cd308d1fb892bfcce9f2f99498a | ola-lola/Python-Projects | /Hangman.py | 2,070 | 4.125 | 4 | import random
import time
from termcolor import colored
print("Hello there!")
time.sleep(1)
print("If you know some cities from Europe... ")
time.sleep(1)
print(colored("Let's play HANGMAN!", "green"))
time.sleep(1)
namey = input("What's your name?: ")
time.sleep(1)
print( "Hello " + namey + "!\n")
time.sleep(1)
pr... |
425e31750033cc79b0f2dbb38457f9b41b1b5cf8 | jkohans/adventofcode2020 | /day15/day15.py | 1,339 | 3.640625 | 4 | def get_number(starting_numbers, turn):
num_starting_numbers = len(starting_numbers)
last_seen_idx = dict()
for i, num in enumerate(starting_numbers[: len(starting_numbers) - 1]):
last_seen_idx[num] = i
last_spoken = starting_numbers[-1]
for i in range(turn - len(starting_numbers)):
... |
71d63fd0763f47c13a70464065f6f9a29382e7aa | jkohans/adventofcode2020 | /day23/day23.py | 3,038 | 3.53125 | 4 | def pick3_ll(right_pointers, current_cup):
pick3 = []
next_ = right_pointers[current_cup]
for _ in range(3):
pick3.append(next_)
next_ = right_pointers[next_]
# chop out the picked list
right_pointers[current_cup] = next_
for label in pick3:
del right_pointers[label]
... |
0e739fad9a189252d99c5614e30e545b7b06f3d0 | jkohans/adventofcode2020 | /day9/day9.py | 1,736 | 3.578125 | 4 | def find_first_invalid_number(numbers):
preamble_size = 25
for idx, number in enumerate(numbers[preamble_size:]):
offset_number = preamble_size + idx
prev_slice = numbers[offset_number - 25 : offset_number]
if not find_pairs(prev_slice, number):
return offset_number, number
... |
d7b9399b86cde9cc79864ef7bdd42902adb98cb1 | alex00321/Python | /Self_learning/twolistmerge_algorithm.py | 1,706 | 3.671875 | 4 | from typing import Optional
class ListNode:
def __init__(self, val = None):
if isinstance(val, int):
self.val = val
self.next = None
elif isinstance(val, list):
self.val = val[0]
self.next = None
cur = self
for i in val[1:]:
... |
6707c007958b3b6f89f507fb9e317983833b4598 | seanremenyi/Game-of-21 | /extras.py | 2,952 | 3.953125 | 4 | ###rules and instructions to be printed with the --help tag
def help():
print("""
Help
Objective
* The objective of the game is to reach 21 points or as close as possible without going over.
Rules
* The player is dealt 2 cards giving a certain total.
* The computer opponent known as the dealer is dealt 2 cards as... |
9d997fb7a3c1963eaf32697e75007e0831cb6ce6 | tiaraprtw/basic-phyton | /string formating.py | 329 | 3.921875 | 4 | #untuk memasukan argumen, ditempatkan untuk mengisi string yg berisi {}
#sallary = 8
#txt = "my name is ara, and i want my sallary is {}".format(sallary)
#print(txt)
nama=str(input ("write your name here: "))
age= int(input("how old are you: "))
teks= "im {} and {} years old".format(nama,age)
#print(txt)
prin... |
49f1d420b08fe1e6f67f2cf4f0de8a59ed0492c0 | surenderreddychitteddy/python_practice | /Netmiko_to_ssh.py | 1,290 | 3.53125 | 4 | import Netmiko
def ssh(device_type, ipaddress):
"""
This function is used for performing ssh to linux devices
:param device_type: The device for which you want to perform ssh login.
:param ipaddress: IP address of the device.
:return: connection | None
"""
try:
connection = netmiko.... |
8d1eb0a46803b18af195483c71ee52b14aa932c9 | xpqz/aoc-18 | /day9.py | 2,399 | 3.5625 | 4 | """
day 9 of Advent of Code 2018
by Stefan Kruger
Solution using actual linked list to avoid O(n) insertion behaviour that
cripples part 2.
An alternative approach could have used a deque:
https://stackoverflow.com/questions/39522787/time-complexity-of-random-access-in-deque-in-python
"""
from collections import Co... |
1c69dac16dd39b6e774dcc2b0574b40ebf08d76b | hwpvanholsteijn/SmartPug | /Servo/servo.py | 905 | 3.65625 | 4 | #!/usr/bin/python
import wiringpi
import time
# ====== VARIABLES ====== #
delay_period = 0.01
# ====== FUNCTIONS ====== #
# Set pins to PWM mode and set frequency
# - https://learn.adafruit.com/adafruits-raspberry-pi-lesson-8-using-a-servo-motor/software
def init():
# use 'GPIO naming'
wiringpi.wiringPiSetupGpio()
... |
d49c03a009a1bffc88273c17230453a1ee7ecd01 | AtulSinghTR/AtulSinghTR | /exercism-py/python/raindrops/raindrops.py | 261 | 3.734375 | 4 | def convert(number):
sound=''
if number%3==0:
sound='Pling'
if number%5==0:
sound=sound+'Plang'
if number%7==0:
sound=sound+'Plong'
if len(sound)==0:
sound=str(number)
return sound
|
82fbd2329d3cb784b37943f7845808dbd8eee886 | AtulSinghTR/AtulSinghTR | /exercism-py/python/scrabble-score/scrabble_score.py | 319 | 3.890625 | 4 | def score(word):
marks = {'1':['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'], '2':['D', 'G' ], '3': ['B', 'C', 'M', 'P'], '4': ['F', 'H', 'V', 'W', 'Y'], '5': ['K'], '8': ['J', 'K'], '10': ['Q','Z']}
print(marks.values())
if 'A' in marks.values():
print('exists')
print(score('ABCD')) |
9c88249c564273d910853815b5465518be5be476 | AtulSinghTR/AtulSinghTR | /python/tuple-dicts.py | 2,122 | 3.671875 | 4 | import sys
x=(1)
print(type(x))
x=(1,)
print(type(x))
# Common array func work with tuple also
tup_1=(1,2,3,4,5)
print('length:', len(tup_1))
print('Slicing:', tup_1[:2])
# tuples are immutables
try:
tup_1[0] = 9
# except:
# print(sys.exc_info()[0], sys.exc_info()[1])
except Exception as e:
print(e)
# tuple... |
f8da1e91278146bc58125352cbbeacd0a11827b5 | stephenjkaplan/mta-data-analysis | /data_visualization_utilities.py | 2,663 | 3.734375 | 4 | """
This file contains all utility functions used in the "Data Analysis & Visualization" Notebook
Stephen Kaplan, 2020-07-05
"""
import matplotlib.pyplot as plt
import seaborn as sns
def get_top_stations_by_total_traffic(df, num_stations=10):
"""
Returns a DataFrame containing the busiest stations by total tr... |
508f8733c7a928faa06ef664b232f5d81aaf3460 | yaroslavtsepkov/chord-alg | /main.py | 1,005 | 3.609375 | 4 | from typing import *
from chord_node import ChordNode
def stabilize_and_print(nodes: List[ChordNode]):
print('**************************')
for i in range(10):
for node in nodes:
node.stabilize()
node.fix_fingers()
for node in nodes:
print(node)
print('********... |
275c0320c0858b5ffd852e69191fe0dcc50f5ebf | arneger/english-anagram-translator | /anagram_program.py | 4,266 | 3.640625 | 4 | from nltk.corpus import words
from tkinter import *
import random
# Function that takes the user-input and checks if there's english words from
# the nltk words list that got the exact same characters as the input.
def anagram_matcher():
output_word2.config(state=NORMAL)
output_word2.delete(0.0, END)
... |
029f12d5b321a2a7bec86797ea11acd06b8d7bf2 | rf2046/python-course | /fizzbuzz/fizzbuzz.py | 197 | 3.75 | 4 | count = 0
while (count < 100):
if count%15==0:
print ("fizzbuzz")
elif count%3==0:
print ("fizz")
elif count%5==0:
print ("buzz")
else: print ("%d" % (count))
count += 1 |
e06f6aac1d590e16acf26a36f19112d250580300 | gareia/DataStructures | /Hackerrank/PreorderTraversal.py | 529 | 3.84375 | 4 | """
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def preOrder(root):
print(preOrderHelper(root))
def preOrderHelper(root):
if(root):
result = str(root.info) + " "
#print(result)
result += preOrde... |
ebf4fae9e217276076c8cdcee0f074e2fe827c6e | gareia/DataStructures | /Hackerrank/ReverseArray.py | 335 | 3.546875 | 4 |
def reverseArray(a):
pos0 = 0
posF = len(a)-1
while(pos0 < posF): #O(n/2) => O(n)
aux = a[pos0]
a[pos0] = a[posF]
a[posF] = aux
pos0 += 1
posF -= 1
return a
#MAIN
# INPUT a: array n: len(a)
# n [1-10^3]
# a[i] [1-10^4]
# reverseArray(a) call
# OUTPUT... |
d688bf04940a7684ac77cff9666bb67d402d1f5d | sheilazpy/ML-AndrewNg | /ex1-python/gradientDescent.py | 1,047 | 3.9375 | 4 | ##############################################
# Author: Jivitesh Singh Dhaliwal
# Date: 07-11-2013
# Description:Gradient Descent Algorithm
# without regularization
##############################################
from computeCost import *
def gradientDescent(X, y, theta, alpha, numIter):
''... |
2dbb417f34777ae77b8b5ca45e652f8c71df5806 | sheilazpy/ML-AndrewNg | /ex2-python/gradientFunction.py | 544 | 3.546875 | 4 | ################################################
# Author: Jivitesh Singh Dhaliwal
# Date: 09-11-2013
# Program: Compute Cost for Logistic Regression
################################################
from computeCost import *
def gradientFunction(X, y, theta, alpha, numIter):
'''Return the gradient for give... |
f1922a5f7e6139b3909e0c804c6277d66e44f314 | AliAldobyan/queues-data-structure | /queues.py | 2,407 | 4.15625 | 4 | class Node:
def __init__(self, num_of_people, next = None):
self.num_of_people = num_of_people
self.next = next
def get_num_of_people(self):
return self.num_of_people
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class Que... |
7ff6d894cb5fd11ebc5e67f8e8b54113cd5865cc | MdNaina/python_random_projects | /bank.py | 1,364 | 3.59375 | 4 | import time
customer_name = ""
acc_no = ""
bal = 500
while True:
time.sleep(2.5)
print('+------------------------------------+')
print('| 1 - get the values |')
print('| 2 - deposit to account |')
print('| 3 - withdraw in account |')
print('| 4 - ... |
0277a293d7e820b11b9cb1bf05c12440b39e476b | 321HG/NeuralPy | /neuralpy/layers/sparse/embedding.py | 5,237 | 3.515625 | 4 | """Embedding layer for NeuralPy"""
from torch.nn import Embedding as _Embedding
from neuralpy.utils import CustomLayer
class Embedding(CustomLayer):
"""
A simple lookup table that stores embeddings of a fixed dictionary and size
To learn more about RNN, please check pytorch
documentation at https://p... |
2a2c833ee70c33f7aeb62c85dd400fab04c5ad8d | 321HG/NeuralPy | /neuralpy/layers/regularizers/dropout3d.py | 2,160 | 3.546875 | 4 | """Dropout3D Layer"""
from torch.nn import Dropout3d as _Dropout3D
from neuralpy.utils import CustomLayer
class Dropout3D(CustomLayer):
"""
Applies Dropout3D to the input.
The Dropout3D layer randomly sets input units to 0 with a frequency of `rate`
at each step during training time, which helps pre... |
414243ac380ab55d740804838030ba11ba39c7cb | 321HG/NeuralPy | /neuralpy/layers/activation_functions/gelu.py | 1,624 | 3.796875 | 4 | """GELU Activation Function"""
from torch.nn import GELU as _GELU
from neuralpy.utils import CustomLayer
class GELU(CustomLayer):
"""
Applies the Gaussian Error Linear Units function to the input tensors.
For more information, check https://pytorch.org/docs/stable/nn.html#gelu
Supported Arguments
... |
2a992878eb7049a4e63b04317e7a0c0d44972927 | 321HG/NeuralPy | /neuralpy/layers/other/flatten.py | 2,090 | 3.953125 | 4 | """Flatten layer for NeuralPy"""
from torch.nn import Flatten as _Flatten
from neuralpy.utils import CustomLayer
class Flatten(CustomLayer):
"""
Flattens a contiguous range of dims into a tensor
To learn more about Dense layers, please check PyTorch
documentation
https://pytorch.org/docs/stable/... |
85399a1213b77968a68592055d28e02075440f27 | dairycode/Python-language | /03_循环/hm_04_累加求和.py | 383 | 3.703125 | 4 | # 计算0-100之间所有数字的累计求和结果
# 0.定义最终结果的变量
result = 0
# 1.定义一个整数的变量记录循环的次数
i = 0
# 2.开始循环
while i <= 100:
print(i)
# 每一次循环,都让result这个变量和i这个计数器相加
result += i
# 处理计数器
i += 1
print("0-100之间的数字求和结果 = %d" % result) |
a2854e2dc98c50748506f8efb41affe3254f2264 | dairycode/Python-language | /02_分支/hm_02_判断年龄改进版.py | 412 | 3.8125 | 4 | # 输入用户年龄
age = int(input("请输入年龄:"))
# 判断是否满18岁(>=)
if age >= 18:
# 如果满18岁,允许进入网吧嗨皮
print("你已经成年,欢迎来网吧嗨皮")
else:
# 如果未满18岁,提示回家写作业
print("你还没有成年,请回家写作业吧")
# 这句代码无论条件是否成立都会执行
print("这句代码什么时候执行?") |
a928884a6c5200c8a4ebff292ef60f612fd66c02 | dairycode/Python-language | /03_循环/hm_03_程序计数.py | 335 | 4.0625 | 4 | # 打印5遍Hello Python
# 1.定义一个整数变量,记录循环次数
i = 0
# 2.开始循环
while i < 3:
# 1>希望在循环内执行的代码
print("Hello Python")
# 2>处理计数器
# i = i+1
i += 1
# 3.观察一下,循环结束后,计数器i的数值是多少
print("循环结束后,i = %d" % i) |
9182e71d91c1c32ef92fc2847c9326f98f54d4b6 | TomasHenriqueSantos/Python-Exercises | /ex004.py | 394 | 3.921875 | 4 | print('===Exercício 04===')
s = input('Digite algo:')
print('O tipo primitivo desse valor é', type(s))
print('Só tem espaços?', s.isspace())
print('É um numero?', s.isnumeric())
print('É alfabético?', s.isalpha())
print('É alfanumerico', s.isalnum())
print('Esta maiusculo?', s.isupper())
print('Esta minusculo?'... |
fc90cd9a54a819f1ecb6ca2488fc30f0f69fdfa0 | kimotot/pe | /py28.py | 1,350 | 3.734375 | 4 | # プロジェクトオイラー Problem28
# coding:UTF-8
MAX_LOOP = 500
def get_rightup(max = MAX_LOOP):
''' 中心からみて右斜め上方向に出現する数字列を求める関数
最大max個まで求める
先頭(0番目)は1である'''
list_rightup = [1]
n = 1
while n <= max:
list_rightup.append(list_rightup[n-1] + n*8)
n += 1
return list_rightup
def... |
f958dfe13580d6aee7338aa4b57a658e3a5772e1 | kimotot/pe | /py46.py | 1,832 | 4.03125 | 4 | '''pe46の解答'''
import basic
import Prime
def is_odd_composite_number(n):
'''引数nが奇数の合成数であるか判定する関数'''
i = 1
r = n - (i**2) * 2
while r > 0:
if Prime.is_prime(r):
return True
i += 1
r = n - (i**2) * 2
else:
return False
class Odd_composite_number_Iterat... |
b925015be06011d41139ef95aeb6a7c0876370f6 | kimotot/pe | /py35.py | 2,662 | 3.5 | 4 | # coding:UTF-8
'''
100万未満の循環素数の個数を求める
'''
import math
import time
import copy
def get_sosu(maximum):
'''
引数max以下の素数を求める
戻り値は求めた素数を含むリスト
なお、1は素数ではないので、リストに含めない
'''
sosu_list = [2, 3] # 自明の素数をセットしておく
for n in range(5, maximum, 2):
sq = int(math.sqrt(n))
... |
cc856863bf356c569efce883609d6dc2bd369b55 | sanjay1711/100-days-of-code | /2.5. Numbers:sum of digits.py | 110 | 3.734375 | 4 | # Read an integer:
num = int(input())
a=(num%10)
b=(num//10)%10
c=(num//10)//10
# Print a value:
print(a+b+c)
|
e70c5700828ed6b9aca63aa8f7fcab81d4b8903f | flutesa/pythondevclub | /2 lesson (if-elif-else)/burkova/ZadachaB.py | 212 | 3.96875 | 4 | number = int(input())
if number % 5 == 0:
print('zero')
if number % 5 == 1:
print('one')
if number % 5 == 2:
print('two')
if number % 5 == 3:
print('three')
if number % 5 == 4:
print('four')
|
bad46d4862133163dca0723f79cdd661ce9ebbcc | flutesa/pythondevclub | /4 lesson (functions, classes)/burkova/111158.py | 281 | 3.828125 | 4 | # Desc sorting
def BubbleSort(a):
for i in range(len(a)):
for j in range(len(a) - 1):
if a[j + 1] > a[j]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
a = list(map(int, input().split()))
a = BubbleSort(a)
print(' '.join(list(map(str, a))))
|
765e8508a91bf87bdfba292e97c009f1dfcef684 | mtu2/stargazing | /stargazing/utils/print_funcs.py | 1,663 | 3.609375 | 4 | from typing import List
from blessed import Terminal
import math
def print_xy(term: Terminal, x: int, y: int, value: str, flush=True, max_width: int = None,
center=False, trim=False):
"""trim and center both require max_width to be given"""
if max_width is not None:
empty_len = max(max_wi... |
37d025ee7f23ecd7270f4e7702a42124f51c2c39 | yunblack/Movie-Data-Viewer | /moviedatareader.py | 1,742 | 3.734375 | 4 | # name: Juyoung Daniel Yun
# email: juyoung.yun@stonybrook.edu
# id: 112368205
from datetime import datetime
import csv
#----------------------------------------------------------------------
movieItems = []
def csv_dict_reader(file_obj):
"""
Read a CSV file using csv.DictReader
The line is ... |
cb884c3a3a6e612b8e1d69b44a24362af4a826cc | chris-mega/ObstacleSlam | /events/src/obstacle_run_slam/obstacles.py | 609 | 3.59375 | 4 | class Obstacle(object):
def __init__(self):
self.area = -1
self.x = -1
self.y = -1
self.angle = -100
self.width = -1
self.height = -1
self.position = 'None'
def update(self, x, y, width, height, area, angle, pos):
self.area = area
... |
cc349db0742aaebc7650af633e66bc10cb3f14b2 | matheusjunqueiradasilva/Jogo-adivinhacao | /jogo da adivinhacao.py | 561 | 4.15625 | 4 | import random
rand = random.randint(1, 200)
tentiva = 10
print(" Bem vindo ao jogo da advinhacao!")
print(" Tente advinhar o numero sorteado, e ele deve ser menor que 200!")
while True:
numero1 = int(input("digite o numero: "))
if numero1 == rand:
print(" parabens voce acertou! ")
break
... |
dc37784ec5ecc60523139480f96242bcc91695bf | appanchhibber/CHEERS | /Solution.py | 1,425 | 3.984375 | 4 | from MathOperations import MathOperation
"""
Python file for implementing the solution of the project
"""
class Solution:
"""
This class is responsible for the calculation of the value of alpha and the length between the two coasters of same
radius
"""
alpha_value = float(10)
@staticmethod
... |
f69eb91c047160eaa5583235cfc700261df952f8 | dldydrhkd/Problem-Solving | /leetcode/1137.py | 353 | 3.59375 | 4 | class Solution:
def tribonacci(self, n: int) -> int:
if(n==0):
return 0
if(n==1):
return 1
if(n==2):
return 1
n1 = 0
n2 = 1
n3 = 1
for i in range(3,n+1):
n4 = n1+n2+n3
n1 = n2
n2 = n3
... |
69fde7d67b3b07b88dcf9e844d12c59d08739064 | dldydrhkd/Problem-Solving | /프로그래머스/전화번호 목록.py | 219 | 3.6875 | 4 | def solution(phone_book):
answer = True
phone_book.sort()
for i in range(1,len(phone_book)):
if(phone_book[i-1] == phone_book[i][:len(phone_book[i-1])]):
answer = False
return answer
|
13394b73571a3f164a9c7a1461fa2b6e6ba4f63f | alicebalayan/Algorithms | /General Problems/General/5/solution.py | 790 | 4.09375 | 4 | # General Problem 5:
# Find the only element in an array that only occurs once.
# Solution:
# Store the array into a dictionary while counting the occurences
# Then print out values that occur once, if there is exactly one
# function printOneCount
# Takes an array of integers as the input
# Outputs the element that i... |
2a99a9e07ad02b5d5ae3c785ef43f1b57f560ac9 | alicebalayan/Algorithms | /General Problems/General/8/solution.py | 1,566 | 4.03125 | 4 | # General Problem 8:
# Implement binary search in a rotated array (ex. {5,6,7,8,1,2,3})
# Solution:
# Similar to general 7
# We assume that the rotated array is sorted
# First we find the real starting index of the rotated array
# Then we perform binary search, except we consider the real starting index
# Therefore, w... |
f50ec07ceb69c0e52b26ebcb3e2e6b0672d6de99 | GaoFan98/algorithms_and_ds | /DS and Algorithms in Python/random_tests.py | 7,020 | 3.984375 | 4 | # list = [1, 4, 3, 4, 5]
#
# i = 0
# while i < len(list):
# print(list[i])
# i += 1
# modulus comparison keyword parameter
# print(max(-2, -65, 32, 11, key=abs))
# Integer related point and character on the integer point
# print(ord('~'))
# print(chr(65))
# return the whole value of division and it's reminde... |
d3fa518047f00633b3e21037013f6c0bc6b1c648 | GaoFan98/algorithms_and_ds | /Grokking/3_quick_sort.py | 343 | 3.796875 | 4 | def quick_sort(arr):
if len(arr) < 2:
return arr
else:
pivot = arr[0]
less = [num for num in arr[1:] if num <= pivot]
greater = [num for num in arr[1:] if num > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
q = quick_sort([7, -9, 12, 8, 89])
print(q)
... |
b50f2c2dfa19a96d431b030b5a0551fc932e9141 | GaoFan98/algorithms_and_ds | /Algo/Arrays/find_miss_el.py | 649 | 3.640625 | 4 | # def finder(l1, l2):
# num_dict = {}
#
# for num in l1:
# if num not in num_dict:
# num_dict[num] = 1
# else:
# num_dict[num] += 1
#
# for num in l2:
# if num not in num_dict:
# num_dict[num] = 1
# else:
# num_dict[num] -= 1
#
... |
3c35cae20db00a8798be0a18ce87d93bb628d673 | GaoFan98/algorithms_and_ds | /Coursera/7_fibonacci_partial_sum.py | 308 | 3.546875 | 4 | def calc_fib(frm,till):
arr_nums = [0,1]
if (till <= 1): return till
for i in range(2,till+1):
arr_nums.append((arr_nums[-1]+arr_nums[-2])%10)
a = sum(arr_nums[frm:till+1]) %10
return a
if __name__ == '__main__':
frm, till = map(int, input().split())
print(calc_fib(frm, till)) |
5f25a0a9ad7ae81345007761fb6641542edcdd3b | GaoFan98/algorithms_and_ds | /Coursera/1_fibonacci_number.py | 697 | 4.15625 | 4 | # Recursive way
# def calc_fib(n):
# if n <= 1:
# return n
# return calc_fib(n-1)+calc_fib(n-2)
# n = int(input())
# print(calc_fib(n))
# Faster way of fibonacci
# def calc_fib(n):
# arr_nums = [0, 1]
#
# if (n <= 1):
# return n
#
# for i in range(2, n + 1):
# arr_nums.append(arr_nums... |
dff4d3df76fef571af82586fa6b1436ac38231d7 | EmilieTrouillard/ComputationalTools | /preprocessing/parser.py | 2,254 | 3.5 | 4 | # coding=utf8
import json
import re
import mmh3
'''
GOAL: Get all links to other wikipedia pages from the json file of a single page.
'''
# DEPRECATED USED FOR PARSING JSON FROM API
# WIKILINK_REGEX = r"/<a\s+(?:[^>]*?\s+)?href=\\([\"'])\/wiki\/(.*?)\\\1/"
WIKILINK_REGEX = r'\[\[([\| \w+]*)\]\]'
rgx = re.compile(WIK... |
91a3b5ba76ba9b77775c981e048aec2cae7e8d9d | Fabulinux/Project-Cognizant | /Challenges/Brian-08302017.py | 1,007 | 4.25 | 4 | import sys
def main():
# While loop to check if input is valid
while(1):
# Try/Except statement for raw_input return
try:
# Prompt to tell user to input value then break out of while
val = int(raw_input("Please input a positive integer: ").strip())
break
... |
78f333af2427a13909aa28b67c4be1675d3e81f7 | AlexOKeeffe123/mastermind | /game/board.py | 2,682 | 4.15625 | 4 | import random
from typing import Text
#Chase
class Board:
def __init__(self, length):
"""The class constructor
Args:
self (Display): an instance of Display
"""
self._items = {} # this is an empty dictionary
self._solutionLength = length
def to_string(self):
"""Convert... |
f27dd793820c4035d0e89ddc6dc1d590c744270d | nzsakib/leetcode | /palindrome_number.py | 617 | 3.71875 | 4 |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# Negative number is not palindrome
if x < 0:
return False
z = x
rev = 0
prev = rev
while ( z != 0 ):
current = z % 10
... |
cc77887815ab66a9dc2d20459de45c864fb9c5ff | shahara21-meet/meet2019y1lab6 | /lab_6.py | 186 | 4 | 4 | def add(start,end,n):
total = 0
for number in range(start, end + n):
num=num+
print(num)
total = total + number
return total
x=add(1,10,2)
print(x)
|
99d06c8c3a682c0b07c39bdcd0c6d2943625f8ee | cubanmakers/OttoDIYPython | /Otto_allmoves_V9.py | 1,120 | 3.71875 | 4 | """
Otto All moves python test
OttDIY Python Project, 2020 | sfranzyshen
"""
import otto9, time
Otto = otto9.Otto9()
Otto.init(5, 12, 13, 14, True, 0, 1, 2, 3)
Otto.home()
Otto.walk(2, 1000, 1) #-- 2 steps, "TIME". IF HIGHER THE VALUE THEN SLOWER (from 600 to 1400), 1 FORWARD
Otto.walk(2, 1000, -1) #--... |
8f8253d0ebd6f6d823958e1af0720e5455d2713f | josht047/Ising-Model-Project | /Plotting Ising Model.py | 1,681 | 3.90625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
beta = 1.0
#defining function to randomly generate initial spin configuration
def initialise(n):
state = np.random.randint(2,size=(n,n))
return 2*state -1 #as spin can be -1 or 1, but the previous line gives a random matrix of ... |
cc1760c2ecbd3b7501e46b86eb9f3ae214975d84 | ValerieGM/Learn-Python-The-Hard-Way | /exercises/ex05.py | 599 | 3.921875 | 4 | my_name = 'Valkyrie'
my_age = 23 # sorta
my_height = 130 # cm I think
my_weight = 66 # kg
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Black'
print(f"Let's talk about {my_name}.")
print(f"She's {my_height} centimeters tall.")
print(f"She's {my_weight} kilograms heavy.")
print(f"Actually that's not too heavy.")
prin... |
28846684ac2b1aa260b3e6eff527664f9d1fad32 | ValerieGM/Learn-Python-The-Hard-Way | /exercises/ex24.py | 1,047 | 4.0625 | 4 | print("From The Top!!!")
print('You\'d need to know \'bout escapes with \\ that do:')
print("\n newlines and \t tabs.")
poem = """
\tMove him into the sun—
Gently its touch awoke him once,
At home, whispering of fields half-sown.\nAlways it woke him, even in France,
Until this morning and this snow.
If anything might ... |
b4cdffb10f427f0b26c319f973b6d57d0959ee5e | frasanz/LTS | /chapter6/onehotword.py | 1,050 | 3.828125 | 4 | # This is an example of one hot encoding using words
import numpy as np
samples = ('The cat sat on the mat.', 'The dog ate my homework.')
#First, build an index of all tokens in the data
token_index = {}
for sample in samples:
# We simply tokenize the samples via the `split`method.
# In real life, we would al... |
c3c33db359afa186f81827a9898d27885310ccb1 | olifantix/python_tools | /tic-tac-to_sim.py | 1,203 | 4.0625 | 4 | def check_win(d):
"""Input is a dictionary with keys 1-9 according to a numerical
keypad: 789
456
123
function checks win condition for tic tac toe and returns the dicts value"""
w = ( (7, 8, 9), (4, 5, 6), (1, 2, 3,),
(1, 4, 7), (2, 5, 8), (3, 6, 7),
... |
1f15da7c30ac1cc5651b23777bda357d6edb6b53 | gaogao0504/gaogaoTest1 | /homework/pytestagmnt/calculator1.py | 818 | 4.28125 | 4 | """
1、补全计算器(加法,除法)的测试用例
2、使用数据驱动完成测试用例的自动生成
3、在调用测试方法之前打印【开始计算】,在调用测试方法之后打印【计算结束】
坑1:除数为0的情况
坑2: 自己发现
"""
# 被测试代码 实现计算器功能
class Calculator:
# 相加功能
def add(self, a, b):
return a + b
# 相减功能
def sub(self, a, b):
return a - b
# 相乘功能
def multi(self, a, b):
return a * b
... |
f1b93a968eeeefd9605cc9976cec3f09a48eb610 | poldrack/pybraincompare | /example/make_connectogram.py | 960 | 3.609375 | 4 | # Make a connectogram d3 visualization from a square connectivity matrix
from pybraincompare.compare.network import connectogram
from pybraincompare.template.visual import view
import pandas
# A square matrix, tab separated file, with row and column names corresponding to node names
connectivity_matrix = "data/parcel... |
8a11a21c2675c2b6f5859e8224a3d1dbb77cd6f8 | ncouturier/Exercism | /python/twelve-days/twelve_days.py | 929 | 3.84375 | 4 |
NUMBERS = ["a ","two ","three ","four ", "five ", "six ","seven ","eight ","nine ","ten ","eleven ","twelve ", "thirteen ", "fourteen ", "fifteen ","sixteen ","seventeen ", "eighteen ","nineteen "]
NUMERALS = ["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"]
O... |
b614122fb0117d4dd5afb5f148f5f803013a3397 | LeedsCodeDojo/Rosalind | /AndyB_Python/fibonacci.py | 1,355 | 4.25 | 4 |
def fibonacci(n, multiplier=1):
"""
Generate Fibonacci Sequence
fib(n) = fib(n-1) + fib(n-2)*multiplier
NB Uses recursion rather than Dynamic programming
"""
if n <= 2:
return 1
return fibonacci(n-1, multiplier) + fibonacci(n-2, multiplier) * multiplier
def fibonacciDynamic(n,... |
b86bf2023c5ca61cb86198a7b469aabeb837036e | pokhachevskiy/administrationUtility | /DataBaseWrapper.py | 1,068 | 3.5625 | 4 | import json
class DictWrapper:
def __init__(self, data):
self.data = data
# Обертка над базой данных для отладочного режима (не требует домена в окружении)
class DataBaseWrapper:
def __init__(self):
try:
db = open('db.json', 'r')
# Reading from json file
d... |
8619254a232ae1d3acdb21f911a689b22b836bde | mbutkevicius/Sequences | /tuples_intro.py | 1,292 | 3.65625 | 4 | albums = [("Welcome to my Nightmare", "Alive Cooper", 1975),
("Bad Company", "Bad Company", 1974),
("Nightflight", "Budgie", 1981),
("More Mayhem", "Emilda May", 2011),
("Ride the Lightning", "Metallica", 1984),
]
print(len(albums))
# my solution (was right! yay me!)
... |
d656321a25f1158956cfa195418a4d8cc5ddaee5 | AlexDerr/Kattis | /Problems/Anagram Counting/AnagramCounting.py | 469 | 3.5 | 4 | import math
import string
import sys
occurences = {}
for line in sys.stdin:
str = line.splitlines()[0]
denominator = 1
for char in string.ascii_letters:
occurences[char] = 0
for char in str:
occurences[char] += 1
for item in occurences:
if occurences[item] != 0:
... |
9e5b696eb085411da4bcdfa2a74c8b6378d01fa0 | JadaShipp/ds-methodologies-exercises | /regression/split_scale.py | 6,025 | 3.609375 | 4 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, QuantileTransformer, PowerTransformer, RobustScaler, MinMaxScaler
def split_data(df, train_pct=0.75, seed=123):
train, test = train_test_split(df, train_size=train_pct, rand... |
620b00694388d6590399efc4517b2cbcf7a3c6df | ly061/learn | /基础/嵌套函数.py | 418 | 4.0625 | 4 | # 外层函数的变量可以被内部函数调用,但是不能被修改。需要nonlocal 声明之后才能进行修改
def outer(num):
print('outing')
test_num = 10
def inner(num_inner):
nonlocal test_num
print(test_num)
test_num += 1
if type(num_inner) is int:
print('是整数')
else:
print('不是整数')
inner(num)
o... |
7c87545b7dbeeda6137fa964bdc18d1b47fb3cda | ly061/learn | /基础/士兵突击.py | 772 | 3.8125 | 4 | class Gun:
def __init__(self, model):
self.model = model
self.bullet_num = 0
def add_bullet(self, count):
self.bullet_num += count
def shoot(self):
if self.bullet_num <= 0:
print(f'{self.model}没有子弹了')
return
self.bullet_num -= 1
print... |
0f54ced3006c9c262d29354742a89688345a00f5 | ly061/learn | /基础/推导式.py | 592 | 3.75 | 4 | # 列表推导式
li1 = [x for x in range(5)]
li2 = [[x for x in range(3)] for x in range(3)]
li3 = [[x for x in range(3)] for x in range(3) if x > 0]
li4 = [(x, y) for x in range(3) for y in range(3)]
print(li1, li2, li3, li4, sep='\n')
# 字典推导式
text = 'i love you'
dic1 = {x: text.count(x) for x in text}
print(dic1)
# 生成器推导式(元... |
ea529fea345aaf3a88e6e0a9e02b1419c67c5603 | ly061/learn | /算法/冒泡排序.py | 1,097 | 3.90625 | 4 | # 两种解法都可以,第一种是把最大的往后排,第二种是把最小的往前排
def bubble_sort1(seq):
for i in range(len(seq)):
for j in range((len(seq)-i-1)):
if seq[j] > seq[j+1]:
seq[j], seq[j + 1] = seq[j + 1], seq[j]
return seq
def bubble_sort(seq):
for i in range(len(seq)):
exchange = False ... |
7258f76011bedbf7e28c7c9f9f0401e1a2b78f17 | ly061/learn | /基础/JSON序列化和反序列化.py | 543 | 4.21875 | 4 | # 序列化:把python转化为json
# 反序列化: 把json转为python数据类型
import json
# data = {"name": "ly", "language": ("python", "java"), "age": 20}
# data_json = json.dumps(data, sort_keys=True)
# print(data)
# print(data_json)
class Man(object):
def __init__(self, name, age):
self.name = name
self.age = age
def obj2j... |
65a0a9921a54d50b0e262cccf64d980c2762f2f7 | edwinjosegeorge/pythonprogram | /longestPalindrome.py | 838 | 4.125 | 4 | def longestPalindrome(text):
'''Prints the longest Palendrome substring from text'''
palstring = set() #ensures that similar pattern is stored only once
longest = 0
for i in range(len(text)-1):
for j in range(i+2,len(text)+1):
pattern = text[i:j] #generates words of min lenght 2 (s... |
cc87e6aace0ee46f2d8b64170137d9e2a4cde7d8 | Omri49/Four-in-a-row | /four_in_a_row.py | 2,814 | 3.546875 | 4 | from ex12.game import Game
from ex12.ai import AI
from ex12.gui import GUI
from ex12.starting_menu import Menu
P_V_P = 1
AI_V_P = 2
P_V_AI = 3
AI_V_AI = 4
DRAW = -2
def player_decider(main_menu):
""" This will call game_loop with the proper player configurations"""
game_type = main_menu.get_pla... |
d817775841ff14b2060a44cb2901713bce4a74f3 | maxigor/forcaAdivinhacao | /adivinhacao.py | 1,490 | 4.0625 | 4 |
def jogar():
import random
print("###############################")
print("Bem vindo ao jogo de Adivinhacao")
print("###############################")
numero_secreto = int(round(random.randrange(1 , 101)))
total_de_tentativas = 0
pontos = 1000
print("Escolha o nivel de dificuldade")
print("(1)-Facil (2)-Me... |
d1a31cf00996eab089ce44d54e0ac15f562c82fa | jhylands/csteach | /prac4/extention pt2.py | 444 | 3.625 | 4 | def matrixSize(matrix):
print "Size:, " + str(len(matrix)) + "x" + str(len(matrix[0]))
def addMatrix(a,b):
c = []
for n in xrange(0,len(a)):
c.append([])
for i in xrange(0,len(b)):
c[n].append(a[n][i] + b[n][i])
return c
def T(a):
c = []
for i in xran... |
4d087b7671815aa117a2a03bdbc24b488b704553 | jhylands/csteach | /prac2/ex4.py | 420 | 3.9375 | 4 | def get_year():
year = int(raw_input("Please enter the year you wish to check."))
return year
#if a is devisible by b
def dvsbl(a,b):
return a%b ==0
def is_leap_year(year):
if dvsbl(year,4) and not dvsbl(year,100) or dvsbl(year,400):
return True
else:
return False
def main():
year = get_year()
if is_leap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.