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 |
|---|---|---|---|---|---|---|
3b8148eac8c299701a5fae9b108ce0f7bd0bbefe | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Fundamentals/04_Lists/01.1.Courses.py | 606 | 3.796875 | 4 | """
Lists Basics - Lab
Check your code: https://judge.softuni.bg/Contests/Practice/Index/1724#0
SUPyF2 Lists Basics Lab - 01. Courses
Problem:
You will receive a single number n. On the next n lines you will receive names of courses.
You have to create a list of them and print it.
Example:
Input:
2
PB Python
BF Python
... |
363030191f794c5a84970328b31beb94d1b41b61 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/4_Conditional_Statements/point_on_rectangle_border.py | 311 | 3.96875 | 4 | x1 =float(input())
y1 =float(input())
x2 =float(input())
y2 =float(input())
x =float(input())
y =float(input())
x_condition = (x == x1 or x == x2) and (y1 <= y <= y2)
y_condition = (y == y1 or y == y2) and (x1 <= x <= x2)
if x_condition or y_condition:
print('Border')
else:
print('Inside / Outside')
|
eec96339c928ff8c2148957172c237c2cb015a2f | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/2_simple_calculations/Fish_Tank.py | 582 | 4.1875 | 4 | # 1. Read input data and convert data types
lenght = int(input())
width = int(input())
height = int(input())
percent_stuff = float(input())
# 2. Calculating aquarium volume
acquarium_volume = lenght * width * height
#3. Convert volume (cm3) -> liters
volume_liters= acquarium_volume * 0.001
#4. Calculating litter tak... |
1e806ce58b492eda1c4656f02c5bef7768eab167 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Basics/5_While_Loops/coin.py | 635 | 3.671875 | 4 | change = float(input())
coins = round(change * 100)
coins_count = 0
while coins > 0:
if coins >= 200:
coins -= 200
coins_count += 1
elif coins >= 100:
coins -= 100
coins_count += 1
elif coins >= 50:
coins -= 50
coins_count += 1
elif coins >= 20:
co... |
2c58a2f5329a497af7858044d65ec1d738142231 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Advanced/Modules-Lab/01_CalculateLogarithm.py | 167 | 3.765625 | 4 | from math import log
n = float(input())
base = input()
if base == 'natural':
print(f'{log(n):.2f}')
else:
base = float(base)
print(f'{log(n, base):.2f}')
|
dd9d5e69d01b89ff6e01c97f86386f51ab255fed | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Advanced/File-Handling-Exercise/01_EvenLines.py | 481 | 3.5625 | 4 | try:
with open('text.txt') as text:
symbols = ["-", ",", ".", "!", "?"]
for idx, line in enumerate(text):
for symbol in symbols:
line = line.replace(symbol, '@')
line_list = line.split()
reverse_line_lst = reversed(line_list)
... |
33819fb9c0c9985202b41b31b7a314435f15e666 | stevalang/Coding-Lessons | /SoftUni/Python Developmen/Python-Fundamentals/26_Text-Processing/digits_letters_other.py | 558 | 4.0625 | 4 | def all_digits(text):
digits = ''
for char in text:
if char.isdigit():
digits += char
return digits
def all_letters(text):
letters = ''
for letter in text:
if letter.isalpha():
letters += letter
return letters
def all_other_characters(text):
symbol... |
939affa4357fb8122842e652a8353c05f1960ce7 | wb82test/Battle | /BattleTestA.py | 3,154 | 3.75 | 4 | # надо сделать таймаут
# надо сделать таблицу
# таблицу надо положить в файл.
from random import randint
import numpy
class Voin():
health = 100
score = 0
power = 100
def kick(self):
score += 1
invite = "Удар рукой - 2, удар ногой - 3, блок - 1: "
VoinUser = Voin()
VoinPC = Voin()
def pri... |
7f3b41c010f206fcc9b7982367d425b8748ef347 | JonDGS/Intro-y-Taller | /Recursion de cola/Eliminardivisores del 3.py | 354 | 3.59375 | 4 | def eliminar(num):
if isinstance(num, int):
return eliminar_aux(num,0,0)
else:
return 'No es un numero valido'
def eliminar_aux(num, d,new):
if num == 0:
return new
elif (num%10) % 3 == 0:
return eliminar_aux(num//10, d, new)
else: return eliminar_aux(num // 10, d+1, ... |
c93c3f28a802cdb94833f218ae9f2285dabc09e0 | JonDGS/Intro-y-Taller | /Recursion de cola/Suma de antidiagonal de matriz.py | 388 | 3.765625 | 4 | def sumarAntiDiagonal(matriz):
if isinstance(matriz,list) and matriz != []:
return sumarAntiDiagonal1(matriz,len(matriz)-1, 0, 0)
else: return " Error no es una lista"
def sumarAntiDiagonal1(matriz,indice1,indice2,resultado):
if indice1==-1:
return resultado
else: return sumarAntiDiagon... |
e17ae310e2dcd3f68ec17a1f14e6b3fbdfc82774 | JonDGS/Intro-y-Taller | /Recursion de cola/Mayor y menor de lista.py | 723 | 3.515625 | 4 | def listas(lista):
if isinstance(lista,list):
return high(lista,0,lista[0]), low(lista,0,lista[0])
else:
return 'El valor no es valido'
def high(lista,i,m):
if i == len(lista):
return m
elif isinstance(lista[i],list):
return high((([lista[i:]] + [(high(lista[i],0,1))]),i+... |
4a80cc63cd80da2aeedddf05c548d628afd3f75d | JonDGS/Intro-y-Taller | /Recursion de cola/Numero en lista.py | 474 | 3.6875 | 4 | def fun(x,lista):
if isinstance(x, int) and isinstance(lista,list):
return procesar(x,lista,0)
else:
return 'No es una lista'
def procesar(x,lista,i):
if i == len(lista):
return False
elif isinstance(lista[i],list):
if (procesar(x,lista[i],0)) == False:
retur... |
196a54b8603b2a0d0bfe331b9d5b247960285046 | lelandbatey/whereIAm | /app/models/geo_utils/geo_utils.py | 4,512 | 3.890625 | 4 | from __future__ import print_function, division
import math
#pylint: disable=W0312
# Below taken from here:
# http://www.johndcook.com/blog/python_longitude_latitude/
def distance_on_unit_sphere(lat1, long1, lat2, long2):
"""Calculates the distance between two lat/long points. Returns distance in
'arc length' ... |
6879f828fed9937e99d4a6b1908c86c55ef258f2 | keidakira/Learning | /Dynamic Programming/Rod Cutting Problem.py | 1,683 | 3.6875 | 4 | """
Problem Statement:
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n.
Determine the maximum value obtainable by cutting up the rod and selling the pieces.
Example:
If the price for length of rod is the following,
length | 1 2 3 4 5 6 ... |
4de1171dc3de711df030e143af51e3d1d2a26b86 | jerickleandro/uri_online_python | /1060 - Números Positivos.py | 144 | 3.796875 | 4 | positivos = 0
for c in range(0,6):
a = float(input())
if a > 0:
positivos += 1
print('{} valores positivos'.format(positivos))
|
2a92d685a92c43a2d863a8f3aa6d794fa55fda62 | jerickleandro/uri_online_python | /FuncaoMenu.py | 603 | 3.90625 | 4 | def realizaSoma(a,b):
print(a+b)
def realizaSubtracao(a,b):
print(a-b)
def realizaMult(a,b):
print(a*b)
def realizaDiv(a,b):
if(b!=0):
print(a/b)
else:
print("Não é possivel dividir por 0")
opt = int(input('Digite uma opção: \n1-Soma\n2-subtração\n3-Multiplicação\n4-Divisão\n'))
a ... |
77190a8d392a8bfa8eea78fe8770153868f45609 | codeamazone/hangman | /Problems/Checking email/task.py | 258 | 3.765625 | 4 | def check_email(string):
if ' ' in string:
return False
elif '@' in string and '.' in string:
position1 = string.index('@')
position2 = string.rfind('.')
return position2 > position1 + 1
else:
return False
|
79b1e7769f0392d2053818270d7703fb3d6e0c65 | DuskTillDwan/Intro-To-Python | /Assignment 3/csc242-901hw3.py | 4,130 | 4.15625 | 4 | # CSC 242-901
# Assignment 3 template
# Put your name here
# List your collaborator(s) here (no more than two other people
# either directly or indirectly)
# Add a comment in this file with a clear and detailed explanation
# of the contributions of each collaborator
# If you did not collaborate with anyone, say that... |
e80a099dfe4e50940dc6284a37a78639f16441ad | ashish17133/TicTacToe_Python | /CrissCrossGame.py | 3,216 | 3.578125 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import IntVar
import random as rd
win=tk.Tk()
win.title("Criss Cross Game")
win.geometry("480x410+400+200")
def user():
if (r==0):
lab1=tk.Label(win,text="USER 1",fg="RED",bg="GREEN")
lab1.grid(row=0,column=4,ipadx=20,ipady=20... |
63b3cf630da3afc4afb54bffc51d4acf5d7f2b12 | AnnisMcl/AmongUsProject | /AmongUsStep2.py | 2,579 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 11 14:24:26 2020
@author: yanni
"""
class Node: #Simple Node class
'''We just need a "listVoisins" attribute and an iD'''
def __init__(self,iD,listVoisins=[]):
self.iD = iD
self.listVoisins = listVoisins
def __str__(self): #To have a nice display
return str(sel... |
8e3f1a36bc4a21e6ebcadc05eecb135a39bd3919 | Svbongale/AlgoSketch | /gui.py | 5,449 | 3.515625 | 4 | from tkinter import *
from tkinter import ttk
from bubblesort import bubble_sort, changeRun, bubble_sort_step
from quick_sort import *
from merge_sort import *
from insertion_sort import *
from selection_sort import *
import copy
import random
root = Tk()
root.title("AlgoSketch - An Algorithm Visualizer")
root.maxsize... |
1d542a590f9d64141e78112416c1c2dc91a150ae | PoojaGoswami/DS | /insert-in-sorted-linkdlist.py | 1,082 | 4.03125 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class sLinkedList:
def __init__(self):
self.head = None
def insert(self,NewData):
newNode = Node(NewData)
if self.head is None:
newNode.next = self.head
self.head = newNo... |
2dc934ff9914191b12a1b4b6ae5f7508aa0ae4fc | brianmchoi/Python-Avatar-Game | /number.py | 237 | 3.578125 | 4 |
string = "hh"
val = ord("n")
for c in string:
val = val + ord(c)
val = val * val
val = val - ord(".") * ord(".") - ord("a") - ord("]") - ord("a") - ord("]") - ord("a") - ord("]") - ord("a") - ord("]") - ord("J")
print(val)
|
94fe2d87c859a6946cbc127ab558c86bdc42e02a | chandana-codes/python-practice | /functions.py | 484 | 3.890625 | 4 | # function are the group of statements are together perform a specific task
# function formation
def func(Name, Age):
print(Name, Age)
func("jojo", 21)
# printing the arguments
def func1(*args):
for i in args:
print(i)
func1(20, 40, 60)
func1(80, 100)
# return statement.
def code(a, b):
re... |
73ca29ffb697d7e08b72cbc825a7a7672d989dd4 | happyandy2017/LeetCode | /Rotate Array.py | 2,287 | 4.1875 | 4 | # Rotate Array
# Go to Discuss
# Given an array, rotate the array to the right by k steps, where k is non-negative.
# Example 1:
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps ... |
ab4b0424777999fbe22abb732279e9f3de3efeb3 | happyandy2017/LeetCode | /Target Sum.py | 2,048 | 4.125 | 4 | '''
Target Sum
Go to Discuss
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: ... |
eded0cbae1fd38cd77b7e99c38ef98af89430480 | happyandy2017/LeetCode | /Find Pivot Index.py | 406 | 3.546875 | 4 | class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total_sum = 0
for num in nums:
total_sum += num
sum=0
length = len(nums)
for i in range(length):
if sum*2+nums[i] == total_su... |
60d3b3ff940cb16ab0b88cd4915b221c9c8183a1 | SaberHardy/ML_Tests | /GradientDesent/GD-OneHiddenLayer.py | 2,180 | 4 | 4 | import numpy as np
def sigmoid_function(sop):
return 1.0 / (1 + np.exp(-1 * sop))
def error_function(predicted, target):
return np.power(predicted - target, 2)
def error_predicted_deriv(predicted, target):
return 2 * (predicted - target)
def sigmoid_sop_deriv(sop):
return sigmoid_function(sop) *... |
b1361f96c7cf7ebf16baf4cb8d1e07c64955b95b | AissatouCISSE/Python | /Exercice3.py | 434 | 3.953125 | 4 | #Version1
r1 = float(input("Entrer R1 :"))
r2 = float(input("Entrer R2 :"))
r3 = float(input("Entrer R3 :"))
Rser=r1+r2+r3
Rpar=(r1*r2*r3)/(r1*r2+r1*r3+r2*r3)
print("La résistance en série est ", Rser)
print("La résistance en parallele est ", Rpar)
#Version2
choix = int(input("Entrer Votre choix 1 ou 2 ?"))
if choix... |
6c1dff70c6a5c5878cf77e057224fb9c0905444f | AissatouCISSE/Python | /Exercice5.py | 138 | 4.03125 | 4 | somme=0
for i in range(5):
val=int(input("Entrer une valeur :"))
somme=somme+val
print("la somme des valeurs saisies est:", somme) |
08f74e4e4e15adf799a99d83c2ee4cbf94580294 | YaojieLu/LAI_optimization | /Optimal_gs/MDP_gs.py | 6,668 | 3.796875 | 4 | """
Markov Decision Process
First we define an MDP.
We also represent a policy as a dictionary of {state: action} pairs.
We then define the value_iteration and policy_iteration algorithms.
"""
from utils import argmax
import random
import numpy as np
def Ef(gs, slope, dt):
""" Given stomatal conductance, return ... |
1e458d8bbd986b4b838f784b15ed9f6aaf5eccfc | mblue9/melb | /factorial.py | 928 | 4.1875 | 4 | import doctest
def factorial(n):
'''Given a number returns it's factorial e.g. factorial of 5 is 5*4*3*2*1
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(3)
6
'''
if not type(n) == int:
raise Exception("Input to factorial() function must be an integer")
if n <... |
a000ab576b9eefeb3be6565177102dea660a1b74 | TrafalgarSX/graduation_thesis_picture- | /lineChart.py | 678 | 4.4375 | 4 | import matplotlib.pyplot as pyplot
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
# plotting the points
pyplot.plot(x, y, color='green',linestyle='dashed', linewidth=3, marker='*',markerfacecolor='blue',markersize=12, label = "line 1")
x1 = [1,2,3]
y1 = [4,1,3]
# plotting the line ... |
c57ebba99cd70844d196c4215278664d7017c064 | fexli/ArknightsAutoRunner | /utils/logcolor.py | 2,612 | 3.71875 | 4 | class Color(object):
class print(object):
class html(object):
RED = "<font color='red' size='3'>"
BOLD = "<font color='bold' size='3'>"
BLUE = "<font color='blue' size='3'>"
CYAN = "<font color='cyan' size='3'>"
GREEN = "<font color='green' size='3... |
3cd11cebe241885faa1eefa55945f738c503a54c | cys9689/Election_Analysis | /PyPoll.py | 3,407 | 3.71875 | 4 | ## Chaining
import csv
import os
#Assign a variable to load a file from a path
file_to_load=os.path.join("Resources/election_results.csv")
with open(file_to_load) as election_data:
print(election_data)
#Assign a variable to save the file to a path
file_to_save=os.path.join("analysis","election_analysis.txt")
# 1. I... |
e6a202560ec2bec6f46c9dd087cdb7d34d5c1d13 | c0sta/estruturaDeDados | /EPs/EP1/EP1.py | 5,092 | 3.671875 | 4 | from random import shuffle
import random
import time
# Gera lista de acordo com o tamanho passado
def geraLista(n):
lista = list(range(n))
random.shuffle(lista)
return lista
# Algoritmo de Seleção
def seleção(lista):
vet = []
global contSelec
contSelec = 0
while list... |
fb9f9021232eab92ec5275c4541cbd0fd1f9a995 | kikihiter/swordAtOffer | /problem05ex.py | 392 | 3.640625 | 4 | #!user/nin/env python
# kiki 2018/09/22
# python problem05ex.py
def A2toA1(A1,A2):
left = 0
while left < len(A1) and len(A2) > 0:
if A2[0] < A1[left]:
A1.insert(left,A2[0])
print (A1)
del A2[0]
left += 1
A1.extend(A2)
return A1
if __name__ == "__main__":
A1 = [1,2,3]
A2 = [4,5,6]
... |
60e5f98c6dcd2ec1b991f5d86a3dcdeca04dc043 | chucvuive008/MineSweeper | /src/play.py | 2,275 | 3.84375 | 4 | from minesweeper import *
from tkinter import *
mine= MineSweeper()
mine.setGameBoard()
def make_board_game():
print(" ", end="")
for i in range(10):
print(str(i) + " ", end = "")
print("")
print("-----------------------------------------------")
for i in range (10)... |
139a8c92328a9f4ab7a7a8f659bad145cc710653 | RakshanaGovindarajan/BinarySearchTree | /TestBinaryTree.py | 6,359 | 3.734375 | 4 | # File: TestBinaryTree.py
# Description: Writing helper functions for binary trees
# Student Name: Rakshana Govindarajan
# Student UT EID: rg38236
# Course Name: CS 313E
# Unique Number: 50945
# Date Created: 27 April 2016
# Date Last Modified: 28 April 2016
class Queue (object):
def __init__ (self)... |
5a1e1f26f43ddeaedc02165a520a9801c6792eb4 | sanktoom/dz | /hw_8/task_1/__init__.py | 152 | 3.84375 | 4 | def acronym():
x = input('ввод: ')
p = 0
c = ''
for i in x.split():
c += i[p]
print('результат: ' + c.upper())
|
4717d11f6721f13beaf4e82b7c6bdb3e4e84f0da | xvoss/cryptochallenges | /challenge12_server.py | 2,920 | 3.59375 | 4 | """
Set 2: Byte-at-a-time ECB decryption (simple)
Open server that encrypts clients data with added secret text. The client's
goal is to decrypt the secret text only with repeated calls to the server.
"""
import os
import socket
import base64
import struct
from challenge9 import pkcs7_pad
from Crypto.Cipher import AES... |
aba9e9acb0072f9b1015650d826154de66397be1 | xvoss/cryptochallenges | /challenge5.py | 709 | 3.625 | 4 | """
set1: Implement repeating-key XOR
"""
import binascii
def xor(ptext, key):
""" repeating key XOR encryption, accepts only bytes"""
ctext = []
for i, b in enumerate(ptext):
c = b ^ key[i % len(key)]
ctext.append(c)
return bytes(ctext)
def main():
# given test input
input1... |
992e6ee0179e66863f052dce347c35e0d09b9138 | rowaxl/WAMD102 | /assignment/0525/factorial.py | 316 | 4.25 | 4 | def fact(number):
if number == 0:
return 1
if number == 1 or number == -1:
return number
if number > 0:
nextNum = number - 1
else:
nextNum = number + 1
return number * fact(nextNum)
number = int(input("Enter a number for calculate factorial: "))
print(f"{number}! = ", fact(number))
|
f538eae916794887d833f315b15681445e2d8fba | MiguelDelCastillo/GRUPO-31-Evidencia-1-Estructura-de-Datos | /Eq_EdD_GPO_31_CCKEM_Actualizado.py | 3,484 | 4 | 4 | from datetime import datetime
from collections import namedtuple
Datos = namedtuple("Ventas",("descripcion", "cantidad_pzas","precio_venta", "fecha"))
lista_ventas = []
diccionario_ventas = {}
while True:
print("\tLlantas Michelin")
print("")
print("1) Registrar una venta")
print("2) ... |
4b52d601646ac88a58de8e75d09481e65d758fa5 | seriousbee/ProgrammingCoursework | /src/main.py | 2,452 | 4.125 | 4 | def print_welcome_message():
print('Welcome to Split-it')
def print_menu_options():
menu_dict = {'About\t\t': '(A)', 'CreateProject\t': '(C)',
'Enter Votes\t': '(V)', 'Show Project\t': '(S)',
'Quit\t\t': '(Q)'}
for k, v in menu_dict.items():
print(f'{k} {v}') # not 100% w... |
ef789d4a52ef038d8432950be308997ea77b9749 | KatyaKalache/holbertonschool-higher_level_programming | /0x06-python-test_driven_development/5-text_indentation.py | 488 | 3.828125 | 4 | #!/usr/bin/python3
def text_indentation(text):
if not isinstance(text, str):
raise TypeError("text must be a string")
[i.strip for i in text.split(".")]
text = text.replace(". ",".\n\n")
text = text.replace(".",".\n\n")
[i.strip for i in text.split("?")]
text = text.replace("? ","?\n\n")... |
f1a1fcf2223a9c2d62512e0864d98ed8d37447e9 | KatyaKalache/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 172 | 3.90625 | 4 | #!/usr/bin/python3
class MyList(list):
list = []
def print_sorted(self):
MyList.list.append(self)
for i in self.list:
print(sorted(i))
|
79cbfaa31fc2b38b4107f2f3b92aadc20e1fdf16 | CUXIDUMDUM/python-tutorial | /pyintro_c_extra/exception_b_example.py | 570 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
# exception example
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
pri... |
81e152c3a2374be8632dabd9a0b7e947507b7ec5 | vikastv18/newimp | /ss.py | 575 | 3.8125 | 4 | import random
words = ['hello', 'what', 'buddy']
word = random.choice(words)
allowerd_errors = 7
guessess =[]
done = False
while not done:
for letter in word:
if letter in guessess:
print(letter)
else:
print("_")
guess = input("enter the char: ")
guessess.append(gu... |
d60ce1dada99b234ac9eaf94e2e59826656e048b | Abhirashmi/Python-programs | /Faulty_calculator.py | 934 | 4.3125 | 4 | op = input("Enter the operator which you want to use(+,-,*,/):")
num1 = int(input("Enter 1st Number:"))
num2 = int(input("Enter 2st Number:"))
if op == "+":
if num1 == 56 or num1 == 9:
if num2 == 9 or num2 == 56:
print("Addition of", num1, " and", num2, " is 77")
else:
print(... |
5512636bd9448f5548e32df1cf1c54a75e3b4c59 | DongxuanLee/leetcode_easy | /findDisNum.py | 557 | 3.609375 | 4 | def findDisappearedNumbers(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# n = len(nums)
# disappear = []
# for i in range(1,n+1):
# if i not in nums:
# disappear.append(i)
# return disappear
for i in range(len(nums)):
n = abs(nums[i])
num... |
7f562230dfe43b750fc25a0c4b5eb3cc10a6a455 | DongxuanLee/leetcode_easy | /maxSubArray.py | 316 | 3.875 | 4 | def maxSubArray( nums):
"""
:type nums: List[int]
:rtype: int
"""
sum = 0
list = []
for i in nums:
sum = i +sum
if sum <0:
sum = 0
list.append(sum)
print(max(list))
if __name__ == "__main__":
nums = [-2,1,-3,4,-1,2,1,-5,4]
maxSubArray(nums) |
859ce41ff1ae3e13c97a36efb77e924d984f6d67 | gathanei/mastermind | /play.py | 6,222 | 3.59375 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 21 22:01:42 2018
@author: thaneig
"""
import numpy as np
from collections import Counter
import warnings
from random import shuffle
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
colors = ["white", "black", "yellow", "o... |
ed02489854449be24b9d51b157e940262d4327ee | dzwiedz90/Tic-tac-toe | /TicTacToe.py | 3,729 | 3.796875 | 4 | import os
import players
import tictactoeMainMenu
tictactoeMainMenu.main()
#przerobić na słownik
f = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
# a1 a2 a3 b1 b2 b3 c1 c2 c3
# 0 1 2 3 4 5 6 7 8
players = players.playerName()
print('Hello '+players[0]+', you will be X, hello '+players[1]+',... |
1e8fbac81e66954d0e5572734136888b43467fd0 | tanyaphung/popgen_scripts | /compute_divergence/parse_args.py | 1,335 | 3.625 | 4 | def parse_args():
"""
Parse command-line arguments
:return:
"""
parser = argparse.ArgumentParser(description="This script computes the number of sites that are different between"
"two species in each line of the BED file. "
... |
d4e5ffa0ae06223f1b7d91cbd807a6f429cb1f4f | qianjinfighter/py_tutorials | /earlier-2020/python_mod_tutorials/built-in_fn.py | 2,170 | 3.828125 | 4 | # coding:utf-8
"""
Test for built-in function
"""
import os
class A(object):
bar = 1
class model(object):
def __init__(self):
self.a = 11
def call(self,s):
print self.a , s
def main2():
# 这个只有在新式类中才有的,对于对象的所有特性的访问,都将会调用这个方法来处理。。。可以理解为在__getattr__之前
class Fjs(object):
... |
4d5d390da43a54b02d874ef6bf3f8c91deb1d434 | qianjinfighter/py_tutorials | /earlier-2020/python_mod_tutorials/with_f.py | 1,305 | 3.734375 | 4 | #!/usr/bin/env python
#coding:utf-8
# with_example01.py
class Sample:
def __enter__(self):
print "In __enter__()"
return "Foo"
def __exit__(self, type, value, trace):
print "In __exit__()"
def get_sample():
return Sample()
with get_sample() as sample:
print "sam... |
cda7433a23b977e754e2f493cf0f5583b6be2267 | qianjinfighter/py_tutorials | /earlier-2020/python_mod_tutorials/property_t.py | 598 | 3.5 | 4 | #coding:utf-8
class Student(object):
def __init__(self):
self._birth = 1 # 如果初始化了self._birth 则可以直接输出,否则会报错没有这个值
self._height = 180
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value
@property
def age(sel... |
18c271cc6a83f2402125fe692919b625e2af5265 | shants/LeetCodePy | /225.py | 1,627 | 4.125 | 4 | class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = []
self.q2 = []
self.isFirst = True
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
... |
2718891097748a95dfd5e8235ba479dd264c4034 | shants/LeetCodePy | /814.py | 1,105 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getValue(self, root):
if root is None:
return 0
l = 0
r = 0
if root.left... |
523ae2a2668a3105adf1ac5aee74c3affa0dff3c | shants/LeetCodePy | /45.py | 526 | 3.609375 | 4 | class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 0
i=0
jumps = 0
end = 0
e = 0
n = len(nums)-1
if (len(nums)==0 or len(nums)==1):
return 0
for i in range(0,n):
... |
28a12882127370356a48995e7f3b86153e22eede | shants/LeetCodePy | /802.py | 753 | 3.546875 | 4 | class Solution(object):
def eventualSafeNodes(self, graph):
def dfs(node, path, visited, cycle):
if visited[node] == 1 or node in cycle:
cycle |= set(path)
elif visited[node] == 0:
path.append(node)
visited[node] = 1
for... |
dc07853fc2edec664a842ee27bae95519cef50b7 | shants/LeetCodePy | /872.py | 974 | 3.96875 | 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 __init__(self):
self.l1 = []
self.l2 = []
def traverse(self, root, l):
if root is None:
retu... |
282fe20b10e865314dee2a7e124d08c7c86b00ce | shants/LeetCodePy | /606.py | 854 | 3.890625 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.ans = ""
def dfs(self, root):
if root is None:
return ""
if root.left is None and root.right is No... |
2fadeecad4cbe1e14f4b08495785a0f5ed70354f | shants/LeetCodePy | /1029.py | 411 | 3.53125 | 4 | class Solution(object):
def twoCitySchedCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
c = sorted(costs, key = lambda x: x[0]-x[1])
return sum([cost[0] for cost in c[:len(c)//2]]) + sum([cost[1] for cost in c[len(c)//2:]])
if __name__ == "__mai... |
bd7de5693427f3de5d6bd576d7056c0ed6aa7163 | shants/LeetCodePy | /27.py | 806 | 3.5625 | 4 | class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums)==0:
return 0
if len(nums)==1 and nums[0]==val:
return 0
if len(nums)==1 and nums[0]!=val:
... |
7c836542bc014f996a9bfac3bddbbf2ca0662de3 | shants/LeetCodePy | /409.py | 517 | 3.671875 | 4 | from collections import Counter
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
c = Counter(s)
# print(c)
even = 0
odd = 0
for k, v in c.items():
even += int(v / 2)
odd += v % 2... |
e5e887cf370d11736f08f2f3b70b9592172af57e | shants/LeetCodePy | /442.py | 471 | 3.515625 | 4 | class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
for i in range(len(nums)):
if nums[abs(nums[i])-1]<0:
ans.append(abs(nums[i]))
else:
k = abs(nums[i... |
26ec0ef981680241f65e58902ff5fe49944b8b3a | shants/LeetCodePy | /143.py | 1,771 | 4.03125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def printNone(self, head, c="-"):
print(c*5)
while(head is not None):
print(head.val)
head=head.next
print(c ... |
2ed4a1f874102ecfdbdc02f6733fee807228a6ca | shants/LeetCodePy | /797.py | 792 | 3.53125 | 4 | class Solution(object):
def __init__(self):
self.path = []
def dfs(self, u, graph, visited, path):
if u == len(graph)-1:
p = path[:]
p.append(u)
self.path.append(p)
else:
visited[u]=1
path.append(u)
for v in graph[u... |
ec83ab7aad9254327d18f1a2d5238c7ec1bb895f | shants/LeetCodePy | /102.py | 1,349 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root i... |
e4e5ba06d8ebfb2cf66b1b5d561888e0be9705c2 | shants/LeetCodePy | /118.py | 576 | 3.515625 | 4 | class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows==0:
return []
if numRows==1:
return [[1]]
if numRows ==2:
return [[1],[1,1]]
ans = [[1],[1,1]]
... |
e8d6960127fca1b93d14fe13f09e7e53451ace19 | shants/LeetCodePy | /37.py | 2,175 | 3.75 | 4 | class Solution(object):
def __init__(self):
self.d = 0
def check_block(self, board, r,c,x):
r1 = (int(r/3))*3
c1 = (int(c/3))*3
canAdd = True
for i in range(3):
for j in range(3):
if board[r1+i][c1+j]==str(x):
return False
... |
267b69941974a20763ab70a0395af718defaa413 | shants/LeetCodePy | /215.py | 499 | 3.8125 | 4 | import heapq
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
heap = []
for i in range(k):
heap.append(nums[i])
heapq.heapify(heap)
for i in range(k,len(nums)):
i... |
4fceca18744ecab1b7b128f95eaaf2a98dc64953 | Theesawan89/CP3_Theesawan_Sae-ng | /exercise_return_TheesawanS.py | 155 | 3.875 | 4 | totalPrice=float(input("total="))
def VatCalculate(totalPrice):
Result=totalPrice+(totalPrice*7/100)
return Result
print(VatCalculate(totalPrice)) |
93b9ec668c77ede6d706da4e475eff222c3fa3ae | uplyw/Python_Crash_Course | /chapter8/8.3return_value.py | 3,251 | 4.28125 | 4 | # 返回简单值
# def get_formatted_name(first_name,last_name):
# full_name = first_name + ' ' + last_name
# return full_name.title()
# musician = get_formatted_name('li', 'lei')
# print(musician)
# 让实参可选
# def get_formatted_name(first_name,last_name,middle_name = ''):
# if middle_name:
# full_name = first_name + ' ' + m... |
9aa911ad1630ef1ab81b0459139fe8e515432a25 | uplyw/Python_Crash_Course | /chapter10/10.1read_file/pi_string.py | 324 | 3.75 | 4 | filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
# print(pi_string[:52] + '...')
# print(len(pi_string))
birthday = input("enter your birthday:")
if birthday in pi_string:
print('yes')
else:
print('... |
13275692e67a41581586c0221b9438fb8153417c | uplyw/Python_Crash_Course | /chapter11/11.1test_function/names.py | 292 | 4 | 4 | from name_function import get_formatted_name
print("enter 'q' to quit" )
while True:
first = input("your first name:")
if first == 'q':
break
last = input("your last name:")
if last == 'q':
break
formatted_name = get_formatted_name(first, last)
print("fullname:" + formatted_name) |
16e49101c58c555e4ef3ec134f008d5043658b94 | uplyw/Python_Crash_Course | /chapter4/4.5tuple.py | 398 | 4 | 4 | #元组
#元组是不可变的列表
#和列表不同的是元组使用圆括号来标识,而非方括号
fruits = ('banana','apple','orange','kiwi','coco')
print(fruits)
print(fruits[2])
print(fruits[4])
#元组是不可变的 因此改变元组内的元素是会报错
# fruits[1] = 'qqqq'
#不过可以通过改变元组的整体 来改变
fruits = ('aaa','bbb','ccc','ddd')
print(fruits) |
b8e627e0d0825126e22412a75a8a6b7f9a2676d8 | mmasso/Exercicis-Codewars-Python | /Sudoku Codewars/checkTresxTres.py | 1,143 | 3.78125 | 4 | def checkTresxTres(sudoku):
assert isinstance(sudoku, list)
if len(sudoku) == 9:
tresXtres = []
contador = 0
for fila in sudoku:
if fila not in tresXtres:
tresXtres.append(fila[0:3])
contador = contador + 1
if contador == 3... |
69a2fb67776f545580a46c6ae620bae380771611 | pentaclexyz/love-triangles | /ancient-scripts/MandelbrotInPythonAndTk.py | 3,674 | 4.25 | 4 | #!/usr/bin/env python
# 140211 Raoul Meuldijk
# http://en.wikipedia.org/wiki/Mandelbrot_set
def mandel(x0, y0):
""" Iterate the Mandelbrot function, returns the number of
iterations until x^2 + y^2 > 4 or 200 iterations.
"""
x = 0
y = 0
iteration = 0
max_iteration = 200
while ( x*x + y*y <= (2*2) and itera... |
84fb02ae6dafe7d2dca728b42400cf769eb8be99 | HarshitCodex/Python_mini_projects | /random_num.py | 382 | 4.03125 | 4 | import random
print("Welcome people. I am Harshit trying to learn python .\n Lets play a game to generate random number ")
r = random.randint(1, 100)
print("Guess the number I have generated randomly from 1-100 inclusive ")
u = input("Enter your guess ")
u = int(u)
if r == u:
print("Your answer is right : " + str(r... |
24e002cda0a15537da36d599f19eef995a4fc823 | charignon/financier | /tests/test_salary.py | 739 | 3.609375 | 4 | """Tests for the Salary component"""
import datetime
from financier.components import Salary
def test_salary_pay_per_day():
"""Check that the pay per day is computed properly"""
assert Salary(yearly_amount=365000).pay_per_day() == 1000
def test_salary_value():
"""Check that the value over date ranges is... |
867c61b4b7828542395c2b952e095ca84fe01d91 | ParadigmHyperloop/testing-software | /Pidaq/Examples/Multiprocessing/pipe_example.py | 2,462 | 3.71875 | 4 | """ pipe_example.py
Proof of Concept - Controlling a process from another process using a pipe
This example demonstrates the control of one process from another using a Pipe.
The process would be very similar if using a Pool/Queue/Duplex pipe.
In this example the active_test thread controls the telem thread by sendin... |
51beafe2097e063262ed4404fb1bb6f7aa2e37c7 | SonBui24/Python | /Lesson07/Bai06.py | 240 | 3.53125 | 4 | list_ = ['pip', 'pyp', 'sad', 'funny', 'a', 'v']
count = 0
for i in list_:
if len(i) >= 2 and i[0] == i[-1]:
count += 1
print(f"Số chuỗi có 2 ký tự trở lên và ký tự cuối giống ký tự đầu là: {count}")
|
c562540d21cf51db344b871c6e344b3418b7fa96 | SonBui24/Python | /Lesson12/Bai05.py | 189 | 3.625 | 4 | n = int(input("nhập vào n : "))
with open('test.txt', 'r', encoding='utf-8') as f:
for i in range(n):
line = f.readline().rstrip("\n")
print(f'Dòng {i+1}: {line}')
|
4998f4b7d9ed310ac7d88cd98bbb883b54af1ff2 | SonBui24/Python | /Lesson08/Bai02.py | 77 | 3.765625 | 4 | my_tuple = (1, 2, 3, 'a', 'b')
new_tuple = my_tuple[::-1]
print(new_tuple)
|
04437e7c6ed55fd4c44bb154d256026fa91a5ce0 | SonBui24/Python | /Lesson06/Bai07.py | 642 | 3.640625 | 4 | def body_mass_index(m, h):
bmi = m / (h * 2)
return bmi
def bmi_infomation(body_mass_index):
if body_mass_index < 18.5:
print(f'BMI: {body_mass_index} - Gầy')
elif 18.5 < body_mass_index < 24.9:
print(f'BMI: {body_mass_index} - Bình thường')
elif 25 < body_mass_index < 29.9:
... |
6cd58d2ac014fe2bf9b769c6313c3b93f7a07dd0 | SonBui24/Python | /Lesson09/Bai06.py | 179 | 3.71875 | 4 | my_dict = {
1: 5,
2: 4,
3: 3,
4: 2
}
a = sorted(my_dict.values())
b = a[-3:]
c = set()
for i, o in my_dict.items():
if o in b:
c.add((i, o))
print(c)
|
b224f43b1c90dab4be29281b3b37ba46dd60160b | a-j/advent-of-code | /2019/day01/puzzle1.py | 194 | 3.640625 | 4 | def fuel_needed_for_module(mass):
return (mass//3) - 2
with open('input.txt') as file:
sum = 0
for line in file:
sum = sum + fuel_needed_for_module(int(line))
print(sum) |
b3f97efca60a1045cb9aa6f71622280902830797 | jmg0137/3D-Viewer-v2.0 | /Resources/ply_utils/__init__.py | 1,708 | 3.609375 | 4 | """
Make the user able to correct a PLY file entirely with a command.
"""
from __future__ import print_function
def process_ply_file(filename, force_encoding=None):
"""
Processes a PLY file and stores it with the appropiated encoding.
"""
from .PARSER import parse_all
from .CORRECTOR import correct... |
0546fc2ca0c26be550d4fb2f5a059ac63e4966cf | samjwu/Brain-Teasers | /autori.py | 164 | 3.609375 | 4 | names = input().split("-")
numnames = len(names)
shortvariation = ""
for i in range(0, numnames):
shortvariation += names[i][0].upper()
print(shortvariation)
|
b6c5d31df3d771d8db8a9498141b8256c90268af | ecly/junkcode | /wordle/wordle.py | 2,548 | 3.625 | 4 | """Small script for finding optimal word combinations for wordle.
In this case we define optimal as 5 words with no overlapping characters
yielding a total coverage of 25 characters after the 5 words.
The script has an added element of randomness, by allowing it to sometimes
choose a suboptimal word, so rerunning the... |
87078f08cd48dd2371dad7609fd6069280381200 | Ashish138200/Hackerrank | /Scripts/WavePrint.py | 346 | 3.796875 | 4 | z=input()
l0=list(z.split(" "))
m=int(l0[0])
n=int(l0[1])
l=[]
for i in range(m): # A for loop for row entries
a =[]
for j in range(n): # A for loop for column entries
a.append(input())
l.append(a)
# For printing the matrix
for i in range(m):
for j in range(n):
print(l[i][... |
2637aa0a95fea8e3140341353d2cd3b3fae656cc | gurudurairaj/gp | /rmvspac.py | 123 | 3.5 | 4 | a=input()
a=list(a)
i=0
while i<len(a):
if a[i]==" ":
a.remove(a[i])
i=i-1
i=i+1
print("".join(a))
|
311dd9ad798a9408afaa1cdfbf50d88c0c998d89 | KDraco/Python-2018 | /magic 8 ball project idle file 8.py | 787 | 3.78125 | 4 | import random
import time
answers = ["you will have no luck in finding out even from me" , "you should spend your time on something with more importance" , "all will be revealed in time" , "to find the answers you must walk the long difficult road" , "ask yourself the question most likley you already know the answer"]... |
8ef099fb55bcc641a948b6d2c2a4ed26d0cc7b58 | usr-bin32/cn-p2 | /integrals/simpson38.py | 595 | 3.65625 | 4 | import math
def integral(f, a, b):
h = (b - a) / 3
return (3 * h / 8) * (f(a) + 3 * f(a + h) + 3 * f(a + 2 * h) + f(b))
def repeated_integral(f, a, b, m):
def c(i):
if i == 0 or i == m:
return 1
elif i % 3 == 0:
return 2
else:
return 3
if ... |
ade68d54dc2872f704f67cf5673777bb7736356b | Cutwell/python-auto-gui | /tests/adventure.py | 2,467 | 3.609375 | 4 | import logging
import random
from pythonautogui import print, input, run, clear
run()
if __name__ == "__main__":
logging.basicConfig(format='%(asctime)s - %(message)s',
level=logging.DEBUG)
characters = ["an adventurer", "a wizard", "a princess", "a tax collector"]
# random charac... |
d06b6d3d1a5790a0101985203ddda38fd20da4d6 | jenkwang/Othello | /othello_game_logic.py | 6,907 | 3.75 | 4 | #Jenny Chong 23733553 Lab Section 8
NONE = 0
BLACK = 'B'
WHITE = 'W'
class InvalidMoveError(Exception):
'''Raised when an invalid move is made'''
pass
class GameOverError(Exception):
'''Raised when game is over but attempt to make a move occurs'''
pass
class GameState():
def __ini... |
be4579851af7ea20e3ed8cfeeeb0e493426273c4 | mayankkuthar/GCI2018_Practice_1 | /name.py | 239 | 4.28125 | 4 | y = str(input(" Name "))
print("Hello {}, please to meet you!".format(y))
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = y
print ("Did you know that your name backwards is {}?".format(reverse(s))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.