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 |
|---|---|---|---|---|---|---|
f89f6b08c525c5fdb4dd44771da293e726b20bcf | gosephjoh/encore-examples | /211/recursion/rumour.py | 1,230 | 3.71875 | 4 | """
Class Encore CIS 211 w/ Joseph
rumour.py
Author: Joseph Goh
Updated: 04/23/2020
"""
class Gossiper:
def __init__(self, name: str, rumour: str, source: "Gossiper" = None):
self.name = name
self.rumour = rumour
if source is None:
self.source = self
else:
s... |
954351b0d1f0732a2de04ac6d49e826b5419ea20 | adamkittel/src | /VMWsolutions/at2-vclient-032/cft/toggle_port.py | 6,760 | 3.609375 | 4 | #!/usr/bin/python
# This script will disable and then enable a switch port
# ----------------------------------------------------------------------------
# Configuration
# These may also be set on the command line
switch_ip = "10.200.1.230" # the IP address of the switch
... |
00fd23048aa3d9c7384099b1dbf6e2c28a66c6ac | Jenionthenet/Week-2 | /Day-3/remove_duplicate.py | 544 | 3.609375 | 4 | with open("emails.txt") as file:
emails = file.read()
split_emails = emails.split(',')
#print(split_emails)
#emails_arr = split_emails
dup_arr = []
unique_arr = []
for email in split_emails:
if email not in unique_arr:
unique_arr.append(email)
if emai... |
3c0f17d1c38b36d5702d51e5f50f854f923d9eb5 | daviddeasy/PythonLearning | /Messing/ListMessing.py | 600 | 3.796875 | 4 |
def test(iterable, cmp=None, key=None, reverse=False):
print iterable, cmp, key, reverse
def main():
a = [2, 3, 1, 5, 4]
print 'sorted(a):', sorted(a)
print 'sorted(a, reverse=True)', sorted(a, reverse=True)
print 'test(a)'
test(a)
print 'test(a,reverse=True)'
test(a, reverse=True... |
5163481a5d3e5e95a0b44d3dca625e0c4b316176 | daviddeasy/PythonLearning | /Messing/messing.py | 1,234 | 3.5625 | 4 | print '\nTHIS IS THE FIRST LINE IN messing.py\n'
s = 'hiya'
print 's1=' + s[1] # i
print 'len(' + s + ')=' + str(len(s)) # 2
print s + ' there' # hi there
print s, 'there'
pi = 3.1417
# text = 'The value of pi is ' + pi # NO, does not work
text = 'The value of pi iiii is ' + str(pi) # yes
print 'text=', text... |
93a0cf706a83f9093a5bc8bb4d011e0ed57a0523 | CiceroWesley/Questions | /Questions in Python/hamming.py | 1,268 | 4.09375 | 4 | def distance(strand_a, strand_b):
if len(strand_a) == len(strand_b):
cont = 0
for i in range(0,len(strand_a)):
if strand_a[i] != strand_b[i]:
cont+=1
return cont
else:
raise Exception("ValueError")
strand1 = ("G")
strand2 = ("")
print(distance(strand1,strand2))
'''
Calculate... |
1746145758785251deaa7b07d0d43c112c9f83b6 | iChoake/nft-gen | /src/nftgen/utils/none.py | 579 | 3.5625 | 4 | from typing import TypeVar, Optional, Dict, Any
T = TypeVar("T")
def not_none(t: Optional[T], default: T):
"""
Returns `t` if not None, else `default`.
:param t: the value to return if not None
:param default: the default value to return
:return: t if not None, else default
"""
return t ... |
75b9059de7dc0489d165d723a3933aec92599a1f | katoluo/Python_Crash_Course | /chapter_10/10-11.py | 730 | 3.6875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
# coding style: pep8
# ====================================================
# Copyright (C) 2021 All rights reserved
#
# Author : kato
# Email : 1123629751@qq.com
# File Name : 10-10.py
# Last Modified : 2021-01-08 10:25
# Describe :
#
# ===... |
4743239fe23328e50376acba310d06e433a248b8 | katoluo/Python_Crash_Course | /chapter_03/del_list.py | 659 | 3.796875 | 4 | names = [ 'Davie', 'Aragne', 'James' ]
print("I have found a big table.")
# 使用 insert() 将一位新嘉宾添加到名单开头
names.insert(0, 'kaly')
# 使用 insert() 将另一位新嘉宾添加到名单中间
names.insert(2, 'mike')
# 使用 append() 将最后一位新嘉宾添加到名单末尾
names.append('yarl')
print(names)
print("I just can invite two guest.")
message = "I'm so sorry, "
print(messag... |
bc440b3260e358a3229933b60c506706d32fd007 | katoluo/Python_Crash_Course | /chapter_07/7-2.py | 498 | 3.96875 | 4 | #!/usr/bin/env python3
# encoding: utf-8
# coding style: pep8
# ====================================================
# Copyright (C) 2021 All rights reserved
#
# Author : kato
# Email : 1123629751@qq.com
# File Name : 7-2.py
# Last Modified : 2021-01-06 16:37
# Describe :
#
# =====... |
f1fe2d0ee08fd6ff898efdfb5c2335c8552504f7 | katoluo/Python_Crash_Course | /chapter_04/4-11.py | 381 | 4.25 | 4 | my_pizzas = [ 'one', 'two', 'three' ]
print("my_pizzas: " + str(my_pizzas))
friend_pizzas = my_pizzas[:]
print("friend_pizzas: " + str(friend_pizzas))
my_pizzas.append('my_four')
friend_pizzas.append('friend_four')
print("My favorite pizzas are:")
for value in my_pizzas:
print(value)
print("My friend's favorite... |
90807d548cc21c6c1c72dcca4339023779fe5db2 | katoluo/Python_Crash_Course | /chapter_10/10-5.py | 699 | 3.734375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
# coding style: pep8
# ====================================================
# Copyright (C) 2021 All rights reserved
#
# Author : kato
# Email : 1123629751@qq.com
# File Name : 10-5.py
# Last Modified : 2021-01-07 23:13
# Describe :
#
# ====... |
89c137f9909a7dc26bf819483ba72c1636da7dca | LinsonJoseph/python | /DemonstratingPowerCalculation.py | 179 | 3.84375 | 4 | n = int(input("Input a number (n): "))
m = int(input("Input another number (m): "))
sol = 2*(n**3) + 5*(m**2) + 7*n + 10
print("2*(n**3) + 5*(m**2) + 7*n + 10 is: ", sol)
|
b6973ffd3f4694f36cac5a83200874a1a734072c | LinsonJoseph/python | /SummingUpFiveUserInputNumbers.py | 255 | 3.8125 | 4 | a = 0
x = 1
while(x<=5):
try:
n = int(input("Input an integer(" + str(x) + "): "))
except ValueError:
continue
else:
a += n
print("Sum of current and previous input(s) is: ", a)
x += 1
|
365d066474e18dafccfeecf141a6f339052edc73 | LinsonJoseph/python | /use_of_is.py | 1,090 | 4.1875 | 4 | #Use of 'is'
list_123 = [1, 2, 3]
list_321 = [3, 2, 1]
tuple_123 = (1, 2, 3)
tuple_321 = (3, 2, 1)
# == compares the value of both operands
if id(list_123[0]) == id(list_321[2]):
print(f'ID of 1st element of list_123 is {id(list_123[0])} and is same as id of 3rd element of list_321 {id(list_321[2])}')
els... |
ef95230cdd5ecfde761946e6cc6fc6b97f240600 | ballcap231/Projects | /monte_carlo.py | 623 | 3.75 | 4 | #Monte Carlo Estimation of Pi
#Randomly generate values between -1 and 1.
#Count how many generated points are within unit square and unit circle
#The ratio of how many are in unit circle to unit square is equal to pi / 4 (i.e. the ratio of their areas)
import random
random.seed(1)
iterations = 1_000_000
circle_count... |
5cff1c9c75d7168570bbe9ec9fe6e0fb0428a805 | licche/LeetCode_record | /Binary Search/034. Find First and Last Position of Element in Sorted Array.py | 2,933 | 4.0625 | 4 | 题目:
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
这题可以好好研究,主要思路是需要分别找到target第一次出现的位置和最后一次出现的位置,返回即可。
套用模板的时候,每一步... |
72a11877653fff1303ab253d07d35cdb74114164 | KoomeA/p-manager | /test_user.py | 1,174 | 3.765625 | 4 | import unittest
from user import User
class TestUser(unittest.TestCase):
"""
"""
def setUp(self):
"""
method to run before each testcase
"""
self.new_user = User("Koome", "4444")
def tearDown(self):
"""
clean up after each test case runs
... |
892dbb51692a0b507da19686627dcea1973312c7 | jasonl0209/CCC-Solutions-Senior | /CCC '19 S1.py | 335 | 3.75 | 4 | rawinput = input()
original = [1,2,3,4]
for i in range(len(rawinput)):
if rawinput[i] == "H":
original = [original[2], original[3], original[0], original[1]]
elif rawinput[i] == "V":
original = [original[1], original[0], original[3], original[2]]
print(original[0], original[1])
print(original[2]... |
5dd7575755ea470395623763a0a49c1f086f71da | jasonl0209/CCC-Solutions-Senior | /CCC '05 S1.py | 777 | 3.6875 | 4 | number = int(input())
lst = []
for i in range(number):
string = ''
for s in input():
if s.isalpha() == True:
if s=="A" or s=="B" or s=="C":
s = 2
elif s=="D" or s=="E" or s=="F":
s = 3
elif s=="G" or s=="H" or s=="I":
s ... |
53b5e0a564b279e63ceb6458310fcbaeec68d933 | DustinRPeterson/lc101 | /crypto/vigenere.py | 2,230 | 4.125 | 4 |
#Encrypts text using the vignere algorithm (https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher)
from helpers import alphabet_position, rotate_character #import alphabet_position and rotate_character from helpers.py
lower_case_dict = dict() #create dictionary for lowercase letters
upper_case_dict = dict() #creat... |
1f05bb1a762345e4fb8642fc7d23a237a83d2ded | sgarcialaguna/Project_Euler | /problem12.py | 1,347 | 3.765625 | 4 | """The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,1... |
b74c5dc4178814dc5218585173c084e8f41125ce | sgarcialaguna/Project_Euler | /primes.py | 1,155 | 3.640625 | 4 | import math
def prime_factorization(n):
if n < 1:
raise NotImplemented
if n == 1:
return [1]
primeFactors = []
i = 2
while i * i <= n:
if n % i != 0:
i += 1
else:
n //= i
primeFactors.append(i)
if n > 1:
primeFactors.a... |
2429f7197590c3cb760c9a9257b1daad48773f6d | veioxidation/api-example-1 | /create_tables.py | 618 | 3.890625 | 4 | # import sqlite3
#
# connection = sqlite3.connect("data.db") # SQLite DB
#
# cursor = connection.cursor()
# create_table = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text, password text)"
# cursor.execute(create_table)
#
# insert_query = "INSERT INTO users VALUES (?, ?, ?)"
# users = [(1, 'prz... |
245cfc80a5834e9161d9535b37920b2762409a29 | RiccardoConti10/informatica | /17:_pag_189.py | 1,344 | 3.90625 | 4 | '''Risolvi il problema precedente partendo da due liste che generano un dizionario
con la nazione come chiave e la capitale come valore. Successivamente interroga il dizionario
per visualizzare la capitale di una nazione
'''
def crea_dict(Nazioni, Capitali, dizionario={}):
for i in range(len(Nazioni)):
dizi... |
decab82ac08f3dd4b166a120720056dc41f1c3c2 | RiccardoConti10/informatica | /es_5_6_pag_292.py | 2,622 | 3.671875 | 4 | class Prodotto():
def _init_(self, quantità, materiale, oggetto):
self.quantità = quantità
self.materiale = materiale
self.oggetto = oggetto
def assegna_prezzo(self):
dizionario_prodotti_in_vendita = {
1: "Assi",
2: "Tubi",
3: "Gioielli"}
... |
40e122319fdfdee3539dd6898ea9c0c709f04da3 | HegemanLab/extra_tools | /compoundcounter.py | 3,426 | 3.546875 | 4 | '''
Reads in csv of mzs, outputs how many times the mzs
were present in a number of input files
'''
# import packages. csv is standard package and pandas is widely used and part of Anaconda packages
import csv
import pandas as pd
# short helper to pass into map. Takes number and rounds to 3 decimal place... |
f33253da6d7428ed37017fd69525f9bc87bbc34a | VIRTUALGOD325/Project100 | /atm.py | 615 | 3.53125 | 4 | class ATM():
def __init__(self):
self.self = self
def access(self):
pin = input("ENTER YOUR PIN TO START: ")
print(pin)
print("ACCESS GRANTED")
def cashWithdraw(self):
amount = input("HOW MUCH DO YOU WANT TO WITHDRAW: ")
print("AMOUNT WITHDRAWN",a... |
957b002bc3e619043c8f5376b8395737749e3478 | Antohnio123/Portfolio | /L3_Decorator_fabric.py | 1,052 | 3.96875 | 4 | from functools import wraps
def apply(func2: callable) -> any:
"""It decors a function and gives its stdout to the second function, that it has as the first attribute.
Returns a result (stdout) of an attribute function.
:func2: attribute function, that needs to get the result of other one (func1).
... |
2cf92595d7b8cb51b3145629030ee622d543e1a6 | Waldemar-Makalafen/Lecture_1 | /Zadanie_3.py | 313 | 3.578125 | 4 | import math
a = int(input('Введи а '))
b = int(input('Введи б '))
c = int(input('Введи с '))
d = b**2+4*a*c
d = math.sqrt(d)
print (d)
if d > 0:
x1 = -b-d/2*a
x2 = -b+d/2*a
print(x1,x2)
else:
x = -b/2*a
print(x)
Chtoby_ne_vilitalo = input ()
|
d6bd2c447f5821498f454ba1bfc5f655e4330d25 | Waldemar-Makalafen/Lecture_1 | /Dl Academy/Лекция_первое_занятие/3занятие/normal/PN4.py | 400 | 3.78125 | 4 | list1 = []
list2 = []
a = int(input())
b = int(input())
d = int(input())
c = int(input())
e = int(input())
list1.append(int(a))
list1.append(int(b))
list1.append(int(d))
list1.append(int(c))
list1.append(int(e))
print(list1)
list2= list(set(list1))
print(list2)
#list1.append(int(a))
#list1.app... |
27e01237b6fcd1b6f140ce593c1eec2399b1d724 | Waldemar-Makalafen/Lecture_1 | /Dl Academy/Лекция_первое_занятие/2занятие/HW2.py | 612 | 3.78125 | 4 | x1 = input('чётные или не ?')
chet = [0 ,2 ,4 ,6 ,8 ,10 ,12 ,14 ,16 ,18 ,20 ]
nechet = [1 ,3 ,5 ,7 ,9 ,11 ,13, 15 ,17 ,19 ]
n = 0
list (chet)
list (nechet)
while n == 0:
if x1 == "чётные" or "чёт":
print (chet)
exit = input("exit ?")
if exit == "no":
x1 = input('чётные или не ?')
else:
br... |
6e5ff90d17167bd016075c9baae8e55a1a4ee073 | RavicharanN/Compiler-Design | /lab3/regex_to_dfa/sol.py | 1,022 | 3.578125 | 4 | class StateMachine(object):
def __init__(self, name, automaton_alphabet):
self.name = name
self.automaton_alphabet = automaton_alphabet
self.states = {} # Contains all the states in the machine.
self.add_state('start', state_type='s')
def add_state(self, state_name, state_t... |
e9be3ca9cabd148343f7f3dbb3ef82604359db85 | Dreamcomputer/TradeAnalysis | /Question5.py | 11,312 | 3.5 | 4 | '''
QUESTION 5:
Suppose you are a dealer and start with 0 shares of Apple stock and must take the other side of orders in trades.txt
that should cross in the market immediately upon order entry. Then, suppose you were given a maximum of 1 minute to
either buy or sell those shares to get back to 0, assuming that you c... |
7672bc9f9fee9f1ab0dde5bb39af478e02a1ab75 | victormanuel-q/PracticaLab_QuispeQuispe | /Preg03.py | 151 | 3.828125 | 4 | # Autor: Pilar_Navarro
cadena = input ("Cadena: ")
total_caracteres = len(cadena)-(len(cadena.split())-1)
print (f"Resultado: {total_caracteres}") |
0ebc30ff3f710310db361194090f163abcf9e8c7 | MarsWilliams/PythonExercises | /How-to-Think-Like-a-Computer-Scientist/DataFiles.py | 2,582 | 4.34375 | 4 | #Exercise 1
#The following sample file called studentdata.txt contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student.
#joe 10 15 20 30 40
#bill 23 16 19 22
#sue 8 22 17 14 32 17 ... |
01706c6a73d183265c77df8b37f6475bf3cb19cb | MarsWilliams/PythonExercises | /practiceProblems/best_profit.py | 851 | 3.796875 | 4 | def best_profit(stock_prices_yesterday):
lowest_price = stock_prices_yesterday[0]
final_price = 0
profits = [ ]
for i in range(1, len(stock_prices_yesterday)):
if stock_prices_yesterday[i] > final_price and stock_prices_yesterday[i] > lowest_price:
final_price = stock_prices_yesterday[i]
profits.appe... |
418e30ef9e66a82a215c81a781c4b83a9a0792c4 | MarsWilliams/PythonExercises | /How-to-Think-Like-a-Computer-Scientist/Lists.py | 4,762 | 4.34375 | 4 | Exercise 1
#Draw a reference diagram for a and b before and after the third line of the following python code is executed:
a = [1, 2, 3]
b = a[:] #making a copy of a, b now points to that copy
b[0] = 5 #reassigning the zeroth index of b to the integer 5
#b now points to the list [5, 2, 3]
#a still poi... |
e8cc853cd0d913344ece1934d3390a89d5abeb4b | MasterOdin/8block-sliding-puzzle | /main.py | 2,968 | 3.828125 | 4 | '''
Name:
8-Block Solver
Desc:
Needs to solve the 8-block sliding puzzle using the A* search algorithm
using Manhattan Distance as the heuristic function
https://www.dropbox.com/s/mwpmtfr0t0qckfi/HW1.pdf
Date Due:
9-29-2013 @ 11:59pm
Author:
Matthew Pev... |
6d36b72644f99c8d988ca4669f952400fc684899 | RubenMkrtchyan30/lesson | /2/exersiceslist.py | 1,001 | 3.75 | 4 | # list1 = [1,1.2,'name',True,(2,4)]
# print(list1)
# list_mac = ['macbook','apple','lg']
# if 'macbook' in list_mac:
# print('yes')
# else:
# print('no')
# spec =('!','@','#','$','%','&','*')
# password = input('enter your password ')
# dig = 0
# spec_num = 0
# for i in password:
# if i.isdigit():
# dig += 1
# ... |
4afd26c07fb05bea86f1b2e8c41b3098d63f9c45 | RubenMkrtchyan30/lesson | /exercises.py | 212 | 3.546875 | 4 | nahanj = int(input('mutqagreq taretivy '))
payman1 = nahanj % 4 == 0
payman2 = nahanj % 100 == 0
payman3 = nahanj % 400 != 0
if payman3 or payman1 and payman2:
print('nahanj tari e ')
else:
print('nahanj che ') |
b1b691cfcee01994d45b1bc388f6349bdd1d0189 | RubenMkrtchyan30/lesson | /2/dictexer.py | 1,627 | 3.609375 | 4 | dictionary = {'Arsen':10,'Davit':6,'Sargis':5,'Ani':2,'Hayk':4,'Davit':8,'Syuzanna':7,'Alis':9,'Armen':4,'Marta':7}
res = 0
# mijin tvabanakan
# for i in dictionary.values():
# res += i
# print(res/len(dictionary))
# for j in dictionary.values():
# if j > res:
# res = j
# for i in dictionary.keys():
# if dic... |
5dd570568a4c5a100831ef9d1185853f6461f8d6 | RubenMkrtchyan30/lesson | /2/list.py | 881 | 4 | 4 | # fruits = ['banana', 'apple','cherry']
# print(fruits)
# numbers = [34,56,-456,7.56,-2.34]
# print(numbers[1])
# fruits[1] = 'kiwi'
# print(fruits)
# fruits = ['banan','apple','cherry']
# print('len =',len(fruits))
#append() avelacnum e listin nor arjeq listi verjum
# fruits = ['banana','apple','cherry']
# fruits... |
43c01d5fa0398c95e9c12d614ea2feaed4540a42 | eamirmohammad/Python-Summer-Course | /EX_10.1.py | 864 | 3.53125 | 4 | # EX_10.1:
import numpy as np
import matplotlib.pyplot as plt
#1.1:
print ('1.1:')
x = 10
print ('x is equal to ', x, '\n')
#1.2:
print ('1.2:')
xx = np.power (x ,2 )
print ('square of x is equal to ',xx, '\n')
#1.3:
print ('1.3:')
theta = 30
print ('Angle is equal to ',theta, '\n')
#1.4:
print ... |
8e71ccf8077dd425f04ff76d38215828b2d2b234 | welsny/code | /gpa.py | 1,149 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import optparse
def read_cl():
parser = optparse.OptionParser()
parser.add_option("-f","--filename", default="grades.csv", help="file to read")
parser.add_option("-n","--neu", default=True, action="store_false",
help="use stan... |
79f26259e338f29ab0830685f0f73a427e6d25fb | Ghong-100/Python | /Algorithm/DataStructure/03_LinkedList.py | 4,848 | 4.15625 | 4 | class Node:
def __init__(self, data, nextNode = None):
self.data = data
self.next = nextNode
# node1 = Node(1)
# node2 = Node(2)
# node1.next = node2
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def add(self, data, index = 0... |
8599e087982ee28bf24eae192aec3c11c6a8f5a7 | Ghong-100/Python | /Practice/Quiz9.py | 1,166 | 3.84375 | 4 | '''
치킨 자동 주문 제작 시스템.
조건1 : 1보자 작거나 숫자가 아닌 값이 들어올 때는 ValueError 처리
출력 : 잘못된 값을 입력하였습니다.
조건2 : 준비된 닭은 총 10마리임
치킨 소진시 SoldOut 에러 발생 후 종료
출력 : 재고가 소진되어 더 이상 주문을 받지 않습니다.
'''
chicken = 10
waiting = 1 # 대기번호 1부터 시작
class SoldOut(Exception):
def __str__(self):
return "재고가 소진되어 더 이상 주문을 받... |
9cd004fe94f48236314b5c51a3367e86189265f2 | Ghong-100/Python | /Algorithm/Algorithm/11_SelectionSort.py | 811 | 3.703125 | 4 | '''
O(n²)
1. 주어진 데이터 중 최소값 찾기
2. 최소값을 맨 앞의 값과 스왑
3. 그 다음위치부터 반복
'''
import random
def sort_selection(sortList):
size = len(sortList)
minIndex = 0
for i in range(0, size):
minIndex = i
for j in range(i+1, size):
if sortList[minIndex] > sortList[j]:
minIndex = j
... |
12f6a29c1def0e9c1abd600d331cd470c49b37e5 | Ghong-100/Python | /Practice/Condition.py | 3,239 | 4.125 | 4 | '''
# if 조건:
# 처리
# else 조건:
# 처리
weather = input("What the weather today ? ")
if weather == "rain" or "snow":
print("Need umbrella!")
elif weather == "dusty":
print("Need mask!")
elif weather == "hot":
print("Need fan!")
else:
print("Go free!!!")
temp = int(input("temperature?? "))
if temp >= 3... |
089e9a777df74014caad7bf23e74f5f01b12c299 | Ghong-100/Python | /Practice/Std_IO.py | 1,689 | 3.625 | 4 | import sys
'''
print("Python", "Java", sep = " and ") # seperator 를 지정해서 ,로 붙인 문자열 사이에 넣어줄 수 있다.
print("Python", "Java", sep=',', end='??')
print("무엇이 더 재미있을까요오오오오오오오오오오ㅗ오오ㅗ")
print("Python", "Java", file=sys.stdout) # 표준 출력으로 출력
print("Python", "Java", file=sys.stderr) # 표준 에러로 출력
'''
# scores = {"math":0, "... |
70396f22a7b2094dcef2afd1e5c43a56f8fb1fad | jameshicks/avl | /avl/avl.py | 12,649 | 3.765625 | 4 | import sys
assert sys.version[0] == '3'
class Stack(object):
'A first-in last-out datastructure'
def __init__(self, starts=None):
self.front = None
if starts:
for val in starts:
self.push(val)
def __bool__(self):
return self.front is not None
def... |
34daa1dd0798b77c64085a0b289cd4750de01480 | naiieandrade/tcc-studies | /bernoulli.py | 2,773 | 3.765625 | 4 | #%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from auxiliar_functions import calculate_median, calculate_variance
# with three variables is dirichlet distribution
def generate_dirichlet_distribution_with_three_variables(list_alpha, si... |
a6a99be0d91b758a13eb0f10d4f42101dd22b2ae | lindameh/cpy5p2 | /q11_find_gcd.py | 220 | 3.8125 | 4 | n1 = int(input("Enter a positive integer: "))
n2 = int(input("Enter another postive integer: "))
a = [n1, n2]
a.sort()
d = a[0]
while a[0] % d != 0 or a[1] % d != 0:
d -= 1
print("The greatest common divisor is", d)
|
2162bf64a994dacf07b137082fc87fb2d2214388 | Ir4ik28/irka | /vozdenie.py | 295 | 3.71875 | 4 | def car_18(x, y):
if y > 18:
print(f'{x} может водить машину')
elif y < 18:
print(f'{x} не может водить машину')
else:
print('команда введена не верно')
return
car_18('Ринат', 28)
|
0b817295182ab2efce507342069f6065768fdc7b | ArtemTsukanovv/game | /gameComponents/winLose.py | 684 | 3.546875 | 4 | from gameComponents import gameVars
def winorlose(status):
if status == "won":
pre_message = "You win! "
else:
pre_message = "You lose! "
print(pre_message + 'Play again?)')
choice = False
while choice == False:
choice = input("Y / N? ")
if choice == "Y" or choi... |
48bbc03748ad8181115ecd491dbebd1e8a585b1c | Sapan-Ravidas/Machine-Learning-Built-In-Modules | /01_linear_reg/gradient_decent.py | 673 | 3.890625 | 4 | import numpy as np
def gradient_descent(x, y):
m_curr = b_curr = 0
rate = 0.08
n = len(x)
iterations = 10000
for i in range(iterations):
y_predicted = m_curr * x + b_curr
cost = (1/n) * sum([val ** 2 for val in (y - y_predicted)])
# print(m_curr, b_curr, y_predicted, i)... |
613192b11ca35197445586289a608f7a6e00916a | jammy-data/Practicals | /Prac1-2/model(1+2).py | 2,709 | 3.828125 | 4 | import random
import operator
import matplotlib.pyplot
agents = []
#random seed for testing. comment out to view alternate agent plots
random.seed(10)
#Remove y0,x0 and replace with the randoms within parenthesis
agents.append([random.randint(0,99),random.randint(0,99)])
#assign a random number to Rando;
#also avai... |
6032e5cd91b2d6b098db7c7dc19263b11123eb24 | weiyuyan/LeetCode | /三数之和.py | 1,514 | 3.734375 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/1/10
'''
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
'''
from typing import List
class Solution:
... |
bd0568c32d0d48cf194b6c06b07643f68a46be6d | weiyuyan/LeetCode | /DP/198. 打家劫舍.py | 2,178 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/5
'''
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,
如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
示例 1:
输入: [1,2,3,1]
输出: 4
解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + ... |
cca0db286b81980ff0def1e502f924a21b46d3c1 | weiyuyan/LeetCode | /剑指offer/21. 斐波那契数列.py | 574 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/11
'''
输入一个整数 n ,求斐波那契数列的第 n 项。
假定从0开始,第0项为0。(n<=39)
样例
输入整数 n=5
返回 5
'''
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
res = [0, 1, 1]
if n <= 2:
... |
3eabb306595d44defc56a3f7afa2767d606a00e8 | weiyuyan/LeetCode | /2020年4月18日春季全国编程大赛/2. 传递信息.py | 2,611 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/4/18
'''
小朋友 A 在和 ta 的小伙伴们玩传信息游戏,游戏规则如下:
有 n 名玩家,所有玩家编号分别为 0 ~ n-1,其中小朋友 A 的编号为 0
每个玩家都有固定的若干个可传信息的其他玩家(也可能没有)。传信息的关系是单向的(比如 A 可以向 B 传信息,但 B 不能向 A 传信息)。
每轮信息必须需要传递给另一个人,且信息可重复经过同一个人
给定总玩家数 n,以及按 [玩家编号,对应可传递玩家编号] 关系组成的二维数组 relation。返回信息从小 A (编号 ... |
4a7b5288e4f1553f8de6a6b7c02a60041fa30b03 | weiyuyan/LeetCode | /剑指offer/面试题50. 第一个只出现一次的字符.py | 719 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/3
'''
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。
示例:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
限制:
0 <= s 的长度 <= 50000
'''
# 思路:哈希表用作辅助空间
class Solution:
def firstUniqChar(self, s: str) -> str:
hash_dict = {}
for char in s:
... |
7b3052a9048fd7c120c7eefe478740f41fa967f2 | weiyuyan/LeetCode | /013.py | 1,745 | 3.515625 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/1/3
'''
Title: 罗马数字转整数
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5... |
8cc2ade23519756c6201759d95c1d110caa1d826 | weiyuyan/LeetCode | /LeetCode周赛/2020年5月2日双周赛/5385. 改变一个整数能得到的最大差值.py | 2,836 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/5/2
'''
给你一个整数 num 。你可以对它进行如下步骤恰好 两次 :
选择一个数字 x (0 <= x <= 9).
选择另一个数字 y (0 <= y <= 9) 。数字 y 可以等于 x 。
将 num 中所有出现 x 的数位都用 y 替换。
得到的新的整数 不能 有前导 0 ,得到的新整数也 不能 是 0 。
令两次对 num 的操作得到的结果分别为 a 和 b 。
请你返回 a 和 b 的 最大差值 。
示例 1:
输入:num = 555
输出:888
解释... |
37cdb590321183be23f65759ec6ddb325e0560a0 | weiyuyan/LeetCode | /21. 合并两个有序链表.py | 2,233 | 4.09375 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/1/12
'''
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solut... |
4aa82c9de8f706a45de3e5a02235f7c75b060a31 | weiyuyan/LeetCode | /DP/746. 使用最小花费爬楼梯.py | 1,965 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/2
'''
数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
示例 1:
输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
示例 2:
输... |
e1153dc1454de2bc461d3d04de41759dd0aaefa2 | weiyuyan/LeetCode | /每日一题/March/1071. 字符串的最大公因子.py | 1,534 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/12
'''
对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
示例 1:
输入:str1 = "ABCABC", str2 = "ABC"
输出:"ABC"
示例 2:
输入:str1 = "ABABAB", str2 = "ABAB"
输出:"AB"
示例 3:
输入:str1 = "LEET", str2 ... |
1cdffd1746ecc675ee1a9e662fbe3690719862d6 | weiyuyan/LeetCode | /每日一题/April/445. 两数相加 II.py | 3,514 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/4/14
'''
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
通过次数22,782提交次数40,565
'''
# Defi... |
0dca0b990610cc3d92d4e89e3cc33fd367b63abc | weiyuyan/LeetCode | /24. 两两交换链表中的节点.py | 2,180 | 4.125 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/1/13
'''
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
'''
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# ... |
b94f79e730e851dfd3f3fb5cebbb935bb5417ca1 | weiyuyan/LeetCode | /20. 有效的括号.py | 1,372 | 3.984375 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/1/12
'''
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"... |
7ee4ed2d1167372fad229e6daf1958767613e19b | weiyuyan/LeetCode | /AcWing算法基础课/堆/838. 堆排序.py | 1,653 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/17
'''
输入一个长度为n的整数数列,从小到大输出前m小的数。
输入格式
第一行包含整数n和m。
第二行包含n个整数,表示整数数列。
输出格式
共一行,包含m个整数,表示整数数列中前m小的数。
数据范围
1≤m≤n≤105,
1≤数列中元素≤109
输入样例:
5 3
4 5 1 3 2
输出样例:
1 2 3
'''
# 如何手写一个堆?
# 1、插入一个数
# 2、求集合中的最小值
# 3、删除最小值
# 4、删除任意一个元素
# 5、修改任意一个元素
# 堆是一... |
244543fc08967bbac707908757330d85a58d0e2e | weiyuyan/LeetCode | /剑指offer/面试题43. 1~n整数中1出现的次数.py | 1,719 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/25
'''
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
'''
# 第一个方法超时了,观察数据规律,可以想出另一个方法
# class Solution:
# def countDigitOne(self, n: int) -... |
960ad5787144bd64d00346e00f3cec07bfbc3258 | weiyuyan/LeetCode | /DP/1218. 最长定差子序列.py | 3,223 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/4
'''
子数列,又称子序列,在数学中,某个序列的子序列是从最初序列通过去除某些元素但不破坏余下元素的相对位置(在前或在后)而形成的新序列。
给你一个整数数组 arr 和一个整数 difference,请你找出 arr 中所有相邻元素之间的差等于给定 difference 的等差子序列,并返回其中最长的等差子序列的长度。
示例 1:
输入:arr = [1,2,3,4], difference = 1
输出:4
解释:最长的等差子序列是 [1,2,3,4]。
示例 2:... |
47f4bbfbc784d1261bbf98960692108f2cca6d3e | weiyuyan/LeetCode | /剑指offer/面试题32 - III. 从上到下打印二叉树 III.py | 4,044 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/19
'''
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
提示:
节点总数 <= 1000
'''
# Definition... |
4976723934665a9ec4f0a545a454f7d78c1d7352 | weiyuyan/LeetCode | /每日一题/April/23. 合并K个排序链表.py | 2,639 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/4/26
'''
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
'''
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
... |
54330d4906d1e24026625c97f4c527f7a05adae2 | weiyuyan/LeetCode | /剑指offer/面试题37. 序列化二叉树.py | 3,280 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/20
'''
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
注意:本题与主站 297 题相同:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
'''
# Definition for a binary tr... |
d95e31b12b32a683542d10f1adc97570b4964a8a | weiyuyan/LeetCode | /DP/72. 编辑距离.py | 1,959 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/12
'''
给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
示例 1:
输入: word1 = "horse", word2 = "ros"
输出: 3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
示例 2:
输入: wor... |
ba723fb6aa89932eaa4f38b3cd6479aafd767c4d | weiyuyan/LeetCode | /剑指offer/面试题40. 最小的k个数.py | 1,634 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/21
'''
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
示例 1:
输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
示例 2:
输入:arr = [0,1,2,1], k = 1
输出:[0]
限制:
0 <= k <= arr.length <= 1000
0 <= arr[i] <= 1000
通过次数1,639提交次数2,726
'... |
207cf30c991acc80f93d649837080e712a9143e9 | weiyuyan/LeetCode | /LeetCode周赛/2020年3月1日周赛/5344. 有多少小于当前数字的数字.py | 1,812 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/1
'''
给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。
换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。
以数组形式返回答案。
示例 1:
输入:nums = [8,1,2,2,3]
输出:[4,0,1,1,3]
解释:
对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。
对于 nums[1]=1 不存在... |
e1d8145ed71f5e1c738176b8fceb1fdda2ca9de8 | weiyuyan/LeetCode | /剑指offer/面试题33. 二叉搜索树的后序遍历序列.py | 3,134 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/19
'''
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。
假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
提示:
数组长度 <= 1000
'''
from typing impor... |
05191d372ab8ed7b6d0a48b13c5d9ce2e99519e5 | weiyuyan/LeetCode | /LeetCode周赛/2020年5月24日周赛/5418. 二叉树中的伪回文路径.py | 5,556 | 3.859375 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/5/24
'''
给你一棵二叉树,每个节点的值为 1 到 9 。我们称二叉树中的一条路径是 「伪回文」的,当它满足:路径经过的所有节点值的排列中,存在一个回文序列。
请你返回从根到叶子节点的所有路径中 伪回文 路径的数目。
示例 1:
输入:root = [2,3,1,3,1,null,1]
输出:2
解释:上图为给定的二叉树。总共有 3 条从根到叶子的路径:红色路径 [2,3,3] ,绿色路径 [2,1,1] 和路径 [2,3,1] 。
在这些路径中,只有红色和... |
7215c50298614baed4cb9b8346560b6fa20e7857 | weiyuyan/LeetCode | /LeetCode周赛/2020年4月5日周赛/5376. 非递增顺序的最小子序列.py | 1,798 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/4/5
'''
给你一个数组 nums,请你从中抽取一个子序列,满足该子序列的元素之和 严格 大于未包含在该子序列中的各元素之和。
如果存在多个解决方案,只需返回 长度最小 的子序列。如果仍然有多个解决方案,则返回 元素之和最大 的子序列。
与子数组不同的地方在于,「数组的子序列」不强调元素在原数组中的连续性,也就是说,它可以通过从数组中分离一些(也可能不分离)元素得到。
注意,题目数据保证满足所有约束条件的解决方案是 唯一 的。同时,返回的答案应当按 非递增顺序 排列。
... |
f355de3509a3044408d82379c7ccf772be6330af | weiyuyan/LeetCode | /加减乘除/乘法.py | 1,528 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/7
'''
【题目】
给定两个32位整数a和b,可正、可负、可0。不能使用算术运算符,分别实现a和b的加减乘除运算。
【要求】
如果给定的a和b执行加减乘除的某些结果本来就会导致数据的溢出,那么你实现的函数不必对那些结果负责。
'''
# 方法一
class Solution:
def multi(self, a, b):
return b and ((b & 1 and a) + self.multi(a<<1, b>>1))
solution = S... |
9e55bc9bcd926a09b4a97705a978887a52442aaa | weiyuyan/LeetCode | /LeetCode周赛/2020年5月24日周赛/5419. 两个子序列的最大点积.py | 2,185 | 3.546875 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: ShidongDu time:2020/5/24
'''
给你两个数组 nums1 和 nums2 。
请你返回 nums1 和 nums2 中两个长度相同的 非空 子序列的最大点积。
数组的非空子序列是通过删除原数组中某些元素(可能一个也不删除)后剩余数字组成的序列,但不能改变数字间相对顺序。比方说,[2,3,5] 是 [1,2,3,4,5] 的一个子序列而 [1,5,3] 不是。
示例 1:
输入:nums1 = [2,1,-2,5], nums2 = [3,0,-6]
输出:18
解释:从 nums1 中得... |
064f486a3f9c3693d504431911a55e2bbd5988b8 | weiyuyan/LeetCode | /AcWing算法基础课/快速排序/AcWing 785. 快速排序.py | 2,207 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/11
'''
给定你一个长度为n的整数数列。
请你使用快速排序对这个数列按照从小到大进行排序。
并将排好序的数列按顺序输出。
输入格式
输入共两行,第一行包含整数 n。
第二行包含 n 个整数(所有整数均在1~109范围内),表示整个数列。
输出格式
输出共一行,包含 n 个整数,表示排好序的数列。
数据范围
1≤n≤100000
输入样例:
5
3 1 2 4 5
输出样例:
1 2 3 4 5
'''
# def quicksort(nums, left, righ... |
4f782161af9d326aa74b1df8aa9344d7f8f312f9 | weiyuyan/LeetCode | /剑指offer/面试题32 - II. 从上到下打印二叉树 II.py | 2,091 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/2/19
'''
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
注意:本题与主站 102 题相同:https://leetcode-cn.com/problems/bin... |
da656c7b187d415acfe8ebe2f8180d42582bed8a | weiyuyan/LeetCode | /每日一题/March/面试题 10.01. 合并排序的数组.py | 2,114 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/3/3
'''
给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。
初始化 A 和 B 的元素数量分别为 m 和 n。
示例:
输入:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
'''
from typing import List
# 第一种方法:直接拼接到A的尾部然后使用sort()方法排序
# class So... |
4194930b9126d522ffc281fd904347cd58153c27 | weiyuyan/LeetCode | /Search/77. Combinations.py | 1,371 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/1/28
'''
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
'''
# 方法一:回溯法
from typing import List
# class So... |
afa6deb21750d20666a88d037cebd5493e89c90b | weiyuyan/LeetCode | /LeetCode周赛/2020年5月3日周赛/5400. 旅行终点站.py | 1,729 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/5/3
'''
给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,
其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。
请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。
题目数据保证线路图会形成一条不存在循环的线路,因此只会有一个旅行终点站。
示例 1:
输入:paths = [["London","New York"],["New York","Lima"],["Lima",... |
12185824be7220a825a20e5ff5dd522e4f5f7523 | Kostiancheck/dict | /home_task_matrix/task6.py | 810 | 4.15625 | 4 | """Дан двумерный массив и два числа: i и j. Поменяйте в массиве столбцы с номерами i и j и выведите результат.
Программа получает на вход размеры массива n и m, затем элементы массива, затем числа i и j. """
n=int(input('n='))
m=int(input('m='))
list=[[int(input('Введіть число ')) for j in range(m)]for i in ra... |
9ca37ab66fbc8fe397d61ee1f66353a6061aa121 | yvkrishna/My-Initial-Days-Of-Coding | /np-shape-reshape.py | 183 | 3.84375 | 4 | # https://www.hackerrank.com/challenges/np-shape-reshape/problem
from numpy import *
a=array([])
lists = [int(i) for i in input().split()]
arr=asarray(lists)
print(arr.reshape(3,3))
|
5b6896da2e990a3133e477f04cafff27dc0acc3a | yvkrishna/My-Initial-Days-Of-Coding | /Lexical_Addition.py | 1,899 | 3.890625 | 4 |
# Python 3 program to generate all
# non-increasing sequences of sum
# equals to x
# Utility function to print array
# arr[0..n-1]
def printArr(arr, n,a,b,x):
abc=[a]*len(arr)
abcdef=[b]*len(arr)
c=0
for j in range(0,n):
if abc[j]<=arr[j] and abcdef[j]>=arr[j] :
c=1
... |
349e64b3dd3f2513f54adcfed0673c04d0a7f457 | nhzaci/KattisSolutions | /Sibice/sibice.py | 391 | 3.625 | 4 | import sys
import math
multiline_input = sys.stdin.read().split('\n')
hyp_len = 0
no_matches = 0
for line in multiline_input:
if hyp_len == 0 and no_matches == 0 and line != '':
no_matches, width, height = map(lambda x: int(x), line.split())
hyp_len = math.sqrt(width ** 2 + height ** 2)
elif line != '':
... |
be2425501bee44b8cb2620211e9f895902576c96 | cigna2020/CS50_prometheus | /Programming/super_fibonacci.py | 215 | 3.765625 | 4 | def super_fibonacci(n, m):
l = []
while m != 0:
l.append(1)
m -= 1
z_list = len(l) - 1
while len(l) < n:
l.append(sum(l[-1 - z_list:]))
print(l[-1])
super_fibonacci(3, 5) |
4e6859e15f9b1745fcc433894d3d20ca2a2918bb | cigna2020/CS50_prometheus | /Programming/count_holes.py | 590 | 3.71875 | 4 |
def count_holes(n):
if type(n) != int and type(n) != str:
print('ERROR_1')
else:
try:
dictionary = {'9': 1, '8': 2, '6': 1, '4': 1, '0': 1}
counter_holes = 0
n = int(n) # видаляє зайві "0" на початку
n = str(n)
for i in n:
... |
c850dbe7bc0fd74d7f0767bfcd63fd82046b2c2f | jonDuke/cs-module-project-hash-tables | /applications/histo/histo.py | 712 | 3.765625 | 4 | # Read the input file
with open("robin.txt") as f:
txt = f.read()
# Strip special characters
txt = ''.join(c for c in txt if c not in '":;,.-+=/\\|[]{}()*^&')
# Count the words
counts = {}
for word in txt.lower().split():
if word in counts:
counts[word] += 1 # existing word, increment count
else:... |
61cbccec85567b98ffced9ee24e41e1d83b36654 | PickUpLiu/day1 | /day3/my_toninght.py | 1,375 | 4.25 | 4 |
# 等边三角形
# 九九乘法表
def multiplicationTable(num=9):
i = 1
while i <= num:
j = 1
while j <= i:
print(j, "X", i, "=", str(j * i).rjust(2), end="")
j += 1
i += 1
print()
# 菱形
def rhombus(num=10):
num = num // 2
i = 1
while i <= num:
j = num
... |
a1b046b122b929d70219469606f9254fd8cc76a2 | PickUpLiu/day1 | /day2/my-replace.py | 290 | 3.71875 | 4 | if __name__ == '__main__':
#替换
mstr="good good study,day day up"
ms=mstr.replace("good","bad")
print(ms)
#分割
mtr = "good good study,day day up"
s = mstr.split(" ")
print(s)
mr = "good good study,day day up"
a = mstr.capitalize()
print(a)
|
269d5cc0a76451adb63b01d6810e175ffaa96334 | PickUpLiu/day1 | /day2/my-index.py | 1,095 | 3.890625 | 4 | import random
if __name__ == '__main__':
mstr="good good study,day day up"
ms=mstr.index("good")
print(ms)
msr = "good good study,day day up"
mrs=msr.index("good",1)
print(mrs)
m = "good good study,day day up"
mc=m.index("good",1,10)
print(mc)
mlist=list()
mlist.append("yi")
... |
6270db5a716f863b26feea0f755e7a8f219b3812 | PickUpLiu/day1 | /day2/my-list.py | 486 | 3.59375 | 4 | if __name__ == '__main__':
mlist=list()
ms=[]
print(type(mlist))
print(type(ms))
mlist.append("一")
mlist.append("三")
#给定位置添加
mlist.insert(0, "二")
print(mlist)
ms.insert(0,"二")
print(ms)
mlist.pop(0)
print(mlist)
del mlist[0]
print(mlist)
mlist.remove("三")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.