blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
283a99231dffcf3c277c9f0411cf6bcd4fd8925c | yooq/PythonUp | /leetcode/77.py | 552 | 3.75 | 4 | '''
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
'''
class Solution:
def combine(self, n: int, k: int) :
pre = [_ for _ in range(1,n+1)]
l = {(pre[0],)}
for i in pre[1:]:
l.update({j+(i,) for j in l ... |
e8086dbc9c66ebaedd78ce68f671978d19ce7d60 | MalsR/python-learning | /examples/hello_python.py | 543 | 3.734375 | 4 | aircraft_name = "Boeing"
aircraft_model = 777
# print adds spaces between variables!
print(aircraft_name, aircraft_model)
# concatenating the variables python needs to be informed of the explicit conversion
# else it will result in the following error
# Traceback (most recent call last):
# File "hello_python.... |
51bca40d000e48994982058f12e11a263fb5ea73 | ieee-saocarlos/desafios-cs | /Luís Peres/produtos.py | 1,259 | 4.09375 | 4 | # DESAFIO 2, TERCEIRA TAREFA
class Produto:
"""
nome: nome do produto
pacote: quantos produtos um pacote tem
"""
def __init__(self, nome, pacote):
self.nome = nome
self.pacote = pacote
self.conjuntos = 0
def pergunta(self):
#pede a entrada da quantidade de pa... |
c63d9def41059d53ff0b896f973fcc9c4bff1631 | nachomf/memotest-game | /game.py | 1,931 | 3.828125 | 4 | class Game:
def __init__(self, elements, players):
self.elements = elements
self.players = players
def start(self):
turn = 1
end_game = False
while(not end_game):
turn_player = self.get_player(turn)
print("Turn number: " + str(turn) + " player nam... |
2cab5a052d5ea29684259c682aae03d1807bce84 | sbsdevlec/PythonEx | /Hello/Lecture/Example_jungol/Ex009.py | 417 | 3.921875 | 4 | """
이름과 나이를 입력받아 다음 "실행 예"와 같이 출력하는 프로그램을 작성하시오.
실행 예
이름? 한사람
나이는? 32
한사람씨 방가방가~~~ 내년에 33살이네 행님이라 불러~~
"""
name = input("이름? ")
age = int(input("나이는? "))
print(name + "씨 방가방가~~~", end=" ")
print("내년에 " + str(age+1) + "살이네 행님이라 불러~~") |
6acd947714e09721cff57e0ce5ef071a94b8f6b3 | Blizarre/Python-Challenge | /10/challenge10.py | 885 | 3.671875 | 4 | # coding:utf-8
# http://www.pythonchallenge.com/pc/return/bull.html
# the riddle's answer is really simple (and yet I haven't found it by myself :-/ ). Juste read the array "RLE-style" :
# 1 : one 1
# 11 : two 1
# 21 : one 2 one 1
# 1211 : one 1 one 2 two 1
a = [1, 11, 21, 1211, 111221]
def t... |
8fe6ef6c0e2be8341eb12bb0f9b9a148e192970a | bigeyesung/Leetcode | /268. missing number.py | 315 | 3.9375 | 4 | def missingNum(nums):
i=0
n=len(nums)
while(i<n):
print("i:",i)
print("nums[i]:",nums[i])
j=nums[i]
#e.g. 2 != array[2]->swap
if j<n and j!=nums[j]:
nums[i],nums[j]=nums[j],nums[i]
else:
i+=1
arr=[3,0,1]
missingNum(arr)
print(arr) |
0ef07b44e277befee0908fde7396a226d6b5d6c1 | smallwater94/password | /password.py | 229 | 3.78125 | 4 | x = 0
while True:
password = input('請輸入密碼: ')
if password != '123':
x = x + 1
print('密碼錯誤 你還有',3 - x,'次機會')
if x == 3:
print('登入失敗')
break
else:
input('登入成功')
break |
f98f2c1104a37ddc30e88ceb3be2bdbe224bf4d4 | srikanthpragada/PYTHON_02_NOV_2018_DEMO | /ex/sort_students_marks.py | 839 | 3.6875 | 4 | students = []
with open("marks.txt", "rt") as f:
# read all lines one by one
for line in f:
parts = line.strip("\n").split(",")
# skip if two elements not found
if len(parts) < 2:
continue
name = parts[0]
# convert all marks from str ot int and ignore errors
... |
cf8af6e2ac070b3298da5676b0ffeac62552dd49 | MihaiAnton/University | /Semester 4/Artificial Intelligence/Lab1/Sudoku/DFS/SudokuSolver.py | 1,684 | 3.890625 | 4 | from SudokuLogic.Table import Table
class SudokuSolver:
"""
Solves a valid sudoku grid using DFS(backtracking)
:param - the sudoku table
"""
def solveSudoku(self, table):
treeStack = [table] #the DFS stack
while len(treeStack) > 0: ... |
98aec16433de883ae8df322792d2ed9adacc1af3 | ykambham/mydev1 | /stringexamples/check_string_frequency.py | 808 | 4.34375 | 4 | #Check if a string has all characters with same frequency with one variation allowed
'''
Input : string str = "abbca"
Output : Yes
We can make it valid by removing "c"
Input : string str = "aabbcd"
Output : No
We need to remove at least two characters
to make it valid.
Input : string str = "abbccd"
Output : No
'''
d... |
d64d509554643fc585988153e0e87b869228657d | yiming1012/MyLeetCode | /LeetCode/股票购买专题/122. 买卖股票的最佳时机 II.py | 2,663 | 3.546875 | 4 | """
122. 买卖股票的最佳时机II
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
... |
aaf05d20fb7500baeab15116508b57d0ebca0093 | Jamie-Chang/advent2019 | /d4/main.py | 1,084 | 3.6875 | 4 | from __future__ import annotations
from typing import Iterator
def check_digits(num: int) -> bool:
# the digits of the digits must be in increasing order
# and at least two are the same (must be adjacent given)
digits = f"{num:06}"
return (
int(digits[0])
<= int(digits[1])
<= ... |
811f38da55e77c61b02fcad3a57c5fba33089219 | rogerchang910/stanCode-projects | /stanCode projects/breakout_game/breakoutgraphics.py | 9,552 | 3.859375 | 4 | """
File: breakout.py
Name: Roger(Yu-Ming) Chang
-----------------------------------------
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
-----------------------------------------
Provide vary methods that may be helpful to build a breakout ga... |
813e28df3ccfa0e7a713d0013d96f9b8f1d22613 | JurijNesvat/LearnPython | /2 - Data Structures/Week 3 - Files.py | 766 | 3.828125 | 4 | #New line character
#stuff = "X\nY"
#print stuff
#Assignement1:
# Use words.txt as the file name
#try:
# fname = raw_input("Enter file name: ")
# fh = open(fname)
# filenorm = fh.read()
# filecap = filenorm.strip()
# filecap = filecap.upper()
# print filecap
#except:
# print ("No such file found"... |
314463869aa802aae3a098ab906e2c5751e0bbbd | danielthorr18/forritun_git | /2lokaprof.aefingar.py/2.8.py | 236 | 4.125 | 4 | size = int(input("Input size: "))
arr = []
for i in range(size):
arr.append(int(input('Enter value {}: '.format(i + 1))))
sum1 = 0
for i in arr:
sum1 += i
average = sum1 / len(arr)
print('{} is the average!'.format(average))
|
6bc0e7f061f798856793a38aea2a9623c229a67b | SoundaryaAdaikkalavan/Hacker-Earth | /book_of_potion.py | 153 | 3.515625 | 4 | # Write your code here
n=input()
a=0
for i in range(len(n)):
a+=int(n[i])*(i+1)
if(a%11==0):
print("Legal ISBN")
else:
print("Illegal ISBN")
|
ac8bb30a664ac77885c1ad67418acbe1bace2a55 | kaiwolff/Eng88-cybercourse | /Week_2/Python_Functions/calculator_exercise.py | 927 | 3.78125 | 4 | class Calculator:
#made them static methods so that I don't have to create an object.
@staticmethod
def add(value1,value2) : return value1 + value2
def subtract(value1, value2): return value1 - value2
def multiply(value1, value2) : return value1 * value2
def divide(value1, value2) : return va... |
ea7db69edb7f9ac09800f6956fde5c2dd9f9715a | iblanco29/LabTICVI | /python_practice/python_practice.py | 1,456 | 3.859375 | 4 | # Ejercicio 1
def dividers(number):
dividersArr = [tentativeDivisor for tentativeDivisor in range(1,number+1) if number%tentativeDivisor==0]
return dividersArr
print("DIVISORES DEL NUMERO HARCODEADO")
print(dividers(55))
#Ejercicio 2
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
even_numbers_in_a = [evenNumbe... |
99ca33c2c1913770f71a07aacb4492338b283922 | mehulchopradev/fatih-python | /playdatetime.py | 842 | 3.78125 | 4 | from datetime import date, datetime, timedelta
today = date.today()
print(today)
print(type(today))
print(today.year)
print(today.day)
print(today.month)
past = date(year=1986, month=11, day=25)
print(past)
print(type(past))
future = past.replace(year=today.year)
datestr = future.strftime('%d/%m/%Y')
print(datestr)... |
aeb5db85ab99ca5eebf827ae9482981deeaec898 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/hgxkon001/question3.py | 1,028 | 4.3125 | 4 | #Konrad Hugo
#question 3
#Function that gets names of parties and the subsequent votes for each party
def party_finder():
listA = [] #
string = '' #initially we want a blank string input, but we want a variable
print("Independent Electoral Commission\n--------------------------------\nEnter the na... |
7badd9fce26ca00207a1eb299b195a604d937717 | Kronostheus/Python | /Euler/015.py | 603 | 3.890625 | 4 | # exercise describes something like NE lattice paths which are counted by the binomial coefficient (and arranged in Pascal's Triangle)
def binomial(n, k):
res = 1
# symmetry of the binomal coefficient means we can set upper limit to the smaller of k and (n-k)
for i in range(min(k, n-k)):
# multiplic... |
333d8a44f181913e8cee4f931384bd3966ee870d | justinph615/lab-08-for-loops | /fizzbuzz.py | 192 | 3.96875 | 4 |
for i in range (1, 101):
if (i % 3 == 0 and i % 5 == 0):
print(i,"Fizzbuzz")
elif (i%3 == 0):
print(i,"Fizz")
elif (i%5 == 0):
print(i,"Buzz")
else:
print(i)
|
07c2f4df4c0d97df93c7cbca628e8eed628a1d25 | wangzhankun/python-learn | /basic/code/test.py | 1,540 | 3.53125 | 4 | class Product():
def __init__(self,id,name,price,yieldly):
self.id = id
self.name = name
self.price = price
self.yieldly = yieldly
class Cart():
def __init__(self):
self.product = {}
self.products = []
self.total_price = 0
def buy_product(self,produ... |
1b00aac23ad6f8c35ac1e5dd520630abc28ababb | shirdha/ss | /factplay.py | 150 | 3.859375 | 4 | n=int(input(""))
fact=1
if(n<=0):
print(fact)
elif(n==1):
print(fact)
if(n>1):
for i in range(1,n+1):
fact=fact*i
print(fact)
|
bba2afd55ebc996aaef68c48532e956bf0dbb5a1 | Th3Lourde/l33tcode | /problemSets/top75/128_longest_consecutive_sequence.py | 870 | 3.8125 | 4 | '''
Given an unsorted array of integers nums,
return the length of the longest consecutive elements sequence.
[100,4,200,1,3,2]
^
memo = {
100 : 0
4 : 0
200 : 0
3 : 0
2 : 0
}
top-down makes most sense
'''
class Solution:
def longestConsecutive(self, nums):
memo = {}
... |
d5a74bbd08d7966fd832578002a3f7b26ee8ab7b | varghesetom/Modern-Python-3-Bootcamp | /Decorators/decorators_exercises.py | 1,543 | 4.125 | 4 | # Higher Order Functions -- passing funcs as args to other funcs
def sum(n, func):
total = 0
for num in range(1, n):
total += func(num)
return total
def square(x):
return x * x
# print(sum(3,square))
### 2. Nesting Functions
from random import choice
def make_laugh_func():
def get_lau... |
e5224fa4c116f2c8981a8cb72bd2ef29cbe4757d | yogeshdewangan/Python-Excersise | /string_examples/reverse_string_but_not_special_char.py | 698 | 4.15625 | 4 | input = "a$b#c"
# output = "c$b#a"
# input ="abc"
# output = "cba"
def reverseSting(text):
index = -1
# Loop from last index untill half of the index
for i in range(len(text) - 1, int(len(text) / 2), -1):
# match character is alphabet or not
if text[i].isalpha():
temp = text[... |
fb445c2654ee12114da56da91195211918a42ab5 | MDGSF/PythonPractice | /algo/leetcode-tencent/array-and-strings.py | 951 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
https://leetcode-cn.com/explore/interview/card/tencent/221/array-and-strings/898/
"""
def longestCommonPrefix(strs) -> str:
result = ""
curIdx = 0
strNumber = len(strs)
if strNumber == 0:
return ""
if strNumber == 1:
return strs[0]... |
e6da5a1b21e7edfa9dc6c6b98ac28d38b62e1117 | sjain93/wdi_crm_python | /CRM with DBs/crm_new.py | 4,167 | 3.65625 | 4 | from contact_new import Contact
class CRM:
def main_menu(self):
while True: # repeat indefinitely
self.print_main_menu()
user_selected = int(input())
self.call_option(user_selected)
def print_main_menu(self):
print('[1] Add a new contact')
print(... |
f7fe1dd68e2ceea5aca05f1cf0cbd8604acef1a3 | NickMateus11/All-Python-Projects | /Sorting Algorithms/InsertionSort.py | 508 | 3.859375 | 4 | import TextFileReader
def sort(numList = TextFileReader.readTxt()):
for i in range(1,len(numList)):
currentNumIndex = i
for j in range(i+1):
if numList[currentNumIndex] <= numList[currentNumIndex-j]:
insertIndex = currentNumIndex-j
else:
... |
ea4a593a16542235c6aa1ee43d7041775c6451fa | kimtaeyong123/python-starter | /week2/dic1.py | 473 | 4 | 4 | # aFruitList = [ 'apple', .....]
#
# if aFruitList[1] == 'banana':
# print(3000)
# elif aFruitList[0] == 'apple':
# print(1000)
aFruitList = { 'apple' : 1000, 'banana' : 3000, 'orange':2000}
print(aFruitList['banana'])
# 딕셔너리는 key와 value 형태로 정의를 해준다
# 딕셔너리의 접근은 리스트와 동일하게 대괄호[]를 이용하여 접근한다
# 대괄호에 키값을 입력하여 접근, ... |
76f1e5e7335d7e31d6d6c53c3ec00314aaab1da5 | aaronhnash/JARVIS-Gesture-Control | /classes/mouse.py | 2,454 | 3.609375 | 4 | from os import putenv
import pyautogui
from time import sleep
class Mouse():
"""Helper class. Cleanly implements a way to control and track what the mouse is doing."""
def __init__(self):
self.width = pyautogui.size()[0]
self.height = pyautogui.size()[1]
self.x = pyautogui.position()[... |
a135b667a5238868160ae975fac4c4c6399756d1 | darumada/alghoritms | /geeksforgeeks/Rearrange an array such that arr[i] = i /rearrange.py | 214 | 4.125 | 4 | def rearrange(arr):
for i in range(len(arr)):
if arr[i] != i and arr[i] > -1:
arr[arr[i]], arr[i] = arr[i], arr[arr[i]]
arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
rearrange(arr)
print(arr)
|
7f8adf5b394d9335e8eeae77294da185054ecfdc | sureleo/leetcode | /archive/python/RemoveDuplicatesFromSortedListII.py | 876 | 3.828125 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @return a ListNode
def deleteDuplicates(self, head):
dummy = ListNode(0)
dummy.next = head
p = dummy
while p and p.next:
slow = p.next
fast = slow
... |
13266d265c5b91787ea8def67266c0e557c23353 | IkerRG1/Modelo | /P06.Lista de cuadros V.2.py | 102 | 3.796875 | 4 | n = int(input('Dime un número:'))
i = 1
while True:
print(i**2)
i = i+1
if i**2 >= n:
break |
001288dc3c9a48d5a6374f1fb1570f67536b6cfd | LukeG-dev/CIS-2348 | /homework1/1.20.py | 505 | 3.578125 | 4 | # Luke Gilin 1216992
print("Enter integer:")
userNum = int(input())
print("You entered:", userNum)
userNumSquared = userNum ** 2
print(userNum, "squared is", userNumSquared)
userNumCubed = userNum ** 3
print("And", userNum, "cubed is", userNumCubed, "!!")
print("Enter another integer:")
user_num1 = int(input()... |
ff8afffa9a9ee6a5f07d44b0b85ad94443d6acfe | rajeshberwal/sudoku-solver | /sudoku-solver.py | 4,015 | 4.0625 | 4 | # first we take input from every row
# insert the value with spaces
row1 = list(map(int, input("Enter values of row1: ").split()))
row2 = list(map(int, input("Enter values of row2: ").split()))
row3 = list(map(int, input("Enter values of row3: ").split()))
row4 = list(map(int, input("Enter values of row4: ").split... |
54811a5082bc9f1fa973fb4d664dd06191e86df7 | nfearnley/RangeSet | /ranges.py | 2,415 | 3.578125 | 4 | def normalize(ranges):
if not ranges:
return ranges
old_ranges = sorted(ranges)
new_ranges = [old_ranges.pop(0)]
for r in old_ranges:
if r.intersects(new_ranges[-1]):
r = r + new_ranges.pop()
new_ranges.append(r)
return new_ranges
class RangeList:
def __init... |
60ebde56c16364c43aa8a06b733958245e623ca0 | Cristian-alfa/helloworld | /volume.py | 467 | 3.828125 | 4 | #volume.py
import math
print "Calcolo volume cubo o volume sfera"
print "inserire 1 per volume cubo"
print "inserire 2 per volume sfera"
n = input()
if n==1:
x = input("inserire lato del cubo")
v = x *x *x
print "il volume del cubo di lato ", n, "e' ", v
elif n==2:
x = input("inserire il raggio dell... |
5e8527a56ebd313785eecb0bc76533e434e80954 | Mesquita001/Conte-doPython | /scripts-python/ex014.py | 159 | 3.703125 | 4 | graus = float(input("Qual a temperatura "))
conversor = (graus * 1.8) + 32
print("A temperatura {}C convertida em Fahrenheit é: {}F ".format(graus,conversor)) |
b545e1c8cac65c015606f2fb3971adf438ee989c | agarrharr/code-rush-101 | /something-learned/Algorithms and Data-Structures/python/tree/longest_consecutive.py | 901 | 3.921875 | 4 | # Given a binary tree, find the length of the longest consecutive sequence path.
# The path refers to any sequence of nodes from some starting node to any node
# in the tree along the parent-child connections.
# The longest consecutive path need to be from parent to child
# (cannot be the reverse).
# For example,
... |
2093e850112b728dc1438961c0a79ede07df991d | shridharkute/sk_learn_practice | /tasks/practice2.py | 697 | 3.875 | 4 | #!/usr/bin/python3
'''
Question 2: Given a range of numbers. Iterate from o^th
number to the end number and print the sum of the current
number and previous number
'''
PRV=0
for i in range(1,10):
print(f"previous number {PRV}", end = " ")
print(f"Current number {i}", end = " ")
print(f"Sum of previous and... |
e7b3e9a0bc0621e8f2fa2cbc571937e6d96d5956 | MyLanPangzi/py4e | /chapter9-dict/exercise5.py | 520 | 3.9375 | 4 | # Exercise 5: This program records the domain name (instead of the address)
# where the message was sent from instead of who the mail came from (i.e., the whole email address).
# At the end of the program, print out the contents of your dictionary.
fin = open('../mbox-short.txt')
r = dict()
for line in fin:
if no... |
a59faa3f1d200b86b58438ca925897877af9fb74 | aliceshan/Practice-Questions | /strings_lists/unique_email_addresses.py | 1,668 | 4.21875 | 4 | """
Type: strings
Source: Leetcode (Easy)
Prompt: Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') ... |
386d0452574641967144a8890950d22cbcd87dbf | TashanManiyalaghan/discord-classroom | /schedule.py | 2,805 | 3.984375 | 4 | # Use the datetime library
from datetime import datetime
# Schedule class that will keep track of all necessary events and their corresponding dates and times.
class Schedule:
# Inner class for an individual Event, which will keep track of the name, date, time, and description of the event.
class Event:
... |
0624099d6cf3f02cd373260c47519f4f3f59f4a0 | OctoBrownie/Stats_Calculator | /Stats_Calculator.py | 5,912 | 4.5 | 4 | import math
def stats_calc(inputs='help', *args):
"""This is a basic stats calculator. Call the function with "stats_calc([list of numbers], 'commands')". All commands \
must be inside quotes, otherwise it won't work.
List of commands:
sort - sorts the list
mean - finds the average of all values within the list
... |
614eee3379707b42797f0b664d1890743d535f1d | sbtries/Class_Polar_Bear | /Code/Gabe/python/practice/02_booleans.py | 1,929 | 4.1875 | 4 |
# Practice 2: Booleans, Comparisons, & Conditionals
# Copy and paste this file into your own "02_booleans.py"
# Fill in the code for each of the functions
# Run the tests by typing "pytest 02_booleans.py"
# Go Hiking
# Write a function that takes a string indicating energy level and weather
def go_hiking(energy, w... |
1cf6beb648ee02b996d1f228521978461eb9ec90 | subhasreemurugan/eclipse-oxygen | /pybook/src/paperscicor.py | 395 | 3.78125 | 4 | def val(x):
if x==0:
txt='scissor'
elif x==1:
txt='rock'
elif x==2:
txt='paper'
return txt
import random
comp=random.randint(0,2)
urs=eval(input("enert"))
if urs>comp:
print("cmp",val(comp),"urs",val(urs),"thus u win")
elif urs==comp:
print("cmp",val(comp),"urs"... |
138281d287deb479b27d34c54e592347fb537360 | ansonmiu0214/algorithms | /2018-09-13_Linked-List-Components/solution.py | 1,160 | 3.671875 | 4 | #!/bin/python3
import sys
sys.path.append('../')
from adt import ListNode, array_to_list
"""
Iterative approach using flag to keep track of a connected component
over the iterations.
"""
def numComponents(head, G):
# convert to set to take advantage of membership function
candidates = set(G)
curr = head # linke... |
1cca48dc0db7693bf46fb57caf9ffabb7d5daf94 | LiuJiYangYang/python-game | /python小游戏/variablestr.py | 779 | 4.0625 | 4 | # python 没有“变量”只有“名字"
teacher = "liujiyang"
print(teacher)
teacher = "xingren"
print(teacher)
# 字符串拼接
myteacher = 'liujiyang'
yourteacher = 'tang'
ourteacher = myteacher + yourteacher
print(ourteacher)
str1 = '''
先赋值,后调用
变量名包含字母,数字,下划线。不能以数字开头
python区分大小写
= 是赋值,不能写反
尽量取一个专业的名字(英文)
字符串:也成为文本,用引号表示字符串
单引号和双引号同时用,转义符
'''... |
32459df05476087dbafc5c1522f2f5e909989bec | nervaishere/DashTeam | /python/HOMEWORK/6th_Session/Answers/Class/3/T3.py | 232 | 4 | 4 | a=float(input("Enter your number:"))
print(format(a,".3f"),end="\\")
if (a<0 and (-1*a)<10):
print(format(a))
elif(a<0 and (-1*a)>10):
print("-50")
elif(a>0 and a<10):
print(format(a))
else:
print("+50") |
a92530ef3b292f2e844c0a7242ddf215f9c71ba1 | achan90/python3-hardway | /exercises/ex13.py | 219 | 3.515625 | 4 | from sys import argv
script, first, second = argv
print("Your first variable is:", first)
print("Your second variable is:", second)
third = input("Please define your third variable. \n")
print(first, second, third)
|
d9732e9e20a2dc90ea6246963b13586d1e2c406f | uw-bionlp/ards | /src/corpus/utils.py | 299 | 3.875 | 4 |
def remove_white_space_at_ends(text, start, end):
# leading white space
n = len(text)
text = text.lstrip()
start += n - len(text)
# trailing white space
n = len(text)
text = text.rstrip()
end -= n - len(text)
return (text, start, end)
|
dec0359b6a7247c32acfb4022469a3041a79bf8d | weichuntsai0217/leetcode | /373-Find_K_Pairs_with_Smallest_Sums.py | 1,154 | 3.640625 | 4 | """
* Ref: https://discuss.leetcode.com/topic/50450/slow-1-liner-to-fast-solutions/2
* Key points:
- It turns each row into a generator of triples [u+v, u, v],
only computing the next when asked for one. And then merges these
generators with a heap. Takes O(m + k*log(m)) time and O(m) extra space.
* Explain y... |
0958a21edee79d3aacb4333ed513d019e0861801 | wncbb/prepare_meeting | /abnb/pyramid_transition_matrix/main.py | 1,152 | 3.75 | 4 | class Solution:
"""
@param bottom: a string
@param allowed: a list of strings
@return: return a boolean
"""
def helper(self, level, nextLevel):
if len(level)==2 and len(nextLevel)==1:
self.result.append(nextLevel)
return
if (len(level)-1)==len(nextLevel):... |
fbf2559dc0aaf6fe380af6fd9cb7f56565638510 | YangLiyli131/Leetcode2020 | /in_Python/0981 Time Based Key-Value Store.py | 1,232 | 3.734375 | 4 | class TimeMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {}
def set(self, key, value, timestamp):
"""
:type key: str
:type value: str
:type timestamp: int
:rtype: None
... |
d7c543615db443935aae499ec7db7d44f192226a | nsforero10/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 196 | 3.59375 | 4 | #!/usr/bin/python3
"""
0-read_file.py
"""
def read_file(filename=""):
""" Prints a file """
with open(filename, encoding='utf8') as f:
for ln in f:
print(ln, end='')
|
4b93c57a83573b0f027d227a62a23c8156833a74 | amangupta0107/python-project | /aman_py_coursera/ex_08/ex_08_04.py | 263 | 3.8125 | 4 | file = input('Enter file: ')
handle = open(file)
read = handle.read()
#print(read)
s = read.split()
#print(s)
array = list(s)
#print(array)
array.sort()
print(array)
x=[]
for final in array:
if final not in x:
x.append(final)
continue
print(x) |
6390cd8443a35c44b3d7611a545c373b1537f1b4 | vdakinshin/learn_python | /info.py | 362 | 4 | 4 | user_info = {"first_name" : "Василий", "last_name" : "Акиньшин"}
new_first_name = str(input("Введите своё имя!"))
user_info["first_name"] = new_first_name
new_last_name = str(input("Введите свою фамилию!"))
user_info["last_name"] = new_last_name
print(user_info.get("first_name") +" "+ user_info.get("last_name"))
|
1634dfdc7800d00587bcb0e506bb5e6eb509c8c7 | Journey99/boj-studyfolio | /class2/2751.py | 126 | 3.625 | 4 | n = int(input())
num = []
for i in range(n):
num.append(int(input()))
num = sorted(set(num))
for j in num:
print(j)
|
28745c26dc5c858383799b521a991fbb930149ac | hmunduri/MyPython | /lists/ex59.py | 134 | 3.90625 | 4 | #Python program to check if he n-th element exists in a given list.
x = [1,2,3,4,5,6,8]
print(len(x))
xlen =len(x)-1
print (x[xlen])
|
7d8d80d785abba333e79f6b611d17a724d829e90 | kyungyul/Practical | /prac_01/shop_calculator.py | 340 | 3.96875 | 4 | total = 0
number = int(input("Number of Items : "))
while number < 0:
print ("Invalid number of items")
number = int(input("Number of Items : "))
for i in range (number):
price = float(input("price_item: "))
total += price
if total > 100:
total *= 0.9
print("Total price for {} items is ${:.2f}".for... |
4ac1137e439d14d9e06f1b40e094985cf9013850 | rogerhendricks/implanted_device_parser | /db.py | 420 | 3.671875 | 4 | import sqlite3
CONN = sqlite3.connect("patient.db")
def getCardiologistList():
c = CONN.cursor()
cardio = c.execute(f''' SELECT * FROM cardiologist''').fetchall()
list = []
for row in cardio:
data = "%s %s %s" % (row[0], row[1], row[2])
list... |
fa1a97a5e37871ca480034cd5a9bd64c150209af | JoshVarty/AlgorithmDesignManual | /CrackingTheCode/Chapter4/Ch4_TreesAndGraphs_3.py | 1,007 | 4.0625 | 4 | # List of depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth
# (e.g. if you have a tree with depth D, you'll have D linked lists)
from node import *
def listOfDepths(root):
lists = []
#Queue up the root next
nextLevel = [root]
currentLevel = [... |
2b3e6492d0a3298c0aa9dbfbfb117fccafb37d12 | yugin96/cpy5python | /practical03/q7_display_matrix.py | 670 | 4.5625 | 5 | #filename: q7_display_matrix.py
#author: YuGin, 5C23
#created: 20/02/13
#modified: 22/02/13
#objective: Write a function which displays an n by n matrix where n is an
# integer entered by the user and each element is randomly generated
# to be either 0 or 1.
#main
import random
#function
def prin... |
9d6777bcbc44a8a3fe6d018f64a5e32761eca807 | Viktorrya/Tesris | /Board.py | 1,677 | 3.625 | 4 | import pygame
class Board:
# создание поля
def __init__(self):
self.width = 10
self.height = 16 # всю таблицу будем заполнять цветами клеток
self.board = [[(0, 0, 0)] * self.width for _ in range(self.height)]
self.cell_size = 50
def render(self, screen): # отрисовка
... |
12d572a36923f5773204c86645cf126f399f63a5 | harshilpatel/academics | /cryptography/mul.py | 809 | 3.5625 | 4 | # Multiplcative cipher
import string
import math
a = string.ascii_lowercase
a = list(a)
p = raw_input("Mutiplicative cipher: \nEnter plaintext: ")
p = p.replace(" ","")
key = int(raw_input("Key: "))
c = ""
for i in p:
pos = ( a.index(i) * key ) % 26
c += a[pos]
# print i + " " + str(pos) + " " + a[pos]
print ... |
86b739e5f62effab9ee4be957bebe93f8aca7c86 | Zotern/Python-lessons | /Python-base/Lesson-4/HW-L4-easy.py | 1,443 | 3.84375 | 4 | import random
# Все задачи текущего блока решите с помощью генераторов списков!
# Задание-1:
# Дан список, заполненный произвольными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] --> [1, 4, 16, 0]
l = [1, 2, 4, 5, 6]
l2 = [x**2... |
25227af77a035fdf8dc6b0a92d65357e608ee706 | nitkgupta/MMU_Project_1 | /spyChat/add_status.py | 1,491 | 3.5625 | 4 | from globals import STATUS_MESSAGES
updated_status_message = None
def add_status(current_status_message):
if current_status_message != None:
print 'Your current status message is %s \n' % (current_status_message)
else:
print 'You don\'t have any status message currently \n'
default = raw_... |
561d1fb7fe43b112fc01635b105cf3b12b87f2d1 | jepify/SudokoSolver | /src/solver_internet.py | 1,645 | 3.796875 | 4 | solvedTable = []
initialTable = []
try:
lines = open('sudokus/Sudoko1.txt').read().splitlines()
except:
print("File does not exist")
exit()
index = 0
for line in lines:
initialTable.append([])
solvedTable.append([])
for number in line:
initialTable[index].append(int(number))
sol... |
ce30519620f56e1437c5faf9d2ae96653255238d | moidshaikh/hackerranksols | /chegg/filtering_noise.py | 2,999 | 3.953125 | 4 | """
To be done in PYTHON
Given the a starter code:
import matplotlib.pyplot as plt
import math as m
import random as rand
x = [ d * m.pi / 180 for d in range(360*3)]
y = [m.sin(k) for k in x ]
y_noisy = [m.sin(k) + rand.gauss(0, .1) for k in x]
(a) Write a function called filter_noise that takes two parameters: 1) a l... |
3d7e611a0132a1141558c26fcad2f1a68552e55f | PrasadJoshi12/Object-Oriented-Programming-in-Python | /Class_and_Objects.py | 639 | 3.6875 | 4 | class Student:
# instance attributes
def __init__(self, name, marks):
self.name = name
self.marks = marks
# instance method
def check_pass_fail(self):
if self.marks >= 40:
return "Congratulation you have successfully passed"
else:
return "Bett... |
d32e125b48001205d24b4b556effbe73e7d03cf5 | bwagenseller/GeneralPythonFunctions | /MatchConfidence.py | 15,338 | 3.515625 | 4 | import re
import pandas as pd
import numpy as np
import difflib
import DateFunctions as DateFunc
"""
This file holds functions that help match records in one table/dataframe with records in another table/dataframe across variable columns with variable confidence levels.
"""
def findMatches(dataframeA, dataframeB, matc... |
9e5891afdb6e4bb3355e13a57d5baa4a43944a5a | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise11_29.py | 498 | 4.0625 | 4 | def main():
SIZE = 3
m1 = input("Enter list1: ").split()
m2 = input("Enter list2: ").split()
if equals(m1, m2):
print("Two lists are identical")
else:
print("Two lists are not identical")
def equals(m1, m2):
list1 = []
for row in m1:
for e in row:
li... |
d8f2ab025537370ef9638eed15d404b809b50bf5 | YuriyPyter/Python | /5.py | 909 | 4.15625 | 4 | revenue = int(input('Введите значение выручки фирмы: '))
cost = int(input('Введите значение издержек фирмы: '))
profit = revenue - cost # прибыль
loss = cost - revenue # убыток
profitability = profit / revenue # рентабельность
if revenue > cost :
print('Ваша прибыль составляет:', profit)
print(... |
95a95701ef443170f21b02da4ada5260b16cb732 | Danko99/pythonProject | /Distance_between_two_points_Class.py | 900 | 3.875 | 4 | import math
class Point:
def set_coordinates(self, *args):
if len(args) >= 2:
for i in range(0, len(args)):
setattr(self, str(i), args[i])
else:
print("Переданы неверные координаты")
def get_distance(self, object):
if isinstance(object, Point)... |
f10826f2a428da6315ec86ac6c5263148025a8e5 | squared9/Self-driving-Car | /Advanced_Lane_Detection/color.py | 1,980 | 3.59375 | 4 | import cv2
import numpy as np
def hls_select(image, threshold=(0, 255)):
"""
In HLS model masks pixels with saturation S-value inside threshold range
:param image: image
:param threshold: saturation threshold
:return: mask with pixels with saturation within threshold
"""
hls = cv2.cvtColor... |
b8c4ae0d0cf2643a74d4bbc7f57884fc61061668 | msdf2244/winter-break-projects | /FizzBuzz/fizzbuzz.py | 366 | 3.6875 | 4 | def fizzbuzz(num, x, y):
result = ''
if num % x == 0:
result += "Fizz"
if num % y == 0:
result += "Buzz"
if num % x != 0 and num % y != 0:
result = num
return result
def solver(x, y , n):
for i in range(1, n + 1):
print(fizzbuzz(i, x, y))
n, x, y = inpu... |
dc2e03e13b9fcc31e5d307d67465e574fc7ea674 | JaceVel97/Programacion_Python | /Codigo Python/Lista/Lista.py | 805 | 3.65625 | 4 | from Nodo import Nodo
class Lista:
def __init__(self):
self.first = None
self.last = None
def insert_node(self, titulo, contenido):
new_nodo = Nodo(titulo, contenido)
if self.first == None:
self.last = new_nodo
self.first = self.last
else:
... |
b0ccdc85854f4013025786b87a4fb7ea515b8f80 | Eketek/ShuffleCrypt | /shufflecrypt.py | 17,322 | 3.609375 | 4 | from random import randrange, shuffle
class SCCipher:
# operational modes. (SCCipher.opmode)
# These are used to determine what an instance of SCCipher should do after encrypting or decrypting
OPMODE_CONTINUOUS=0 # do nothing, retain state
OPMODE_SINGLE=1 # reset before encrypting... |
f711134f727746337ffa8ca1d324831a185afde8 | Anirban2404/LeetCodePractice | /3_lengthOfLongestSubstring.py | 2,187 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 15:11:12 2019
@author: anirban-mac
"""
"""
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating
characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answe... |
c45767f0570419b5f88e9e9f37cb68b5e676d6a3 | dr04dred/Kit | /DnD_Krit_V-1.1.py | 2,150 | 3.953125 | 4 | import random
print("Давайте узнаем что случилось с вашим персонажем")
X = 0 # X это показатель обозначающийся отрицательное значение броска
Y = 0 # Y это показатель обозначающийся положительное значение броска
Z = 0 # Z это флаг прекращения while
Ti = int(input("что вы хотите узнать,\n 0 для броска \n 1 для судьбы... |
ccf909e82cdb325190f78bd7faa363ee827aa819 | CoolyXIE/git_repo | /python/src/100Ex/17.py | 387 | 3.828125 | 4 | line = raw_input("please input a line:")
char_stat_dict = {'letter':0, 'blank':0, 'digit':0, 'other':0}
for char in line:
if char.isalpha():
char_stat_dict['letter'] += 1
elif char.isdigit():
char_stat_dict['digit'] += 1
elif char.isspace():
char_stat_dict['blank'] += 1
... |
6939008034ab45bce75c3ef534721b6f6f4d1a98 | sangm1n/problem-solving | /BOJ/11652.py | 310 | 3.5625 | 4 | """
author : Lee Sang Min
github : https://github.com/sangm1n
e-mail : dltkd96als@naver.com
title : 카드
description : Sorting
"""
from collections import Counter
N = int(input())
card = [int(input()) for _ in range(N)]
count = Counter(card)
result = sorted(count.items(), key=lambda x: (-x[1], x[0]))
print(result[0]... |
218e32ef5521629ad3ac449cc41633ef6670fcb9 | isdewo/python | /practice/module1.py | 279 | 3.71875 | 4 | # 1. 원의 반지름을 사용자 입력으로 받아 원의 면적을 출력하는 프로그램을 작성하시오.
import math
r = int(input("반지름을 입력하세요: "))
area = r * r * math.pi
print("반지름이 {0}인 원의 면적은 {1}입니다.".format(r, area)) |
b6c549864fc4eab3f64cc9ff41e6a5cb4d697fe5 | KocUniversity/studyquestions2-py-Aylinmelek | /search_sort_answers.py | 3,375 | 3.9375 | 4 | import random
# Question 1
# Time complexity: O(n + k) where k is maximum possible element
def counting_sort(lst):
sorted_lst = []
aux = [0 for i in range(101)]
for elt in lst:
aux[elt] += 1
for i, elt_count in enumerate(aux):
for _ in range(elt_count):
sorted_lst.append(i)
return sorted_lst
#... |
2dd405bb913b6e7936d823be541877acf3501816 | nstvn/Zoo | /Volier.py | 1,792 | 4 | 4 | class Volier:
def __init__(self):
self.habitat = 0
self.status = 'free'
def choose_volier(self, zoo):
type_of_volier = input('Choose type: Ground(1) or Water(2) ')
if type_of_volier == '1':
print('Ground volier - price: 100 \n')
choose = input('y - yes,... |
41b0ec0cee7c6709b6eae019e342337432ea37bf | RoyMcCrain/Mastering-Vim | /Chapter06/animal.py | 343 | 3.78125 | 4 | """An animal base class."""
class Animal(object):
def __init__(self, kind):
self.kind = kind
def get_kind(self):
return self.kind
def act(self, target, verb):
return 'Suddenly {kind} {verb} at {target}!'.format(
kind=self.kind,
verb=verb,
... |
c2083dc48b4929f8186ce3c563a1ca07100eecfd | AIFDR/tsudat2 | /tsudat/landward.py | 5,064 | 3.984375 | 4 | #!/usr/bin/env python
"""
Sample 'landward_boundary' code.
The object of the exercise is to take a set of points defining a bounding
polygon and extract the 'landward boundary' set of points, that is, the
polygon points that are on land. We assume that the caller can 'adorn'
each point with some sort of flag indicat... |
222df7287c5380fe618cd86b94405a4288ba2514 | bbaroi/mind_reader | /mind_reader.py | 1,123 | 4.0625 | 4 | '''This program will ask you to think of a number between 1 and 31 and will guess the
correct answer'''
a=[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31]
b=[2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31]
c=[8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31]
d=[4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31]
e=[16,17,18,19,20,21,2... |
c7a3c62a63e46f915219ff699209d257e7143a90 | Anulali/guvi | /reverse.py | 75 | 3.75 | 4 | num=int(input())
while(num!=0):
a=num%10
print(a,end="")
num=num//10
|
ddc1996b3f5cd3be9729d53036c5ed6fde332d46 | aimdarx/data-structures-and-algorithms | /solutions/Recursion & Dynamic Programming/tower_of_hanoi.py | 2,213 | 4.0625 | 4 | """
Tower of Hanoi
https://youtu.be/rf6uf3jNjbo
https://runestone.academy/runestone/books/published/pythonds/Recursion/TowerofHanoi.html
https://leetcode.com/discuss/general-discussion/1517167/Tower-of-Hanoi-Algorithm-%2B-Python-code
https://www.notion.so/paulonteri/Recursion-DP-Backtracking-525dddcdd0874ed9837251872... |
39d4808169d3ef80890a09b0ac84184775ae8b4f | sungminoh/algorithms | /leetcode/solved/378_Kth_Smallest_Element_in_a_Sorted_Matrix/solution.py | 4,507 | 3.875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 sungminoh <smoh2044@gmail.com>
#
# Distributed under terms of the MIT license.
"""
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
Note that it is ... |
c76ee7fa5a53a31fe410f103be77d6c73ed3a079 | Zetinator/just_code | /python/data_structures/avl.py | 5,463 | 3.75 | 4 | """custom implementation of a self balanced binary search tree with the purpose of practice
the ADT contains the following methods:
- insert
- search
- travese
- delete
- successor
"""
from data_structures import bst
class AVL(bst.BST):
class Node():
"""Node basic chainable storage unit... |
8176eb29e74e3420c9456f02cab254739c1e1fc5 | Rinzing-NR/Learning-Python | /ques5.py | 166 | 4.125 | 4 | x=int(input("Enter x\n"))
y=int(input("Enter y\n"))
if(x>y):
print(x," is greater")
elif(y>x):
print(y," is greater")
else:
print("Both are equal") |
bb4c9206cf9ebe8cb0763c1c05396d877f135aa1 | spryor/Machine-Learning | /Python/MeanShift/mean_shift.py | 2,246 | 3.671875 | 4 | #Author: Stephen Pryor
#Date: 10/6/12
"""
This is my implementation of the Mean Shift algorithm applied for Clustering.
Useful references which I used to help my understanding of the algorithm:
http://saravananthirumuruganathan.wordpress.com/2010/04/01/introduction-to-mean-shift-algorithm/
http://www.inf.tu-dresden.d... |
424cee535451cf76e23f578fa1fef46de48d2cf0 | AkihikoTakahashi/ProjectEuler | /Problem094.py | 2,207 | 3.546875 | 4 | # coding: utf-8
# 辺の長さがそれぞれ (x, x, x+1) とするとヘロンの公式から
# S = (s(s - x)^2(s - x - 1))^(1/2), s = (3x - 1)/2
# となり, 整理すると
# S = (x + 1)/2 * ((3x +1)/2 * (x - 1)/2)^(1/2)
# よって x は奇数なので, x = 2n + 1 とすると,
# S = (n + 1) * (n(3n + 2))^(1/2) となる. (n > 0)
#
# n(3n + 2) は平方数となるので, n(3n + 2) = y^2 とする.
#
# 3n^2 + 2n - y^2 = 0
# ... |
002c53cc4ee7b7614bcb72a1b6b1515f965075f9 | 4WHITT04/COM411 | /oop/human.py | 639 | 3.84375 | 4 | class human:
MAXENRG = 100
def __init__(self, name="Human", age = 0):
self.name = name
self.age = age
self.energy = human.MAXENRG
def display(self):
print("{}, is, {} years old with a current energy level of {}" .format(self.name, self.age, self.energy))
def __repr__(self):
retur... |
137f3b223ce023f639251d19e863642a5ea1d04b | mickey0524/leetcode | /868.Binary-Gap.py | 1,124 | 3.6875 | 4 | # https://leetcode.com/problems/binary-gap/description/
#
# algorithms
# Easy (62.0%)
# Total Accepted: 5.1k
# Total Submissions: 8.2k
# beats 77.89% of python submissions
# Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.
# If there are... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.