blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
491c2742d15d8be5d872a4c59f3bb920afd8edd8 | Lucas130/leet | /53-maxSubArray.py | 659 | 3.671875 | 4 | """
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
"""
class Solution:
def maxSubArray(self, nums) -> int:
ans = nums[0]
for i in range(1, len(nums)):
if nums[i] + nums[i - 1] > nums[i]:
nums[i] +=... |
22c4d7e3bdb5779dba3b403c33c91956a05a9755 | panthitesh6410/python-programs | /string-functions.py | 622 | 4.65625 | 5 | # String Functions :
# join() : it joins items of a list with a particular symbol :
print(",".join(["apple", "banana", "orange"]))
# replace() : to replace certain old element with new element:
print("hello world".replace("world", "John"))
# startswith() - to check a string starts with a part... |
53d9410695649ae1cfe25deb11ecfff734fe6408 | TrySickle/Saugus | /Euler/euler12.py | 518 | 3.5625 | 4 | import math
def getFactors(x):
factorList = []
factorList.append(1)
factorList.append(x)
for y in range (2, int(math.sqrt(x))):
if x % y == 0:
factorList.append(y)
factorList.append(int(x / y))
return factorList
factors = 0
counter = 1
while factors < 500:
t... |
07caed184c85cf53485d6cbbd108a2e214ef2cc5 | EliotRagueneau/OBIpython | /Kevin.py | 5,409 | 3.875 | 4 | from typing import *
from Theo import read_flat_file
def get_features(txt: str) -> str:
"""Extract features lines from flat text and return them
This function is written by Kévin Merchadou.
Args:
txt: flat text with features to extract
Returns:
... |
2d934868869909f1a4e2e8d9456fd8f97412fb54 | kh4r00n/Aprendizado-de-Python | /ex011.py | 228 | 3.71875 | 4 | n1 = float(input('Digite a altura da parede'))
n2 = float(input('Digite a largura da parede'))
a = n1 * n2
b = a / 2
print('Será necessário {:.2f} litros de tinta para pintar uma parede com {:.2f} m2'.format(b, a))
|
344640c1eaadc03b106d41ff368fa18e68cebd7e | savi8sant8s/em-busca-das-nozes | /Em Busca das Nozes - V1/Em Busca das Nozes.py | 4,069 | 3.59375 | 4 | import random
import time
#Posição dos personagens
posicao = []
#Movimentos
quantpassos = 0
sementespegas = 0
#Mapa do jogo
mapa = [[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1... |
d12017d2423c8020f7d4f57b983aad4b34efc0af | penghaos/learn_python3_by_hardway_notes | /ex40_a.py | 1,031 | 4 | 4 |
# dict
mystuff = {'apple': "I AM APPLES!"}
print(mystuff['apple'])
# this goes in mystuff.py
def apple():
print("I AM APPLES!")
# so I can 'import mystuff.py' and use 'apple' function
import mystuff
mystuff.apple()
# put a variable named tangerine
def apple():
print("I AM APPLES!")
tangerine = "Living reflectio... |
1890cffdc871db396792a9ed1a17451a1e1f525b | bmanandhar/python_refresher | /palindrome.py | 759 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 19:39:33 2019
@author: bijayamanandhar
"""
class Solution(object):
#code starts below
def palindrome(self, string):
i = 0
while i <= len(string)//2:
if string[i] != string[len(string) - 1 - i]:
... |
1ba2269fe464dee7481e20adfbab9b0c1406fefe | lijinglj90/shop | /case/test_database.py | 711 | 3.609375 | 4 | """
目标:自动化测试中操作项目数据库
案例:
判断用户id(1)是否收藏了id为2的文章
1--未收藏,0--收藏
"""
# 导包
import pymysql
# 获取连接对象
conn = pymysql.connect("127.0.0.1",
"root",
"123456",
"hmtt",
charset = "utf-8")
# 获取游标对象
cursor = conn.cursor()
# 执行方法sql
sql... |
776c7cc5e15d1f0038fabd943f819e33c748fe30 | eronekogin/leetcode | /test_helper.py | 6,863 | 3.765625 | 4 | class ListNode:
def __init__(self, x: int):
self.val = x
self.next: 'ListNode' | None = None
def __repr__(self):
nextVal = self.next.val if self.next else None
return '{0} -> {1}'.format(self.val, nextVal)
def create_node_list(
self, start: int | None = None,
... |
cfd7692e4a9d358c38dba9d285a7a1a4a0a48c9c | BlendaBonnier/foundations-sample-website | /color_check/controllers/get_color_code.py | 1,060 | 3.859375 | 4 | # This file should contain a function called get_color_code().
# This function should take one argument, a color name,
# and it should return one argument, the hex code of the color,
# if that color exists in our data. If it does not exist, you should
# raise and handle an error that helps both you as a developer,
# fo... |
00234e92b20dd30caa6db1f35e9aeb499d35a4a4 | smazzone/python_playground | /toppings.py | 1,515 | 4.09375 | 4 | requested_toppings = 'mushrooms'
if requested_toppings != 'anchovies':
print(requested_toppings)
else:
print('oh oh')
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings... |
d1997cc360217d5afcb7e996bdddd1d698451a86 | hkdahal/CodingProblem1 | /Main.py | 1,033 | 4.03125 | 4 | import re
def do_stuff(filename):
highest = 0
the_word = ""
with open(filename) as f:
for line in f:
line = line.strip().split()
for word in line:
# cleaned_word = clean_word(word)
cleaned_word = clean_by_regex(word)
value = c... |
ff081f501ecf253307a049dfba82118a486afc47 | CrazyITDream/fullstacks | /week4/day1/fonction_Return.py | 370 | 3.78125 | 4 | #!/usr/bin/python
#coding:utf-8
"""
@author: 小火
@contact: xx@xx.com
@software: PyCharm
@file: fonction_Return.py
@time: 2019/1/24 14:31
"""
#函数有返回值
# def add(*args):
# Sum=0
# for i in args:
# Sum+=i
# return (Sum)
# f=add(1,2,3,4,5,6,4,7,8,9)
# print(' %s ' %f)
def foot():
return ['a','b','c'... |
bf3358d4a150cdbad04245047016df5affe5cce0 | esrok/algo | /trees/__init__.py | 5,231 | 3.578125 | 4 |
class BinaryTreeNode(object):
def __init__(self, value, parent=None):
self.value = value
self.parent = parent
self._left = self._right = None
@property
def left(self):
return self._left
@left.setter
def left(self, node):
self._left = node
node.paren... |
5dea3bc50aa229c114fb787095b5e7d752611d6d | Remus1992/PDXCGLabs | /day_10/word_count.py | 2,456 | 3.5625 | 4 | # book = open ("faust.txt", "r")
# print (book.name)
# book.close()
# with open ("faust.txt", "r") as book:
# print (book.name)
# with open ("faust.txt", "r") as book:
# book_contents = book.read()
# print(book_contents)
# with open ("faust.txt", "r") as book:
# for line in book:
# print(line, en... |
57144a2fdb7f49cbfe4950d12ea49d01198437db | QuentinDuval/PythonExperiments | /arrays/HandsOfStraight_Interesting.py | 1,446 | 3.859375 | 4 | """
https://leetcode.com/problems/hand-of-straights
Alice has a hand of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.
Return true if and only if she can.
"""
from typing import List
class Solution:
def ... |
de25f5865dee2a36da2421b6bb319863df5779d3 | Niki227/Nikhita-sPythonAssessmentTask | /99FinalTest.py | 5,652 | 4.09375 | 4 | # Assigns a function to the whole menu
def my_menu():
import os # clear statement
os.system('cls')
print(" ------------------------------------------------")
print("| |")
print("| 99FinalTest |")
print("| Name... |
21816f17050910e9e18ccd56d0411ceab4b65bd8 | shambhand/pythontraining | /material/code/advanced_oop_and_python_topics/4_ManagedAttributeDemo/ManagedAttributeDemo2.py | 649 | 3.8125 | 4 | # Attribute properties are inherited by the
# derived class
import sys
class Person:
def __init__(self, name):
self._name = name
def getName(self):
print('fetch...')
return self._name
def setName(self, value):
print('change...')
self._name = value
def delName(self):
print('remove...')
del self._na... |
305081295b34e634765d5bada0bf383082d08515 | Ikshitkate/java-html-5-new-project | /python/checkAnagram.py | 435 | 4.15625 | 4 | def checkAnagram(str1, str2):
len1 = len(str1)
len2 = len(str2)
if len1 != len2:
return 0
str1 = sorted(str1)
str2 = sorted(str2)
for i in range(0, len(str1)):
if str1[i] != str2[i]:
return 0
return 1
str1 = input("Enter String 1: ")
str2 = input("Enter Stri... |
9252f1de223cfea3c7031a5b22df080ea6b3c0bd | zoro666/Travelling_Santa_2018 | /baseline.py | 2,529 | 3.578125 | 4 | # Load all the libraries
import numpy as np
import pandas as pd
def find_closest_point(p1,p2):
""" Finds the euclidean distance between 2 points"""
xa = p1[1,]
ya = p1[2,]
xb = p2[1,]
yb = p2[2,]
dist = np.sqrt((xa-xb)**2 + (ya-yb)**2)
return dist
def nearest_point_in_array(ref_pt,arr):
... |
2fd22a779ca3a6c146eb1969c446b50f6d1d9fd1 | xanderyzwich/Playground | /python/tools/games/tic_tac_toe.py | 3,652 | 4.0625 | 4 | """
# Find Winner on a Tic Tac Toe Game
Tic-tac-toe is played by two players A and B on a 3 x 3 grid.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares `(" ")`.
The first player A always places "X" characters, while the second player B always places "O" characters.
"X" and "... |
ee5542d8b47d87f4e73ed20e8bc742567e858f31 | RicardoAugusto-RCD/exercicios_python | /exercicios/ex091.py | 795 | 3.59375 | 4 |
# Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um
# dicionário. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado.
from random import randint
from time import sleep
jogada = dict()
contador = 1
jogada['jogad... |
820ee70774109fdb7c32b511f5f8ff281fa321c1 | caw13/pi-top-sandbox | /name_game.py | 386 | 4.125 | 4 | name = input("What is you name?")
if name == "Chad":
print("That is the best name ever!!!")
print("Hi %s" % name)
else:
print("Sorry you are not Chad")
favorite_movie = input("What is your favorite movie? ")
if favorite_movie == "Batman":
print("Awesome!")
elif favorite_movie == "The Breakfast Club":
... |
0f62098a7e7d3e87f3cbacebcea2776e7c355b5e | hyxmartin/LeetCode | /1-1000/0003-Longest_Substring_Without_Repeating_Characters.py | 1,002 | 4.0625 | 4 | """
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Expl... |
9b81c4213c8241ba1c4e78941332c0e74e42fb43 | matthewdargan/Cozmo-Capture-the-Flag | /common/setup.py | 1,956 | 3.78125 | 4 | import time
from typing import List, Dict
import cozmo
from cozmo.objects import LightCube, LightCube1Id, LightCube2Id, LightCube3Id
def setup(robot: cozmo.robot.Robot, cube_color: cozmo.lights.Light) -> (List[LightCube]):
"""
Setup up the cozmo program to run for each computer to use.
:param robot robo... |
6a01da653a18c1d2bf1f683ac5f2cc84441529fb | gabriellaec/desoft-analise-exercicios | /backup/user_280/ch21_2020_03_04_02_27_34_915049.py | 229 | 3.703125 | 4 | dias = input('Quantos dias?')
horas = input('Quantas horas?')
minutos = input('Quantos minutos?')
segundos = input('Quantos segundos?')
total_segundos = (24*60*60*dias)+(60*60*horas)+(60*minutos)+(segundos)
print(total_segundos) |
1e8f6a2c67089ebf7562e9863ae2d7bacd19e118 | Testudinate/Lectures | /Lectures/Lecture_13/cycled_queue.py | 190 | 3.953125 | 4 | A = [10, [20, [30, None]]]
A[1][1][1] = A #зацикливание списка
def print_list(A):
p = A
while p: #!=None
print(p[0])
p = p[1]
print_list(A)
|
8803245f15f19d637ee1f32922cf175a8beb018e | neilbd/Arithiga_Original | /ship.py | 1,241 | 3.65625 | 4 | import pygame
from pygame.locals import *
from sys import exit
import os.path as osp
class Ship(pygame.sprite.Sprite):
def __init__(self, screen, ship_image, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.screen_width, self.screen_height = self.screen.get_size()
self.image = ship_ima... |
029fe733593c597270b4da18cf51a18694b75c47 | yanmarcossn97/Python-Basico | /Exercicios/exercicio042.py | 720 | 4.0625 | 4 | r1 = int(input('Comprimento reta r1(cm): '))
r2 = int(input('Comprimento reta r2(cm): '))
r3 = int(input('Comprimento reta r3(cm): '))
if r1 == r2 and r1 == r3:
print('Esses valores foram um triângulo.')
print('Tipo: Equilátero(todos os lados são iguais.).')
elif abs(r2 - r3) < r1 < r2 + r3 and abs(r1 - r... |
c5d3b0558eeb456da2e89b9b9952cb850cb05d74 | Er-Rakesh-Yadav/text-Editor | /editor.py | 3,775 | 3.625 | 4 | """
@author : Rakesh Yadav
@task : To develop a text-editor
"""
from tkinter import *
from tkinter.messagebox import showinfo
from tkinter.filedialog import askopenfilename, asksaveasfilename
import os
def newFile():
global file
editor_root.title("Untitled - Text-Editor")
file = None
TextArea.delete(... |
3b2986bf081c44fd8e1e0642c665cd8a65caa8c2 | Tititun/python-basics | /lesson_1/task_3.py | 115 | 3.65625 | 4 | n = input('Введите число\n')
nn = n + n
nnn = n * 3
result = int(n) + int(nn) + int(nnn)
print(result)
|
1e3066998b166b55d950ee8fce25dbe41fed1cab | GodamSwapna/list-Question | /sumof 6.py | 133 | 4.03125 | 4 | n=int(input("enter you are number:"))
i=1
sum=0
while i<=n:
num=int(input("enter a number"))
sum=sum+num
i=i+1
print(sum) |
674ac1dd6b509eed495b5e07f10d6bb541751003 | Gavinee/Leetcode | /500 键盘行.py | 1,497 | 3.515625 | 4 | """
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。
示例1:
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
注意:
你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。
"""
__author__ = 'Qiufeng'
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
dict1 = {... |
9e8ca9ebff179dd7569b772480fa5cdc0d819573 | nitheeshmavila/practice-python | /Think Python Book/Conditionals-and-recursion/Exercise5.2.py | 390 | 4 | 4 | # Exercise 5.2. Write a function called do_n that takes a function object and a number, n , as arguments, and that calls the given function n times.
square = lambda x: x*x
def do_n(square, n):
# return sum of squares of integers starting from 1 to n
sumOfSquares = 0
for i in range(1, n+1):
sumOfS... |
230c68de00e968fc7b665e41d9fc64caef652be7 | chjlarson/Classwork | /python/hw3/print_bill.py | 1,115 | 4 | 4 | # Christopher Larson
# CSCI 238 homework #3, Problem #4
# print_bill.py
# 9/14/13
#
# This program will calculate the sales tax and then the total bill.
def main():
print('This program tests the print_bill function.\n')
print('Calling print_bill with the arguments subtotal = 25 ' \
+ 'and rate = 5.')... |
06dba562792e1abffbe8f6c6d451f4760b78162c | ranggaahsana/Basic-Python | /09 - Latihan Perhitungan Sederhana/Kelvin.py | 446 | 4.125 | 4 | #Latihan konversi satuan temperatur
print('Program Konversi Temperatur Sederhana')
kelvin = float(input("Masukan Suhu dalam kelvin: "))
print('Suhu dalam kelvin:', kelvin, "kelvin")
#Reamur
celcius = kelvin-273
print('Suhu dalam Celcius:', celcius, "Celcius")
#Reamur
reamur = (4/5)*(kelvin-273)
print('Suhu dalam ream... |
a7f38b036c6968fb3a81d18baddd1159b3440b0f | RomuloAS/TBFSBS | /parse.py | 8,412 | 3.8125 | 4 | #!/usr/bin/env python3
import os
import argparse
import textwrap
from pathlib import Path
from collections.abc import MutableSequence
"""
Parse TBFSBS (Text-Based Format for Storing Biological Sequences):
The parser reads the file(s) and print the header and the
sequence length of all sequences in the file(s). Parse... |
8604557faa012ff4806431d2aa2f72e1fd9f2b6a | BugliL/TDD_step_by_step | /Refactoring by Martin_Fowler/Theory/Encapsulate collection/example.py | 934 | 3.609375 | 4 | from dataclasses import dataclass, field
from typing import List
@dataclass
class Course:
__name: str
__is_advanced: bool
@property
def name(self):
return self.__name
@property
def is_advanced(self):
return self.__is_advanced
@dataclass
class Person:
__name: str
__c... |
a227045057ba43e38bee7f679c495a1a4e1f3521 | KyleSMarshall/30-Day-LeetCoding-Challenge | /Day 16 - Valid Parenthesis String.py | 2,598 | 4.21875 | 4 | '''
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a correspondi... |
78d45ae88ae98b016853d7e7beee71605bc87e8e | mattsinbot/DataStructures-Algorithms | /Lesson1_PythonRefresher/Project0/Task2.py | 1,343 | 3.875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
import operator
max_duration = 0
phonedict = {}
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
for one_record in calls:
if one_record[0] in phonedict:
pho... |
ecb3da4d78e19573868b0e1aedf8b03436ee256d | limwonki0619/Python-lecture | /Notebook/Unit17_while.py | 1,525 | 3.921875 | 4 | # Unit 17. while 반복문으로 Hello, world! 100번 출력하기
i = 0
while i < 100:
print('hello, world', i)
i += 1
# 17.1.1 초깃값을 1부터 시작하기
i = 1
while i <= 100:
print(i)
i += 1
# 17.1.2 초깃값을 감소시키기
i = 100
while i > 0:
print(i)
i -= 1
# 17.1.3 입력한 횟수대로 반복하기
count = int(input('반복할 횟수를 입력하세요: '))
i = 0
while... |
0499ac082aea8d76f3035f80af817d0bf6347496 | fernandochimi/Intro_Python | /Exercícios/042_Tabuada_Inicio_Fim.py | 219 | 3.828125 | 4 | n = int(input("Tabuada de: "))
comeca_em = int(input("Começa em: "))
termina_em = int(input("Termina em: "))
while comeca_em <= termina_em:
print("%d X %d = %d" % (n, comeca_em, (n*comeca_em)))
comeca_em=comeca_em+1 |
1b5cab645fcfa693d065cc83f4bfa75c6777d619 | sankumsek/assorted-python | /Regular Expressions HW.py | 419 | 3.8125 | 4 | #Regular Expressions HW
#1
s = "3.1415, -2,71828, 4.0, 8.9, the value is 3.2, etc."
import re
def findfloats(s):
return re.findall("-?[0-9]+[0.-9.]+",s)
#2
prices = open("print.txt").read()
def findPrices(prices):
return re.findall("\$[0-9\.]+", prices)
#3
def findCapitalizedWords(s):
return re.findal... |
6686a49cda6e0f5d9a494ba4be711b5658b7ea50 | Erschwe/Python-Learning | /CelsiusConverter.py | 226 | 4.03125 | 4 |
Celsius = int(input("Enter a temperature to be converted to Fahrenheit: "))
#Fahrenheit = 9.0/5.0 * Celsius + 32
#print ("Temperature:", Celsius, "Celsius =", Fahrenheit, " F")
far = (Celsius * (9.0/5.0)) + 32
print (far)
|
d3015e3ad1beb585c61b85f32a25be5b34114946 | smoulinos/Chapter-4-Even | /Squares.py | 363 | 3.796875 | 4 | import turtle
wn=turtle.Screen()
bob=turtle.Turtle()
wn.bgcolor("lightgreen")
bob.color("hotpink")
def make_square (length):
for i in range(4):
bob.forward(length)
bob.left(90)
length=20
for j in range(5):
bob.pensize(3)
make_square(length)
length=length+20
bob.penup()
bob.goto(... |
006e5a130f3f3789ff182f789c8b1056aab957a7 | robinsharma1911/pythonfiles | /ada/binary.py | 584 | 4.15625 | 4 | #Binary Search program using recursive method...
def binarysearch(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarysearch(arr, low, mid-1, x)
else:
return binarysearch(arr, mid+1, high, x)
else:
return -1
arr = [4 ,6, 8, 13, ... |
ad55a21c492832cd968e7b3fe8c9034c8dd3dfd2 | GitKurmax/coursera-python | /week01/task21.py | 658 | 3.671875 | 4 | # Улитка ползет по вертикальному шесту высотой H метров, поднимаясь за день на A метров, а за ночь спускаясь на B метров. На какой день улитка доползет до вершины шеста?
# Формат ввода
# Программа получает на вход целые H, A, B. Гарантируется, что A > B ≥ 0.
# Формат вывода
# Программа должна вывести одно натуральн... |
0713a0e0aabb364a24d1dc588824915930871c77 | bwisgood/leetcode | /Hash/group_words.py | 706 | 3.578125 | 4 | class Solution:
def groupAnagrams(self, strs: list) -> list:
def cal(str_):
# list(str_).sort()
c = list(str_)
c.sort()
return "".join(c)
c = list(map(cal, strs))
d = {}
for i in range(len(c)):
if c[i] in d:
... |
8e3fd92ad88ed670b724cab7731eac7d01a2c488 | jrahm/DuckTest | /writeup/examples/duck.py | 467 | 3.578125 | 4 | class Person:
def walk(self):
print("I walk")
def talk(self):
print("I talk")
def think(self):
print("I think")
class Duck:
def walk(self):
print("Waddle")
def talk(self):
print("Quack!")
def swim(self):
print("I swim")
def tryToSwim(duck):
d... |
00f6eac17cca0bf19f9f5471fbccd7a5aefbe6c9 | Lslonik/python_algorithm | /HW_3/HW_3.6.py | 1,389 | 4.0625 | 4 | # В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.
# Сами минимальный и максимальный элементы в сумму не включать
import random
SIZE = int(input('Введите размер массива: '))
MIN_ITEM = 0
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)... |
8ae43ae93dd1cfd569610948dd8d9d88855174c7 | ChiaJung1031/WeekTwo | /two.py | 404 | 4.03125 | 4 | def avg(data):
# 請用你的程式補完這個函式的區塊
count = data["count"]
sum=0
averge=0
for i in range(3):
salary = data["employees"][i]["salary"]
sum += salary
averge = sum / count
print(averge)
avg({
"count":3,
"employees":[
{
"name":"John",
"salary":30000
},
{
"name":"Bob",
"salary":60000
},
{
"name":... |
182fd95f2b9f3cff0c38bef5f040eed73aefa299 | JSwidinsky/CompetitiveProgramming | /MAPS2020/J.py | 476 | 3.640625 | 4 | from fractions import Fraction as frac
n = input()
n = int(n)
A = []
for i in range(n) :
A.append(input())
curr = frac(0)
p = 0
val = frac(4, 5)
for x in A:
x = int(x)
curr += (x * val**p)
p += 1
print("{0:.8f}".format(float(curr*frac(1,5))))
average = frac(0)
for i in range(n) :
p = 0
ans = frac(0)
... |
a1ee9009295bb28fc1c7a5fa604f176782347e5d | marcosaraujo2020/ifpi-ads-algoritmos2020 | /Lista_Prof_Fabio/Fabio01_Parte02/f1_q23_loja.py | 702 | 3.984375 | 4 | from time import sleep
print('---'*13)
print(' LOJA DA ALEGRIA ')
print('---'*13)
# ENTRADA
valor_mercadoria = float(input('Informe o valor da compra: R$ '))
# PROCESSAMENTO
valor_entrada = (valor_mercadoria // 3) + (valor_mercadoria % 3)
valor_parcelas = valor_mercadoria // 3
# SAÍDA
print('')
print("Pro... |
a6570d63ef2c6e4a144d2462367db690c75a85e5 | Jor0Stam/HackBulgaria | /week03/Polynomials.py | 2,524 | 3.515625 | 4 | from Monomials import Monomial
class Polynom:
def __init__(self, poly):
self.poly = poly
self.poly_monomials = self.to_monomials(poly)
self.first_derivativ = self.get_first_derivativ()
def __str__(self):
return "The derivative of f(x) = {domain} is :\nf'(x) = {equasion}".forma... |
35e8fcdf41ecc2e9785ff2f63e3ca953966de5ee | KokoShterev/python | /201120/1120_3.py | 131 | 3.578125 | 4 | def my_f(a):
count = 0
while a >= 2:
a = a**0.5
count += 1
return count
a = int(input())
print(my_f(a)) |
007daacd9d034c42d90c0c165d70cb2ed71bb6e1 | lmontopo/Text-Adventure-Game | /MyGameClasses.py | 7,549 | 4 | 4 | from sys import exit
from random import randint
x = 0
y = 0
s = 0
# Here I define arrays of acceptable user inputs
call_out = ["call", "calling", "yell"]
walking = ["continue", "walking", "walk"]
run = ["run", "running", "away"]
ask = ["ask", "asking"]
dig = ["dig", "digging", "hole"]
would_not = ["wouldn't", "not... |
eb82b5ed24d525aac9abf0a8b2fad1eed8e6a3eb | Arthur-Lozano/data-structures-and-algorithms-1 | /python/code_challenges/linked_list/linked_list.py | 4,016 | 4.375 | 4 | # Create a node class, which is essentially a sub-class on the LinkedList class.
# Node class next is initialized with None
# The last element/node in a linked list will always be None
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# Create a Linked List(sin... |
663ad60d4d50dfce36b2339e2c3e0bbdeb1d3ba9 | Daniellau331/Sudoku | /GUI.py | 7,034 | 3.609375 | 4 | # GUI.py
# There are two classes in this program
# Grid and Cube
# Grid holds 9 Cubes
import pygame
from solver import checker, solver, print_board
pygame.font.init()
class Grid:
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, ... |
f17fcc440548ac9f545e475306fcc34c6a77e521 | anishLearnsToCode/python-workshop-8 | /day_2/inbuilt_functions.py | 364 | 3.5625 | 4 | def abs(x: str) -> float:
return x if x > 0 else -x
# print(abs(10))
# print(abs(-10))
x = set()
# print(type(x))
x.add(10)
x.add(10)
x.add(10)
# print(x)
# print(len(x))
# print([ord(character) for character in input()])
# print(x.__repr__())
# var = map(int, input().split())
# print(var)
n = int(input())
... |
6c756e2b22c29a295a112a5f2712deb810b04050 | shrutijain0/python-small-projects | /GuessTheWord.py | 1,924 | 4.1875 | 4 | import random
#FOR WELCOME SCREEN
def welcome():
print("**********WELCOME TO GUESSING GAME**********")
print("________________GAME DESCRIPTION_____________")
print("YOU WILL BE GIVEN A CHANCE TO GUESS A NUMBER AND IF YOUR NUMBER IS SAME AS THE NUMBER SLELCTED BY COMPUTER THEN YOU WIN OR ELSE YOU LOOSE")
... |
f6717e29d46f0e277be4099dae42447aaf1561c8 | coltonneil/IT-FDN-100 | /Assignment 6/hw6.py | 3,868 | 4.28125 | 4 | #!/usr/bin/env python3
import math
"""
python 3
this script calculates and splits the cost of a pizza order based on the number of slices, it will read names and slice
amount from a file named "order.txt" that is stored in its local directory, if that file is not found it will calculate
based off of a default order
... |
f46d95f5c4f3db62c19dd1851db97f47c3ea678e | beautytiger/project-euler | /problem-012.py | 1,300 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from tools.runningTime import runTime
def fn(number):
stop = int(pow(number, 0.5))
# always including 1 and the number itself
# but if number=1, return 1
count = 1
for i in xrange(2, stop+1):
if number%i == 0:
count += 1
return co... |
ec4bc256618a6d450180a8e832dd791ef1da8a06 | Wizdave97/Algorithms-and-Data-Structures | /linked_lists/even_after_odd.py | 1,873 | 4.21875 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self, head=None):
self.head = head
def append(self, value):
if self.head is None:
self.head = Node(v... |
5d9bbc0b6535cfb1635ecf275817d5fddb3264d2 | ccampion/predicting-crime | /references/analysis-notes/multi-class-auc-roc-functions.py | 10,352 | 3.796875 | 4 | ##################################################################
# DEFINE FUNCTIONS FOR CALCULATING ROC AND AUC AND PLOTTING CURVES
##################################################################
# MULTI-CLASS AUC REQUIRES scikit-learn v0.22
# required imports
import numpy as np
import geopandas as gpd
import ma... |
a5dc998f2fce218c3f7f85cc211d1a9fffdb4b49 | harshildp/python_oct_2017 | /eric.jones/Mathdojo/mathdojo.py | 822 | 3.796875 | 4 | class MathDojo(object):
def __init__(self):
self.result = 0
def add(self, arg1, *arg2):
self.result += arg1
for idx in list(self.recursetree(arg2, (list, tuple))):
self.result += idx
return self
def subtract(self, arg1, *arg2):
self.result -= arg1
... |
6872f5a7e94b5921960b6113c630c852beabdd6a | TahuraShaikh/Python_Scripts | /convert_temperture.py | 129 | 3.71875 | 4 | # convert celcius to farhenheit:
def farh(cel):
return(cel*(9/5))+32
c=37
f=farh(c)
print(f"farhenheit temperature is : {f}") |
dbeaae64e885db91481d94faa67b26e93c8b1ca0 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex091.py | 983 | 3.609375 | 4 | """
Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatorios.
Guarde esses resultados em um dicionario. No final, coloque esse dicionario
em ordem, sabendo que o vencedor tirou o maior numero no dado.
"""
from random import randint
from time import sleep
import operator
rpg_rodada = []
jogador =... |
c513416dc1b7a5f1c9c0ef5819aba2e8d6d21521 | andrei541/PEP21G01 | /communicator/modul6_1.py | 1,312 | 3.59375 | 4 | # # #classes
# #
# # class Object:
# # variable="this is my text"
# # def print_var(self):
# # print(self.variable)
# # def change_var(self):
# # self.variable="this is another text"
# #
# # Object1=Object()
# # Object1.print_var()
# # Object1.change_var()
# # print("class variable:",Object.... |
e0a7ead3b4702d848914fd1052390f0cff4564f5 | CagiriciOzlem/GlobalAIHubMachineLearningCourse | /Homeworks/HW_2.py | 5,098 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Course Date: 22.03.2021
Name: Özlem
Surname: Çağırıcı
Email: ozlemilgun@gmail.com
"""
**************************HOMEWORK - 2 *************************
# Import boston dataset and convert it into pandas dataframe
from sklearn.datasets import load_boston
import pandas as pd
... |
6a1107e4c75596975bcb3f5098224afda098d0bf | eric-czech/portfolio | /functional/ml/python/py_utils/zip_utils.py | 797 | 3.5 | 4 | # Utilities for processing zip archives
import zipfile
def _validate_archive(zip_filepath):
assert zip_filepath.endswith('.zip'), \
'File should have a .zip extension (filepath given = "{}")'.format(zip_filepath)
def get_zip_archive_files(zip_filepath):
_validate_archive(zip_filepath)
with zipf... |
3c871b9cf4b59477171a62a7f41692e763e3194b | rwieckowski/project-euler-python | /euler371.py | 754 | 3.75 | 4 | """
Oregon licence plates consist of three letters followed by a three
digit number each digit can be from 09<BR />While driving to work Seth
plays the following game<BR />Whenever the numbers of two licence
plates seen on his trip add to 1000 thats a win
Eg MIC012 and HAN988 is a win and RYU500 and SET500 too as l... |
28b14ef27fbf56b02b3eb7f9d482231a966fd2a8 | StarliteOnTerra/csci127-Assignments | /lab_04/mad.py | 1,161 | 3.921875 | 4 | import random
adj = ["beautiful", "aggressive", "calm", "delightful", "silly"]
noun = ["tiger", "cat", "house", "banana", "music"]
verb = ["running", "jumping", "swimming", "laughing", "skating"]
pnoun = ["tigers", "cats", "houses", "bananas", "musics"]
game = ["Scrabble", "Twister", "Tag", "Digging"]
statement = "A v... |
0dc632b6d270dfb5732ad6b1b1390ee0eaa84a3b | longchushui/How-to-think-like-a-computer-scientist | /exercise_03070_0308.py | 1,351 | 4.4375 | 4 | # A drunk pirate makes a random turn and then takes 100 steps forward, makes another
# random turn, takes another 100 steps, turns another random amount, etc. A social
# science student records the angle of each turn before the next 100 steps are taken.
# Her experimental data is [160, -43, 270, -97, -43, 200, -940,... |
ab461793e6af592d270fdfeece93dba38136c7aa | btwmendes/Data-Structures-Algorithms | /section_3_recursion/power_of_number.py | 369 | 4.21875 | 4 | def power(base, exponent):
assert exponent >= 0 and int(exponent) == exponent, "The exponent must be greater than or equal to zero" \
" and an integer."
if exponent == 0:
return 1
if exponent == 1:
return base
else:
return b... |
4b55269c3cfcbda637d05e02421866d8f5fd37ea | Ankong0914/mancala | /play.py | 2,511 | 4 | 4 | from hole import PlayerHole, SideHole
import sys
class Play():
def __init__(self, num_hole, init_stone):
"""initial function in Play class
Arguments:
num_hole {int} -- the number of holes on one side except side holes
init_stone {int} -- the number of stones tha... |
6d17e4d59b55518fc1ff965ae2160cd2b398c606 | arumakan1727/sudoku-solver | /validator/validator.py | 1,398 | 3.84375 | 4 | #!/usr/bin/env python3
from typing import List, Iterator
N = 9
def main():
mat = [[int(e) for e in input().split()] for _ in range(N)]
assert_board_validity(mat)
def is_valid_sequence(seq: List[int]) -> bool:
n = len(seq)
return all(seq.count(i + 1) == 1 for i in range(n))
def assert_board_validi... |
317033e4b836413c86c0bc3cdf1c4ab2dc29dfdd | SangYong-Park/python_practice | /Day1/print_sample.py | 404 | 3.734375 | 4 | s = '서울'
d = '대전'
g = '대구'
b = '부산'
print(s,d,g,b, sep = ' , ')
print (b)
a = input("당신의 나이는?")
print (a)
print('당신의 나이는', a, '살 입니다') # 5년 뒤 나이 표시
print("당신의 나이는 5년 뒤에 " , int(a)+5 , "살입니다.") #casting : 하나의 데이터 타입에서 다른 데이터 타입으로 바꿈.
a = "first\nsecond"
print(a)
|
8d7dfe835540f9ca0d4a17f596b0fd47c4e7797e | cmychina/Leetcode | /leetcode_链表_16.重排链表.py | 1,719 | 3.75 | 4 | """
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
思路:快慢指针找到中点Lm,然后将Lm后面的翻转得 Ln,Ln-1,Ln-2
然后得到两个序列L0,L1,...Lm和Ln,Ln-1,Ln-2,然后交替连接即可
#交替连接,首先保存左右的next,然后将左指针连接到右指针,把右指针和左next连接
然后更新左右指针
"""
from linklist import *
class Solution:
def reorderList(self, head: ListNode... |
6975866b9af860e45f618fc58f3a99b3ef08876f | mocorr/algorithm013 | /Week_09/day61_[151]翻转字符串里的单词_homework.py | 2,800 | 3.890625 | 4 | # 给定一个字符串,逐个翻转字符串中的每个单词。
#
#
#
# 示例 1:
#
# 输入: "the sky is blue"
# 输出: "blue is sky the"
#
#
# 示例 2:
#
# 输入: " hello world! "
# 输出: "world! hello"
# 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
#
#
# 示例 3:
#
# 输入: "a good example"
# 输出: "example good a"
# 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
#
#... |
5b7d181931d190982e3d1eb103994135c079ac6f | alaz1812/My_Homework | /Pack_2/Task_1.py | 271 | 3.90625 | 4 | def recfact (x):
if x == 0:
return 1
else:
return x * recfact(x - 1)
def factorial(x):
mult = 1
for i in range (2,x+1):
mult = mult * i
return mult
x = int(input("Inputn the number: "))
print (recfact(x))
print (factorial(x))
|
6148b3ae7f62d4683972d50935bdfd9255af8ae2 | NaiveMonkey/Datastructure_HackerRank | /linkedlist/insert_node_tail.py | 749 | 4.1875 | 4 | """
Insert Node at the end of a linked list
head pointer input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method
"""
clas... |
37a4c9e6c70905be4c5670345959451aade22ef7 | skybohannon/python | /PracticeExercises/question35.py | 504 | 4.4375 | 4 | # Question:
# Define a function which can generate a list where the values are square of numbers between
# 1 and 20 (both included). Then the function needs to print all values except the first 5
# elements in the list.
#
# Hints:
#
# Use ** operator to get power of a number.
# Use range() for loops.
# Use list.append(... |
2828ac8e13c93c95169b653048efdda51479b40f | dpdahal/python6am | /introduction.py | 1,816 | 4 | 4 | # print("Hello", "Welcome", "Python")
# print('mother\'s')
# print('mother"s')
# print("mother's")
# print(1+5)
"""
Here is a list of the Python keywords. Enter any keyword to get more help.
False break for not
None class from or
T... |
717a80c36df3ed38c778a9ba128fd8f09ed727ec | DiksonSantos/Curso_Intensivo_Python | /Pagina_83_Exemplo_Concatenação_Listas.py | 1,846 | 3.90625 | 4 | '''bike = ['trek', 'cannodale','redline','specialized']
messege = "My Favorite bicycle Was a: " + bike[-2].title()+'.'
print(messege)'''
#3.2 Nomes:
'''friends = ['joão', 'maria', 'josé bonifacio','bono vox','madalena']
message = 'Tempim Bãao Hein: ' + friends[-4].title()
message_2 = 'The Rain Drops Is Falling ... |
9eacdc0ae6443db7c66c4b5f45614121c176677f | Ratajq/coffee-machine | /coffee-machine.py | 4,045 | 3.59375 | 4 | class MyCoffee:
water = 400
milk = 540
coffee_b = 120
cups = 9
money = 550
state = 'menu'
end = 1 #ending condiotion
def remaining(self):
print('The coffee machine has:')
print(f'{self.water} of water')
print(f'{self.milk} of milk')
print(f'{self.coffee_b}... |
5b6e9d55beb5fd5f8e1fdc490fe0429d914a1871 | itcsoft/itcpython | /python/day14/dict_1.py | 1,522 | 3.953125 | 4 | # Наши Аккаунты в банках
accounts = [
{
"name": 'Demir Bank',
"balance": 500000.00,
"valuta": "KGS",
"password": 1994
},
{
"name": 'Optima Bank',
"balance": 9654321,
"valuta": "RUS",
"password": 1995
},
{
"nam... |
a8dc7fa9206db42300345aba27c1e6425edc4591 | edson-onishi/cursoemvideo | /088.py | 670 | 4.03125 | 4 | ''' Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos
serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.'''
import random
lista = list()
jogos = list()
qtdjogos = int(input("Quantos jogos: "))
total = 1
w... |
7f544df4669dfdc444e5662f1c2cdb1e37fbfe9a | ingridsor/number_extraction | /baseline_extraction.py | 2,652 | 3.71875 | 4 | # Number recognition project, Speech Technology DT2112
# By Ingrid Sör, Manon Knoertzer and Carina Rawein
# A script for acquiring a "baseline" of number extraction from ASR
# For filesystem support
import os, re
def cut_extras(number):
number_cut = number.replace(' ','').replace('(','').replace(')','')
retur... |
20cf5b34e570d982ae6a87c47d62ddab00c2b011 | DayGitH/Python-Challenges | /DailyProgrammer/DP20130701A.py | 2,368 | 3.875 | 4 | """
[07/01/13] Challenge #131 [Easy] Who tests the tests?
https://www.reddit.com/r/dailyprogrammer/comments/1heozl/070113_challenge_131_easy_who_tests_the_tests/
# [](#EasyIcon) *(Easy)*: Who tests the tests?
[Unit Testing](http://en.wikipedia.org/wiki/Unit_testing) is one of the more basic, but effective, tools for ... |
dae26d8bb27c6615529675bb00e572161a7eb496 | YotamZiv298/cyber-python | /persian_box.py | 1,952 | 4.21875 | 4 | import argparse
FILE_NAME = __file__.split('/')[-1]
OPERATION = 'operation'
OPERATION_HELP = 'math function'
OPERATION_TYPE = str
PARAM1 = 'first_number'
PARAM1_HELP = 'first number'
PARAM1_TYPE = int
PARAM2 = 'second_number'
PARAM2_HELP = 'second number'
PARAM2_TYPE = int
def add(a, b):
"""... |
21ad6107640ceaefef25e436d6d6248bed644929 | wanqizhu/finitefield | /utils.py | 6,191 | 3.765625 | 4 | """
Perform Gaussian Elimation on the input matrix.
Elements of this matrix need to support +, *, /,
and identity checking with 0.
If the matrix is non-square, reduction is performed on as many
rows/columns as possible.
@param A
Input matrix, of any dimension
@return
A', input matrix transformed to reduced ... |
800a14b341863b8531a87ad4d2afdd8ff5112a9d | zsmountain/lintcode | /python/161_rotate_image.py | 876 | 4.25 | 4 | '''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Have you met this question in a real interview?
Example
Example 1:
Input:[[1,2],[3,4]]
Output:[[3,1],[4,2]]
Example 2:
Input:[[1,2,3],[4,5,6],[7,8,9]]
Output:[[7,4,1],[8,5,2],[9,6,3]]
Challenge
Do it in-place.
'... |
6386e839f671f844a58bb26f731493d14dc8be4c | jazzmanmike/python-intro | /solutions/2_1.py | 224 | 4.125 | 4 | bases = ['A', 'T', 'T', 'C', 'G', 'G', 'T', 'C', 'A', 'T', 'G', 'C', 'T', 'A', 'A']
print "All bases:"
for base in bases:
print base
print "Every 3rd base:"
pos = 2
while pos <= 12:
print bases[pos]
pos += 3
|
ae988d82f2f6ccc1b798307086bb9e4095e1e1a7 | arch1904/Python_Programs | /count_vowels.py | 642 | 4.34375 | 4 | # Count Vowels
#
# For our purposes a vowel is either a, e, i, o, or u. Iterate through
# a string and return the number of vowels in it. Case does not matter.
#
# Example(s)
# ----------
# Example 1:
# Input: aAaeeizzzzz
# This string contains 3 a's, 2 e's, 1 i. So 5 vowels.
# Output:
# 5
#
# Parameters
# ----... |
36af996fb77849baff38a00eb170f7c6629daf7a | Amudha2019/INeuron-Assignment-1 | /ex3.py | 245 | 3.5 | 4 | names1=['Amir','Bear','Charlton','Daman']
names2=names1
names3=names1[:]
names2[0]='Alice'
names3[1]='Bob'
sum=0
for ls in (names1,names2,names3):
if ls[0]=='Alice':
sum+=1
if ls[1]=='Bob':
sum+=10
print(sum)
|
4ba52dc43dbc0755c13ac42da5d393c94e0311cc | marcfies/Classroom-Scheduler | /faculty_test.py | 1,321 | 3.8125 | 4 | import faculty
import csv
faculty_file = open('test_faculty.txt', 'r')
################################# PART ONE #####################################
"""
Part one uses faculty input file to creat list of faculty members
"""
data = faculty_file.readlines() #read in faculty file
faculty_file.close(... |
096aacaa4996064d040fcda8dd6e27abe927260c | rishuraj1857/Python | /factorial.py | 262 | 4.125 | 4 | x = int(input("Please enter a number:=>"))
y=1
if x > 0:
for i in range (1,x+1):
y=y*i
print(f"factorial of {x} is {y}")
elif x==0:
print("Factorial of 0 is 1")
else:
print("Sorry, Factorial of Negative number does not exit") |
1e54636829408e5566b2e1cb58e4d7d5e824c9b7 | J14032016/LeetCode-Python | /leetcode/algorithms/p0037_sudoku_solver.py | 1,202 | 3.5625 | 4 | from typing import List
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
self._solve(board)
def _solve(self, board: List[List[str]]) -> bool:
for row in range(9):
for column in range(9):
if board[row][column] != '.':
contin... |
707d534117c0bbc35346edaba69913b7ff18aba1 | franzleeyan/PCC | /name_cases.py | 1,131 | 4.40625 | 4 | # 赋值名字
# first_name = "eric"
# 用名字首字母大写的方式拼接短语
# hello_message = "Hello " + first_name.title() + ", would you like to learn some Python today?"
# 打印短语
# print(hello_message)
# 分别打印名字首字母大写,全小写,全大写
# print(first_name.title())
# print(first_name.lower())
# print(first_name.upper())
# 打印双引号的语句"A person who never made a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.