blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b6f3bea88f816112d565058b7bc287fe6c1ca327 | self-learning-alliance/machine-learning | /aether/codebase/201904/03_属性方法.py | 831 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# 使用场景,经过一些列的操作才能获取的一个状态(航班状态查询)
# 博客地址
# http://www.cnblogs.com/alex3714/articles/5213184.html
class Dog(object):
def __init__(self,name):
self.name = name
self.__food = None
# 属性方法:将方法作为静态属性
@property
def eatStatic(self):
print ("%s is eating %s" %(self... |
dbf86b5a3ed182360898abf157d9fcabc5dc199f | johnnylindbergh/ConnectFourAI | /ConnectFourAI.py | 6,680 | 3.609375 | 4 | class Board:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.state = [[0 for i in xrange(cols)] for i in xrange(rows)]
def display(self):
print"-----------------------------"
for i in range(6):
for j in range(7):
print "|", self.state[i][j],
print "|"
print"--------------... |
445501b7e3746e3d42f639818f84d86beacba2d6 | aagm/pymartini | /pymartini/util.py | 1,550 | 3.90625 | 4 | import numpy as np
def decode_ele(png, encoding):
"""Decode array to elevations
Arguments:
- png (np.ndarray). Ndarray of elevations encoded in three channels,
representing red, green, and blue. Must be of shape (tile_size,
tile_size, >=3), where `tile_size` is usually 256 or 512
... |
9c560a54908c13b83bc7359bc1369a51a424ce2b | cadelaney3/networks | /BellmanFord.py | 1,613 | 3.671875 | 4 | # Chris Delaney
# Bellman-Ford, Distance-Vector Routing
# Homework 6
import math
graph_edges = [[0, 1, 1],
[0, 3, 2],
[1, 0, 1],
[1, 2, 3],
[1, 4, 6],
[2, 1, 3],
[2, 3, 3],
[2, 4, 2],
[3, 0, 2],
... |
310bb224a330cda47f66fb3a8192008e9e142424 | nsibal/Python-DS-Algo-Implementation | /algo/sort/merge_sort.py | 1,513 | 4.28125 | 4 | """
MERGE SORT:
Uses Divide-and-Conquer approach.
Divides the list into two sorted lists, and then merges them.
Pseudo Code:
Divide the list into two halves.
Sort those two halves.
Merge those two.
"""
def merge(lst1, lst2, lst):
"""Merge the two sorted lists lst1 and lst2 into proper... |
b530c24c495039b100a102bc345540d70d9272eb | Jin-RHC/daily_algo | /2021/Oct/1010/9536_여우는어떻게울지/s1.py | 371 | 3.703125 | 4 | T = int(input())
for tc in range(1, T + 1):
words = input().split()
others = {}
while True:
target = input()
if target == 'what does the fox say?':
break
else:
others[target.split()[2]] = 1
for word in words:
if others.get(word, 0):
... |
1c207799028f1e0c756b00aff7377584f88660a9 | matthew-maya-17/CSCI-1100-Computer-Science-1 | /RPI-CS1100-Lectures/Lecture_9_exercise_3.py | 412 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 16:29:52 2019
@author: matth
"""
LIST = []
x = input("Enter a value (0 to end): ")
print(x)
x = float(x)
while x != 0:
LIST.append(x)
x = input("Enter a value (0 to end): ")
print(x)
x = float(x)
print("Min: {:.0f}".format(min(LIST)))
... |
0b552a4b4b062d445603cae57f04dccce3942f83 | niamul64/study-4.1 | /cse 406/code/Operating system lab/disk scheduling/fcfs.py | 672 | 3.59375 | 4 | #Id : 17201026
#input 98 183 37 122 14 124 65 67
queue= input("Enter the queue: ").split(" ") # taking queue input
head= int(input("Enter Head start at: "))
print()#line gap
pre=head
totalDistance=""
distance=0
print("Path: " + str(head) ,end=" ")
for i in queue:
print(i,end=" ")
if pre>int(i):
totalD... |
86878f1d62717d08a7fe530ae70e10cb34e11d6b | FRodrigues42/codeeval-string-permutations | /string_permutations.py | 957 | 3.953125 | 4 | import sys
import string
import itertools
# Numbers < Uppercase < Lowercase
characters = string.digits + string.ascii_uppercase + string.ascii_lowercase
my_alphabet = [c for c in characters]
def custom_key(word):
weight = []
for char in word:
weight.append(my_alphabet.index(char))
# the first... |
d1665f44fd231e6f08936c38bf6a28e53282f613 | DavidStirling/centrosome | /centrosome/princomp.py | 802 | 3.546875 | 4 | from __future__ import absolute_import
import numpy
def princomp(x):
"""Determine the principal components of a vector of measurements
Determine the principal components of a vector of measurements
x should be a M x N numpy array composed of M observations of n variables
The output is:
coeffs... |
7b2094a72c0eba2025067fb45a4970676d26f44c | PrathushaKoouri/Trees-2 | /45_ConstructTreeUsingInorderPostOrder.py | 837 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, inorder, postorder) -> TreeNode:
# edge case
if len(postorder) == 0:
return None
... |
74636698772241dfe233dc24f8bcac21c0dc857d | algorithm006-class01/algorithm006-class01 | /Week_02/G20200343030583/LeetCode_49_583.py | 712 | 3.71875 | 4 | #
# @lc app=leetcode id=49 lang=python
#
# [49] Group Anagrams
# hash function: sort, map str to a sorted_str
# @lc code=start
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
if len(strs) == 0:
return [... |
198e19b4c13547abdba341fb8e8229232b39ffd0 | ShilpaGopal/machine-learning-problems | /credit-worthiness/utils.py | 4,734 | 3.5625 | 4 | import pandas as pd
import numpy as np
import random
import costFunctionHelper as ch
# Split the data based on test size
from scipy.stats import stats
def train_test_split(df, test_size):
if isinstance(test_size, float):
test_size = round(test_size * len(df))
indices = df.index.tolist()
test_in... |
0274b8c264fa1e7dfff16561957acc5159a296ef | randyzingle/javaalg | /javascript/createjs-old/simple.py | 160 | 3.53125 | 4 | #!/usr/bin/env python
def hello(n):
return str(n) + " is the loneliest number"
def main():
word = hello(5)
print word
if __name__ == "__main__": main()
|
ef0a5215cc0bd2adeaa4e659a3dfaf09770b051e | allyboy08/addition-tk | /exercise.py | 977 | 4.03125 | 4 | from tkinter import *
numbers = Tk()
numbers.title("addition")
numbers.geometry("300x200")
num1 = IntVar()
num2 = IntVar()
num3 = IntVar()
firstlabel= Label(numbers, text= "FirstNumber")
firstlabel.grid(row=0, column=0)
firstentry= Entry(numbers, textvariable=num1)
firstentry.grid(row=0, column=1)
secondlabel= L... |
beb5d3a5007447e67d4cbcae6fc6b3499180d36b | BoyYongXin/algorithm | /Problemset/fan-zhuan-lian-biao-lcof/fan-zhuan-lian-biao-lcof.py | 530 | 3.671875 | 4 |
# @Title: 反转链表 (反转链表 LCOF)
# @Author: 18015528893
# @Date: 2021-01-17 22:36:03
# @Runtime: 36 ms
# @Memory: 19.7 MB
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListN... |
5695497b6b6a223576c70422088589b443807e51 | MauzM/Mastermind | /LuckyLuke & OptimizePrime_Mastermind.py | 11,627 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 01:18:17 2018
@author: user
"""
def response_ok1(response):
""" The function returns "True" if the response of the user is either 1 or 2
and "False" otherwise. This is needed to check the first user responses
before the actual game starts."""
wh... |
144e3388840427d9a0ee0b5e895ff467eb1716a8 | luiz-vinicius/URI-Online-Judge | /problems/2542.py | 960 | 3.546875 | 4 | while True:
try:
num_atributos = int(input())
num_cartasm, num_cartasl = map(int, input().split())
cartasm = []
for i in range(num_cartasm):
atributos = input().split()
for j in range(num_atributos):
atributos[j] = int(atributos[j])
... |
e71f29263b85dcb06ce1e3a4170e9794ecb3e8e7 | mbrotos/Collatz-Conjecture | /Collatz.py | 269 | 4.0625 | 4 |
def CollatzRecursive(n):
if (n==1):
return n
elif (n % 2 == 0):
n = n/2
return CollatzRecursive(n)
else:
n = (3*n)+1
return CollatzRecursive(n)
n = int(input("Input a positive integer: "))
print(CollatzRecursive(n)) |
05b8870128d9e20e099bf29ee74ee0265d93c30e | aaursan/PythonDiferiteProiecte | /regex.py | 566 | 4.1875 | 4 | import re
text = 'This is some text -- with punctuation.'
print(text)
print
for pattern in [ r'^(\w+)', # word at start of string
r'(\w+)\S*$', # word at end of string, with optional punctuation
r'(\bt\w+)\W+(\w+)', # word starting with 't' then another... |
af543bae41926aa4e67dbf66178374bc3bff7b9d | josevini/python | /Curso de Python/Mundo 1/aula10/ex034.py | 243 | 3.640625 | 4 | sal = float(input('Qual é o salário do funcionário? R$'))
if sal <= 1250:
NovoSal = sal + ((sal * 15) / 100)
else:
NovoSal = sal + ((sal * 10) / 100)
print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora'.format(sal, NovoSal))
|
d534ddace2cae4340bb92690fd49e015b0bbd573 | 13528770807/practice | /qiang12_instance2/q04_line_search.py | 392 | 3.75 | 4 |
def search(arr, x, n):
for i in range(n):
if arr[i] == x:
print('exist')
return i
else:
return -1
if __name__ == "__main__":
arr = ['A', 'B', 'C', 'D', 'E']
x = 'E'
n = len(arr)
result = search(arr, x, n)
if result != -1:
print('存在,查找的索引为:{... |
638b8be0d47acf40b4edc0415a71db23cda513c1 | Zeryuzos/TrabajoPython | /ejericicio 4.py | 137 | 3.75 | 4 | AT = 3
D = 3
while D < 365:
print("El ahorro del dia ", D, "es ", AT)
AT = AT * 3
D = D + 1
print("El ahorro total es: ", AT) |
93ef8b0de0d2db08e1fbbd62283fe44d77a0cc43 | kirkwood-cis-121-17/exercises | /chapter-7/ex_7_3.py | 1,460 | 4.03125 | 4 | # Programming Exercise 7-3
#
# Program to compute simple statistics for one year of monthly rainfall.
# This program prompts the user for 12 monthly rainfall values,
# calculates the total and average, finds the high and low values,
# and displays the results on the screen.
# define the main function
... |
a2a58f9b53a54f7fc2fb24678883c326aaed89c0 | livlab/agate | /agate/table/homogenize.py | 2,739 | 3.609375 | 4 | #!/usr/bin/env python
from agate.rows import Row
from agate import utils
@utils.allow_tableset_proxy
def homogenize(self, key, compare_values, default_row=None):
"""
Fills missing rows in a dataset with default values.
Determines what rows are missing by comparing the values in the given
column_name... |
6f4995ca1a6a0e5d303b5bbe43d75e464608ba93 | Dioni1195/holbertonschool-higher_level_programming | /0x0B-python-input_output/11-student.py | 701 | 4.125 | 4 | #!/usr/bin/python3
""" This module define a class Student """
class Student:
""" This is a class for a student
args:
first_name(str): The first name of the student
last_name(str): The last name of th student
age(int): The age of the student
attrs:
first_name(str): The first name of the stu... |
9386671727629fb4545678ff504ad3867bdaaf99 | msmarchena/Int.Python | /IntPython_10.For_While_Loops.py | 1,639 | 4.28125 | 4 | ###########################
# Loops #
# Auteur: Marlene Marchena#
###########################
# For loop
# Ex. 1 :
for i in range(20):
print(f"La valeur est : {i}")
# Ex. 2 :
for i in range(1, 20, 2):
print(f"La valeur est : {i}")
# Ex. 3 :
for i in range(1, 13):
print(f"La valeur {... |
139b50438df9356c06323e43615220b2bf1f82e8 | IkramMOPHS/Y11Python | /whileloopchallenges01.py | 173 | 4.0625 | 4 | #Ikram Munye
#whileloopchallenges01
total = 0
while total <= 50:
num = int(input("Please enter a number: "))
total = total + num
print("The total is now" ,total)
|
abd3024b55582da5a5697ff2414f15c1bdc0a8f9 | Mr-Georgie/Grading-System | /functions_and_methods.py | 421 | 3.75 | 4 | class Basic_Arithmetic:
def add(self, a, b):
return a + b
arithmetic = Basic_Arithmetic()
print(arithmetic.add(5,5))
# # A function
# def add(a, b):
# return a + b
# class Basic_Arithmetic:
# def add(self, a, b):
# return a + b
# def subtract(self, a, b):
# ..... |
346d6548a1afc00b227878a3fbeaa685bad3590c | maohaoyang369/Python_exercise | /228.统计一下首字母为a的单词.py | 218 | 3.890625 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# 统计一下首字母为"a"的单词 s = "I am a boy!"
s = "I am a boy!"
s = s.split()
result = ""
for i in s:
if i[0] == "a":
result += i
print(result)
|
34d04b598f9d191c91ef2881edd212fd384fe7d8 | iistrate/ChutesAndLadders | /PyChutesLadders/Board.py | 1,732 | 3.6875 | 4 | import Tile
class Board(object):
"""A board of tiles"""
def __init__(self):
self._board = [[]]
self._boardCopy = [[]]
counter = 0
for i in range(0, 10):
self._board.append([])
self._boardCopy.append([])
for j in range(0, 10):
c... |
b1fb4f2b220524f6ee12f9e9bf43dd0a99d6b9a3 | malfridur18/python | /assignments/digits.py | 322 | 3.90625 | 4 | x_str = input("Input x: ")
x_int=int(x_str)
first_three=x_int//1000
last_two=x_int%100
middle_two=(x_int//100)%100
# remember to convert to an int
# first_three =
# last_two =
# middle_two =
print("original input:", x_str)
print("first_three:", first_three)
print("last_two:", last_two)
print("middle_two:", middle_two... |
e671c5210787adca391839cc5782c4dae3db1fb1 | NoahNacho/python-solving-problems-examples | /Chapter2/Example1.py | 360 | 3.734375 | 4 | #Take the sentence: All work and no play makes Jack a dull boy. Store each word in a separate variable, then print out the sentence on one line using print.
var1 = "All "
var2 = "work "
var3 = "and "
var4 = "no "
var5 = "play "
var6 = "makes "
var7 = "Jack "
var8 = "a "
var9 = "dull"
var10 = "boy."
print(var1+var2+va... |
d1a7bc84cdb2ca62c0a3d78dc4e4626538fcc3b7 | cortezmb/Function-Exercises | /ex1small.py | 258 | 3.984375 | 4 | #Function exercise 1 Small
def madlib(fName, subject):
if fName <= " " or subject <= " ":
print("You must love all subjects.")
else:
return f"{fName} loves learning {subject}."
result = madlib("Michael", "Python3")
print(result)
|
a868221624ff9e4d8ba03889f80ca54d077cb957 | BrandonOdiwuor/Design-of-Computer-Programs | /poker/poker.py | 2,439 | 3.8125 | 4 | def poker(hands):
''' Returns a list of winning hand: poker([hand,...]) => hand '''
return allmax(hands, key=hand_rank)
def allmax(iterable, key=None):
'''
Returns a list equal to max in the iterable
'''
return [x for x in iterable if hand_rank(x) == hand_rank(max(iterable, key=key))]
def hand_rank(hand):... |
25c7a968731c6a6ee9f47889e7162e022103c872 | Anm-pinellia/PythonStudy | /testMenu.py | 860 | 3.578125 | 4 | from tkinter import *
root = Tk()
def sayhello():
print('触发菜单栏选项')
def nothing():
print('无事发生')
#初始化一个菜单
menu1 = Menu(root)
#初始化一个菜单的子选项菜单
filemenu = Menu(menu1, tearoff=False)
filemenu.add_command(label='打开', command=sayhello)
filemenu.add_command(label='保存', command=nothing)
filemenu.add_separator()
fi... |
b70143758f509f92dc13604dfcef4b73bc8cee99 | eulersformula/Lintcode-LeetCode | /Account_Merge.py | 8,076 | 4.25 | 4 | # Lintcode 1070//Medium//Facebook
# Description
# Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
# Now, we would like to merge these accounts. Two accounts definitely bel... |
c0220be5e21dde9dccb677db6b800a9cd260424d | kevenallan/Python | /projetos_ED/pilha.py | 3,725 | 3.53125 | 4 | class No:
def __init__(self, dado=None, proximo=None):
self._dado=dado
self._proximo=proximo
def get_dado(self):
return self._dado
def set_dado(self,novoDado):
self._dado=novoDado
def get_proximo(self):
return self._proximo
def set_proximo(self,outro):
... |
d9b10156952817140c138a20801006a7eabe2a90 | yoonhyeji07/python | /dice/mineSweeperMain.py | 2,527 | 3.5625 | 4 | import mineSweeperField
import mineSweeperSQL
import time
from random import randint
while True:
print("You've entered my mineField!\n")
time.sleep(2)
print("1. login")
print("2. register")
print("3. quit")
action = input("\nChose your action!")
player = mineSweeperSQL.PlayerToServer()
... |
d11b642ce6f56a8a2165c5ee9df7778d22a510ac | rfcarter/test | /day6_warmup_coin_dice.py | 1,046 | 4.0625 | 4 | import random
def flip_coin():
'''
Input: None
Output: Str - 'H' for head or 'T' for tail
Perform an "experiment" using random.random(), return 'H' if result is above .5, 'T' otherwise.
'''
toss = random.random()
if toss > .5:
return('H')
else:
return('T')
... |
b7be977065ccda1605c1e9a357763bb962f00de3 | VictorCastao/Curso-em-Video-Python | /Desafio73.py | 615 | 3.671875 | 4 | print('=' * 12 + 'Desafio 73' + '=' * 12)
tabelabrasileirao = (
"Flamengo", "Santos", "Palmeiras", "Grêmio", "Athletico-PR", "São Paulo", "Internacional", "Corinthians",
"Fortaleza", "Goiás", "Bahia", "Vasco", "Atlético-MG", "Fluminense", "Botafogo", "Ceará", "Cruzeiro", "CSA",
"Chapecoense", "Avaí")
print(... |
66e9be00a55a5d10a1cc87ad44c9e53a5bc4919f | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/410.py | 522 | 4.09375 | 4 | """
Word Counter
Write a program that given a phrase can count the occurrences of each word in that phrase.
For example for the input `"olly olly in come free"`
olly: 2
in: 1
come: 1
free: 1
"""
def word_count(phrase):
"""Split phrase on spaces. Count occurrence of each word."""
word... |
be44289ccc01111ac7279341e08b1523989646bf | tjennt/python-calculator-ez | /calculator.py | 2,631 | 3.75 | 4 | import os
class Mess:
# Print choose the function
def program():
print ("---CHƯƠNG TRÌNH MÁY TÍNH---")
print ('| 1.Tính cộng |')
print ('| 2.Tính trừ |')
print ('| 3.Tính nhân |')
print ('| 4.Tính chia |')
prin... |
db53421041fc622f7c4322ab1f5548fdf8646734 | davidfenomeno/520python | /media.py | 322 | 3.796875 | 4 | #!/usr/bin/python
N1 = int(input('digite a nota')) * 2
N2 = int(input('digite a nota')) * 3
N3 = int(input('digite a nota')) * 4
N4 = int(input('digite a nota')) * 1
media = [N1+N2+N3+N4/10]
if media >= 7:
print('voce foi aprovado')
elif media < 5:
print('aluno reprovado')
else:
print('aluno em exame')
... |
f2cdce948702bab805fa532c480879ba9b71c6c0 | hsuweibo/lc-problems | /216-CombinationSumIII.py | 2,364 | 3.578125 | 4 | import unittest
class TestCombinationSum(unittest.TestCase):
def setUp(self) -> None:
self.sol = Solution()
def test_input1(self):
output = self.sol.combinationSum3(3, 6)
expected = [[1,2,3]]
self.assertTrue(test_equal(output, expected))
def test_input1(self):
... |
ba9ee5aad7c5fe253c6eb75abc85593bd5afff0c | alexiscv/DAM2_SGE | /Ej_FigurasGeometricas/Figura.py | 1,206 | 3.71875 | 4 | import math
# Mostrar ménu, devuelve la opción elegida
def menu():
print ("Introduce una opcion:")
print ("1 - Alta")
print ("2 - Area")
print ("3 - Perimetro")
print ("4 - Mostrar")
print ("0 - Salir")
op = int(input())
return op
#########################################
# Clase Pr... |
5ffad20f0fbe2904727f02d3ca6e0e10c28219ed | chanakaudaya/cs50-source-code | /python/lists.py | 140 | 3.734375 | 4 | # A list of values
names = ["Saneli", "Vethumya", "Fernando"]
print(names)
names.append("Chanaka")
print(names)
names.sort()
print(names)
|
b79bd9d16a0377458478f3c9d90718983bf8dbe1 | CEsarABC/practicalPython | /testing_file_handles.py | 716 | 3.875 | 4 | import unittest
import app
''' This file tests the creation of the lists used to store riddles,
answers and the list of tuples used in the game '''
class TestRiddle(unittest.TestCase):
'''Test Suit for app.py '''
def test_riddles_not_empty(self):
riddles = app.riddles
assert (riddles != '... |
4b57557fb3414a269a744bf167a1819385a052b5 | parlizz/home_work_3 | /dz_3_4.py | 1,448 | 3.9375 | 4 | # 4. Программа принимает действительное положительное число x и целое
# отрицательное число y. Необходимо выполнить возведение числа x в степень y.
# Задание необходимо реализовать в виде функции my_func(x, y). При решении
# задания необходимо обойтись без встроенной функции возведения числа в степень.
# Подсказка:... |
31f4359103cc7e98621db012cc4616e475c796bb | shotop/scripts | /stopwatch.py | 1,603 | 3.53125 | 4 | # template for "Stopwatch: The Game"
import simplegui
# define global variables
time = 0
stops = 0
precise_stops = 0
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(time):
minutes = time // 600
tens_of_seconds = ((time // 10) % 60) // 10
s... |
551cccc13fdf949837e7bcc372bfcd28d0210190 | ashjune8/Python-Algorithm-Solutions | /General Algorithms/implement multiply without using *.py | 187 | 3.609375 | 4 | def newmultiply(a,b):
maximum = max(a,b)
minimum = min(a,b)
solution = 0
for i in range(minimum):
solution += maximum
return solution
print newmultiply(10,2) |
6adb0dcfe63d6eeb3cca664fc4decd7615dbe38f | AndelaVanesa/SIT17-18 | /Osnove programiranja/Vjezba_5/vjezba5_zd01.py | 904 | 3.671875 | 4 | #Andela Vanesa Tuta, 23.11.2017.
#Vjezba 5, zadatak 1
#Ispis prvih n prirodnih brojeva
n = int(input('Unesite prirodan broj: '))
print('a) Prvih n prirodnih brojeva: ', end=' ')
for i in range(n) :
print(i+1, end=' ')
#while petlja,
#iterator "i" definiran i nakon što for petlja završi s izvršavanjem
... |
06cb568555ccbd6bd620b99770d26ff69ecb0b50 | JiahuiZhu1998/Interview-Preparing | /googleOA_Q2_mysolution.py | 2,311 | 3.921875 | 4 | # There are some processes that need to be executed. Amount of a load that process causes on a server that runs it, is being represented by a single integer.
# Total load caused on a server is the sum of the loads of all the processes that run on that server. You have at your disposal two servers, on which mentioned ... |
4adfff7fcd0bec2ce673c4f50e1a6f71367a0aa2 | poojashahuraj/CTCI | /practice/spiral_matrix.py | 566 | 3.765625 | 4 | class SpiralMatrix(object):
def __init__(self):
pass
def run(self, input_arr, rows, columns):
rt_list = []
if rows <= columns:
iterations = rows
else:
iterations = columns
for i in range(iterations):
i += 1
# print first row
... |
d6566cdea9683c87f672fcefa16a2bb864b64712 | byTariel/Algoritms | /dz_1_task_9.py | 496 | 4.21875 | 4 | """ Вводятся три разных числа.
Найти, какое из них является средним (больше одного, но меньше другого).
"""
a, b, c = map(int, input('введите три разных числа через пробел: ').split())
if a > b > c or a < b < c:
print(f'среднее число {b}')
elif b > a > c or b < a < c:
print(f'среднее число {a}')
else:
... |
6c62250067716d3c3557de1de23f0c4eedce53b6 | entrekid/algorithms | /basic/1546/average.py | 218 | 3.515625 | 4 | sub_num = int(input())
num_list = list(map(int, input().split()))
num_max = max(num_list)
for i in range(len(num_list)):
num_list[i] = num_list[i] / num_max * 100
average = sum(num_list) / sub_num
print(average)
|
e5b591e8478748429f3f12ef78e8a49c5521c84e | mHacks2021/pythonbook | /Python 基础教程/1.5.2 商品买卖练习.py | 917 | 3.625 | 4 | # 列表综合练习 写一个循环,不断的问用户想买什么,用户选择一个商品编号,
# 就把对应的商品添加到购物车里,最终用户输入q退出时,打印购物车里的商品列表
l1 = [['a',23],['b',34],['c',33],['d',345]]
l2 = []
print("商品列表****************")
for (index, i) in enumerate(l1):
print(f"商品{index},价格为{i}")
while True:
choise = input("请输入你选择的商品编号:")
if choise.isdigit():
if int(choise) ... |
dfc8c78c1547029da0dff83bdd3d0ed357835cec | geekyprince/CompetitiveProgrammingLibrary | /LinkedListFunctions.py | 894 | 4.0625 | 4 | def reverse_linked_list(head):
prev = None
nxt = head
while(nxt):
head = nxt
nxt = head.next
head.next = prev
prev = head
return head
def print_list(head):
print("List : ", end=' ')
while head:
print(head.val, end= ' ')
head = head.next
p... |
90d497c0c54099e650aaf8646ced6724c264f3da | jonasht/CursoEmVideo-CursoDePython3 | /mundo2-EstruturasDeControle/069 - Análise de dados do grupo.py | 1,015 | 4.09375 | 4 | #Exercício Python 069:
# Crie um programa que leia a idade e o sexo de várias pessoas.
# A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar.
# No final, mostre:
# A) quantas pessoas tem mais de 18 anos.
# B) quantos homens foram cadastrados.
# C) quantas mulheres tem menos de 20 an... |
b8df1e9ae304ae24f2e259433ae8f823b7041cad | jedzej/tietopythontraining-basic | /students/slawinski_amadeusz/lesson_05_lists/07_swap_min_and_max.py | 359 | 3.78125 | 4 | #!/usr/bin/env python3
numbers = input().split()
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
min_number = min(numbers)
max_number = max(numbers)
min_index = numbers.index(min_number)
max_index = numbers.index(max_number)
numbers[min_index] = max_number
numbers[max_index] = min_number
for number ... |
2de0bfd1d8fbba30c747497a9a4df73b624962c4 | dongyang2/hello-world | /interview_q/nowcoder_华为机试/HJ92-在字符串中找出连续最长的数字串.py | 957 | 3.859375 | 4 | # coding: utf-8
# Python 3
import sys
# 注意边界条件——只有字母的情况
def longest_num_substr(s: str, num_li: list):
sub_li = []
tmp_str = ''
for i in range(len(s)):
if s[i] in num_li:
tmp_str += s[i]
if i == len(s) - 1:
sub_li.append(tmp_str)
else:... |
a5866318162be8e6f013b61ca95d3254fd31513c | qmnguyenw/python_py4e | /geeksforgeeks/python/expert/2_7.py | 3,091 | 4.28125 | 4 | Pulling a random word or string from a line in a text file in Python
File handling in Python is really simple and easy to implement. In order to
pull a random word or string from a text file, we will first open the file in
**read** mode and then use the methods in Python’s **random** module to pick a
random w... |
d59a3d1ba50ac8a0947d07e34bca0bcaf5bb60b7 | AnmolKhawas/PythonAssignment | /Assignment1/Q2.py | 117 | 3.953125 | 4 | n1=float(input("Enter sub1 marks:"))
n2=float(input("Enter sub2 marks:"))
sum=n1+n2
avg=sum/2
print('Aggregate=',avg) |
a9c33014ce1b2d2d923f0e885134406ee15fed3a | amosricky/LeetCode_Practice | /Problems/LeetCode_1261_Find Elements in a Contaminated Binary Tree/LeetCode_1261_Find Elements in a Contaminated Binary Tree_1.py | 1,521 | 3.859375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class FindElements:
def __init__(self, root: 'TreeNode'):
self.root = root
self.root.val = 0
self.recoveredTree(self.root)
def reco... |
0372fcc6355f1022a18f3953661ec921663865a1 | luckycontrol/Algorithm_with_python | /Graph/Kruskal.py | 2,172 | 3.8125 | 4 | class Element:
def __init__(self, key, x, y):
self.key = key
self.x = x
self.y = y
class Kruskal:
def __init__(self):
self.elements = []
def insertEdge(self, x, y, key):
element = {
"key": key,
"s1": x,
"s2": y
}
... |
7c633d797b08c817ac804fd18b74883e80d0a99b | thehayat/DSA | /LinkedList/Practice/finding_middle_element_in_linked_list.py | 1,420 | 4.03125 | 4 |
# https://practice.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1/?ref=self
def length(head):
count = 1
while head.next != None:
head = head.next
count += 1
return count
def findMid(head):
start = head
middle = head
if head:
if length(head) % 2 ... |
f919bb787da4e2c0191ea455cd954e27359ec488 | diogomascarenha/Filho-Estudo-Python-Modulo-2 | /Login simples.py | 1,443 | 4.125 | 4 | adminUsuario = "ADMIN"
adminSenha = "Admin"
usuario = ""
senha = ""
print("-=-" *10)
print("Bem Vindo(a)")
print("-=-" *10)
opcaoSelecionada = ""
while opcaoSelecionada != "S":
opcaoSelecionada = str(input("Digite [L] para Logar, [R] para Registrar ou [S] para sair. ")).strip().upper()[0]
if opcaoSelecionad... |
a3860bec184af332052846a97fcfa38be887b8fb | acaciooneto/cursoemvideo | /ex_videos/ex-092.py | 624 | 3.828125 | 4 | from datetime import date
pessoa = {}
pessoa['nome'] = str(input('Digite o seu nome: ')).title()
nascimento = int(input('Diga o ano de seu nascimento: '))
pessoa['idade'] = date.today().year - nascimento
pessoa['CTPS'] = int(input('Informe o número de sua Carteira de Trabalho: '))
if pessoa['CTPS'] != 0:
pessoa['co... |
9198c75a87ca931a23698d5ea2a8b40094665a68 | TorrentofShame/Flask-React-Mongo-Boilerplate | /backend/server/common/validators.py | 314 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
server.common.validators
~~~~~~~~~~~~~~~~~~~~~~~~
"""
def validate_phone_number(phone_number: str):
"""Validates Phone Number Strings"""
if not phone_number.isdecimal() or len(phone_number) != 10:
raise ValidationError("Value is not a 10-digit phone number!")
|
b53b8a66b775c9f37a7accbd12bb7ae7114d18ad | Zeratoxx/adventOfCode2020 | /day_6/group.py | 1,199 | 3.5 | 4 | from day_6.member import Member
class Group:
def __init__(self, group_entries):
self.group_members = []
self.add_group_members(group_entries)
def add_group_members(self, group_entries):
for member_entry in group_entries:
self.group_members.append(Member(member_entry))
... |
a3aa117a54f4e3d475222136479c62db5120f00a | vincentiusmaurich/Vincentius-Maurich_I0320108_Andhika_Tugas4 | /I0320108_Soal4_Tugas4.py | 433 | 3.875 | 4 | #Usia
usia = int(input("Berapa usia kamu?")) #Masukkan usia dalam tahun
hasil_usia = (usia >= 21)
#Kelulusan
kelulusan = input("Apakah kamu sudah lulus ujian kualifikasi? (Y/T)") #Masukkan hasil ujian dengan Y atau T
hasil_kelulusan = (kelulusan == "Y")
#Menampilkan Hasil
if hasil_usia and hasil... |
e3a634954c0a72ee04704c3f907d700a46875f3f | eledemy/PY110-2021 | /debug.py | 213 | 3.984375 | 4 | table = []
N = 3 # строки
M = 3 # столбцы
a = 0
for i in range(N): # по строкам
row = []
for j in range(M):
row.append(a)
a += 1
table.append(row)
print(table) |
d2ffe7bb8c133fb05f76ef35af5d0d19c8022621 | renjieliu/leetcode | /0001_0599/434.py | 529 | 3.796875 | 4 | def countSegments(s):
"""
:type s: str
:rtype: int
"""
reg = 0
cnt = 0
w = 0
s = s.strip(" ")
for i in s:
if i == " ":
reg = 1
elif i!= " " and reg == 1:
reg = 0
cnt +=1
elif i!= " " and reg == 0:
w+=1
... |
3e16d6f9a39b5da961e0a84ba235b5453ceb0fe3 | RamboSofter/LeetCode_practice | /algorithm-mind/dynamic_programming/413_arithmetic-slices.py | 560 | 3.71875 | 4 | """
413. 等差数列划分
https://leetcode.cn/problems/arithmetic-slices/
"""
from typing import List
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
n = len(nums)
if n < 3:
return 0
diff = nums[1] - nums[0]
acc_len = 0
res = 0
for i i... |
b8e67bba14af5af2d54f0dc03d16381f78146c6e | vamsitallapudi/Coderefer-Python-Projects | /programming/leetcode/linkedLists/removeLinkedLists/RemoveLinkedListElements.py | 982 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
# edge cases - if the element is present at start or last
if not head:
... |
47d0057e4c7a186e74f15345fbbb9809c35f112b | kimsungho97/Algorithms | /baekjoon/temp.py | 1,246 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
print(list(range(5,5)))
def minCost(rows, cols, initR, initC, finalR, finalC, costRows, costCols):
result=0
ic=min(initC,finalC)
fc=max(initC,finalC)
ir=min(initR,finalR)
fr=max(initR,finalR)
for r in range(ir,fr):
... |
ecf655a956eea23e35c9b1ea8d5e1e519cb4d1f7 | devinnarula/sudoku-solver | /python/functions.py | 1,401 | 3.640625 | 4 | import random
def find_next(grid):
for row in range(0,len(grid)):
for col in range (0, len(grid[0])):
if grid[row][col] == 0:
return (row, col)
return None
def is_cell_valid(cell, num, grid):
return check_row(cell, num, grid) and check_col(cell, num, grid) and check_bo... |
c0a5d71057dd4d2d0401bccc9ee20762e823238e | shagtv/blog | /questions/4.py | 460 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
def batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
def grouper(iterable, n):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chun... |
20e01a119abc17c42ed983bc1daf187c5c5e3786 | VINSHOT75/PythonPractice | /python/armstronginRamge.py | 229 | 3.78125 | 4 | # armstrong number
num , b = map(int,input('two numbers'))
while num
x= num
y=0
z=0
while x>0 :
y =int( x%10)
z = z+(y*y*y)
x =int(x/10)
print(z)
if z == num :
print('armstrong')
else:
print('not armstrong') |
5709bbfe3f183edd926e75e2af86f9e41b10d2ba | gauraviitp/python-programs | /Fibonacci_last_digit.py | 222 | 3.65625 | 4 | # Uses python3
def calc_fib(n):
if (n <= 1):
return n
a0, a1 = 0, 1
for _ in range(n-1):
x = (a0 + a1) % 10
a0 = a1
a1 = x
return a1
n = int(input())
print(calc_fib(n))
|
d620af01182cf07bf8b32f3f79639c53559314ba | Lordjiggyx/PythonPractice | /Basics/Dictionaries.py | 1,630 | 4.75 | 5 | #Dictionary
"Creatiung a dictionary is like creating a json object they need keys and values "
thisdict = {
"Brand":"Ford",
"Model":"Mustang",
"Year":"1964"
}
print(thisdict)
"To access items in a dictionary you must refer to the key in square brackets"
print(thisdict["Model"])
"You can also use the .g... |
9560f20ca5594d861401b85b8e5b19eeae875a42 | wangyendt/LeetCode | /Hard/128. Longest Consecutive Sequence/Longest Consecutive Sequence.py | 527 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: wangye
@file: Longest Consecutive Sequence.py
@time: 2019/07/02
@contact: wangye.hope@gmail.com
@site:
@software: PyCharm
"""
class Solution:
def longestConsecutive(self, nums: list) -> int:
if not nums:
return 0
nums ... |
4322704bab50e28ec8292e60eda25fb8e730c503 | phuongnam7899/NguyenPhuongNam-Fundamental-C4E23 | /session4/dictinnary.py | 521 | 3.6875 | 4 | solama={
1:"I",
2:"II",
3:"III",
4:"IV",
5:"V",
6:"VI",
7:"VII",
8:"VIII",
9:"IX",
10:"X",
}
print("day la tu dien so he thap phan - so la ma (pham vi tu 1-10)")
while True:
so = int(input("nhap chu so can chuyen doi sang so la ma(1-10):"))
if so not in solama:
... |
55ad25ccaf7f376ba515e3b0eb1edcf8c184ba7e | ddc899/cmpt145 | /Tanner's Docs/A8/a8q1.py | 2,375 | 3.859375 | 4 | # CMPT 145: Binary trees
# CMPT 145 201801 Assignment 8 Question 1
import treenode as tn
import exampletrees as egtree
def subst(tnode, t, r):
"""
Purpose:
Replace every occurrence of data value t with r in the tree
Pre-conditions:
:param tnode: a treenode
:param: t: a target value... |
90abd98297a2ec0223dd17d5387e6b4e56471e66 | nonnikb/verkefni | /Lokapróf/1 Basics/Population estimation.py | 525 | 3.765625 | 4 | """Assume that the current US population is 307,357,870
- a birth every 7 seconds
- a death every 13 seconds
- a new immigrant every 35 seconds
Write a program that takes years as input (as an integer) and prints
out estimated population (as integer).
Assume that there are exactly 365 days in a year."""
years = input(... |
3ebc91da96364ab3bda022074c51b28279e5a187 | bayramcicek/mini-programs | /p000_find_prime_number.py | 197 | 3.9375 | 4 | for i in range(3,100): # between 3 and 100 - you can change these numbers
prime = 1
for k in range(2,i):
if i % k == 0:
prime = 0
if prime != 0:
print(i)
|
d9331d0b400c28b1579d785e7b9d7d54ea517f20 | mikeyPower/python-programming-efficiently | /HackerRank/Nested Lists/nested_lists.py | 1,179 | 3.859375 | 4 | name_to_grade=[]
n = 0
for _ in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
name_to_grade.append([name,score])
n = n +1
#sort list
#print(name_to_grade)
for i in range(n):
# m = name_to_grade[i]
for j in range(n):
m = name_to_grade[i]
k = name_to_grade[... |
6e671ccc023ecbcd163aecc57633d93a78d106e7 | chidoski/Python-Projects | /ex32.py | 1,040 | 4.625 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apriocts']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#the first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
#same as above
for fruit in fruits:
print "These are the fruit %s" % fruit
#G... |
015f6643af02d0636ad2b8ccac97e437a4d3064a | lhd0320/AID2003 | /official courses/month01/day06/exercise01.py | 314 | 3.65625 | 4 | import copy
list01=["北京",["上海","深圳"]]
list02=list01
list03=list01[:]
list04=copy.deepcopy(list01)
list04[0]="北京04"
list04[1][1]="深圳04"
print(list01)
list03[0]="北京03"
list03[1][1]="深圳03"
print(list01)
list02[0]="北京02"
list02[1][1]="深圳02"
print(list02)
print(list01)
print(list03) |
ab5160bc178431ddc828f048f0df859bb3ea1015 | shivam90y/practice-py | /add_given_node.py | 691 | 3.921875 | 4 |
/* Given a node prev_node, insert a new node after the given
prev_node */
void insertAfter(struct Node* prev_node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_node == NULL)
{
printf("the given previous node cannot be NULL");
return;
}
... |
71703d44ccd3cbaf94994e7b64912403a150e21f | rbevacqua/python | /csc384/A2/test.py | 300 | 4.125 | 4 | import itertools
def main():
v = list([1,2,3])
b = list(v)
b.pop(0)
print(v)
print(b)
g = list()
g.append(2)
for i in range(3):
for j in range(3):
for x in range(j+1, 3):
print(i,j,i,x)
for i in itertools.product(*[[1,2],[1,2,3]]):
print(i)
r = list([1,2,3])
print(r)
main() |
a15c244f99037986c384321ba0676b405e28c935 | DF-Kyun/python_demo | /demo_code/sort_demo.py | 250 | 3.515625 | 4 | L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return str(t[0]).lower()
L2 = sorted(L, key=by_name)
print("名字",L2)
def by_score(t):
return t[1]
L3 = sorted(L,key=by_score,reverse=True)
print("成绩",L3)
|
159989f3407e63ef48618ab8c582a98f60fa3638 | mateuszkanabrocki/LPTHW | /python_examples.py | 2,352 | 3.9375 | 4 | # break
def break_test():
for i in "abcdefghijklmnopqrstuvwxyz":
if i == "j":
break
print(i, end="")
print("!")
# with-as
# open file and close it automatically
def with_as_file_test():
# "file" is a local variable
with open("with_as_test.txt") as file:
print(file.... |
29bb6db745a3fb92c4e5005015f83d587369991b | saintsim/adventofcode-2018 | /src/day2/part2.py | 780 | 3.65625 | 4 | #!/usr/bin/env python3
def common_letters(sequences):
for index, item in enumerate(sequences):
item_stripped = item.strip()
for other_index, other_item in enumerate(sequences):
if index == other_index:
continue
diffs = 0
in_common = ''
... |
4140fc4844e7b39b5d863fe4fb72ac927cf005d4 | abhaypainuly/data_structures_and_algorithms | /sorting/selection_sort.py | 362 | 3.703125 | 4 | #SelectionSort
def selection_sort(unsorted):
l = len(unsorted)
for i in range(l-1):
mini_index = i
for j in range(i+1,l):
if unsorted[j]<unsorted[mini_index]:
mini_index = j
if mini_index !=i:
unsorted[i],unsorted[mini_index] = unsorted[mi... |
9b941ae0501f619e375a27ec06917425f5527403 | dudey/databricks | /04-Working-With-Dataframes (1)/3.Display-function.py | 15,991 | 3.859375 | 4 | # Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC # Use the Display function
# MAGIC
# MAGIC There are different ways to view data in a DataFrame. This notebook covers these methods as well as transformations to further refine the data.
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC **Technical Accomplish... |
9fbe77400528b434571bb4a45e65c9f3e0adba21 | JingyeHuang/Python-Learning | /Pygame-8.py | 2,233 | 3.671875 | 4 |
# coding: utf-8
# In[1]:
import pygame
import sys
from pygame.locals import *
pygame.init()
size = width,height = 600,400
speed = [5,0]
bg = (255,255,255) #RGB
screen = pygame.display.set_mode(size)
pygame.display.set_caption('First pygame')
turtle = pygame.image.load('turtle.png')
position = turtle.get_rect()
t... |
2a0a8ade10bef62061c3d2521aec7802ccaf03fa | krnets/codewars-practice | /7kyu/Move 10/index.py | 827 | 3.703125 | 4 | # 7kyu - Move 10
""" Move every letter in the provided string forward 10 letters through the alphabet.
If it goes past 'z', start again at 'a'.
Input will be a string with length > 0. """
from string import ascii_lowercase as abc
# def move_ten(st):
# return ''.join(abc[(abc.index(c)+10) % 26] for c in st)
de... |
66462f059ca64dc68f024f6f9a26e5a1190a60bb | ELatestark/pythonhw | /hw14/5_14_import.py | 533 | 3.609375 | 4 | # !/usr/bin/env python3
# import using pickle
import pickle
class Employee:
def init(self, name, id, department, title):
self.employee_name = name
self.employee_id = id
self.employee_department = department
self.employee_title = title
file_to_import = open("first_employee.pickle",'... |
21342d1344887f6d74b8582c761b3eade7e390b6 | SwimCath4/Seizure-Project | /spectral_entropy.py | 817 | 3.671875 | 4 | # -*- coding: utf-8 -*-
'''
CIS 519 Project: Seizure Prediction
Spectral Entropy Calculator
Author: Tyrell McCurbin
'''
import math
import numpy as np
def spectral_entropy(X):
# process the data
num_data_pts = int(X.shape[0]);
# The following routine is based off of information... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.