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
bd7d3da5c3917644520e2fd9528bee66e85ade32
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 4/ex.02.py
884
4.4375
4
'''Turtle objects have methods and attributes. For example, a turtle has a position and when you move the turtle forward, the position changes. Think about the other methods shown in the summary above. Which attibutes, if any, does each method relate to? Does the method change the attribute? ''' '''Write a program tha...
d15fa577adbdc9cf9ac0c3ad0652ad2430eb8bca
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 12/Crypto/Caesar Cipher/caesar01/caesar 02.py
1,272
4.375
4
def caesarCipher(t, s): """ caesarCipher(t, s) Returns the cipher text in a given plain text or vice versa. Variables: t - text (input), nt - new text (output) lc - lowercase, uc - uppercase pt[c] - nth character of the plain text (also used to get the ...
d6323c7df4f3e97361499a366b2142e95afab202
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 9/studio bugz/studio bugz 03.py
717
3.8125
4
''' When registering for an online account, users must create a password. For your service, you enforce the following rules on passwords: The password must contain at least one non-alphabetical character, and may not contain any spaces. The function below is supposed to check the validity of passwords. But!...
f28518d051966fdf6a870c2697cc4c42ceecdbf4
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Turtle/Drawing a five star.py
254
3.671875
4
'''Additional notes Why did I pick the number “144”? Why is that significant? What happens if you try changing a different number?''' import turtle star = turtle.Turtle() for i in range(50): star.forward(50) star.right(144) turtle.done()
9ca5c679daff24925ed410b7b10d4741594b1fbb
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Turtle/flower 07.py
594
3.96875
4
import turtle from random import randint # set the background color wn = turtle.Screen() wn.clear() wn.bgcolor("yellow") def drawSquare(turtle, size, pos): # initialize position turtle.up() turtle.setpos(pos) turtle.down() # for loops iterate in this case from the first value until < 4, so f...
86bd165356c0d04df9db767185f55bfd03bdff46
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 10/ex.04.py
333
4.03125
4
'''Write a function to count how many odd numbers are in a list. ''' import random def countOdd(lst): odd = 0 for e in lst: if e % 2 != 0: odd = odd + 1 return odd # make a random list to test the function lst = [] for i in range(100): lst.append(random.randint(0, 1000)) print(co...
bd9ed5751eee1c211f209fe86a475e63d9c97c2d
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 8/Ex.02 pass 7-04-2016.py
1,628
4.09375
4
''' ’ (GRADED) Write a function analyze_text that receives a string as input. Your function should count the number of alphabetic characters (a through z, or A through Z) in the text and also keep track of how many are the letter 'e' (upper or lowercase). Your function should return an analysis of the text, somet...
a74bc9230688f4af19d7a0864cfc89372975d998
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Turtle/Square Spiral.py
423
3.828125
4
# Spiral outwards in an ever-expanding square # using Turtle graphics from turtle import * lineLen = inc = 20 # Line starts this long, grows this much max = 800 # until it's this long turn = 90 # try different numbers, e.g. 120 # The line grows longer until it fills the window while lineLen < max: #turtle...
3f70120ad076fe5fa9fdd7982919ae35178f5be2
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 9/ex.04.py
508
4
4
''' ) (GRADED) Write a function that mirrors its argument. (Hint: Make use of the reverse function that you wrote in the previous exercise) ''' from test import testEqual def reverse(mystr): reversed = '' for char in mystr: reversed = char + reversed return reversed def mirror(mystr): ...
f5b7e68732fa6888927e458c8a9534b994915a9f
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 10/ex.01.py
360
3.890625
4
''' 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[:] b[0] = 5 ''' Your diagram should show two variables referring to two different lists. a refers to the original list with 1,2, and 3. b refers to a list with 5,2, and 3 since th...
bdc4113371af93953bb86f39707c442be13399c6
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 4/ex.09.py
177
3.8125
4
'''Write a program to draw a shape like this: ../_images/star.png ''' import turtle turing = turtle.Turtle() for i in range(5): turing.forward(110) turing.left(216)
8f7cd7ec535c4358eeea1e866b59239529f3e076
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Turtle/flower 01.py
424
3.6875
4
import turtle def side(size,level): if (level == 0): t.forward(size) return side(size/3,level-1) t.left(60) side(size/3,level-1) t.right(120) side(size/3,level-1) t.left(60) side(size/3,level-1) def snowflake(size,level): ...
396f1c909b043e2aeb94bde87cf8140cdd696ce7
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 3/chapter 3 exercise.py
603
4.0625
4
#studio #prompt user for exchange rate from dollars to pounds exchange_rate=float(input("How many the exchange rate from dollars to pounds?")) #prompt user for number of falgs to sell num_flags=int(input("How many flags are you going to sell?")) #fix values pounds_per_pint=3.79 dollars_per_flag=3 #how many pounds to...
e7c6db8f2ffce9ff466c2be49c9db7bdcfc28745
SmileShmily/LaunchCode-summerofcode-Unit1
/test/00.test.py
981
3.890625
4
n1 = "Hello" n2 = "abc" n3 = "i'm lovin this test" n4 = "i'm not kidding" n5 = "exclamation points are not really my up of tea" # Your function here! def string_function(s): return s + '!' print (string_function(n1)) print (string_function(n2)) print (string_function(n3)) print (string_function(n4)) print (string_f...
b995572ecfc3d03db672348f2ece6505f427229e
KotenaKotya/homework_4
/num_pi.py
153
3.859375
4
import math n=int(input("Напишите количество чисел после запятой:")) print('{num:.{n}f}'.format(n=n, num=math.pi))
6370fe283408c877e6dfd7ffd8ff82da7928dcb3
nastine/interview
/balance.py
884
3.90625
4
def is_balanced(string): brackets_open = ('(', '[', '{', '<') brackets_closed = (')', ']', '}', '>') stack = Stack('') for i in string: if i in brackets_open: stack.push(i) if i in brackets_closed: if stack.size() == 0: return print('Несбаланси...
a798ef9d6f4e0a4014ffcf21858ceb1a31ac1e4e
ashminbhandari/Five-Crowns-Python
/venv/deck.py
875
3.96875
4
import card, random class Deck(object): "Building decks according to how many the user wants" def build(self, howMany): "The array that holds the list of cards" self.cards = [] for x in range(howMany): for suit in ["Spades", "Clubs", "Diamonds", "Hearts", "Tridents"]: ...
4655bcfbcac14f6ff596fc9e9acbade08dae814d
mkosicki1/Python
/cwiczenia_day3/P54/P54 MODYFIKACJA.py
855
3.765625
4
## utwórz liste wartosci losowych naturalnych z zakresu 1:100 import random randomList = [] for x in range(10): randomList.append(random.randint(1,10)) print(randomList) # wyszukaj element z listy i zwróc jego indeks # jeżeli elementu nie ma na liście to zwróc -1 find = int(input("Podaj liczbę z zakresu od 1 do...
6392cba75dcf0bc1ab8b5b5502b93486d909acfd
mkosicki1/Python
/cwiczenia_day4/Funkcje/funkcje.py
5,261
3.515625
4
# funckja zwracająca 5 kolejną liczbe pierwszą #1,2, 3, 5, 7, 11, 13 ... # n=5-> 11 from datetime import date, datetime, time def getPrimaryNumbers(n=5): #argument domyslny primaryNumbers = [1] number = 2 while(len(primaryNumbers) < n): isPrimary = True for div in range (2,number): ...
45912bb7f382972ecafc17e7b5bb50ee0ec5ccf3
mkosicki1/Python
/cwiczenia/P33/p33.py
284
3.5625
4
#v = SPK*(1+ p /m)**(n*m) SPK = float(input("podaj SPK: ")) p = int(input("Podaj procent: "))/100 n = int(input("Podaj okres trwania lokaty: ")) m = int(input("Podaj ilość okresów kapitalizacji: ")) print("Stan konta w przyszłości: ", round(SPK *(1 + (p/m))** (n*m),2))
61e429900f3c17c0232110901a74f14cf16858a6
mkosicki1/Python
/cw_day7/database_app/model/User.py
482
3.5
4
class User: def __init__(self, email, password, name, lastname, gender, user_id=0): self.user_id = user_id self.email = email self.password = password self.name = name self.lastname = lastname self.gender = gender def __str__(self): ...
db915c835f2f3b7dfbe4d5ed6a4709b3452690dd
mkosicki1/Python
/P42/p42.py
327
3.703125
4
from random import sample # losuje bez zwracania z populacji - listy wartości # określoną w argumencie metody liczbę razy population = range(1,50) quantity = 6 result = sample(population, quantity) print(result) result.sort() print(result) result.sort(reverse=False) print(result) result.sort(reverse=True) print(resul...
d90ddf52f92eb110cfcdc9653c1e569a0c50615a
amuzzy/python
/Project Euler/Problem0001.py
604
3.953125
4
## Project Euler Problem 1 ## ## If we list all the natural numbers below 10 that are multiples of 3 or 5, ## we get 3, 5, 6 and 9. The sum of these multiples is 23. ## ## Find the sum of all the multiples of 3 or 5 below 1000. ## ## ## Answer: 233168 def Problem1(): ## Initialize total total = 0 ## Itera...
6ae5656766da2b722314c26b4814e928d512438f
amuzzy/python
/Project Euler/Problem0012.py
1,672
3.8125
4
## Project Euler Problem 12 ## ## 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,26,45,55... ## ## Let us list the factors of the first seven triangle numbers: ## ## 1: 1 ## 3...
7f7f4cd5a877fb9a457cd662ec1cbe4f47cba6cb
CriticalD20/String-Jumble
/stringjumble.py
1,567
4.3125
4
""" stringjumble.py Author: James Napier Credit: http://stackoverflow.com/questions/12794141/reverse-input-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-...
078c3db471a58d485fd6f79c2c9b2730c4ecdca9
elhectorlitro/algorithms
/Binary_Search.py
919
3.921875
4
from random import randint def Binary_Search(value, numbers, tries, maxi, mini): tries+=1 mid=round(((maxi-mini)/2)+mini) print("Is it "+str(mid)+"?") if numbers[mid] == value : print("Yes") return mid, tries elif numbers[mid] > value: print("No") return Binary_Searc...
b84b02df213373b52facb83834a4bd550e6c288d
maglist/wprawki
/Codewars/add_value/test_up_array.py
2,377
3.5625
4
import unittest from up_array import up_array class MyTestCase(unittest.TestCase): def test_positive(self): self.assertEqual(up_array([0]), [1], msg="check list of one integer") self.assertEqual(up_array([6]), [7], msg="check list of one integer") self.assertEqual(up_array([9]), [1, 0], ms...
797dfbd0fb5d7d985ceaba4862987a33069c177f
maglist/wprawki
/Codewars/find_unique/test_find_unique.py
1,120
3.59375
4
import unittest from find_unique_element import find_uniq class MyTestCase(unittest.TestCase): def test_positive(self): self.assertEqual(find_uniq([1, 3, 1, 1, 1]), 3, msg="check list of integers") self.assertEqual(find_uniq([0.7, 0.7, 0.4]), 0.4, msg="check list of floats-last element is unique")...
89f27cd455d3933db0931d22c8b0851cd3eae2bd
Ray980625/2020python0817
/math english.py
465
3.96875
4
math_score = int(input("請輸入數學成績:")) english_score = int(input("請輸入英文成績:")) if math_score >= 0 and english_score >= 0 and math_score <= 100 and english_score <= 100: if math_score >= 90 and english_score >= 90: print("有獎品") elif math_score <= 60 and english_score <= 60: print("要處罰") el...
880dda20e5fc110da4b0b872a27ca86c9efaa314
narenaruiz/Python
/P5/P5E1.py
260
4.03125
4
for i in range (10): print (i+1); print ("\n") for i in range (10): print ((i+1)*2); print ("\n") for i in range (10): print ((i*2)+20); print ("\n") for i in range (6): print ((i*4)+10); print ("\n") for i in range (9): print ((i*-5)+40);
90ee74aeaa1775e83bcf1babe6911ed76a78bc34
narenaruiz/Python
/P4/P4E3.py
499
3.90625
4
Pregunta=input("Para calcular el area del cuadrado pulsa C y para el triangulo T:") if Pregunta !="C" and Pregunta !="T": print("La tecla es incorrecta") if Pregunta=="C": BaseC=float(input("Dime la base:")) AlturaC=float(input("Dime la altura")) AreaC=BaseC*AlturaC print("El area de cuadrado es", A...
a64ec0104a3807dd037e90b6c93753f62c78037d
narenaruiz/Python
/P7/P7E3V2.py
315
4.0625
4
"""3.-Escribe un programa que lea una frase, y la pase como parámetro a un procedimiento, y éste debe mostrar la frase con un carácter en cada línea. Autor:Nicolás Arena Ruiz """ def Separacion_De_Linea(frase): for i in frase: print(i) frase=str(input("Dime una frase:")) Separacion_De_Linea(frase...
c5bf60c3b48425c93a6c39a20b01d10a3fe36bc2
narenaruiz/Python
/P6/P6E5.py
894
4.28125
4
"""5.-Escribe un programa que te pida números cada vez más grandes y que se guarden en una lista. Para acabar de escribir los números, escribe un número que no sea mayor que el anterior. El programa termina escribiendo la lista de números: Escribe un número: 6 Escribe un número mayor que 6: 10 Escribe un número mayor ...
7156e4a491a294fce7e93b898bbe0a83eaf89bb8
narenaruiz/Python
/P6/P6E3.py
639
4.1875
4
"""3.-Escribe un programa que pida notas y los guarde en una lista. Para terminar de introducir notas, escribe una nota que no esté entre 0 y 10. El programa termina escribiendo la lista de notas. Escribe una nota: 7.5 Escribe una nota: 0 Escribe una nota: 10 Escribe una nota: -1 Las notas que has Escrito son [7.5, 0.0...
03478dde7f02433ae2c351c181cefc942e0c75be
parthpanchal0794/pythontraining
/NumericType.py
1,634
4.25
4
""" Numeric types classes 1. Integer e.g 10 2. Float e.g 10.0 3. Complex e.g 3 + 5j 4. Binary type (Class Int) 5. Hexadecimal (Class Int) 6. Octa decimal (Class Int) """ # Integer Values a = 13 b = 100 c = -66 print(a, b, c) print(type(a)) # Floating values x = 33.44 y = -8.78 z = 56.0 # with...
523474ff795187ae2740e98b9a2c2f393e6f71d7
HyeongSeoku/Programmers_CodingTest
/python/datastructure/descendingSort.py
1,130
4.1875
4
''' 1. maxMachine 클래스를 완성하세요. 2. sorting 함수를 완성하세요. ''' class maxMachine : ''' 이곳에 '최댓값 기계' 문제에서 작성했던 클래스를 붙여넣으세요 ''' def __init__(self) : self.numbers = []; def addNumber(self, n) : self.numbers.append(n); def removeNumber(self, n) : self.numbers.remove(n); def g...
f5fa6466ae190105ff19afc64649d46a1b6ed187
george-hawkins/drone-protocols
/boot.py
1,270
3.78125
4
import board import digitalio import storage # When connected via USB, a CircuitPython dev-board appears as a USB drive. By default you can write to the drive # but CircuitPython code running on the board cannot. To toggle this behavior, such that CircuitPython code can # write to the drive but you cannot, the filesys...
45ccf1bca699fa51c21d407145d13d75596f70d2
Mohibtech/Mohib-Python
/NLP/wordcloud_urdu.py
2,252
3.546875
4
# -*- coding: utf-8 -*- import nltk import sys import unicodedata import matplotlib.pyplot as plt from wordcloud import WordCloud def word_populate(FILE_NAME): try: with open(FILE_NAME,'r',encoding='utf8') as set_file: bookwords = set(line.strip() for line in set_file.readlines()) except Va...
85c047ab18834f950b0d29ae23adf4a0aaae2fca
Mohibtech/Mohib-Python
/Test/test1.py
3,710
4.375
4
import re def multi_replace(string, replacements, ignore_case=False): """ Given a string and a dict, replaces occurrences of the dict keys found in the string, with their corresponding values. The replacements will occur in "one pass", i.e. there should be no clashes. :param str string: string to...
23652f96331b2bc5fc1bf9832c51dba80f7e87cd
Mohibtech/Mohib-Python
/short scripts/NamedTuples.py
405
3.9375
4
from collections import namedtuple Person = namedtuple('Person', 'name age') perry = Person(name="Perry", age=30) # Without specifying the field names in NamedTuple jane = Person("Jane", 35) #people = [('John', 30), ('Peter', 28), ('Joe', 42)] Persons = [perry, jane] sortPerson = sorted(Persons, key=lambda p: p.ag...
a862febaed4059785ab37c810b54b6a1034c6901
Mohibtech/Mohib-Python
/UrduPythonCourse/List Comprehension.py
2,248
4.75
5
''' List comprehensions provide a concise way to create lists. It consists of brackets containing an expression followed by a for clause, then optional if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists. The list comprehension always returns a result list. ''' # List co...
d7244b5a935faeb12acf19fb4b52147231806b53
NightLord013/Python
/5_2.py
136
3.78125
4
a = int(input()) b = int(input()) def maxim(a, b): if a > b: return a else: return b print(maxim(a, b))
dda82e6efdbf45f8187ac72f4d62e4f3cf1d3d37
NightLord013/Python
/7_8.py
310
3.8125
4
from random import randint a = randint(1,6) b = randint(1,6) print("Первый игрок: ", a, "Второй игрок: ", b , end= "\n" ) if a > b: print("Первый игрок победил") elif a < b: print("Второй игрок победил") else: print("Ничья")
2e00b5e3a541b64e125fe2542446eb9f75535c54
NightLord013/Python
/8_1.py
203
3.5
4
s = "У лукоморья 123 дуб зеленый 456" print(s.index("я")) print(s.count("у")) if s.isalpha: print(s.upper()) if len(s) > 4: print(s.lower()) b = s[1:] print("O"+b)
970cbab32b1f097f03fc6ad8c8a7b25ad1182850
njenia/project-euler-solutions
/p1/p1.py
335
3.84375
4
limit = 1000 factor_1 = 3 factor_2 = 5 def calculate_sum_of_divisors(factor_1, factor_2, limit): divisors = [num for num in range(limit) if (num % factor_1 == 0 or num % factor_2 == 0)] sum = 0 for divisor in divisors: sum += divisor return sum print(str(calculate_sum_of_divisors(factor_1, fac...
52a0b35862a2e837b927093e6149fa4979b0a5a3
duluth-dnug/talks
/2019/FastestFizzbuzz/fizzbuzz.py
368
3.75
4
#!/usr/bin/env python3 def main(): for i in range(1, 1000000001): fizz = (i % 3 == 0); buzz = (i % 5 == 0); if fizz and buzz: print("Fizzbuzz!") elif fizz: print("Fizz") elif buzz: print("Buzz") else: print("{:010d}".fo...
c5a3805f44356d0f7478f467331bbed4dd52afd0
sameem7/CodingBat
/xyz_there.py
582
4.03125
4
# Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). # So "xxyz" counts but "x.xyz" does not. #Ex: xyz_there('abcxyz') → True # xyz_there('abc.xyz') → False # xyz_there('xyz.abc') → True def xyz_there(str): #Assume there is no 'xyz' in ...
12cc517baff2eba259046de460bb85be5cb3b667
LeeMinChur/GHDD
/jing/new8/thre.py
982
3.5625
4
import threading import time class thre(): def thred7(self): print(1) def thred(self): while True: self.thred7() time.sleep(2) def thred2(self): while True: print(2) time.sleep(2) def thred6(self): a ...
308e2e43cd572f8ce13532ddcb5f8113276ccb83
hockeykozo/150_program
/1-3.py
745
3.6875
4
import unittest def compare_str(str1,str2): if sorted(list(str1.lower())) == sorted(list(str2.lower())): return 1 else: return 0 class TestCompareStr(unittest.TestCase): def test_compare_str(self): t_11 = "test" t_12 = "tets" t_21 = "Test" t_22 = "tets" t_31 = "Test" t_32 = "tet" self.assertEqua...
1a2541ab491c8a4e1f7d8bc28d2ff9d39f00f420
yadavankit/Scikit_ML
/lesson_one.py
4,022
3.640625
4
from sklearn import datasets import numpy as np # Load Iris Dataset iris = datasets.load_iris() x_iris, y_iris = iris.data, iris.target # Print Shape of Data and Target x= 150 instances * 4 features (sepal len, width ; petal len, width) print x_iris.shape, y_iris.shape # Print an example Instance from x_iris, & Spec...
2aa935435c244582a09cae5a74c58bfa663936b8
jorgechato/leetcode
/algorithms/easy/reverse-vowels-of-a-string/main.py
915
3.734375
4
class Solution: """ Input: 1 string. s (string) Output: 1 string. (whether the vowles are reverse) Constrains: - s is a valid string Edge Cases: - len(s) == 0 - wovles no in s - len(wovles) == 1 Time complexity: O(N^2) Space complexity: O(1) """ def r...
5a51b340ba8d0d8c4ec9548812a0b3dd7152c64c
alex88yushkov/les_4.2_salary_echo
/salary_echo.py
1,459
4.25
4
# Exercise #1 def show_employee(name = "Trus", sal = 5000): name = "Name: " + name sal = "Salary: " + str(sal) print(name, sal, sep=", ") show_employee() show_employee(name = 'Balbes') show_employee(name = 'Bivaliy', sal = 4000) # Exercise #2 # VARIANT 1: #Define shout_echo def shout_echo(word1 = "Hey ",...
a9692c1c6688b6812ac9c7dafd89dee915f07bc1
Kogtrey/Big-Data
/Big Data/Big Data Homework/DecisionTree.py
9,540
3.5625
4
import numpy as np import matplotlib.pyplot as plt 'main function' def decision_tree_regression(X,y,max_level,level=0): size = X.shape try: n_features = size[1] except IndexError: n_features = 1 X = X[:,None] 'let the algorithm choose the feature' p_list = np.zeros(n_featur...
5be98dc8daefaf6aa68d3eed0231b4c670061b8e
robin22333/Algorithm
/HeapSort.py
912
3.90625
4
def heapSort(arr, size): bulidHeap(arr, size); i = size; while i >= 0: swap(arr, 0, i); heapAdjust(arr, 0, i-1); i -= 1; def bulidHeap(arr, size): #heapAdjust(arr, 0, size); i = size / 2; while i >= 0: heapAdjust(arr, i, size); i -= 1; def h...
aed6d8e9e944c2cb91ac29f05429c3388c3a1c11
goksinan/Intro-to-PyTorch
/eg_4_multilayer.py
975
3.765625
4
import torch from torch import nn from torchvision import datasets, transforms class Network(nn.Module): def __init__(self): super().__init__() # Inputs to the first hidden layer linear transformation self.hidden_1 = nn.Linear(784, 128) # Inputs to the second hidden layer linear tr...
f9de5d808f43bff6aa430e7f803b4a9d0d8cec93
Fushengliangnian/PracticeEssays
/测试脚本/dict_get.py
344
3.609375
4
dic = {"a": "b"} class B: def __init__(self): print("b+") class A: def __init__(self, app): self.app = app self.app.config = app self.app.config.a = "b" def get_a(self): return getattr(self.app.config, "a", None) a = A(B()) print(a.get_a()) ret = getattr(dic,...
3cf56345025b2e3d5581c689813defd14a38feb7
malhar-pr/side-projects
/pythagorean.py
2,783
4.375
4
import time pyth_list=[] #Creates an empty list that will hold the tuples containing Pythagorean/Fermat triplets power_list=[] #Creates an empty list that will cache the value of each index raised to the specified exponent in the given range print("------------------------------------------------------------------...
803f6021781097ce95b2f5dd4075c961e0dbe6f9
HaneulJ/Python
/funcLab6.py
621
3.71875
4
"""함수명 : print_gugudan, 매개변수 : 1개 리턴값 : 없음, 기능 : 전달된 숫자의 구구단을 출력한다. - 전달된 아규먼트가 int 타입인지 체크하고 int 타입이 아니면 그냥 리턴한다. - 전달된 아규먼트가 1~9 사이인지 체크하고 아니면 그냥 리턴한다. - 그 외의 경우에는 해당 단의 구구단을 행 단위로 출력한다 """ def print_gugudan(n): if type(n) == int : if 1 <= n <= 9: for hang in range(1,10): p...
5b98ac5d68e776135f3dd35ea38b07c3c604f212
HaneulJ/Python
/funcLab4.py
471
4
4
"""구현해야 하는 함수 사양 함수명 : print_triangle, 매개변수 : 1개, 리턴값 : 없음 기능 : 전달된 숫자 개수로 구성되는 삼각형을 출력한다 전달되는 아규먼트 값은 1~10으로 제한한다. 1~10 이외의 값이 전달된 경우에는 처리하지 않고 그냥 리턴한다. """ def print_triangle(n): if 1 <= n <= 10: for i in range(1,n+1): print("*"*i) print_triangle(8) print_triangle(4)
79b7b1b5360dbc6eac5f28eea95a7b289d9ebb13
HaneulJ/Python
/compreLab2.py
518
3.78125
4
""" 함수명 : mydict 매개변수 : 가변 키워드형(키=값 형식으로 전달받을 수 있는 아규먼트 개수에 제한이 없다.) 리턴값 : 1개 기능 : funcLab11.py 에서 구현한 mydict() 라는 함수의 기능과 동일하게 구현하는데 이번에는 딕셔너리 컴프리핸션(지능형 딕셔너리) 구문을 사용해서 생성한다. """ def mycompredict(**p): mdict = { "my"+k:v for k,v in p.items() } return mdict print(mycompredict()) print(mycompredict(a=1, b=3, c=...
c7b3ef651458b531e9696c20d5115421d7c7fe7d
NeilDG/NeuralNets-Experiments
/regression_bare.py
3,151
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 20 11:27:07 2019 Linear regression example by simply using least squares error.. @author: NeilDG """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import dataset_generator as dg from random import seed from random import randrange def cross_vali...
0e7c83d4d2c446c084206623cfc460d5d9e0eb58
SvetlanaTsim/python_basics_ai
/lesson_8/task_8_7.py
1,851
4.46875
4
""" Реализовать проект «Операции с комплексными числами». Создать класс «Комплексное число». Реализовать перегрузку методов сложения и умножения комплексных чисел. Проверить работу проекта. Для этого создать экземпляры класса (комплексные числа), выполнить сложение и умножение созданных экземпляров. Проверить корректно...
96aacf7075c47ccf0c681ce8003b19ec958110e1
SvetlanaTsim/python_basics_ai
/lesson_2_ht/task_2_3.py
1,405
4.03125
4
""" 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict. """ # через list season_list = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] user_m = input('Введите месяц (целое число от 1 до 12): ') while no...
7efb1395d46e4478a38a1e87632274ca4cf07cc4
SvetlanaTsim/python_basics_ai
/lesson_3_ht/task_3_6.py
1,111
4.1875
4
""" 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в...
131a3dbe6122ee71c547a359fac6b84d89597c7e
SvetlanaTsim/python_basics_ai
/lesson_2_ht/task_2_1.py
681
3.84375
4
""" 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. """ my_list = ['day', 12, 154.6, 15+3j, {1, 'one', 2.4}, fr...
6843bfc84b1387c7fd9e0a19b2b586ca9ccc34f9
SvetlanaTsim/python_basics_ai
/lesson_4/task_4_7.py
1,628
3.890625
4
""" 7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: for el in fact(n). Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые n чисе...
e0884489e117dd6c9443d2a97f597bb8e8d3ebd4
prasun420/Some-Examples-of-simple-python2
/palindrome.py
134
4.15625
4
s=input(" Enter a string: ") s1=s[::-1] if(s==s1): print(" Palindrome string") else: print(" Not Palindrome string")
385611c5868864d04fd1bb878531a1149d2c13d2
drivehome/X-Village-2018-Exercise
/Lesson07-Requests Module/ex3.py
1,001
3.828125
4
import re # 設定兩個正規表示法,定義兩個格式。 pattern1 = r'(?P<username>[A-Z][a-z][a-z])' pattern2 = r'(?P<password>[a-z][a-z][a-z][0][0-9][0-9][0-9][0-9][0-9])' input_account = input ("enter account: ") input_password = input("enter password: ") match1 = re.search(pattern1, input_account) match2 = re.search(pattern2, input_passw...
e884acf79724ce595323ca07bf8e9783a2698f2e
shubham-bhoite164/DSA-with-Python-
/Reversing the Integer.py
685
4.21875
4
# Our task is to design an efficient algorithm to reverse the integer # ex :- i/p =1234 , o/p =4321 # we are after the last digit in every iteration # we can get it with modulo operator: the last digit is the remainder when dividing by 10 # we have to make sure that we remove that digit from the original number # so w...
873392163286a651287c898175db15c65ccd6d23
dreamwayjgs/hyu-database-class-2019
/Chap1_Python/project/B2-dataclass/csv_helper.py
550
3.703125
4
import csv # CSV https://docs.python.org/ko/3/library/csv.html?highlight=csv import os def read_csv(filename): rows = [] print(f"Reading: {os.getcwd()}/{filename}") with open(filename) as csvfile: reader = csv.reader(csvfile) for row in reader: rows.append(row) return rows...
8e1e12d5b0d40a94f99d27ce1bbf4ffd449077e5
UBC-MDS/524_easysklearn
/easysklearn/miss_data.py
3,339
3.9375
4
import pandas as pd from sklearn.impute import SimpleImputer def miss_data(x_train, x_test, strategy="mean"): """ Impute value(s) wherever there is (are) a missing value(s) in the dataframe. Takes in the train and test split dataframes and applies univariate feature imputation on the missing values i...
8d9ab6d6ae8d7a8d0874d33b5233f967975c0bc1
smitten0000/ecen5523
/compiler/hw5_test/HagiaSophia_hg1.py
104
3.5
4
def fib(a, b, n, top): print b return b if n == top else fib(b, a+b, n+1, top) fib(1, 1, 1, input())
4a84f2e32ff3ca5601b6281e40eb28bc62c028cc
hdjsjyl/LeetcodeFB
/199.py
1,581
4.03125
4
""" 199. Binary Tree Right Side View Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 ...
0628f072431dd79fcaabe14fea0482f09aab067a
hdjsjyl/LeetcodeFB
/350.py
746
3.671875
4
""" 350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] """ # Solution: time complexity: O(n) class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: dict1 = {...
1c7a92b66d1999fc6158a0422558668498f5aa0f
hdjsjyl/LeetcodeFB
/23.py
2,577
4.21875
4
""" 23. Merge k Sorted Lists Share Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 """ ## solution1: similar to merge sort algorithm, the time complexity is O(nklogn) # n is the length ...
4854fa8e660f09b69650f50f096ee34d207b1a97
hdjsjyl/LeetcodeFB
/215.py
1,517
3.890625
4
""" Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 """ # Solution: Average time complexity: O(n), Worst time complexity: O(n**2) # each time, we select a pivot value and ...
824d8522a2c0824cd850200bea2aab6037ca2650
hdjsjyl/LeetcodeFB
/314.py
1,445
3.859375
4
""" Lintcode: 651. Binary Tree Vertical Order Traversal Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Example Example1 Inpurt: {3,9,20,#,#,15,7} Output: [...
a40e633d5684d091d4fb33dffde197d132741dc4
hdjsjyl/LeetcodeFB
/349.py
622
3.5
4
""" 349. Intersection of Two Arrays Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] """ # solution: hashtable class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: res = [] dicts1 =...
e956a2fa52285ce8729f954a1ba19f360e744f74
hdjsjyl/LeetcodeFB
/67.py
1,363
3.796875
4
""" 67. Add Binary Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output: "100" """ # Solution: time complexity: O(n) class Solution: def addBinary(self, a: str, b: str) -> str: ...
87b3157aab47d50634fb9a9d0ae263394ec61b53
christianreimer/snippets
/bitmap.py
533
3.546875
4
""" Utility functions to make it easy to work with bitmaps. """ def set(bitmap, bit): bitmap |= 1 << bit return bitmap def clear(bitmap, bit): bitmap &= ~(1 << bit) return bitmap def flip(bitmap, bit): bitmap ^= 1 << bit return bitmap def test(bitmap, bit): return (bitmap & (1 << bit)) >...
2c2a10a805c83e81ad6b55d102980818d030ca24
coderdojoka/py2cd
/py2cd/vektor.py
2,888
3.953125
4
from math import sqrt from numbers import Number __author__ = 'Mark Weinreuter' class Vektor2: def __init__(self, x=0, y=0): """ Erstellt einen neuen 2D-Vektor. :param x: :type x: Number|list[Number] :param y: :type y: Number """ if (isinstance(x, ...
7b2c1784c36d9a1ba3109e244079107cbdd2aad8
marwane8/algorithms-data-structures
/HashMaps.py
727
3.984375
4
''' HASH MAPS: Hash Maps are a very integral data structure that provide very quick look up time This Class shows algorithms which implement hash maps unique ways ''' class HashMaps: #Leet Code: Two Sum - https://leetcode.com/problems/two-sum/ #Given an array of integers and an integer, return indices of the...
aa866eb07967f983e83b81db0dd63ca2237c8935
marwane8/algorithms-data-structures
/Sorting.py
2,174
4.25
4
import heapq ''' SORTING ALGORITHMS -Sorting Algorithms are a common class of problems with many implementation -This class highlights some of the foundational implmentations of sorting -SORT FUNCTIONS- selectionSort: finds the minimum number and pops it into the result array mergeSort: u...
213eafcb0f3f155390b8aaa3f78e556148546ef8
sindridan/Python_2018
/k4.py
777
3.734375
4
#k4 import re def all_palindromes(txtfile): words = [] file = open(txtfile) for line in file: line = line.strip() if len(line): words.append(line) file.close() palind = [] #it = 0 """for word in words: if word[it] == word[len(word) - 1]: if it...
ff6b77c40b3910c21491db35042e20095bc4680e
jwallnoefer/requsim
/src/requsim/tools/protocol.py
5,339
3.59375
4
import sys from abc import ABC, abstractmethod import numpy as np import pandas as pd from ..events import SourceEvent from ..libs.aux_functions import distance class Protocol(ABC): """Abstract base class for protocols. Parameters ---------- world : World The world in which the protocol will ...
ae9311793a425d493567e648302fbec2020470a7
jwallnoefer/requsim
/src/requsim/world.py
4,701
3.765625
4
from .events import EventQueue from collections import defaultdict class World(object): """A collection of WorldObjects with an EventQueue. The World can be understood as a central object describing an experimental setup. It keeps track of all WorldObjects, which contain all the information a protoco...
8a702f4e97a8c1032c336bf8672b3f62485e58d4
Sirodo8plp/Epistimi_ton_ypologiston
/TicTacToe.py
2,792
3.59375
4
import random def Answer(L): print(" ","0|1|2") c=0 for i in range(0,3): print(c,A[i][0],A[i][1],A[i][2]) c +=1 def HumanTurn(L): while True: row=int(input("Give the number of row(0-2): ")) col=int(input("Give the number of column(0-2): ")) if col>=...
38fdc16614a27fd54758afdcde2adb58a360e95b
cmarch314/PythonProjects
/program5/pulsator.py
929
3.6875
4
# A Pulsator is a Black_Hole; it updates as a Black_Hole # does, but also by growing/shrinking depending on # whether or not it eats Prey (and removing itself from # the simulation if its dimension becomes 0), and displays # as a Black_Hole but with varying dimensions from blackhole import Black_Hole class ...
87784d6b0b95fb4c9b84b0a25d1b9c3423a7a52c
linhdvu14/leetcode-solutions
/code/874_walking-robot-simulation.py
2,149
4.5
4
# A robot on an infinite grid starts at point (0, 0) and faces north. The robot can # receive one of three possible types of commands: # -2: turn left 90 degrees # -1: turn right 90 degrees # 1 <= x <= 9: move forward x units # Some of the grid squares are obstacles. # The i-th obstacle is at grid poin...
7908915172b367d592be102e890a18001709d6e2
linhdvu14/leetcode-solutions
/code/231_power-of-two.py
639
4.375
4
# Given an integer, write a function to determine if it is a power of two. # Example 1: # Input: 1 # Output: true # Explanation: 20 = 1 # Example 2: # Input: 16 # Output: true # Explanation: 24 = 16 # Example 3: # Input: 218 # Output: false # ---------------------------------------------- # Ideas: power of two iff...
27d0a1cf62e6b23956fdea3d45bf9ecf26ed2947
linhdvu14/leetcode-solutions
/code/513_find-bottom-left-tree-value.py
983
4.09375
4
# Given a binary tree, find the leftmost value in the last row of the tree. # Example 1: # Input: # 2 # / \ # 1 3 # Output: 1 # Example 2: # Input: # 1 # / \ # 2 3 # / / \ # 4 5 6 # / # 7 # Output: 7 # Note: You may assume the tree (i.e., the given root ...
32d32aca4eaad4c317eb85ce5ad2429ef3ca78c7
linhdvu14/leetcode-solutions
/code/884_uncommom-words-from-two-sentences.py
1,199
3.8125
4
# We are given two sentences A and B. (A sentence is a string of space separated # words. Each word consists only of lowercase letters.) # A word is uncommon if it appears exactly once in one of the sentences, and does # not appear in the other sentence. # Return a list of all uncommon words. # You may return t...
621be8d77aa644179b18acb8d3db88e044e0af63
linhdvu14/leetcode-solutions
/code/693_binary-number-with-alternating-bits.py
1,538
4.09375
4
# Given a positive integer, check whether it has alternating bits: namely, # if two adjacent bits will always have different values. # Example 1: # Input: 5 # Output: True # Explanation: # The binary representation of 5 is: 101 # Example 2: # Input: 7 # Output: False # Explanation: # The binary representation of 7 i...
ded0c70db2cdd448b7041f41266219fe933f1aa7
linhdvu14/leetcode-solutions
/code/589_n-ary-tree-preorder-traversal.py
918
4.125
4
# Given an n-ary tree, return the preorder traversal of its nodes' values. # For example, given a 3-ary tree: # 1 # / | \ # 3 2 4 # / \ # 5 6 # Return its preorder traversal as: [1,3,5,6,2,4]. # Note: Recursive solution is trivial, could you do it iteratively? # --------------------------------------...
c69495f2432aa076ee212234828b331dba5382ae
linhdvu14/leetcode-solutions
/code/500_keyboard-row.py
995
4.09375
4
# Given a List of words, return the words that can be typed using letters of # alphabet on only one row's of American keyboard like the image below. # Example 1: # Input: ["Hello", "Alaska", "Dad", "Peace"] # Output: ["Alaska", "Dad"] # Note: # You may use one character in the keyboard more than once. # You ...
8a8f985d17d00376a2d888e8890ba74484c031d1
linhdvu14/leetcode-solutions
/code/877_stone-game.py
2,706
3.9375
4
# Alex and Lee play a game with piles of stones. There are an even number of piles arranged # in a row, and each pile has a positive integer number of stones piles[i]. # The objective of the game is to end with the most stones. The total number of stones is odd, # so there are no ties. # Alex and Lee take turns, ...
0c7e2ee88918a40dc36e041c36e65c899828e54b
linhdvu14/leetcode-solutions
/code/072_edit-distance.py
2,885
4.0625
4
# Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. # You have the following 3 operations permitted on a word: # Insert a character # Delete a character # Replace a character # Example 1: # Input: word1 = "horse", word2 = "ros" # Output: 3 # Explanat...
f3482a5bb8b665e09c0ba7570a4504342c63af2a
linhdvu14/leetcode-solutions
/code/199_binary-tree-right-side-view.py
1,785
4.03125
4
# Given a binary tree, imagine yourself standing on the right side of it, return the # values of the nodes you can see ordered from top to bottom. # Example: # Input: [1,2,3,null,5,null,4] # Output: [1, 3, 4] # Explanation: # 1 <--- # / \ # 2 3 <--- # \ \ # 5 4 <--- # -...
cebdb38db32688d04a40d3a0e9edef36d6023951
linhdvu14/leetcode-solutions
/code/888_fair-candy-swap.py
1,747
3.65625
4
# Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of # candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has. # Since they are friends, they would like to exchange one candy bar each so that after # the exchange, they both have the same total amount of ca...
8974e6ad67a5112d414a7ad1e238a838e80240a4
AlbertoPascal/CS50-Python-AI
/degrees/degrees.py
7,351
3.65625
4
#Solution Code to CS50 Ai course Degree's problem by Alberto Pascal Garza #albertopascalgarza@gmail.com import csv import sys import copy from util import Node, StackFrontier, QueueFrontier # Maps names to a set of corresponding person_ids names = {} # Maps person_ids to a dictionary of: name, birth, movies (a set ...