blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
67341965a301d547ba5422c3d1e256a2f513999b | JoaolSoares/CursoEmVideo_python | /Exercicios/ex020.py | 360 | 3.5625 | 4 | from random import shuffle
a1 = input('Diga o nome de um aluno: ')
a2 = input('Diga o nome de um aluno: ')
a3 = input('Diga o nome de um aluno: ')
a4 = input('Diga o nome de um aluno: ')
lista = [a1, a2, a3, a4]
shuffle(lista)
print('')
print('{:-^70}' .format(''))
print('A ordem escolhida foi: {}' .format... |
bc0e0a3075ea950cf67bc7bfe44201842624a81f | JoaolSoares/CursoEmVideo_python | /Exercicios/ex029.py | 223 | 3.71875 | 4 | n1 = int(input('Qual foi sua velocidade: '))
if n1 <= 80:
print('PARABENS! Por nao ter utrapassado o limite de 80km/h')
else:
print('ISSO NÃO FOI LEGAL! Você recebera uma multa de R${}' .format((n1 - 80) * 7)) |
fc95289439761478c89aaef10340dd1c0c149a36 | wangchengww/great-ape-Y-evolution | /palindrome_analysis/palindrome_read_depth/calculate_copy_number/Palindrome_scripts/line_up_columns.py | 4,441 | 3.609375 | 4 | #!/usr/bin/env python
import sys
def parse_columns(s):
if (".." in s):
(colLo,colHi) = s.split("..",1)
(colLo,colHi) = (int(colLo),int(colHi))
return [col-1 for col in xrange(colLo,colHi+1)]
else:
cols = s.split(",")
return [int(col)-1 for col in cols]
# commatize--
# Convert a numeric string into one ... |
ebbffeb694f13ec4d1d5282089eb228a9709a422 | jet76/CS-4050 | /Project 04/SumsToN.py | 346 | 3.875 | 4 | def recurse(num, sum, out):
if sum > n:
return
else:
sum += num
if sum == n:
print(out + str(num))
return
else:
out += str(num) + " + "
for i in range(num, n + 1):
recurse(i, sum, out)
n = int(input("Enter a positive integer: "))
for i in range(1, n +... |
d6e556e4afd34c6a8056dfa1df965ba5f6fd5c48 | Z477/concurrent-program | /2_multi_threading/demo_5_threadpoolexecutor.py | 1,533 | 3.640625 | 4 | #!/usr/bin/env python
# encoding: utf-8
'''
Use concurrent.futures to implement multi thread
Created on Jun 30, 2019
@author: siqi.zeng
@change: Jun 30, 2019 siqi.zeng: initialization
'''
import concurrent.futures
import logging
import time
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s [line:... |
ebd6f80484ef4a051fadde4199f8b27c366fa283 | JMSMonteiro/AED-Proj2 | /src/gui.py | 7,450 | 3.75 | 4 | from tkinter import *
from tkinter import messagebox
import main
########## FUNCTIONS JUST TO HAVE TEXT/CLEAR TEXT FROM THE ENTRIES ##########
#Still looking for a way to make all of these into 2 functions
def on_entry_click_0(event): #Cities Entry
"""function that gets called whenever entry is clicked"""
entry_c... |
8ed94e5a5bc207a34271e2bb52029d7b6b71870d | darlenew/california | /california.py | 2,088 | 4.34375 | 4 | #!/usr/bin/env python
"""Print out a text calendar for the given year"""
import os
import sys
import calendar
FIRSTWEEKDAY = 6
WEEKEND = (5, 6) # day-of-week indices for saturday and sunday
def calabazas(year):
"""Print out a calendar, with one day per row"""
BREAK_AFTER_WEEKDAY = 6 # add a newline after ... |
ab7b1bc5da6df5746bed215e196f2208301570df | jonathan-mcmillan/python_programs | /asdf;lkj.py | 1,126 | 3.5 | 4 | from cs1graphics import *
numLevels = 8
unitSize = 12
screenSize = unitSize * (numLevels + 1)
paper = Canvas(screenSize, screenSize)
for level in range(numLevels):
centerX = screenSize / 2
leftMostX = centerX - unitSize / 2 * level
centerY = (level +1) * unitSize
for blockCount in range(level +1):
... |
e96bfc80489c56a2fef2d71ca5ae417f6738a539 | jonathan-mcmillan/python_programs | /notes_2⁄1.py | 591 | 3.671875 | 4 | groceries=['eggs','ham','toast','juice']
for item in groceries:
print item
count = 1
for item in groceries:
print str(count)+')'+item
count += 1
a = [6,2,4,3,2,4]
n=0
print a
for e in a:
a[n]= e*2
n +=1
print a
for i in range(len(a)):
a[i] *= 2
print a
m = [[3,4],[2,1]]
for i in range... |
7a3e2fb304cbb15c640e17841da60543e46e95eb | emrache/Python_600x | /Problem Set 9/ps9.py | 2,824 | 3.65625 | 4 | # 6.00 Problem Set 9
import numpy
import random
import pylab
from ps8b_precompiled_27 import *
#
# PROBLEM 1
#
def simulationDelayedTreatment(numTrials):
"""
Runs simulations and make histograms for problem 1.
Runs numTrials simulations to show the relationship between delayed
treatment and pa... |
85c0cb7b1fb3da5a3e4f20d60d1a55ca1576aad3 | rorjackson/Jack | /tkintergui.py | 553 | 3.9375 | 4 | from tkinter import *
win = Tk()
win.geometry('200x100')
name = Label(win, text="Name") # To create text label in window
password = Label(win,text="password")
email = Label(win, text="Email ID")
entry_1 = Entry(win)
entry_2 = Entry(win)
entry_3 = Entry(win)
# check = CHECKBUTTON(win,text ="keep me logged in")
nam... |
d86ab402a950557261f140137b2771e84ceafbbe | priyankagarg112/LeetCode | /MayChallenge/MajorityElement.py | 875 | 4.15625 | 4 | '''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
'''
from t... |
92bbf967afbb85b943c9af46bde946b2d0d9fdf9 | tusshar2000/DSA-Python | /graphs/dfs_cycle_directed_graph.py | 2,502 | 3.71875 | 4 | # https://leetcode.com/problems/course-schedule/
from collections import defaultdict
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# defaultdict(list) makes work easier
graph = defaultdict(list)
# we need to have eve... |
5b9cd3610bf26e71e74df0a4a869b3969382b5ac | tusshar2000/DSA-Python | /graphs/word-search-using-dfs.py | 1,993 | 3.71875 | 4 | # https://leetcode.com/problems/word-search/
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
col = len(board[0])
row = len(board)
len_of_word = len(word)
is_possible = False #starting with it's not possible to form the string.
visited = ... |
78b22399df13bda1fa6519d86a1192cf358f6e87 | tusshar2000/DSA-Python | /binary tree/max_depth_of_n-ary_tree.py | 599 | 3.75 | 4 | https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
#BFS
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
... |
1e190699791483acd663a85db438602a6169e360 | kp646576/Simple-Compiler | /lexer.py | 4,596 | 3.625 | 4 | import sys
from scanner import Scanner
from token import Token
from symbolTable import symbolTable as st
def isAlpha(c):
if c:
c = ord(c)
return True if c >= 65 and c <= 90 or c >= 97 and c <= 122 else False
def isDigit(c):
if c:
c = ord(c)
return True if c <= 57 and c >= 48 else Fals... |
5fbf2ff1591bdc0a50b2ad9758cf806bf7e4f6e8 | ttsiodras/VideoNavigator | /menu.py | 5,600 | 3.71875 | 4 | #!/usr/bin/env python
"""
A simple Pygame-based menu system: it scans folders and collects the single
image/movie pair within each folder. It then shows the collected pictures,
allowing you to navigate with up/down cursors; and when you hit ENTER,
it plays the related movie.
The configuration of folders, resolutions, ... |
f03de31739574749ee56fabdeffdb43e0dc9229b | divannn/python | /math/sort_util.py | 71 | 3.546875 | 4 | def swap(list, i, j):
tmp = list[i]
list[i] = list[j]
list[j] = tmp
|
61329cb09135f5634b1c64baa1db566836929a26 | shivamach/OldMine | /HelloWorld/python/strings.py | 527 | 4.375 | 4 | print("trying basic stuff out")
m1 = "hello"
m2 = "World"
name = "shivam"
univ = "universe"
print(m1,", ",m2)
print(m1.upper())
print(m2.lower())
message = '{}, {}. welcome !'.format(m1,m2.upper())
print(message)
message = message.replace(m2.upper(),name.upper())
#replacing with methods should be precise
print(messag... |
433027b761e728e242c5b58c11866208fe39ca23 | caesarbonicillo/ITC110 | /quadraticEquation.py | 870 | 4.15625 | 4 | #quadratic quations must be a positive number
import math
def main():
print("this program finds real solutions to quadratic equations")
a = float(input("enter a coefficient a:"))
b = float(input("enter coefficient b:"))
c = float(input("enter coefficient c:"))
#run only if code is great... |
12c96ea6817d91f8d488f13c119752f747971c94 | caesarbonicillo/ITC110 | /Temperature.py | 496 | 4.125 | 4 | #convert Celsius to Fehrenheit
def main(): #this is a function
#input
celsius = eval (input ("Enter the temp in Celsius ")) #must convert to number call function EVAL
#processing
fahrenheit = round(9/5 * celsius + 32, 0)
#output
print (celsius, "The Fehrenheit temp is", fahrenheit)
m... |
27cf55f0f342a4cf7747f3ee7a13e56c5d91bfcc | loganwastlund/cs1410 | /frogger_assignment/froggerlib/frog.py | 675 | 3.546875 | 4 | from froggerlib.player_controllable import PlayerControllable
class Frog(PlayerControllable):
def __init__(self, x=0, y=0, w=0, h=0, dx=0, dy=0, s=0, hg=0, vg=0):
PlayerControllable.__init__(self, x, y, w, h, dx, dy, s, hg, vg)
return
def __str__(self):
s = "Frog<"+PlayerControllable.... |
a48246d152225d226d01bf5139ede5ec88149989 | loganwastlund/cs1410 | /frogger_assignment/froggerlib/truck.py | 551 | 3.71875 | 4 | from froggerlib.dodgeable import Dodgeable
import random
class Truck(Dodgeable):
def __init__(self, x=0, y=0, w=0, h=0, dx=0, dy=0, s=0):
Dodgeable.__init__(self, x, y, w, h, dx, dy, s)
return
def __str__(self):
s = "Truck<"+Dodgeable.__str__(self)+">"
return s
def __repr... |
ad3dcc55ba5993e6e902723f5b4170a259276530 | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance/test_main_getUserFloat.py | 3,461 | 3.84375 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import sys
if sys.version_info.major != 3:
print('You must use Python 3.x version to run this unit test')
sys.exit(1)
import unittest
import main
class TestGetUserFloat(unittest.TestCase):
def input_replacement(self,... |
e72a2b169ddeb44b6c3ab9ee24d4818dbdc89e79 | loganwastlund/cs1410 | /isbn_assignment/isbnTests/test_findBook.py | 1,205 | 3.765625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
from isbnTests import isbn_index
class test_findBook( unittest.TestCase ):
def setUp(self):
return
def tearDown(self):
return
def test001_findBookExists(self):
self.as... |
5f7d558e0dc80f651c1b1fbc79b3748f17451b2c | loganwastlund/cs1410 | /asteroids_assignment/test_all_asteroids_part1/test_005_rock_004_createRandomPolygon.py | 3,624 | 3.515625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import math
import rock
class TestRockCreatePolygon( unittest.TestCase ):
def setUp( self ):
self.expected_x = 100
self.expected_y = 200
self.expected_dx = 0.0
self.expected_dy =... |
a99ebf6cc65ac45f0837c615de75e10ccc3cbc72 | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance/test_main_eatFoodAction.py | 5,507 | 3.59375 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import sys
if sys.version_info.major != 3:
print('You must use Python 3.x version to run this unit test')
sys.exit(1)
import unittest
import re
import main
class TestEatFoodAction(unittest.TestCase):
def input_replace... |
def3e215af2f9d8c874d14ecba1b4b07cc233b4e | loganwastlund/cs1410 | /gas_mileage_assignment/gas_mileage/test_listTripsAction.py | 2,919 | 3.5625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import gas_mileage
class TestListTripsAction(unittest.TestCase):
def input_replacement(self, prompt):
self.assertFalse(self.too_many_inputs)
self.input_given_prompt = prompt
r = self.inp... |
5465a46981d4b4632a15d7003e2bf3b0c11aab1a | loganwastlund/cs1410 | /in_class/notes.py | 3,113 | 4.09375 | 4 | # dictionaries
d = {'key': 'value', 'name': 'Logan', 'id': 123, 'backpack': ['pencil', 'pen', 'pen', 'paper']}
d['name'] = 'John'
# how to update a key ^
d['dob'] = '01-17-18'
d['dob'] = '01-18-18'
# keys can be integers, strings, variables, but not lists. The value can be anything
print(d['backpack'][2])
# prints ... |
bef3086fbcdad462844ab8c80437366d2517b10c | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance.py | 883 | 3.546875 | 4 |
class CaloricBalance:
def __init__(self, gender, age, height, weight):
self.weight = weight
bmr = self.getBMR(gender, age, height, weight)
self.balance = bmr - (bmr * 2)
def getBMR(self, gender, age, height, weight):
bmr = 0.0
if gender == 'm':
bmr = 66 + ... |
a7ea4875f924aceeb06f252fa4d38313c6042436 | loganwastlund/cs1410 | /gas_mileage_assignment/gas_mileage/test_recordTrip.py | 2,457 | 3.8125 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import random
import gas_mileage
class TestRecordTrip(unittest.TestCase):
def test001_recordTripExists(self):
self.assertTrue('recordTrip' in dir(gas_mileage),
'Funct... |
3e419aa050aed59a0a9a5941f69cba22375eacc5 | TobiAdeniyi/hacker-rank-problems | /Algorithms/Implementation/ClimbingTheLeaderboard.py | 848 | 4 | 4 | """
An arcade game player wants to climb to the top of the leaderboard and track their
ranking. The game uses Dense Ranking, so its leaderboard works like this:
• The player with the highest score is ranked number on the leaderboard.
• Players who have equal scores receive the same ranking number, and the
next ... |
d6c282c0e9b51b97f6aa30d44b96ecd2fd9e405f | TobiAdeniyi/hacker-rank-problems | /Algorithms/Implementation/DesignerPDFViewer.py | 795 | 4.0625 | 4 | import os
"""
Sample Input
------------
1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
abc
Sample Output
-------------
9
"""
def designer_viewer(h: list, word: str) -> int:
# 1) Convert word to lower case
word = word.lower()
# print(word)
# 2) Convert word to unicode representation - 97
c... |
fc16775fecae5b5b59885cdde7f6a5c4dcaf7ecf | BrandonIslas/Curso_Basico_Python | /ejemplo3CondicionalesCompuestas.py | 297 | 3.875 | 4 | sueldo1= int(input("Introduce un sueldo1: "))
sueldo2= int(input("Introduce un sueldo2: "))
if sueldo1 > sueldo2:
print("El sueldo1 "+ str(sueldo1)+ " es mayor que el sueldo2 ("+str(sueldo2) +")")
else:
print("El sueldo1 ("+ str(sueldo1)+ ") es menor que el sueldo2 ("+str(sueldo2) +")")
|
21385d2bce3d5ddfb79334cc1a274e108932d0f7 | BrandonIslas/Curso_Basico_Python | /Listas1.py | 993 | 3.984375 | 4 | lista=[] #DECLARACION DE LA LISTA
for k in range(10):
lista.append(input("Introduce el "+str(k)+" valor a la lista:"))
print("Los elementos de la lista son:"+str(lista))
valor=int(input("Introduce el valor a modificar de la lista por el indice"))
nuevo=input("Introduce el nuevo valor:")
lista[valor]=nuevo#MODIFICA... |
db6decc20f095d23d6842efef66cc0de5fbb6893 | BrandonIslas/Curso_Basico_Python | /ProgramacionOrientadaaObjetos/FuncionalidadModuloAs.py | 212 | 4.03125 | 4 | from math import sqrt as raiz, pow as exponente
dato=int(input("Ingrese un valor entero: "))
raizcuadrada=raiz(dato)
cubo=exponente(dato,3)
print("La raiz cuadrada es: ",raizcuadrada)
print("El cubo es: ",cubo)
|
5b080ee8d026affda640ab1284aafe4464329621 | BrandonIslas/Curso_Basico_Python | /ejemplo6While2.py | 286 | 3.875 | 4 | #Ejercicio while 2
cantidad=0
x=1
n=int(input("Cuantas piezas cargara:"))
while x<=n:
largo=float(input("Ingrese la medida de la ( " +str(x) +" ) pieza"))
if largo>=1.2 and largo<=1.3:
cantidad=cantidad+1
x=x+1
print("La cantidad de piezas aptas son"+str(cantidad))
|
e2c69c7053081eb29da7875b1ae37122d8ad1f25 | yukiii-zhong/Leetcode | /Linked List/138. Copy List with Random Pointer.py | 1,444 | 4.09375 | 4 | # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rt... |
15069d7c114bbac94c1eba39fd0c67da4588b56d | yukiii-zhong/Leetcode | /Linked List/24. Swap Nodes in Pairs.py | 1,289 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue... |
906f40cc6ff0bd3eb51af097f84ae975e7ac3957 | yukiii-zhong/Leetcode | /Array/src/16. 3Sum Closest.py | 730 | 3.578125 | 4 | class Solution:
def threeSumClosest(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
closest = nums[0]+nums[1]+nums[2]
for a in range(len(nums)-2):
i=a+1
j=len(nums)-1
while... |
0ec7dd4c022d0d7e9db17817daca8bf7fc721e18 | yukiii-zhong/Leetcode | /Linked List/143. Reorder List.py | 1,545 | 3.65625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue(self, inputList):
pre = sel... |
0d3bb69003e43914bb44c4b3a228635aec14222e | yukiii-zhong/Leetcode | /problems/7. Reverse Integer.py | 487 | 3.5 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < -(2 ** 31) or x > 2 ** 31 - 1:
return 0
if x == 0:
return x
elif x < 0:
return self.reverse(-x) * (-1)
# x>0
rev = 0
... |
9b00ed3ea091453040f192c3e2018f7745970627 | yukiii-zhong/Leetcode | /Linked List/142. Linked List Cycle II.py | 1,191 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle2(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node = head
visited = set... |
eb4b875ea3f86babccc588f48ab8a27d95ce7934 | yukiii-zhong/Leetcode | /Linked List/ListNode.py | 596 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue... |
947af29568cc8fb642503115d2a4c7d582b1c274 | yukiii-zhong/Leetcode | /problems/9. Palindrome Number.py | 1,248 | 3.734375 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x <0:
return False
elif x == 0:
return True
# turn the int to an digit list
dig = []
while x > 0:
dig.append(x % 10)
... |
405cebe01e5875b953e07be442398b3e67275d88 | lockmachine/DeepLearningFromScratch | /ch04/gradient_descent.py | 2,233 | 3.515625 | 4 | #!/usr/bin/env python3
# coding: utf-8
import sys,os
sys.path.append(os.pardir)
import numpy as np
import matplotlib.pyplot as plt
from numerical_gradient import numerical_gradient
def gradient_descent(f, init_x, lr = 0.01, step_num=100):
x = init_x
grad_data = np.zeros(0)
for i in range(step_num):
grad = numeri... |
2c8ddb9a521e97f69e56db1a3ef504c7503c55b1 | Tuffour-Akwasi/Day2 | /part3.py | 672 | 3.875 | 4 | some_var = 5
if some_var > 10:
print('some_var is smaller than 10')
elif some_var < 10:
print("some_var is less than 10")
else:
print("some_var is needed")
print("dog " is "a mammal")
print("cat" is "a mammal")
print("mouse " is "a mammal")
for animal in ["dog","cat","mouse"]:
print("{0} is a mammal".... |
b261cd770064d7e35b55d80821053c79efd62e22 | L111235/Python-code | /嵩天python3/两数之和(字典).py | 1,468 | 3.765625 | 4 | '''给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的
那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
'''
def twoSum( nums, target) :
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
lookup = {} #建一个空字典
#(1,2,3)代表... |
3f365ba40640a9396a784cb3d597a91775bac3ef | L111235/Python-code | /嵩天python3/科赫雪花(递归迭代).py | 867 | 3.65625 | 4 | #科赫雪花
import turtle as t
def koch(size,n):
if n==0:
t.fd(size)
else:
for angle in [0,60,-120,60]:
t.left(angle)
koch(size/3,n-1)
#n-1阶科赫曲线相当于0阶,n阶相当于1阶
#用一阶图形替代0阶线段画二阶科赫曲线
#用n-1阶图形替代0阶线段画n阶科赫曲线
#将最小size的3倍长的线段替换为一阶科赫曲线
... |
edba9fdc0690c73ee47c88f6d77ade4054c2a70d | L111235/Python-code | /力扣/11.盛最多的水-双指针法.py | 827 | 3.75 | 4 | '''
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
'''
#双指针法
def maxArea(height):
#双指针法:短线段不变, 长线段向内收缩的话,无论之后的线段再长,
#也要以短线段长度为基准,但两条线段之间的距离却缩短了,
#所以不可能比之前装的水多
maxarea=0
i=0
j=len(height)-1
while i<j:
if height[i]<h... |
dab7423796be87917bf76e78455eb0fc2853cb33 | L111235/Python-code | /嵩天python3/Hello World.py | 237 | 3.9375 | 4 | a=input('请输入一个整数:')
a=int(a)
if a==0:
print('Hello World 啊!')
elif a>0:
print('He\nll\no \nWo\nrl\nd 啊!')
elif a<0:
print('H\ne\nl\nl\no\n \nW\no\nr\nl\nd 啊!')
else:
print('输入格式有误') |
f88803a8d0b44c62fb19c0e90c5d9e8ad0f43878 | antoniovukovic/test7 | /test.py | 211 | 3.578125 | 4 | # -*- coding: utf-8 -*-
secretNum = 6
test = int(raw_input("Odaberi jedan broj, sigurno ćeš pogriješiti: "))
if test == secretNum:
print("Bravo, 6.")
else:
print("Nisi pogodio prijatelju") |
47f296fe941b489c59dd1952ad6ca111a8a86e8a | pandeesh/CodeFights | /Challenges/sum_of_odd_nos.py | 661 | 3.75 | 4 | #!/usr/bin/env python
"""
Example
For a = 3 and b = 5 the output should be 0.
For a = 3006 and b = 4090 the output should be 1923016.
Note
If you don't want to read the text below, maybe your code won't pass time and memory limits. ;)
[input] integer a
The first integer, -1 < a < 1e8.
[input] integer b
The second i... |
d8325a2d9e1214a72880b37b023d4af1a8d88469 | pandeesh/CodeFights | /Challenges/find_and_replace.py | 556 | 4.28125 | 4 | #!/usr/bin/env python
"""
ind all occurrences of the substring in the given string and replace them with another given string...
just for fun :)
Example:
findAndReplace("I love Codefights", "I", "We") = "We love Codefights"
[input] string originalString
The original string.
[input] string stringToFind
A string to ... |
5fa88d472f98e125a2dd79e2d6986630bbb28396 | pandeesh/CodeFights | /Challenges/palindromic_no.py | 393 | 4.125 | 4 | #!/usr/bin/env python
"""
You're given a digit N.
Your task is to return "1234...N...4321".
Example:
For N = 5, the output is "123454321".
For N = 8, the output is "123456787654321".
[input] integer N
0 < N < 10
[output] string
"""
def Palindromic_Number(N):
s = ''
for i in range(1,N):
s = s + str... |
2f8478b92851cbf82d84d06cae05bd4ab4f9d161 | donghyoya/swp1-test | /Hello175(숫자 맞추기).py | 542 | 3.515625 | 4 | import random
num_selected = int(input("AI의 범위를 정하세요:"))
ai_random = random.randrange(1,num_selected)
try_number = 1
while try_number < 10:
try_number += 1
num_player = int(input("AI가 생각하는 수를 추측해보세요:"))
if ai_random < num_player:
print("당신은 AI보다 높은수를 생각하고 있습니다.")
if ai_random > num_player:
print... |
a69789bfada6cdab50325c5d2c9ff3edf887aebe | dhasl002/Algorithms-DataStructures | /stack.py | 1,562 | 4.3125 | 4 | class Stack:
def __init__(self):
self.elements = []
def pop(self):
if not self.is_empty():
top_element = self.elements[len(self.elements)-1]
self.elements.pop(len(self.elements)-1)
return top_element
else:
print("The stack is empty, you ca... |
d9910eb3deaa08b03c3d5ee6b1aac7ee2a8b5f49 | RuchikDama24/IUB_CSCI_B551_EAI | /Assignment 2/part2/SebastianAutoPlayer.py | 7,877 | 3.859375 | 4 | # Automatic Sebastian game player
# B551 Fall 2020
# PUT YOUR NAME AND USER ID HERE!
#
# Based on skeleton code by D. Crandall
#
#
# This is the file you should modify to create your new smart player.
# The main program calls this program three times for each turn.
# 1. First it calls first_roll, passing in a Dice o... |
fcb556abbd51a184f6dce990399fac1049b2e5a7 | davidlyness/Advent-of-Code-2018 | /17/main.py | 2,660 | 3.65625 | 4 | # coding=utf-8
"""Advent of Code 2018, Day 17"""
import collections
def find_water_overflow(water_x, water_y, step):
"""Locate bucket overflow in a given direction."""
while True:
next_cell = grid[water_y + 1][water_x]
current_cell = grid[water_y][water_x]
if current_cell == "#":
... |
7358df3f9f86fda07fbd980364aa9d2877eed918 | davidlyness/Advent-of-Code-2018 | /09/main.py | 935 | 3.78125 | 4 | # coding=utf-8
"""Advent of Code 2018, Day 9"""
import collections
import re
with open("puzzle_input") as f:
match = re.search("(?P<players>\d+) players; last marble is worth (?P<points>\d+) points", f.read())
num_players = int(match.group("players"))
num_points = int(match.group("points"))
def run_marb... |
cb3f6144b597cb5dc22ce03d9ac54dd7abe3aee4 | Bitcents/exercism_tracks | /python/hangman/hangman.py | 1,425 | 3.6875 | 4 | # Game status categories
# Change the values as you see fit
STATUS_WIN = "win"
STATUS_LOSE = "lose"
STATUS_ONGOING = "ongoing"
class Hangman:
def __init__(self, word):
self.remaining_guesses = 9
self.status = STATUS_ONGOING
self.__word = word
self.remaining_characters = set()
... |
f4a3d3365a114ced431f2a84d6c2b7b631c97575 | Bitcents/exercism_tracks | /python/difference-of-squares/difference_of_squares.py | 240 | 3.9375 | 4 | def square_of_sum(number):
return (number*(number+1)//2)**2
def sum_of_squares(number):
return (number)*(2*number + 1)*(number + 1)//6
def difference_of_squares(number):
return square_of_sum(number) - sum_of_squares(number)
|
1ee723a5d3ac7ccd8883aa6b0e3b7129c90da52d | Bitcents/exercism_tracks | /python/pythagorean-triplet/pythagorean_triplet.py | 297 | 3.765625 | 4 | from math import sqrt
def triplets_with_sum(number):
results = []
for i in range(number//2, number//3, -1):
for j in range(i-1,i//2,-1):
k = sqrt(i*i - j*j)
if i + j + k == number and k < j:
results.append([int(k),j,i])
return results
|
a8934dd089aeb3763409d937502708680e59d765 | AnupritaPro/gittest | /list1.py | 845 | 3.78125 | 4 | #list
l1=[2011,2013,"anu","pratiksha"]
l2=[2021,22.22,2002,1111]
print "value of l1",l1
print ("value of ",l1[1])
print "value of ",l1[0:2]
print "length of list is:",len(l1)
print "minimum lenght",min(l2)
print "maximum length",max(l2)
l1.append("sarita")
print "add update",l1
l1.append(2011)
print l1
c=l1.count(2011... |
46193fb3b9db2783700ef0026a2e1d274eb43842 | ramesheerpina/AutomateBoringStuff | /AutomateBoringStuff.py | 517 | 4.09375 | 4 | print("I am thinking of a number between 1 and 20. \n")
import random
randomnum = random.randint(1,20)
for guesstaken in range(1,9):
print("Take Guess\n")
guess = int(input())
if guess < randomnum:
print("your guess is too low")
elif guess > randomnum:
print("your guess is too high")
... |
33dbfd93f39cc11cca56d3099ac9310a3f488113 | javibolibic/SPSI | /kasiskiAttack.py | 5,683 | 3.640625 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
###################################################################
# _ _ _ _ _ _ _ _ #
# | | ____ _ ___(_)___| | _(_) / \ | |_| |_ __ _ ___| | __ #
# | |/ / _` / __| / __| |/ / | / _ \| __| __/ _` |/ __| |/ / #
# | < (_| ... |
546936ded7cbd026dfd23c02cffda693e9840c01 | aliensmart/week2_day4 | /terminalTeller2/account.py | 1,483 | 3.65625 | 4 | import json
import os
class Account:
filepath = "data.json"
def __init__(self, username):
self.username = username
self.pin = None
self.balance = 0.0
self.data = {}
self.load()
def load(self):
try:
with open(self.filepath, 'r') as json_file:... |
83a2fe0e985ffa4d33987b15e6b4ed8a6eb5703b | Nbouchek/python-tutorials | /0001_ifelse.py | 836 | 4.375 | 4 | #!/bin/python3
# Given an integer, , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5, print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Input Format
#
# A single... |
4e3be7e82c018e9309bf2d16135cd12af6302328 | ByketPoe/gmitPandS | /week02/lab2.3.2sub.py | 790 | 4.0625 | 4 | # sub.py
# The purpose of this program is to subtract one number from another.
# author: Emma Farrell
# The input fuctions ask the user to input two numbers.
# This numbers are input as strings
# They must be cast as an integer using the int() function before the program can perform mathematical operations on it
numb... |
a30b0e3f5120fc484cd712f932171bd322e757df | ByketPoe/gmitPandS | /week04-flow/lab4.1.3gradeMod2.py | 1,152 | 4.25 | 4 | # grade.py
# The purpose of this program is to provide a grade based on the input percentage.
# It allows for rounding up of grades if the student is 0.5% away from a higher grade bracket.
# author: Emma Farrell
# The percentage is requested from the user and converted to a float.
# Float is appropriate in this occa... |
0037856dbebe4ada7ce5edf268bb83f7563e1169 | ByketPoe/gmitPandS | /week02/addOne.py | 327 | 3.90625 | 4 | # addOne.py
# The purpose of this program is to add 1 to a number
# author: Emma Farrell
# Read in the number and cast to an integer
number = int(input("Enter a number: "))
# Add one to the number and assign the result to the variable addOne
addOne = number + 1
# Print the result
print('{} plus one is {}'.format(num... |
0c64591006436bfdf1c666b79f4d2e90da5afcff | ByketPoe/gmitPandS | /week02/nameAndAge.py | 353 | 4.0625 | 4 | # nameAndAge.py
# The purpose of this program is to
# author: Emma Farrell
# Request the name and age of the user
name = input('What is your name? ')
age = input('What is your age? ')
# Output the name and age (using indexing)
print('Hello {0}, your age is {1}'.format(name, age))
# Modified version
print('Hello {0}... |
6f16bc65643470b2bca5401667c9537d88187656 | ByketPoe/gmitPandS | /week04-flow/lab4.1.1isEven.py | 742 | 4.5 | 4 | # isEven.py
# The purpose of this program is to use modulus and if statements to determine if a number is odd or even.
# author: Emma Farrell
# I prefer to use phrases like "text" or "whole number" instead of "string" and "integer" as I beleive they are more user friendly.
number = int(input("Enter a whole number: "))... |
0a13765ecbc3d4c6cae6e666e9ec67149eb7d1a0 | smiks/CodeWars | /ValidateSudoku/program.py | 3,002 | 3.59375 | 4 | __author__ = 'Sandi'
class Sudoku(object):
def __init__(self, sudo):
self.sudo = sudo
def check(self, row):
for v in row.values():
if v != 1:
return False
return True
def is_valid(self):
su = self.sudo # less typing in the future
""" ch... |
acb07871af074d9a4560ffca24697c2bcdda5403 | bhavyavj/python-challenges | /problem6.py | 950 | 4.09375 | 4 | #!/usr/bin/python3
options='''
press 1 to view the contents of a file
press 2 cat -n => to show line numbers
press 3 cat -e => to add $ sign at the end of the line
press 4 to view multiple files at once
'''
print(options)
opt=input("Enter your choice")
if (opt==1):
i=input("Enter your file name")
f=open(i,'r')
d... |
4f70866e867bc46f9c609efece8a7338a3f5ad64 | kee007ney/scripts | /toy.py | 282 | 3.9375 | 4 | import csv
"""
This script will use xxx.csv as an input and output all the rows with the row number.
"""
with open("A.csv", 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in csvreader:
for j in xrange(0,len(row)):
print (j,row[j])
|
5a983b9c67438e27c89c5f973d9d09b05dc6ca79 | airje/codewars | /whatsthefloor.py | 123 | 3.546875 | 4 | def get_real_floor(n):
if n>13:
return n-2
elif n>0 and n<14:
return n-1
else:
return n |
7d38c44f7a46926dbf041ceb774a08284cdf8204 | airje/codewars | /findthenextperfectsquare.py | 213 | 3.921875 | 4 | import math as m
def find_next_square(n):
# Return the next square if sq is a square, -1 otherwise
result = (m.sqrt(n)+1)**2
if result-int(result) > 0:
return -1
else:
return result |
8b6646f5da8840e82476bb97f9e5c2668963a612 | Aeronyx/School | /conversations.py | 1,531 | 3.921875 | 4 | # File: conversations.py
# Name: George Trammell
# Date: 9/8/19
# Desc: Program has a discussion with the user.
# Sources: None
# OMH
from time import sleep
# Initial Greeting
print('Hello! What is your name?')
name = input('Name: ')
# Capitalize name if uncapitalized
name = name[0].upper() + name[1:]
print('Hello %s... |
38b6119f2584c44b97990c72d983b4e55275fc2e | akashchevli/Competitive-Programming | /FindBit.py | 1,349 | 4 | 4 | """
Write a program to find out the bits of the given number
Input
Enter number:7
How many bits want:4
Output
0111
Description
The original bits of number 7 is 111, but the user want 4 bits so you have added zeros in front of the bits
Input
E... |
dd256c28dcb505d183faf042d1ef88f8661435d9 | yaozeye/python | /learner/exercise/greatest_common_divisor.py | 635 | 3.984375 | 4 | # Python Greatest Common Divisor
# Code by Yaoze Ye
# https://yaozeye.github.io
# 09 April 2020
# under the MIT License https://github.com/yaozeye/python/raw/master/LICENSE
num1 = int(input('The first number: '))
num2 = int(input('The second number: '))
num3 = min(num1, num2)
for i in range(1, num3 + 1):
if num1 % ... |
e836385db2c976c6b1c779e25f0717a0eb4f57f9 | yaozeye/python | /learner/exercise/rectangle_area.py | 264 | 3.625 | 4 | # Python Rectangle Area
# Code by Yaoze Ye
# https://yaozeye.github.io
# 19 March, 2020
# under the MIT License https://github.com/yaozeye/python/raw/master/LICENSE
length = float(input())
width = float(input())
area = length * width
print("{:.2f}".format(area))
|
a708feba667fb030f755e5564c9cd1772a127dbc | econocoffee/Econo-Maths | /fun.py | 247 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 18:19:07 2020
@author: gdolores
"""
def area_r():
print(" Radio : ")
Radio = float(input())
return(" El área es: " + str( ( Radio ** 2 ) * 3.1416 )) |
b8d30e11c617a20d87e105c74cdcb05f8b9147d3 | eralpkor/cs-module-project-iterative-sorting | /src/searching/searching.py | 900 | 4.0625 | 4 | def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1 # not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
low = 0
high = len(arr) - 1
# While we haven't narrowed it down to one element ... |
4bac91f95ecabfd99ddc83c288f667c743f00e9a | abtahi-tajwar/python-algo-implementation | /dfs.py | 705 | 4.03125 | 4 | # Calling dfs function will traverse and print using dfs method
def graphSort(graph):
newGraph = dict()
for key in graph:
lst = graph[key]
lst.sort()
newGraph[key] = lst
return newGraph
stack = []
def dfs(graphMap, currentNode):
graph = graphSort(graphMap)
dict_map = dict(... |
4dc6ecdfe3063f3015801cf13472f7f77d742f0a | Denton044/Machine-Learning | /PythonPractice/python-programming-beginner/Python Basics-1.py | 2,217 | 4.5625 | 5 | ## 1. Programming And Data Science ##
england = 135
india = 124
united_states = 134
china = 123
## 2. Display Values Using The Print Function ##
china = 123
india = 124
united_states = 134
print (china)
print (united_states)
print (india)
## 3. Data Types ##
china_name = "China"
china_rounded = 123
china_exact =... |
342201ebee1eea4fcf8e381dfbdba93caae0af61 | Denton044/Machine-Learning | /PythonPractice/data-analysis-intermediate/Pandas Internals_ Series-145.py | 1,021 | 3.734375 | 4 | ## 1. Data Structures ##
import pandas as pd
fandango = pd.read_csv("fandango_score_comparison.csv")
fandango.head()
## 2. Integer Indexes ##
fandango = pd.read_csv('fandango_score_comparison.csv')
series_film = fandango['FILM']
print(series_film[0:5])
series_rt = fandango['RottenTomatoes']
print(series_rt[:5])
## ... |
572fe2d092fa65fb3beec45c1ed467e65529998b | ChandanShastri/PGPTP | /Tools/separateByYear.py | 660 | 3.5 | 4 | #!/usr/bin/env python
'''
Created on Oct 13, 2014
@author: waldo
'''
import sys
import os
import csv
def makeOutFile(outdict, term, fname, header):
outfile = csv.writer(open(term + '/' + fname, 'w'))
outdict[term] = outfile
outfile.writerow(header)
if __name__ == '__main__':
if len(sys.argv) < 1:
... |
6fa32bc3efeb0a908468e6f9cec210846cd69085 | yoli202/cursopython | /ejerciciosBasicos/main3.py | 396 | 4.40625 | 4 | '''
Escribir un programa que pregunte el nombre del usuario en la consola
y después de que el usuario lo introduzca muestre por pantalla <NOMBRE>
tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y
<n> es el número de letras que tienen el nombre.
'''
name = input(" Introduce tu nombre: ")
... |
0606fc6b61277a99f4c5146df4784e2ae5f70e50 | VadimSerov/Zarina2 | /Python и C++/Untitled-3.py | 269 | 3.65625 | 4 | import random
random.seed()
n=int(input("введите разменость массива "))
a=[]
for i in range(0,n) :
a.append(random.randint(0,100))
print(a)
k=int(input("введите целое число для проверки "))
aver=sum(a)
print(aver) |
0c729c03c7a3ed808fe246ae5df3494e6857ac5b | adelbast/Space-Conquest-3012 | /src/Tile/Map.py | 1,144 | 3.65625 | 4 | __author__ = "Arnaud Girardin &Alexandre Laplante-Turpin& Antoine Delbast"
import csv
class Map:
def __init__(self, path):
self.map = []
self.startingPoint =[]
self.numRow = 0
self.numCol = 0
self.generateMapFromFile(path)
def generateMapFromFile(self, path):
... |
e34a8e5ccc558f833d4c50fdc538d1d1cec51616 | rhrhdhdh1/rhrhdhdh1 | /moving/이동하기.py | 959 | 3.59375 | 4 | import moveclass
lo = moveclass.Point2D(100, 100)
lo1 = moveclass.Point2D(0, 0)
atype = 2
btype = 3
Time = 0
T = 0
T2 = 0
unit0 = moveclass.Unit(lo, atype)
p = lo
unit2 = moveclass.Unit(lo1, btype)
p1 = lo1
lenge1 = moveclass.lenge1(lo, lo1)
while True:
Time += 1
print()
T += 1
T2 += ... |
abd16a8c5cd1d032134cdb3afd3a1cb9d8153da1 | rajat1994/LeetCode-PythonSolns | /Topics/Recursion/permutation_with_case_change.py | 324 | 3.8125 | 4 | def permutation_with_case_change (ip,op):
if ip == "":
print(op)
return
op1 = op
op2 = op
op1 = op1 + ip[0]
op2 = op2 + ip[0].upper()
ip = ip[1:]
permutation_with_case_change(ip,op1)
permutation_with_case_change(ip,op2)
permutation_with_case_change("ab", ... |
c1fb5165232637d91f4ca68a696f9aaa850b87cd | rajat1994/LeetCode-PythonSolns | /Arrays/queue.py | 488 | 3.6875 | 4 | from collections import deque
class Queue:
def __init__ (self):
self.buffer = deque()
def enqueue(self,data):
return self.buffer.appendleft(data)
def dequeue(self):
return self.buffer.pop()
def isempty(self):
return len(self.buffer) == 0
def length(self):
... |
471050a9fce4fae1fde774b2be629d428499a8ae | lsieber/BestListData | /src/io/exportCSV.py | 349 | 3.5 | 4 | import csv
def exportCSV(table, filename):
with open(filename, mode='w', newline='', encoding='utf-8') as file:
test_writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in table:
#row.append(" ")
test_writer.writerow(row)
prin... |
31a698480e214a38bf5954b16f0589f9516038c3 | annaprzybysz/projektFUW | /sprspr.py | 545 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
# arr = []
# for i in range(100):
# c = np.random.rand(10, 10)
# arr.append(c)
# plt.imshow(arr[45])
# plt.show()
def data_gen():
while True:
yield np.random.r... |
5901b1fcabefe69b1ecc24f2e15ffe2d3daed18b | MaurizioAlt/ProgrammingLanguages | /Python/sample.py | 454 | 4.125 | 4 |
#input
name = input("What is your name? ")
age = input("What is your age? ")
city = input("What is your city ")
enjoy = input("What do you enjoy? ")
print("Hello " + name + ". Your age is " + age )
print("You live in " + city)
print("And you enjoy " + enjoy)
#string stuff
text = "Who dis? "
print(text*3)
#or for lis... |
a3d36d9a9c98a858ed5b26cb03cb917c0e0889b3 | soni-aditya/pan-aadhar-ocr | /pan.py | 2,659 | 3.609375 | 4 | import re
import string
from processing import clean_text
def clean_gibbersh(arr):
'''
From an input array of OCR text, removes the gibberish and noise, such as,
symbols and empty strings
'''
arr = [x for x in arr if len(x) > 3]
t = 0
d = 0
for i in range(len(arr)):
if "india" ... |
9881a1a5d57b81528b0607185ece6a930817c8ac | EastTown2000/ITGK | /Øvinger/Øving 6/lett_og_blandet.py | 352 | 3.78125 | 4 | def is_six_at_edge(liste):
return liste[0] == 6 or liste[-1] == 6
print(is_six_at_edge([1,2,3,4,5,6]))
print(is_six_at_edge([1,2,3,4,5,6,7]))
def average(liste):
return sum(liste) / len(liste)
print(average([1,3,5,7,9,11]))
def median(liste):
liste.sort()
indeks = int(len(liste) / 2)
return liste[indeks]
... |
e9880136681f934261cfbb6cf1ddb5bbfb541c8e | EastTown2000/ITGK | /Øvinger/Øving 6/generelt_om_lister.py | 227 | 3.59375 | 4 | my_first_list = [1, 2, 3, 4, 5, 6]
print(my_first_list)
print(len(my_first_list))
my_first_list[-2] = 'pluss'
print(my_first_list)
my_second_list = my_first_list[-3:]
print(my_second_list)
print(my_second_list, 'er lik 10') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.