blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3344be405937608d2d2d5856d7f46cb7d4cd5aec
adityachhajer/Hackerrank-Problem-Solving.
/Problem Solving/bst.py
4,381
3.984375
4
class Stack(object): def __init__(self): self.items=[] def push(self,item): self.items.append(item) def pop(self): if not self.is_empty(): self.items.pop() def is_empty(self): return len(self.items)==[] def peek(self): if not self.is_e...
27560d53ba608a6923ed28e1eefde64f3d8bf722
samahDD/MITx6.00.1x_IntroToCS
/PS1_3.py
755
3.890625
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 29 13:53:22 2019 @author: peter """ # s = 'kwayqyzfidhkfxrq' # Longest substring in alphabetical order is: qyz s = 'qnojscygzllrfmpfmrjgini' # Longest substring in alphabetical order is: llr result = [] final = [] for letters in s: result = result + [...
5bc58d53a9648824ec22dd0afcad2fddedde2d54
samahDD/MITx6.00.1x_IntroToCS
/getSublists.py
419
3.796875
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 1 11:04:33 2019 @author: peter """ def getSublists(L,n): """ L is a listz of integers n is an integer returns all sublists of L with with n elements """ answer=[] for i in range(len(L)-(n-1)): answer.append(L[i:i...
302c3c5df618c4e5dcde1ce8f61ad95d937a6a10
maomao-yt/paiza_Arank_skill_up
/chapter (6)/step_1.py
128
3.515625
4
N = int(input()) num_list = [int(i) for i in input().split()] num = 0 for i in range(N): num += num_list[i] print(num)
7b0902cffc43c4c353c67342a0f25b1ce4a311bc
Ravenm/2143-OOP-NASH
/homework1/FractionClass.py
2,015
4.21875
4
class Fraction(object): """ Simple fraction class created to show overloading """ def __init__(self, n=None, d=None): self.numerator = n self.denominator = d def __str__(self): """used to print fraction :description: overrride of print function used to ...
3c912831ce2cdc6eb52878f7115ac60a72a911d5
shalevaz/name
/hello.py
284
3.96875
4
name = input("Insert your name ") age = input("Insert your age ") age = int(age) if age > 18: print ("Hello "+name+" you are allow to continue") else: few = 18 - age few_str = str(few) print("Hello "+name+" you are too little please try again in a "+few_str+" year")
ad87bd69a56fd7627a209bd7ef067e133fb7b3b1
lindameh/cpy5p3
/q2_display_pattern.py
299
3.890625
4
def display_pattern(n): for i in range(1, n+1): for j in range(n, i, -1): d = j // 10 print(end = (d + 2) * " ") for k in range(i, 0, -1): print(k, end = " ") print("") n = int(input("Enter a positive integer: ")) display_pattern(n)
ec02f02d5b04a1658a716c4cf563c7aa9fc2fc3a
carlorizzante/codingbat
/Warmup-1/monkey_trouble.py
285
3.6875
4
# We have two monkeys, a and b, and the parameters a_smile and b_smile indicate # if each is smiling. We are in trouble if they are both smiling or if neither of # them is smiling. Return True if we are in trouble. def monkey_trouble(a_smile, b_smile): return a_smile == b_smile
3ade95f3e7d0b7b2c2db9e52af9fad6f346eb2e4
carlorizzante/codingbat
/String-2/double_char.py
194
4.125
4
# Given a string, return a string where for every char in the original, there # are two chars. def double_char(str): result = "" for c in str: result += 2 * c return result
0703b842379aa9fd0c83ba6ebaed0a7c37380332
carlorizzante/codingbat
/Logic-1/squirrel_play.py
422
3.9375
4
# The squirrels in Palo Alto spend most of the day playing. In particular, they # play if the temperature is between 60 and 90 (inclusive). Unless it is summer, # then the upper limit is 100 instead of 90. Given an int temperature and a # boolean is_summer, return True if the squirrels play and False otherwise. def sq...
0cd7cb37bb7cc2831e93fe03062c55479d88ae07
ChristineMulindi/Password-Locker
/user.py
1,293
3.984375
4
class User: """ Class that generates new instances of users. """ def __init__(self, user_name, password): self.user_name = user_name self.password = password user_list = [] def save_user(self): ''' save_user method saves user objects into user_list ...
5b6b238476facdb0b73ebd3ba9b896694b6bf7ca
Slavik0041/BelHard_education
/bh_5_tasks-Sherlat_ready/easy/generators/even_numbers.py
861
4.3125
4
""" Написать генератор get_even_number, который возвращает подряд четные числа Например: even_gen = get_even_number() next(even_gen) -> 2 next(even_gen) -> 4 next(even_gen) -> 6 """ def get_even_number(): for number in range(30): if number % 2 == 0: yield number even_number = get_even_num...
fba440bbafedf140840a4b172a4466d4f523187f
Slavik0041/BelHard_education
/bh_3_tasks-Sherlat_ready/tasks/dict_task/get_values.py
460
4
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- Написать функцию, которая возвращает значения в словаре """ def get_values(collection: dict): # TODO вставить код сюда result = dict.values(collection) return result if __name__ == '__main__': assert (100, 2...
e9348f80f1094b7ec8425aa04aa88b1ad260f6bc
Slavik0041/BelHard_education
/bh_5_tasks-Sherlat_ready/easy/functions/calc_sum.py
650
4.15625
4
""" Написать функцию calc_sum, которая принимает неограниченное количество целых чисел и возвращает их сумму для расчета суммы можно воспользоваться функцией sum """ def calc_sum(*args): summa = 0 for i in args: summa += i return summa # return sum(args) if __name__ == '__main__': some...
2222ac1b73f93034714c9de03fb8a6c4c0cd5c72
Slavik0041/BelHard_education
/bh_5_tasks-Sherlat_ready/medium/dict_from_lists.py
650
4.3125
4
""" Написать функцию get_dict_from_lists, которая принимает 2 значения - 2 списка одинаковой длины: LIST_1 и LIST_2. Необходимо, чтобы функция составляла и возвращала словарь, у которого ключи - элементы LIST_1, а значения - элементы LIST_2 """ LIST_1 = [str(i) for i in range(20)] LIST_2 = [i for i in range(20)] def...
309e9765b6d5b8a72fe8661b5d000b47b0ca12c0
Slavik0041/BelHard_education
/bh_5_tasks-Sherlat_ready/medium/fibonacci_generator.py
967
4.28125
4
""" Написать генератор fibonacci, которая принимает номер значения num_count из чисел Фибоначчи и выводит на экран результат до заданного значения. Номер значения нужно проверить Пример: fibonacci(0) -> 'Введите значение больше 1' fibonacci(5) 1 2 3 5 8 Traceback (most recent call last): File «C:/Python/Python3/pyth...
8a7b90f12259515f066aca3dda328a466502db00
Slavik0041/BelHard_education
/bh_3_tasks-Sherlat_ready/tasks/dict_task/get_keys.py
733
4.1875
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- Есть база WORKERS с днями рождений сотрудников Написать функцию get_workers_names, которая возвращает все имена работников """ WORKERS = { 'Декоратор Иван Олегович': '13.05.1980', 'Баг Илья Андреевич': '07.09.1995', ...
32dc08843664e3754fe0e91d55c41edcd926dcab
Slavik0041/BelHard_education
/bh_5_tasks-Sherlat_ready/hard/generate_brackets.py
908
4.0625
4
""" Задача из собеседования в яндекс Написать рекурсивную функцию generate_brackets, которая принимает длину - количество пар скобок, и будет генерировать все возможные варианты скобочных последовательностей Например: n = 3 ((())) (()()) (())() ()(()) ()()() n = 4 (((()))) ((()())) ((())()) ((()))() (()(())) (()()(...
28e708cb60fa3a211edc3a7f64b8222aafb421d3
Slavik0041/BelHard_education
/bh_2_tasks-Sherlat_ready/tasks/strings/multiply.py
1,158
4.15625
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- Пользователь вводит строку и число n. Необходимо вернуть строку, которая будет продублирована n раз- ПРИМЕРЫ -------------------------------------------------------------------------------- - ('привет', 3) -> 'приветприветприв...
61664dc33797af7a19608bd72b8ea96d6faac845
Slavik0041/BelHard_education
/bh_3_tasks-Sherlat_ready/tasks/dict_task/unite_dict.py
564
4
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- Написать функцию, которая объединяет элементы 2 словарей """ from copy import deepcopy def unite_dict(dict_1: dict, dict_2: dict) -> dict: dict_1_copy = deepcopy(dict_1) # TODO dict_1_copy обновить элементами dict_2 ...
c4a39ecb13cc31a5a30c4e337afd1c3049e201e2
Slavik0041/BelHard_education
/bh_7_tasks-master/easy/classes/sequence.py
978
4.28125
4
""" Создайте класс RandSequence с методами, формирующими вложенную последовательность. Определить атрибуты: - sequence - последовательность Определить методы: - инициализатор __init__, который принимает длину последовательности n - метод generate, который принимает длину последовательности n - метод print_seq, кото...
c81000e70e91a0423581c5237d39f8fc2db1d96a
nahidhasan007/Python-
/tic_tac-toe_project.py
3,025
3.921875
4
board = ['-','-','-','-','-','-','-','-','-'] game_still_going = True winner = None current_player = 'X' def display_board(): print(board[0] + '|' + board[1] + '|' + board[2]) print(board[3] + '|' + board[4] + '|' + board[5]) print(board[6] + '|' + board[7] + '|' + board[8]) def play_game(): display_board() ...
ab6f7df457daeee93bc336144cb48350dc8bbca6
MaxwellVale/CS01
/cs1_final/rubiks_rep.py
4,960
3.640625
4
# Name: Maxwell Vale # Login: mvale ''' Rubik's cube representations and basic operations. ''' import rubiks_utils as u import copy class RubiksRep: ''' Basic functionality of Rubik's cubes. ''' def __init__(self, size): ''' Initialize the cube representation. ''' asser...
2ae231ff4f8963e4e97ab444ad2ec5d6258c5280
MaxwellVale/CS01
/lab3/lab3ab.py
3,978
4.09375
4
# Maxwell Vale # CS01 Section 1a # Assignment 3 import math # Part A: Exercises # Ex A.1 def list_reverse(lst): ''' Returns the reverse of list lst without modifying it Uses the reverse() function ''' copy = lst.copy() copy.reverse() return copy # Ex A.2 def list_reverse2(lst): ''' ...
161f56b01bde618c7eac9d1ba8b93c2741d37124
srisamatha80/Example-Programs-Python
/tic-tac-toe.py
659
3.8125
4
#this is basic version theBoard = {'top-L':' ', 'top-M':' ', 'top-R':' ', 'mid-L':' ', 'mid-M':' ', 'mid-R':' ', 'low-L':' ', 'low-M':' ', 'low-R':' '} def printBoard(tttDict): print(theBoard['top-L'] + ' |' +theBoard['top-M']+ ' |' +theBoard['top-R']) print('--+--+--') print(theBoard['mid-L'] + ' |' +theBoard['m...
afa1ead3571f9f4a58e52f232c698c9a3db26750
sayak1711/MLPracticeTopicWise
/Regression/polynomial-regression.py
1,166
3.5
4
import pandas as pd from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder import numpy as np dataset_path = 'D://Work//MLCodes//Machine Learning...
e1ba759c0fa2de418b2b0f41bc0061e66c1e3993
kt-tm/python-practic
/lession1-1.py
249
3.75
4
from datetime import datetime as DT current_datetime = DT.now() dt_bith = input("Введите дату рождения ") dt_bith = DT.strptime(dt_bith, '%d.%m.%Y') age = current_datetime.year - dt_bith.year print(f"Ваш возраст {age}")
8b63f0056ad985fc35df9a7bed86acf146f4a8dc
Nehagarde/etl
/list_comprehension.py
625
4.03125
4
#list comprehension l = [2,2,3,4,5,6,6,7,8,8,9] def list_comprehension(l): return [item for item in l if l.count(item)==1] print(len(l)) #dictionary comprehension: def dict_comprehension(l): return {k:k**3 for k in l} l2 = [ [1,2,3],[4,5,6] ] l3 = [] for l1 in l2: for item in l1: l3.append...
7dead48087462f64281d03fe152575530d916bf2
Nehagarde/etl
/exceptions.py
535
3.765625
4
"""Custom Exceptions""" class MyExcept(Exception): def __init__(self): print("Calling Exception") def __str(self): return("This is a custom exception") if __name__ == '__main__': a = MyExcept() print(a) print("Raising Exception") try: raise a print(1/10) ...
e8674b071a947fe87723b5015559d9c4fc04d94f
Nehagarde/etl
/tuples.py
1,223
3.984375
4
#tuples, strings and numbers are immutable t = (1,23,4) print(dir(t)) print(t.count(23)) print(t.index(4)) t1 = (1,2,3) t2 = (2,3,4) print(id(t1)) print(id(t2)) t1 = t1+t2 print(id(t1)) l = [1,2,3] t = (10,20,30,l) print(t) l.append(20) print(t) dict1 = {(1,2,3):'This is a dict with tuple as key'} #you cann...
95b28ad17d7228b3050b98d3d228ab6bc37f2a80
jizheair/algo
/someNeighbor.py
1,414
3.640625
4
class Solution: # @param board, a list of lists of 1 length string # @param word, a string # @return a boolean # i - dx # j - dy neighbor = {} def exist(self, board, word): dx = [0,0,-1,1] dy = [-1,1,0,0] for i,word in enumerate(board): for j...
c0a7cd81aa82f70636243159a9851c637fa5f9d8
jizheair/algo
/partition.py
1,449
3.90625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): return str(self.val) class Solution: # @param head, a ListNode # @param x, an integer # @return a ListNode def partition(self, head, x): ...
1f3a0ce0137bd8641d873b450d6edfa50fda984b
jizheair/algo
/twStackQ.py
416
3.796875
4
class Queue: def __init__(self): self.s1 = [] self.s2 = [] def push(self,item): self.s1.append(item) def pop(self): if len(self.s2) != 0: return self.s2.pop() else: while len(self.s1) != 0: self.s2.append(self.s1.pop()) ...
4bebdc399cf8f08e00c5eec244863fc9fb8c217c
jizheair/algo
/excludemultiply.py
617
3.671875
4
class Solution: def multiply(self,a): fwd = [None]*len(a) bwd = [None]*len(a) mul =1 fwd[0] = 1 for i in range(len(a)-1): mul = mul*a[i] fwd[i+1] = mul bwd[-1] = 1 mul =1 for j in reversed(range(1,len(a))): mul =...
1e1f792436bb2028c7032fce829b229d1f78e65d
euguroglu/cave
/Python_OOP_04.py
380
3.75
4
class Book(): def __init__(self,title,author,pages): self.title = title self.author = author self.pages = pages def __repr__(self): return f"Title: {self.title}, Author: {self.author}" def __len__(self): return self.pages mybook = Book('Py...
0028174b8958638ea6dd4f6bf6b206f5c3b58c33
Sadia2018/fundamentals
/functions_basic_i/functions_basic_i.py
2,153
3.953125
4
# #1 # def number_of_food_groups(): # return 5 # print(number_of_food_groups()) # # returns 5 # #2 # def number_of_military_branches(): # return 5 # # print(number_of_days_in_a_week_silicon_or_triangle_sides() + number_of_military_branches()) # #3 # def number_of_books_on_hold(): # return 5 # retu...
67be56ccba3e62baef4c25735470d56664bcbcde
Hrishikesh-coder/Numpy
/7doc.py
284
3.578125
4
import numpy as np a = np.floor(10*np.random.random((3,4))) print(a) print(a.shape) print(a.ravel()) #returns the array flatenned print(a.reshape(6,2)) print(a.T) #returns the array,transposed print(a.T.shape) print(a.shape) a.resize((2,6)) print(a) print(a.reshape(3,-1))
72424a1821ea0a3031133d996e88feeda7797e0d
AdamC66/pheedloop-interview-challenges-12_9_19
/pheedloop.py
961
3.71875
4
# Absent Attendees # Given a list of attendee ids for attendees who have registered for an event and a list of attendee ids # for attendees who have checked into an event, return the list of attendees who have not checked in. # absentAttendees(registeredAttendees, checkedInAttendees) # // [509, 672] registered...
354afdfdbfbdca1fde9947a8c322cbe8f51d52fe
anaypaul/LeetCode
/StringToInteger(atoi).py
2,241
4.40625
4
""" Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and inte...
f7c9f3cf86824809863740d72bdb937b8aca5077
anaypaul/LeetCode
/RemoveDuplicatesFromSortedArray.py
661
3.828125
4
""" Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. """ def removeDuplicates(arr): """ :type arr: List[int]...
649cfad7e26dcaf3fec2ee5b97f3edd1906e7f4d
anaypaul/LeetCode
/PalindromeNumber.py
1,140
4.375
4
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. """ def isPalindrome(self, x): """ :type x: int :rtype: bool """ res = True if x > 0: number = x reverse = 0 while number > 0: reverse = ...
eb4a9a30949d6ceae6ef99bc2e3a4aa35339a2c0
stepochek/work
/w5.py
1,002
3.546875
4
git statusimport random text_data = input('Write your text: ').split() text_data_index = [] for i in range(len(text_data)): text_data_index.append(text_data[i] + '_' + str(i+1)) shuffled_data_index = [] while text_data_index != []: word = random.choice(text_data_index) shuffled_data_index.append(word) ...
f4f820f697472c38fe6cf2afd4add5c8acfa80c0
cklins/Python
/practice_example/matplotlib_test.py
10,837
3.71875
4
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D #1 基本用法 x = np.linspace(-1, 1, 50) y = 2*x + 1 # y = x**2 plt.plot(x, y, label='y=2*x+1') plt.plot(y, x, label='y=(x-1)/2') plt.legend() plt.show() #2 figure 圖像 x = np.linspace(-3, 3, 50) y1 = 2*x + 1 y2 = x**2 plt.figure()...
1bb750a4239ac6bde5a9c223b1c4d1da0d8838f4
peterrenshaw/tw
/doc/shed3.py
753
3.53125
4
#!/usr/bin/env python # ~*~ encoding: utf-8 ~*~ import time import random from threading import Timer def print_time(): print "From print_time", time.time() def print_some_times(): print time.time() Timer(5, print_time, ()).start() Timer(10, print_time, ()).start() time.sleep(11) # sleep while ...
de09b851bf19d153d70dc8ad5756769ab65abde9
WestbrookT/UltAI
/board.py
4,720
3.625
4
import pprint class Board(): history = [] state = None print_state = False last_move = None # (x, y) current_player = 1 #1 or -1 winner = None moves = 0 finished_boards = [] gameboard = [[None, None, None] for i in range(0, 3)] # [board [col1 [small_board [small_col1] ...sb] ...cols] ...board] def __ini...
64ca39f6950704a0fc13bc59de59e06a2fc4cf58
ymadh/python-practice
/exceptions/exception.py
678
3.609375
4
# raise = throw def calculate_xfactor(age): if age <= 0: raise ValueError("Age cannot be lss than 0") return 10/age try: calculate_xfactor(-1) except ValueError as error: print(error) # try: # # automatically closes this file # # ,open("another.txt") as target: # with open("../in...
ba04e1ef5c44df89ad5eb33608a9d9567da62aae
ymadh/python-practice
/debugging.py
219
4.03125
4
def multiply(*numbers): total = 1 for number in numbers: total *= number return total print("finish") print("start") print(multiply(1, 2, 3)) # alt optmove lines up / down # fn up down left right
4f083ab8f198cac8a6be0f1fd3ce98da71cc4bd0
ymadh/python-practice
/lists/looping.py
263
4.0625
4
letters = ["a", "b", "c"] # gives you a tuple (read only list) for letter in enumerate(letters): # print(letter) # print(letter[0], letter[1]) key, val = letter print(key, val) for index, letter in enumerate(letters): print(index, letter)
c9fb49baacb6c18d143749d7a19afa86bc5a797a
mah1212/opencv-basic-to-advanced
/4. ImageProcessing/2.3_Rotation.py
840
3.8125
4
''' Rotation Rotation of an image for an angle θ is achieved by the transformation matrix α=scale⋅cosθ,β=scale⋅sinθ To find this transformation matrix, OpenCV provides a function, cv.getRotationMatrix2D. Check below example which rotates the image by 90 degree with respect to center without any scaling. ''' impor...
8ba956d2aac8d0d4e9b91e8007f53542cbaf3d11
mah1212/opencv-basic-to-advanced
/5. FeatureDetectionDescription/2.0_Shi_Tomasi_Corner_Detection.py
2,924
3.515625
4
# https://github.com/opencv/opencv/tree/master/samples/python/tutorial_code # ============================================================================= # OpenCV has a function, cv.goodFeaturesToTrack(). It finds N strongest corners # in the image by Shi-Tomasi method (or Harris Corner Detection, if you specify #...
408d00e7d0a3395af9413e5741626e7fccfa374c
mah1212/opencv-basic-to-advanced
/3. CoreConcepts/6_read-mage-property.py
1,165
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 2 05:15:29 2018 @author: Mahbub """ import cv2 import numpy as np def main(): print('This is inside the main function') img = np.zeros((512, 512, 3), np.uint8) image_name = 'New Image' #Draw Line cv2.line(img, (0, 100), (100, 0), (0, 255, 0...
bb3513638adb20ba131888a77c1c3afd7502ecf2
mah1212/opencv-basic-to-advanced
/4. ImageProcessing/12.3_Furier_Why_Laplace_Highpass.py
2,176
3.609375
4
''' Fourier Transform is used to analyze the frequency characteristics of various filters. For images, 2D Discrete Fourier Transform (DFT) is used to find the frequency domain. A fast algorithm called Fast Fourier Transform (FFT) is used for calculation of DFT. ''' ''' Fourier Transform in OpenCV OpenCV provides t...
ec9a6000f4a87b378aea7ff7f0092547e2b572cb
mah1212/opencv-basic-to-advanced
/4. ImageProcessing/12.1_Furier_Transform_Numpy.py
2,176
3.984375
4
''' Fourier Transform is used to analyze the frequency characteristics of various filters. For images, 2D Discrete Fourier Transform (DFT) is used to find the frequency domain. A fast algorithm called Fast Fourier Transform (FFT) is used for calculation of DFT. ''' ''' Fourier Transform in Numpy First we will see ...
d90fdb854d8eb7a4c35b837b54ebfe62470396fd
wocin/py-tool
/py-module/py-itertools.py
251
3.546875
4
#!/usr/bin/env python #By wocin #Email --- #python itertools module ''' from itertools import chain test=chain.from_iterable('ABCDEFG') test.next() same to def iter(iter): for x in iter: for y in x: yield y test=iter('ABCDEFG') test.next() '''
d6cc17c714bb8c0ec299658f816d8112ecb7e18f
Jdavid1001-zz/commonInterviewProbs
/targetSum.py
1,398
4.0625
4
# -*- coding: utf-8 -*- """ Given an array of integers and a target integer sum, return whether there exist a pair of integers in the array which add up to sum. See if you can come up with an O(n^2) solution first. Then—can you come up with an O(n log n) one? """ def targetSumNaive(arrayInts, targetNum): for each...
3ec0779999e6c9437dba385a4cc021941995fc52
praveendusari/Heroku-restart
/app.py
632
4.09375
4
# Python program to illustrate the concept # of threading # importing the threading module import threading import time def print_cube(num): while(True): print("from 1st Thread ",time.ctime()) time.sleep(60) def print_square(num): while(True): print("From 2nd thread",time.ctime())...
7a99e900f9ec6701c114c5548c2ec2baecb45636
rohitshakya/CodeBucket
/2. Coding_Problems/Python's assignmemt/primenumber.py
356
4.09375
4
# # Author : Kajal Shakya # Date : Jan-2021 # IDE : Python Idle 3.7 # Time complexity : O(n) # Title : Prime number # num=int(input("enter a number:")) #check for factors flag=True for i in range(2,num): if(num%i)==0: flag=False break if(flag): print(num,"is a prime number") els...
334eb1ffa6cfb2dc6c47cb936b46e18790d06e52
rohitshakya/CodeBucket
/2. Coding_Problems/Python's assignmemt/palindromenumber.py
340
3.953125
4
# # Author : Kajal Shakya # Date : Jan-2021 # IDE : Python Idle 3.7 # Time complexity : O(log n) # Title : Palindrome # n=int(input("enter the number:")) temp=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(temp==rev): print("the number is palindrome") else: print("the number...
eb04fd4f9175cc6df58c04c7edfcd6b3348af3dd
d-Laurente/WorkXlsToCSV
/Prices.py
915
3.5
4
class Prices: def __init__(self, wasPrice): self.__wasPrice = wasPrice self.__netPrice = 0.5 * wasPrice self.__specialPrice = 0.4 * wasPrice def setWasPrice(self, wasPrice): self.__wasPrice = wasPrice self.__netPrice = 0.5 * wasPrice self.__specialPric...
8f8a2d4beeb8d1f8797a56214c00d8986a9d596e
Tianid/DBCartel
/test.py
69
3.578125
4
val="1,2,3" kek=val.split(",") print(kek) for i in kek: print(i)
3c488067042b4ab7347ce68e3a3069bea0b43a9e
anplase/Practicas_Python
/Practicas/150_pag/practica.py
630
3.90625
4
numero='' def pedir_numero(): while True: try: numero = int(input('Dame un número del 1 al 10: ')) except Exception as error: #lo de Exception as error no #es necesario pero de esta #forma se caza cualquier error print (error) print ('Ha habido un error que hay que depurar AP...
068538aa8dbb50166b5f043198b797583196b9ee
anplase/Practicas_Python
/Practicas/Pruebas2.py
900
4.21875
4
print("hola mundo") curso = 'Curso de ' tipo = 'python' print ('{}{}'.format(curso, tipo)) frase = input("escribe la frase: ") #entrada por teclado print(frase) numerocaracteres=len(frase) # longitud de la cadena de caracteres print(numerocaracteres) num=frase.count('a') #cuenta los caracteres a que hay en la fr...
2eab88c30b72aab038ed303fe4c7c4a1168d79a8
anplase/Practicas_Python
/Practicas/funciones/funciones.py
1,368
4.34375
4
# Aquí practicaremos las funciones # si tenemos por ejemplo: def factorial_numero(): #la nomenclaura de nombre tiene que ser así, con guion bajo para separar numero=5 factorial=1 while numero>0: factorial= factorial*numero numero-=1 pass print(factorial) pass factorial_numero() #como no nos develve nada p...
b4d7662bd667c3d86cdde05a5fe64609edfff243
noahmarble/Ch.04_Conditionals
/4.1_Number_Analysis.py
1,000
4.46875
4
''' NUMBER ANALYSIS PROGRAM ----------------------- Create a program that asks the user for a number and then analyzes it to determine if it is: 1.) odd or even 2.) positive, negative or zero 3.) inclusively between -100 and +100 A small report will then be printed. Use the following to test your program In: 32 Out: ...
0849bbcb2ded36990d412bce7f03dd6b8051688f
wkarney/advent-of-code-2020
/4/day4.py
2,917
3.875
4
#!/usr/bin/env python """ Advent of Code 2020, day 4 Will Karnasiewicz """ import re REQUIRED_FIELDS = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] # Part 1 def count_valid_passport_pt1(input_txt, required_fields): """Function for counting number of valid passports in a group for AOC 2020 Day 4 Pt 1 ...
d49c103a9c42246ca02804654904ed45e18dd949
rushabhjhaveri/HackerRank-Python
/Introduction Challenges/Python If-Else/ifelse.py
233
3.90625
4
if __name__ == '__main__': n = int(input()) if n%2 == 1: print("Weird") elif n%2 == 0 and n in range(2,6): print("Not Weird") elif n%2 == 0 and n in range(6,21): print("Weird") elif n%2 == 0 and n>20: print("Not Weird")
fea06414b436aa4bf3c54176930e8ff1e5036cee
danihartanto/python-project-camp
/tugas_1.py
906
3.671875
4
class bilPrima: def __init__(self): self.awal=0 self.akhir=0 def mainPrima(self): self.awal=int(input("masukkan angka pertama: ")) self.akhir=int(input("masukkan batas prima: ")) self.data=[] if self.awal >= 1 and self.akhir > 1: for x in rang...
9a2a63cd6f2e230c35365f6d2d8293af646ef70d
vitoo199/Tic-Tac-Toe
/Board.py
1,198
3.5
4
from Cell import Cell import consts class Board(): def __init__(self, matrix): self.cells = self._create_cells(matrix) def _create_cells(self, matrix): arr = [] for row_index in range(len(matrix)): row = [] for char_index in range(len(matrix[row_index])): ...
a221302abdd4fa9c02b06903fd972b5ec3f99110
dchentech/leetcode
/151-reverse-words-in-a-string.py
1,243
3.734375
4
""" Question: Reverse Words in a String Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) space. click to show clarification. Clarif...
87c48097c54fa24850b0d8aeddd8d1e92c78640f
dchentech/leetcode
/28-implement-strstr.py
1,862
3.8125
4
""" Question: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Update (2014-11-02): The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a...
6c6fcb488fe3f8c3c4d595abbaff48506fe7db8f
dchentech/leetcode
/27-remove-element.py
1,880
3.6875
4
""" Question: Remove Element Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Performance: 1. Total Accepted: 78411 Total Submissions: 245469 Difficulty: Eas...
4b00be4e40f168e336c5fadb2f4f1f9ee82d8a6c
dchentech/leetcode
/205-isomorphic-strings.py
1,476
3.71875
4
""" Question: Isomorphic Strings Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters ...
20298a6390c98a80e7ce30c45696c8572edbe615
dchentech/leetcode
/66-plus-one.py
850
3.546875
4
""" Question: Plus One Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. Performance: 1. Total Accepted: 66486 Total Submissions: 216562 Difficulty: Easy 2. Your runtime bea...
7d7b94c11090de1b914eacff25c149d272610ba5
meganleahlane/python-challenge
/PyPoll/main.py
1,747
3.671875
4
### PYPOLL ### # Install modules import os import csv output = open("elec_output.txt", "w") # 1. GET FILE & DATA # Link os to csv reader path csvpath = os.path.join("..", "PyPoll", "election_data.csv") with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader...
f234e460fef1c0a7d8c6f93fb3f9c18dd30dc75b
aoloe/scribus-script-repository
/CopyPaste/paste2all.py
2,483
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: paste2all.py # © 2012.01.29 Gregory Pittman # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your o...
a17fb5c0c47444f602f6983160f7f1df9b54e5b9
nivla12345/projectEuler
/Problems/PrimeSet.py
441
3.515625
4
__author__ = 'Alvin' import Tools from ExpandingSet import ExpandingSet class PrimeSet(ExpandingSet): def __init__(self, starting_value=(2, 3), starting_n=1): ExpandingSet.__init__(self, starting_value, starting_n) def sequence_function(self): starting_value = self.sequence_list[-...
cb40803bc03645dc16e15b5ad892da29e80f1fd6
ribohe94/LearningPython
/ML/logistic_regression.py
3,536
3.6875
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import pdb def sigmoid(z): z = z.astype(np.float64) return 1 / (1 + np.exp(-z)) def costFunction(X, y, weights): m = np.size(X,0) return (1 / m) * sum(-y * np.log(sigmoid(X.dot(weights))) - (1 - y) * np.log(1 - sigmoid(X.dot(weight...
74478429371c2a50a5ba0c9156b25431a3eb85db
dan129/Portfolio
/other/projetTowerDefense/Tours.py
11,223
3.640625
4
# -*- coding: UTF-8 -*- import helper import Creeps class Tour(): portee=10 niveauTour=1 compteurTir=1 vitesseTir=4 vitesseTirDefault = 30 def __init__(self, parent, x, y, couleur): self.parent=parent self.x=x self.y=y self.couleur=couleur self.etatDeTi...
066156b7c8dafde23be3a51a8f36bb59e3869b0b
mincanhe/Network-routing-protocol
/heap.py
791
3.65625
4
def max_heapify(A, i): n=len(A) l=2 * i r= 2 * i + 1 if l <= n and A[l] > A[i]: largest = l else: largest = i if r<= n and A[r] < A[i]: largest = r if largest != i: j=A[i] A[i]=A[largest] A[largest]=j max_heapify(A,i) def build_max_hea...
eae02702a55019b21a9fa7794d0aff0e5fc347f0
Mitchell-McShane/week3_day5_homework
/app/models/game.py
1,037
4
4
class Game(): def __init__(self, player_1, player_2): self.player_1 = player_1 self.player_2 = player_2 def play_game(self): if(self.player_1.hand == self.player_2.hand): # print("It's a draw!") return "draw" elif((self.player_1.hand == "rock" and sel...
844a1d8d3b75404fbb5132e198e1f0b3b500af80
IrvingQuirozV/Ingenieria-del-conocimiento
/ejercicios en python/24.py
441
4.03125
4
24. Calcular e Imprimir una tabla de dos columnas que muestre, en la primera, los enteros del 1 al n y en la segunda a n2. No utilizar un numero mayor que 30 para N num=[] num1=[] x = int(input("¿Cuántos números quieres menor que 30?\n")) if x > 30: print("La cantidad debe ser menor que 30") else: for i ...
c9110fd727b65e1e8018efd688d136016a8de4fd
dibovdmitry/laba_3
/User.py
184
3.828125
4
name = input("What is your name?") age = input("How old are you?") country = input("Where are you live?") print("This is:", name) print("It is:", age) print("S(he) lives in", country)
42570eacaa610767aef511c0694bda4702b5c389
rojarfranklin/guvi
/loop/sum natural num.py
60
3.5
4
a=int(input()) i=1 while (i<=a): print(i) i+=1
24d5e535b5382c190b13e2a3c6cb8b5abd761c4c
Inkanus/Biblioteka
/movies_and_series2.py
4,288
3.96875
4
from datetime import datetime from random import choice, randint class Movie: def __init__(self, title, year, type, plays=0): """A class to represent a movie.""" self.title = title self.year = year self.type = type self.plays = plays def play(self): ...
73c76bb143ab182f56e2fefd2acd866c2fb50d62
Ranjan-kumar-97/just-coding
/Fibonacci.py
387
4.21875
4
def fibonacci(): first = int(input("Enter Starting Number: ")) second = int(input("Enter Second Number: ")) terms = int(input("Enter Number of Terma: ")) count=0 print("Fibonnaci Series is : ") while count<terms: print(first, end=' , ') temp=first+second first=second ...
1ac076cc8af800c059dae3f9b4d7c9cc600b6942
ShivamNegi/Daily_Programmer
/easy/Daily_programmer_easy_67.py
268
3.640625
4
n = input("Enter the number: ") machine = bin(n) machine = machine[2:] length = len(machine) convert = machine + '0' * (32-length) print convert """ integer = 0 for i in convert: integer += int(i)*(2**length) length -= 1 print length """ print int(convert,2)
b2041c22161b2e4e36cc9e08fe1831e13884393e
ShivamNegi/Daily_Programmer
/easy/palindrome_py.py
132
3.796875
4
string = raw_input() rev = string[::-1] n = len(string) if string == rev: print "Palindrome." else: print "Not Palindrome."
20d6cf19664e4186081432fc80f7ecece0c19857
ShivamNegi/Daily_Programmer
/easy/The_bogosort.py
305
3.890625
4
inp1 = raw_input("Enter the word to be sorted: ") inp2 = raw_input("Enter the word we want to get: ") count = 0 from random import shuffle while True: if inp1 != inp2: inp1 = list(inp1) shuffle(inp1) inp1 = ''.join(inp1) count += 1 else: break print count
b65d2f6de0b54d0515cd83017ab594f013b80a48
vinh-ngoquang/NgoQuangVinh--D4E11
/Hw1/hw2.py
150
3.734375
4
from turtle import * pencolor("green") fillcolor('yellow') begin_fill() for i in range (3): forward(100) left(120) end_fill() mainloop()
f93b4da567595f667f88dd7a881629e4ee42c7e6
vinh-ngoquang/NgoQuangVinh--D4E11
/session2/conditional.py
144
3.546875
4
score=4 att =' tot' if score < 9 and att == 'tot': print('Good') elif score < 7 or att =='tot': print('Normal') else: print('Weak')
8946e4f460c541dcc8cb4ca9e38ecab029e92413
JMPlourde/Python-Practice
/Euler3.py
584
3.578125
4
#The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143 def primetest(n): y = 2 while y*y <= n: if n % y == 0: return False y+=1 return True def findprime(a): primefac = [] x = 2 while x*x <= a:...
4ebb27c8f3536c8fefea0bc9548fd09ee027bc1c
JMPlourde/Python-Practice
/Euler1.py
304
4.21875
4
#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. total = 0 for n in range(0,1000): if n % 3 == 0 or n % 5 == 0: total += n print(total)
3356e22bbb29fa58ea01c9b888fb903a008fe590
Archana-Chinnaiah/thoughtworks_assignment
/icecream_program_using_class.py
993
4.0625
4
class IceCream: def __init__(self,flavours,types): self.flavours=flavours self.types=types def display_cost(self): return self.flavours*self.types class Chocolate(IceCream): def __init__(self,flavours,types,top): IceCream.__init__(self,flavours,types) self.top=to...
ed59df050e7375d5bb9e49c3ca072443622361f2
Archana-Chinnaiah/thoughtworks_assignment
/avg_using_function.py
369
3.6875
4
'''def avg(name,*marks): sum_num=0 for mark in marks: sum_num=sum_num+mark avg = sum_num / len(marks) print name,"-",avg avg("Mala",80,96,84,70,56) ''' import math def rage(*num): s=avg(*num) return avg print(rage(18,25,3,41,5)) ''' sum_num = 0 for t in num: sum_num = sum_nu...
d5a79cd74cc2649f5ece16f9fb23bf4f44687d97
Archana-Chinnaiah/thoughtworks_assignment
/python_closure.py
535
4.21875
4
'''1.debug to get output: hello hello ''' def function_outside(): msg="Hi" def function_inside(): nonlocal msg msg="Hello" print(msg) function_inside() print(msg) function_outside() print() '''2.Debug the program to get output : 1 and also briefly explai...
3aa2a59b5a415f0e38d466d1140277689d73a28d
py1-10-2017/Sarah.Grayer.py1.2017
/Python Basics/ScoresandGrades.py
592
4.0625
4
def scores(numtests): print "Scores and Grades" for i in range (0, numtests): import random random_num = random.randint(60, 101) if random_num >= 90: print "Score:" + str(random_num) + " Your grade is A!!!" elif random_num >= 80: print "Score:" + str(rando...
2cf9166819969db9ef1f6c825b734a57a1f4a8a5
py1-10-2017/Sarah.Grayer.py1.2017
/Python Basics/TypeList.py
1,077
4.09375
4
#input mixedlist = ['magical unicorns ',19,'hello ',98.98,'world '] integerlist = [1,2,3,4,5] stringlist = ["spiff ", "moon ", "robot "] def typelist(list): #function name newstring = "" total = 0 for value in list: if isinstance(value, int) or isinstance(value, float): #each occurence, if any num...
698a654015b2b56e6a15772f6723ada2a57825b5
py1-10-2017/Sarah.Grayer.py1.2017
/Python OOP/product.py
1,630
3.515625
4
#define class product class Product(object): def __init__(self, price, name, weight, brand, tax): self.price = price self.name = name self.weight = weight self.brand = brand self.status = "for sale" self.tax = tax def sell(self): self.status = "sold" ...
f01f4dadeeb849c00f817ca89bf16bc337a2a54b
AchWheesht/Python
/pygame/programarcadegames/labs/Chapter1Labs/Celsiusconverter/converter.py
234
4.3125
4
#This program takes a farenheit input and converts it to celsius farenheit_input = input("Input temperature in farenheit\n") farenheit_input = int(farenheit_input) celsius_output = (farenheit_input - 32) / 1.8 print(celsius_output)
01339582e93e3854c7be5a978e8783dcaea440ee
AchWheesht/Python
/GavSimV2/gavcode/consoleview.py
1,703
3.59375
4
class ConsoleView(): def __init__(self): pass def display_commands(self, commands): print("Here are the current commands you can use") print(commands) #I have been tinkering with the consoleview. Currently, I'm assigning a personalised #message for each action, rather than building the...