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 |
|---|---|---|---|---|---|---|
f81571a76e551dcd4209409213865c023aa074b8 | DamManc/thinkpython2-ex | /chapter_13/es13_2.py | 941 | 4.03125 | 4 | from chapter_13.es13_1 import delete_punct_white
def isto_words(list_words):
isto = {}
for word in list_words:
if word not in isto:
isto[word] = 1
else:
isto[word] += 1
return isto
def calc_numb_words(list_words_for_line):
new_list = [sub_sublist for sublist i... |
56363a59580d0c1fe2983d1160afdb2103880a84 | DamManc/thinkpython2-ex | /chapter_12/es12_1.py | 676 | 4.0625 | 4 | def most_frequent(s):
# creo un instogramma dizionario
table = {}
for ch in s:
if ch not in table:
table[ch] = 1
else:
table[ch] += 1
# creo una lista di tuple invertendo x e freq in modo poi da ordinarla in base al valore numerico
v = []
for x, freq in ta... |
848717c1393fc07613cc371ef7f773b544138894 | YZWLEO/pythonDemo | /601-1.py | 273 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# print text
def fab(max):
n,a,b = 0,1,1;
#print n,a,b,"\r\n"
while n<max:
#print n, a, b, "\r\n"
#print b
yield b;
a,b = b,a+b;
n = n+1
list = fab(5)
for n in list:
print n |
1ab6e4c0f3db1e7bd0fcf7b43b83ad6d74ae09f0 | VitaliiBandyl/Tic-Tac-Toe-with-AI | /Tic-Tac-Toe with AI/task/tictactoe/tictactoe.py | 10,250 | 3.90625 | 4 | import random
from abc import ABC, abstractmethod
from typing import List, Tuple
class TicTacToeField:
"""Game field"""
def __init__(self):
self.field = [[' ' for _ in range(3)] for _ in range(3)]
self.turn = 'X'
def print_game_field(self):
"""Prints game_field field to console""... |
cc11893744ff06296b623e3ccdbaba7691b0d884 | TinaCloud/Python | /lynda/14 Containers/containers -- tuple and list.py | 1,173 | 3.796875 | 4 | #!/usr/bin/python3
# containers.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
# =========== tuple is immutable =================
t = 1, 2, 3, 4
print( type( t ), t )
t2 = tuple( range( ... |
7c9b04459ffaf48dd718d4002f6c367006d4ac60 | TinaCloud/Python | /lynda/12 Classes/classes -- polymorphism.py | 861 | 3.90625 | 4 | #!/usr/bin/python3
# classes.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Duck:
def quack( self ):
print( 'Quaaack!' )
def walk( self ):
print( 'Walks like a duck.' )
def bark( ... |
9f1a003d18bdaae40932083fd2fb346c80c0cd90 | TinaCloud/Python | /lynda/07 Loops/for--enumerate.py | 473 | 3.796875 | 4 | #!/usr/bin/python3
# for.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
fh = open( 'lines.txt' )
for index, line in enumerate( fh.readlines() ):
print( index, line, end='' )
str = "T... |
8636e770c7a81e46c1e7864f61a5eb6a4e780471 | TinaCloud/Python | /practice/testNumber.py | 594 | 3.75 | 4 | #!/usr/bin/python2.6
'''
Created on Apr 7, 2011
@author: redbug
'''
import sys
def main():
a = 40
printType( a )
b = 40.0
printType( b )
#in python2.x this is integer division, while in python3.x this is float division
c = 40 / 9
printType( c )
#in python2.x this is as same as pr... |
0beb5c7b47fe3b3b770cab85ac01df4707d8e0a2 | TinaCloud/Python | /lynda/13 Strings/strings -- format.py | 631 | 3.78125 | 4 | #!/usr/bin/python3
# strings.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
a, b = 10, 20
print( "this is {}, that is {}".format( a, b ) )
print( "this is %d, that is %d" % ( a, b ) )
pri... |
ab34f527e6b4a03044d5ff8f98bf31f9e81338bf | davidbegin/python-in-the-morning | /Week1/Tuesday/ms.py | 1,103 | 3.875 | 4 | # n log n
# Could we recognize this as a quasilinear algo
def merge_sort(data):
if len(data) <= 1:
return
mid = len(data) // 2
left_data = data[:mid]
right_data = data[mid:]
left_data, right_data = (data[:mid], data[mid:])
merge_sort(left_data)
merge_sort(right_data)
... |
9be32e4206cf565eb02f74057ca454e27621b230 | davidbegin/python-in-the-morning | /Fluent_Python/Day21/simple_decorator.py | 1,256 | 3.734375 | 4 | print('\033c')
print("\t\033[35;1;6;4;5mBest Monday Ever!\033[0m\n")
from dis import dis
import opcode
registry = []
# # DecoratOR
# def register(func):
# # __repr__ of the func
# print('running register(%s)' % func)
# registry.append(func)
# return func
# # DecoratED function
# @register
# def f... |
c182b436b259368c570bf3100a03ada532a8af96 | davidbegin/python-in-the-morning | /Fluent_Python/Day48/cool_code.py | 2,635 | 3.78125 | 4 | print('\033c')
daily_fact = "\033[35m61 Years ago on 1959 - 2 - 6\n\n\t\033[97mJack Kilby of Texas Instruments files the first patent for an integrated circuit."
print(f"\t\033[35;1;6m{daily_fact}\033[0m\n")
from dis import dis
import opcode
import asyncio
import random
import time
# If I call a regular method i... |
c489ceda7e64421e36db74aef0eb42460fb7ed49 | davidbegin/python-in-the-morning | /Week19/622.py | 716 | 3.6875 | 4 | def is_tuple(node):
if isinstance(node, Node) and node.children == [LParen(), RParen()]:
return True
return (isinstance(node, Node)
and len(node.children) == 3
and isinstance(node.children[0], Leaf)
and isinstance(node.children[1], Node)
and isinstance(nod... |
b40fd2dab0c7eebf9690850182ef28e0e4da062a | rishabhshellac/Sorting | /bubblesort.py | 585 | 4.3125 | 4 | # Bubble Sort
"""Comparing current element with adjacent element
Repeatedly swapping the adjacent elements if they are in wrong order."""
def bubblesort(arr):
for i in range(len(arr)):
for j in range(len(arr)-1):
if(arr[j] > arr[j+1]):
temp = arr[j]
... |
639c6121b4ad7d5919be31d579337cebef9b84fe | lmc2179/magikarp | /magikarp/abstract.py | 2,052 | 3.578125 | 4 | class AbstractSolver(object):
def __init__(self, problem):
"""
The problem instance is part of the solver's immutable state.
The solver should allow for as little mutable state as possible.
"""
self.problem = problem
def solve(self, *args, **kwargs):
raise NotImp... |
9984896c3ff42f0b7ee3145883b871c16a3282f6 | zeptoTon/google-code-jam | /2013-qualification/b.py | 1,305 | 3.734375 | 4 | """
2013 - qualification Problem B
Lawnmower
"""
"""
find the top row, left col
sort them from small to large
check do they have a row or col height equal to them (not greater or smaller)
If not satisfy, return NO
dict data structure:
lawn('1'): {h=1..100, clear=True|False}
tuple(height, coord, 'row|col', check)
"""
... |
469afc6cf3587ad0ad3052066c3e96ce9d387843 | bradley27783/TheCivilWarOfMalibu | /CombatMechanics.py | 2,163 | 3.671875 | 4 | from random import *
class army():
totalAtk = 0
totalDef = 0
def __init__(self):
upkeep = 0.1 * self.totalAtk
def soldier(self, amount):
self.totalAtk += 10 * amount
self.totalDef += 5 * amount
def tank(self, amount):
self.totalAtk += 60 * amount
... |
2f14c34ea2634f1f57e78a65552c7671ded1e109 | tertiarycourses/DeepLearningTensorflow | /exercises/module9_2_keras_nn_mnist_restore_model.py | 856 | 3.8125 | 4 | # Module 9 Keras
# NN Model on MNIST dataset
# Author: Dr. Alfred Ang
from keras.models import load_model
import matplotlib.pyplot as plt
# Step 1: Load the Model
model = load_model('./models/mnist_nn.h5')
# Step 2: Evaluate
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets... |
ce276807a22fa77a748295fb0fc0cc53893ceae0 | ybear90/TIL | /Documents/Python/what_is_my_full_name.py | 592 | 3.75 | 4 | def what_is_my_full_name(**kwargs):
if 'first_name' not in kwargs.keys() and 'last_name' not in kwargs.keys():
return "Nobody"
elif 'first_name' in kwargs.keys() and 'last_name' not in kwargs.keys():
return kwargs['first_name']
elif 'first_name' not in kwargs.keys() and 'last_name' in kwargs.keys():
r... |
ca0976d8de8c4155281f8492fcf1b2ab45641649 | jack-goodson/project-euler | /5.py | 414 | 3.53125 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
small_divis = 0
n = 1
while small_divis == 0:
tester = True
for x in range(1,21):
if n % x != 0... |
154def9a4c4e8d3a2b99c1eed02bed8c00b0610c | lics1216/python | /16异步iO/lcs_generator.py | 730 | 3.640625 | 4 | # L = [x*x for x in [1,2,3,4,5]]
# print(L)
# x = range(10)
# print(list(x))
# g = (x*x for x in [1,2,3,4,5,6])
# print(next(g))
# ####斐波那契数列输出前 n 项
# 数列: 1 1 2 3 5 8 13 21 34
def lcs(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a+b # a, a+b 先运行产生一个 tuple 元组 类型,复制给a, b
... |
bc873281356f0af58fe5e0a79ea70260765926bb | parkerdu/leetcode | /94.py | 1,316 | 3.6875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
"""他给的列表是广度遍历的树
实际上你可以推断他肯定是广度遍历,因为只有广度才可以给你就可以画出树,其他都需要两种遍历,还必须有中序
[1,null,2,3] 第一行走完就1,第二行先是空再是2
具体可以看visulize_tree代码运行结果"""
def inorderTraversal(self, ... |
85bbcc3bc87e6b445715ace46f4b45f364863a04 | cxm17/python_crash_course | /do_it_yourself/chapter_4/tiy_page_71.py | 299 | 3.84375 | 4 | # 4-13
foods = ("bread", "crackers", "soup", "wings", "salad")
print("Menu:")
for food in foods:
print("\t", end='')
print(food)
# foods[2] = "beef chips"
foods = ("bread", "ice cream", "cake", "wings", "salad")
print("New Menu:")
for food in foods:
print("\t", end='')
print(food) |
664b19a05fe482bec0af4ce7d9018140e26f5675 | cxm17/python_crash_course | /do_it_yourself/chapter_5/5_9.py | 526 | 3.9375 | 4 | user_names = ["cmack", "jbrooke", "sturner", "smaribelli", "jcashmere", "admin"]
for count in range(1,3):
print(str(user_names) + " loop count " + str(count))
if user_names:
for user_name in user_names:
if user_name == "admin":
print("Hello, " + user_name + " would you... |
760f4503cc48543d541407005aa850ccc0679b3c | cxm17/python_crash_course | /do_it_yourself/chapter_6/6-4.py | 771 | 4.0625 | 4 | keywords = {
"for": "Used to iterate through a collection of objects or a range of values.",
"if": "Keyword used to make boolean evaluations.",
"else": "Default option for an if statement.",
"elif": "Statement used to evaluate a logic statement after an opening if statement.",
"and": "Clause used to... |
21e21109a8c8b4369bf01cbf13c2a5a9a9b29f43 | cxm17/python_crash_course | /do_it_yourself/chapter_10/10-5.py | 557 | 3.90625 | 4 | get_reasons = True
file_name = "reasons.txt"
def ask_for_reasons(name, file_object):
active = True
while active:
new_reason = input("Please enter your reason: ")
if new_reason == "*":
return
else:
file_object.write(name + " said " + new_reason + "\n")
wit... |
1c6f8146ac20816cf2bbb4b157782b1d21ed6441 | cxm17/python_crash_course | /do_it_yourself/chapter_5/5_10.py | 377 | 3.546875 | 4 | current_users = ["cmack", "jbrooke", "sturner", "smaribelli", "jcashmere", "admin"]
new_users = ["Cmack", "bhoyle", "ktravis", "ctravis", "smack", "rreynolds"]
for new_user in new_users:
if new_user.lower() in [current_user.lower() for current_user in current_users]:
print("User name " + new_user + " in us... |
26a52d4514a314d3e2f0157884e80fe1520e29f6 | cxm17/python_crash_course | /do_it_yourself/chapter_8/8-7.py | 350 | 3.734375 | 4 | def make_album(artist_name, album_name, number_of_tracks = None):
album = dict()
album[artist_name] = album_name
if number_of_tracks:
album["Tracks"] = number_of_tracks
return album
album = make_album("Bobby Digital", "Silver Bullets")
print(album)
album = make_album("Bobby Digital", "... |
429ba293ade695992586a0a630b02d8a4feac37b | danarellano/CS100-014 | /HW8_DanielArellano/Problem_4.py | 798 | 3.921875 | 4 | '''
Daniel Arellano
CS 100 2020S Section 014
HW 08, March 16, 2020
'''
### Problem 4 ###
print('Problem 4:\n')
from random import randint
def guessNumber():
print("I'm thinking of a number in the range 0-50. You have five tries to guess it. GO!!!")
ans = randint(0,50)
attempts = 1
while attempts < 6:... |
1dd259445ed98c87f3fc8871559e9a23ed725b84 | rayhancse08/Solved-Problems | /Approximate Matching.py | 1,530 | 3.59375 | 4 | def approximate_matching(text_string,prefix_string,suffix_string):
i,j=0,0
max_prefix_count,max_suffix_count=0,0
prefix_count,suffix_count=0,0
sstr_start,sstr_end=0,0
while i<len(data):
start,end =-1,-1
j,k=0,i
prefix_count=0
while (k<len(data) and j<len(pref... |
522ca3b5c90f1c3973667d3410c8fee602506dd7 | ConnorDieck/python-datastructures | /15_intersection/intersection.py | 508 | 3.9375 | 4 | def intersection(l1, l2):
"""Return intersection of two lists as a new list::
>>> intersection([1, 2, 3], [2, 3, 4])
[2, 3]
>>> intersection([1, 2, 3], [1, 2, 3, 4])
[1, 2, 3]
>>> intersection([1, 2, 3], [3, 4])
[3]
>>> intersec... |
782151b2e632c0d169c048670298a6cb424747a9 | mleers/Python-practice | /prime.py | 275 | 4.03125 | 4 | num = int(input("Enter a number to see if it is prime: "))
a = [x for x in range(2, num) if num % x == 0]
def primer(n):
if num > 1:
if len(a) == 0:
print("Is a prime number")
else:
print("Not a prime number")
else:
print("Not a prime number")
primer(num)
|
57d761f8e80a5327196c9da3104817b6f9e3934b | mleers/Python-practice | /rock_paper_scissors.py | 1,791 | 4.03125 | 4 | print "Welcome to rock paper scissors. Play someone for best of 3"
def player_1():
x = raw_input('Player 1 pick "rock" "paper" or "scissors": ')
while x != "rock" and x != "paper" and x != "scissors":
x = raw_input('You must pick "rock" "paper" or "scissors"')
return x
def player_2():
x = raw_input('Player 2 p... |
6b4f1b28f22a20f664472c74d77fa5bc5de2bbc1 | graph90/python-School-code-mainly- | /lab01.py | 159 | 3.828125 | 4 | name = 'Rachel'
print("Hi there,", name)
age = 18
if age >= 18:
print("You are old enough to vote!")
else:
print("Sorry, you will need to wait.")
|
7c94b7cb28f7e42eff8c12a241f6473af330d394 | Python-November-2018/nshredz | /01-python/02-python/01-required/06-functions_intermediate_1.py | 1,005 | 3.96875 | 4 | import random
# randInt() returns a random integer between 0 to 100
# x = 0
# y = 0
# def randInt():
# return (random.random()*101)
# while (x != 100): # this is purely a test, see how many passes it takes to get to 100, the max possible int
# x = int(randInt())
# print(x)
# y += 1
# prin... |
54ad25eeb050147f642c1c442d21c33b6d4c14dc | fernandoeqc/Project_Euler_Python | /dificuldade 5/2 - Even Fibonacci numbers.py | 659 | 3.640625 | 4 | """ Each new term in the Fibonacci sequence is generated by
adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-v... |
8581cc76a25d5258046d31800c89b60adbda3262 | shivamsharma00/hackerrank-problems | /Artificial Intelligence/BotClean.py | 2,129 | 3.578125 | 4 | '''
We have a cleaning bot which needs to clean the area in most optimized way.
INPUT OUTPUT
b---d RIGHT
-d--d
--dd-
--d--
----d
-b--d DOWN
-d--d
--dd-
--d--
----d
'''
up = 'UP'
down = 'DOWN'
left = 'LEFT'
right = 'RIGHT'
# function to find mos... |
17cacde977e8cd64c89fd276ca3a5c823db4ab16 | phongluudn1997/leet_code | /rescursive_multiply.py | 801 | 3.890625 | 4 | """
Find the result of mulitiply operator not using * / just + - and >> <<
Solution 1:
3*4 = 1*4 + 2*4 = 4 + 1*4 + 1*4 = 4 + 4 + 4 = 12
"""
def min_product(a, b):
bigger = a if a > b else b
smaller = b if b < a else a
memo = [0 for i in range(smaller + 1)]
return min_product_helper(smal... |
b730d9fafc1e80309d731ed1cba91c03c8e1fa79 | phongluudn1997/leet_code | /extra_candies.py | 237 | 3.5625 | 4 | class Solution:
def kids_with_candies(self, candies, extra_candies):
max_candy = max(candies)
return [candy + extra_candies >= max_candy for candy in candies]
print(Solution().kids_with_candies([4, 2, 1, 1, 2], 1))
|
30c456b846862a625b17df1eaff2053d30bfb4b4 | phongluudn1997/leet_code | /sort_list.py | 551 | 3.796875 | 4 | class Solution:
def merge_two_sorted_list_2(self, a, b):
i = j = 0
result = list()
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
wh... |
07dca55631fe597a3357abaa8bfeb8f25bbb3fae | phongluudn1997/leet_code | /palindromeCheck.py | 728 | 4.03125 | 4 | def useString(string):
reversedString = ""
for i in reversed(range(len(string))):
reversedString += string[i]
return reversedString == string
def useArray(string):
reversedChars = list()
for i in reversed(range(len(string))):
reversedChars.append(string[i])
return "".join(rever... |
aedd95a6368543557f399ef44071d871433c2d90 | phongluudn1997/leet_code | /symetric_tree.py | 690 | 3.96875 | 4 | """
link: https://leetcode.com/problems/symmetric-tree/
"""
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.val = value
self.left = left
self.right = right
class Solution:
def is_symetric_tree(self, root: TreeNode):
return root is None or self.is_syme... |
c66ca8a44e9b6c6230302ca51721e5b91d78d142 | phongluudn1997/leet_code | /get_permutations.py | 1,347 | 4 | 4 | def get_permutations(list_number):
permutations = list()
if len(list_number) <= 1:
permutations.append(list_number)
return permutations
for index in range(len(list_number)):
element = list_number[index]
remainder = list_number[:index] + list_number[index + 1:]
for pe... |
c1fe302ea4843fb99c8e418f12e95a489e666a41 | phongluudn1997/leet_code | /num_jewels_in_stones.py | 1,113 | 3.5 | 4 | def split_into_characters(string):
result = list()
for i in string:
result.append(i)
return result
class Solution:
@classmethod
def approach_1(cls, J, S):
result = 0
for i in split_into_characters(S):
if i in J:
result += 1
return result
... |
0e19857f1a6be81407ae55a9c9bde6b3279398ab | Gonyoda/AnotherToughPuzzle | /solver.py | 6,590 | 3.671875 | 4 | # Hello World program in Python
from enum import Enum
class EdgeDef:
def __init__(self, shape, innie):
self.shape = shape
self.innie = innie
self.outie = not innie
def full_name(self):
return "{}-{}".format(self.shape, "In" if self.innie else "Out")
def short_name(self):... |
044e9d7363bd1e5bd8852284fe8a6b0117d3b477 | Gautam8080/Side-Projects | /Python Course Labs/Lab08_Bakliwal_Gautam_505.py | 4,014 | 4.25 | 4 | #Name- Gautam Bakliwal
#
#Course- CS 1411 lab 505
#
#Date- 10/31/2017
#
#Problem-
#Write a function to return a randomly generated 6-element integer set which represents one lotto ticket. For each
#drawing in the dictionary, check the matching numbers between the randomly generated ticket and the drawing. Total... |
f9b2f73a9243f1ffc29ec77b8c611c8cc421c86b | vishwajeet93/dictionary_tools | /split_dict.py | 801 | 3.53125 | 4 | import re
RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')
print("Please make sure you have copied this code in the folder where the text file exists ")
file_name = raw_inpur("Please enter complete name of ocred dictionary file to convert to tab separated csv: ")
generated_dict = {}
csv_file = open(file_name+".csv",'w')
w... |
216620435cf57c4f3dae1d187104a724b993b9f9 | komal-jaiswal/Python-Programs | /venv/python_functions.py | 3,119 | 4.34375 | 4 | def hello():
print("Hello World !")
def hello_person(name,age):
print("Hello "+name +"your age is "+ str(age))
hello()
hello_person("Ruby",10)
def cube(num):
return num * num * num
result=cube(2);
print(result)
#----------------------------------------------Python If statement and AND OR NOT operator... |
77a41ab91683b92d4daf8f27849fb7656537e69f | alekhyavasavi/nani-5 | /48.py | 116 | 3.921875 | 4 | n=int(raw_input())
n=int(n)
average=0
sum=0
for num in range(0,n+1,1):
sum=sum+num
average=sum/n
print(average)
|
264e171489d3a1368625b993459005f0ae398861 | Sizwe2008/Hello-World | /Task 3.py | 2,753 | 3.578125 | 4 | import numpy as np
import pandas as pd
import random as rd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import csv
dataset = pd.read_csv('data2008.csv')
dataset.describe()
#print (dataset)
X = dataset.iloc[:, [1, 2]].values
m=X.shape[0] #number of training examples
n=X.shape[1]
n_c... |
c2ae4f69626c5c5c930dfe3f281b555675952a30 | luckeyRook/python_study | /基礎編/21.print/TEST19.py | 1,086 | 3.5 | 4 | #print
#基本的な使い方(python3)
print('python')
print('-')
print('izm')
print('com')
#基本的な使い方(python2)
#print 'python'
#print '-'
#print 'izm'
#print 'com'
#改行せずに出力(python3)
print('python',end='')
print('-',end='')
print('izm',end='')
print('com')
#改行せずに出力(python2)
#print 'python',
#print '-',
#print 'izm',
#print 'com'
#... |
f8662d63b37d01fbbd154eb27cac1ec4efada389 | luckeyRook/python_study | /応用編/32.最小値・最大値の取得/TEST32.py | 1,241 | 4.21875 | 4 | #32.最小値・最大値の取得
#min
print(min([10,20,30,5,3]))
print(min('Z','A','J','w'))
#max
print(max([10,20,30,5,3]))
print(max('Z','A','J','w'))
#key引数
def key_func(n):
return int(n)
l=[2,3,4,'111']
print(min(l,key=key_func))
print(max(l,key=key_func))
print('========================================-')
def key_func2(n)... |
87dcb926d18c5204dabacf6119bae7601e301967 | luckeyRook/python_study | /応用編/26.順序保持ディクショナリ (2.7 - 3.6)/TEST26.py | 627 | 3.734375 | 4 | #26.順序保持ディクショナリ (2.7 - 3.6)
#collections.OrderedDict
#通常
test_dict={}
test_dict['word']='doc'
test_dict['excel']='xls'
test_dict['access']='mdb'
test_dict['powerpoint']='ppt'
test_dict['notepad']='txt'
test_dict['python']='py'
for key in test_dict:
print(key)
print('======================================')
#col... |
f787cc2b3d4f9c758ddd56e08cbcab76dfbf5fc9 | luckeyRook/python_study | /応用編/09.クラスメソッド/TEST09.py | 829 | 4.09375 | 4 | #09.クラスメソッド
#@classmethod
import datetime
class TestClass:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
#クラスメソッド
@classmethod
def sample_classmethod(cls,date_dif=0):
today=datetime.datetime.today()
d=today+datetime.timedelta(da... |
687959ce96b5adc24dc76becfcfcd407b61a628a | luckeyRook/python_study | /基礎編/07.ディクショナリ/TEST6.py | 1,715 | 3.75 | 4 | #ディクショナリの基本
#ディクショナリは{key:value}で囲む
test_dict_1 ={'YEAR':'2019','month':'04','day':'29'}
print(test_dict_1)
print('--------------------------------')
for i in test_dict_1:
print(i)
print(test_dict_1[i])
print('==================================')
#valueの取得
test_dict_2 ={'year':'2019','month':'04','day':... |
0a4c4d4a80d0bd67456336c3e81b9259cac4bb4d | luckeyRook/python_study | /応用編/28.内包表記/TEST28.py | 1,407 | 4.1875 | 4 | #28.内包表記
#リストの内包表記
comp_list=[i for i in range(10)]
print(comp_list)
#以下のコードと同じ
comp_list=[]
for i in range(10):
comp_list.append(i)
print(comp_list)
#本来は3行必要な処理を一行にできる
comp_list=[str(i*i) for i in range(10)]
print(comp_list)
print('=================================')
#ディクショナリの内包表記
comp_dict={str(i):i*i for i i... |
8833335b73c1ec8011de8dd6e99881e0b22889b9 | nate-stein/cs207_nate_stein | /homeworks/HW8/TreeTraversal.py | 11,178 | 3.734375 | 4 | """
Binary Search Tree Traversal
"""
from enum import Enum
class DFSTraversalTypes(Enum):
PREORDER = 1
INORDER = 2
POSTORDER = 3
class Node():
def __init__ (self, val):
self.value = val
self.parent = None # type: Node
self.left = None # type: Node
self.right = None... |
47440d2c455cd525f6a55d19a1999afdf2992c79 | Kilatsat/deckr | /webapp/game_defs/dominion/dominion.py | 30,875 | 3.9375 | 4 |
"""
This module provides an implementation of a game of Dominion
"""
import math
import random
from engine.game import action, Game, game_step
def turn_face_up(cards):
for card in cards:
card.face_up = True
class Dominion(Game):
"""
Dominion is a more complex card game.
"""
def __init... |
6cb09e7a8ff19cabb2a5b2218c1fbf3b994ffa5e | Kilatsat/deckr | /webapp/engine/card_set.py | 2,455 | 4.125 | 4 | """
This module contains the CardSet class.
"""
from engine.card import Card
def create_card_from_dict(card_def):
"""
This is a simple function that will make a card from a dictionary of
attributes.
"""
card = Card()
for attribute in card_def:
setattr(card, attribute, card_def[attrib... |
f860ed32bf1bbe0286ddfa857bdc44fa8e7f0eb5 | shashiprajj/GUI-for-Hotel-Management | /Manager-login/login.py | 22,071 | 3.53125 | 4 | from tkinter import *
from tkinter import messagebox
import io
import os
from index import Encrypt
import sqlite3
import StudentDatabase_backEnd
conn=sqlite3.connect("data.sqlite")
cur=conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS "AUTHORIZED_DATA" (
"id" INTEGER NOT NULL ,
"name" TEXT NOT NU... |
8243892c420ebb6b38ff7580b21f82d04df660e2 | danielMonas/Minigame | /EnemyClass.py | 1,633 | 3.703125 | 4 | import random
from BaseObject import *
import math
class Enemy(Object):
def __init__(self, id, others):
print("SPAWN ENEMY")
Object.__init__(self,(0, 0 + id * 10, 0 + id * 20), random.randint(5,51), [random.randint(-6,6),random.randint(-6,6)], others)
self.id = id
def move_... |
3bbbcd3214f2326ad4bb26af6a3cb3b2467d44e9 | ruhil528/CV-Projects | /Image-Recognition-Classifier/Cat_image_recognition.py | 7,653 | 3.625 | 4 | # Logistic Regression with a Neural Network mindset
# Build logistic regression classifier to recognize cats
# Packages
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
# Loading the data (cat/non-cat)
train_s... |
7cb877491bcdebf38161379bed8ca4dae883ed89 | Hellengo/PythonTest | /day2/function.py | 591 | 3.765625 | 4 | import re
def sayhi(name,age,salary,job="IT"):
print "name is:", name
print "age is:", age
print "salary is:", salary
print "job is:", job
sayhi("Hellengo",28,50000,"CEO")
def multiply(x,y):
if x>y:
return x*y
else:
return x/y
print multiply(6,4)
def sayhi1(*args):
pri... |
965f4117268913264e21e1924052bbb50c95712d | junawaneshivani/Python | /ML with Python/numpy_crash_course.py | 1,139 | 4.25 | 4 | import numpy as np
# define an 1d array
my_list_1 = [1, 2, 3]
my_array_1 = np.array(my_list_1)
print(my_array_1, my_array_1.shape)
# define a 2d array
my_list_2 = [[1, 2, 3], [4, 5, 6]]
my_array_2 = np.array(my_list_2)
print(my_array_2, my_array_2.shape)
print("First row: {}".format(my_array_2[0]))
print("Last row: {... |
6d4c237ba40cb6e53416cd293aee296a28bb9bab | axelthorstein/tictactoe | /has_won_func.py | 429 | 3.53125 | 4 |
board = [['o','x','o'],
['o','x','x'],
['x','o','o']]
letter = 'x'
def won(board, letter):
boards =[
board,
[[board[j][i] for i in range(3)] for j in range(3)], # Flipped board.
[[board[j][j] for j in range(3)] for i in range(0, 2, 1)] # Diagnols.
]
for board in... |
8c736c7e762ec803fdf8a5bf1b48ec762a084692 | Rehan-Raza/Pythons-stuffs | /exceptional handling.py | 147 | 3.734375 | 4 | age = input('enter your age:')
try:
a = int(age)
except:
a = -1
if a>0:
print('good job !')
else:
print('not a number..')
|
93524835da7280fb75c81723e973cb582a211f85 | luola63702168/leetcode | /primary_algorithm/r_05_sort_search/rusi_02_第一个错误版本.py | 432 | 3.671875 | 4 | def firstBadVersion(n):
left = 0
right = n
# isBadVersion = None
while True:
mid = (left + right) // 2
if isBadVersion(mid) is False and isBadVersion(mid + 1) is True:
return mid + 1
if isBadVersion(mid) is False and isBadVersion(mid + 1) is False:
... |
fc3f998a4c127e991a9290786246da6f2d851503 | luola63702168/leetcode | /greedy_algorithm/ll_01_钞票支付问题.py | 1,583 | 3.921875 | 4 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# Author : rusi_
# 案例描述:
# 这里有几种不同面额的钞票,1元、5元、10元、20元、100元、200元的钞票无穷多张,现在使用这些钞票去支付X元的面额,问最少需要多少张?
# 解决方案:
# 尽可能多的使用面值较大的钞票。
# 例如X=628,我们通常会尝试从面额最大的钞票(200元)开始尝试,此时发现200元的钞票只能使用3张,此时剩余的面额是628-3*200=28元,
# 再依次查看次最大面额100元,因为100>28,因此不能用100元构成结果,再次以查看20元,发现... |
b1b68e288109b0b05c8b8f2217f7e95a6f744e34 | luola63702168/leetcode | /primary_algorithm/r_07_design_problem/rusi_01_shuffle_array.py | 1,308 | 4.125 | 4 | import copy
import random
# 打乱一个没有重复元素的数组。
#
# 示例:
#
# // 以数字集合 1, 2 和 3 初始化数组。
# int[] nums = {1,2,3};
# Solution solution = new Solution(nums);
# // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
# solution.shuffle();
# // 重设数组到它的初始状态[1,2,3]。
# solution.reset();
# // 随机返回数组[1,2,3]打乱后的结果。
# solutio... |
a4453c5c4fa23c644d781f3d36d6694ec7d27fe9 | luola63702168/leetcode | /tencent/r_01_ArraysAndStrings/r_02_寻找两个有序数组的中位数.py | 893 | 3.796875 | 4 | # 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
# 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
# 你可以假设 nums1 和 nums2 不会同时为空。
# 示例 1:
# nums1 = [1, 3]
# nums2 = [2]
# 则中位数是 2.0
#
# 示例 2:
# nums1 = [1, 2]
# nums2 = [3, 4]
#
# 则中位数是 (2 + 3)/2 = 2.5
def findMedianSortedArrays(nums1, n... |
739cd38538c3c6e7bf116f46e9f156be2b6dcdb9 | luola63702168/leetcode | /primary_algorithm/r_01_array/ll_03_旋转数组.py | 856 | 3.75 | 4 | # 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
# 1
# 输入: [1,2,3,4,5,6,7] 和 k = 3
# 输出: [5,6,7,1,2,3,4]
# 解释:
# 向右旋转 1 步: [7,1,2,3,4,5,6]
# 向右旋转 2 步: [6,7,1,2,3,4,5]
# 向右旋转 3 步: [5,6,7,1,2,3,4]
# 2
# 输入: [-1,-100,3,99] 和 k = 2
# 输出: [3,99,-1,-100]
# 解释:
# 向右旋转 1 步: [99,-1,-100,3]
# 向右旋转 2 步: [3,99,-1,-100]
... |
22811f3d9c3624b15dc27517c1b8a98e652e3f3e | luola63702168/leetcode | /primary_algorithm/r_02_str/ll_02_整数反转.py | 739 | 4.28125 | 4 | def reverse(x):
str_ = str(x)
if x == 0:
return 0
elif x > 0:
x = int(str_[::-1])
else:
x = int('-' + str_[::-1].rstrip("-").rstrip("0"))
if -2 ** 31 < x < 2 ** 31 - 1:
return x
return 0
# str_= str(x)
# if x == 0 or x <= -2 ** 31 or x >=... |
72745b6f041f66f70a6f046b2370ebba70226dec | luola63702168/leetcode | /primary_algorithm/r_01_array/ll_11_旋转数组图像.py | 526 | 3.96875 | 4 | def rotate(matrix):
# print(id(matrix))
matrix_01 = matrix + []
# print(id(matrix_01))
for i in range(len(matrix)):
matrix_01[i] = [matrix[k][i] for k in range(len(matrix)-1,-1,-1)]
matrix[:] = matrix_01
# print(id(matrix))
return matrix
# 参考别人的解法,发现是我太局限了
# matri... |
34ace72317fca8dec7ca5f868f2a4d8ff0025eb9 | luola63702168/leetcode | /sort_algorithm_collection/rusi_07_归并排序.py | 2,640 | 3.953125 | 4 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# Author : rusi_
def merge_sort(alist):
'''归并排序'''
n = len(alist)
if n <= 1: # 递归退出条件
return alist # 这个返回值是由最后一次调用递归的那个函数接受的(拆分到不能拆分了就返回了),也就是被left_li或者right_li接受了。这时并不会终止程序,只会终止此次递归,而后这次递归返回的数据也就是(left_li和right__li)都会进行下面的循环代码,之后返回值resu... |
1fc52c7235e77bd8065dde526669a6b9e9f297ec | luahuio/douban_book_names | /douban3.py | 1,259 | 3.5625 | 4 | #豆瓣读书首页第一屏图书封面图下载,图片命名为书名,存放到指定路径
import os
from selenium import webdriver
import urllib.request
def get_driver():
root_dir = os.path.dirname(os.path.abspath(__file__))
drivers_dir = os.path.join(root_dir,'chromedriver_mac64')
return drivers_dir
def open_wbsite(chrome,url):
chrome.get(url)
chrome.... |
9f0a9465e1d2f2328088cc53093a61101005a17c | CaseyTM/day1Python | /tuples.py | 1,320 | 4.34375 | 4 | # arrays (lists) are mutable (changeable) but what if you do not want them to be so, enter a tuple, a constant array (list)
a_tuple = (1,3,8)
print a_tuple;
# can loop through them and treat them the same as a list in most cases
for number in a_tuple:
print number;
teams = ('falcons', 'hawks', 'atl_united', 'silve... |
8a1c3f500b607a9a7a8d821530ff411be9a9d053 | doston12/stepik-selenium-python-me | /selenium-start_1.2.py | 854 | 3.515625 | 4 | import time
# webdriver to manipulate with browser
from selenium import webdriver
# initialize browser driver. literally, it says I'm gonna open a chrome browser
driver = webdriver.Chrome(executable_path='C:\\chromedriver\\chromedriver.exe')
time.sleep(2)
# method get is used to open a page/url/link in browser
driv... |
e1f4cdbf33fb002033aef79837e16499e1a02e53 | karlmueller/sweFinalRepo | /quaternionRotation.py | 3,388 | 3.96875 | 4 | #from here as a replacemnt for scipy https://automaticaddison.com/how-to-convert-a-quaternion-to-a-rotation-matrix/
import numpy as np
import math
from numpy.core.numeric import outer
def quaternion_rotation_matrix(Q):
"""
Covert a quaternion into a full three-dimensional rotation matrix.
Input
:pa... |
3b195641ea592b6599d53e35789589df8c646067 | Sundrops/Pytorch_Mask_RCNN | /tasks/utils.py | 589 | 3.625 | 4 | import numpy as np
############################################################
# Utility Functions
############################################################
def log(text, array=None):
"""Prints a text message. And, optionally, if a Numpy array is provided it
prints it's shape, min, and max values.
""... |
390c91686bff66afd4fe498eb33b8e13a78dd02a | emorycs130r/first-assignment-chumaceiro | /medium_assign.py | 380 | 3.546875 | 4 | def expression_1(x):
return (x ** 3) - ((2 * x)+(x ** 2)) - 100
def expression_2(x, y):
return ((x ** 4)/(2 * y)) - (3 * x * y) + ((6 * y)/(7 * x))
def expression_3(x, y):
return ((x ** 3) + (y ** 2)) / ((x ** 2) + (y ** 3))
if __name__ == "__main__":
print(expression_1(4))... |
28891bdbc403051782fe042f744093c4ea592c91 | tingjianlau/my-leetcode | /326_power_of_three/326_power_of_three.py | 534 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
##########################################################################
# > File Name: 326_power_of_three.py
# > Author: Tingjian Lau
# > Mail: tjliu@mail.ustc.edu.cn
# > Created Time: 2016/05/16
#########################################################################
... |
921432c5dd48fa4ebfb7172bbafaaaefbd56bc8a | tingjianlau/my-leetcode | /88_merge_sorted_array/88_merge_sorted_array.py | 1,592 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
##########################################################################
# > File Name: 88_merge_sorted_array.py
# > Author: Tingjian Lau
# > Mail: tjliu@mail.ustc.edu.cn
# > Created Time: 2016/05/31
#######################################################################... |
b15b8d29b17feadb09bb0c9a2568527b854aaaed | bruno-ralmeida/Estudos_python | /Alura/Conhecendo python/poo/conta.py | 1,125 | 3.609375 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite):
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
self.__cod_banco = "777"
def deposito(self, valor):
self.__saldo += valor
def __aprov_saque(self, va... |
b03461d001ad916fe5c15854567ffd0091fb0fa4 | bruno-ralmeida/Estudos_python | /Curso em video/Mundo_3/Ex_075.py | 440 | 4.0625 | 4 | tpl_int = (int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')))
print(f'{tpl_int.count(9)}')
if(tpl_int.__contains__(3)):
print(f'{tpl_int.index(3)}')
else:
print('Não existe nenhum número 3')
pri... |
d7a20365eeb81eb5c78fa41ed87f56ee6d0446e1 | w0rdsm1th/Project_Euler | /q50.py | 2,798 | 3.78125 | 4 |
import util as ut
import math
from copy import deepcopy
"""
https://projecteuler.net/problem=50
Consecutive prime sum
Problem 50
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The... |
3b96791266502bc2aa5336be8db5c881de8a36ee | w0rdsm1th/Project_Euler | /util/timer.py | 711 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
convenience deocrator to time and print function execution timer
adapted from
"""
import functools
import itertools
import util
import logging
import datetime as dt
import functools as ft
from time import time
# _log = logging.getLogger(level="INFO")
def timer(f):... |
720e91e599298c72103d40704e3b5ba93737ab90 | w0rdsm1th/Project_Euler | /q48.py | 455 | 4.03125 | 4 | ### template question imports
import util as ut
import math
"""
The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.
"""
def exponent_sum(start, end, suffix_len):
return str(sum((in_**in_ for in_ in range(start, end+1))))[-suffix_len:]
if ... |
6582f5477b282481a17be29ca701c7ce6c574ec0 | MasonCLipford/Programs | /8queens_genetic.py | 2,954 | 3.5625 | 4 | # States in this puzzle are represented by tuples indicating where in each
# row the queen is. For instance, (1,3,1,0) has a queen in row 0, col 1;
# row 1, col 3; row 2, col 1; and row 3, col 0;
from random import choice, random, randint, sample
from math import exp
def genetic(pop_size, h):
# generat... |
23c6c7a4495a48995f5d1a3f600c6332d8ae7d46 | nandakumar111/LeetCode-April2020 | /ContiguousArray.py | 1,598 | 3.640625 | 4 | """
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous sub... |
5a17d90414c1f91344175121ffb2db7272a08bb5 | Nilesh3/Stock-Price-Prediction | /src/normalization.py | 777 | 3.671875 | 4 | '''
Data Normalization
'''
import pandas as pd
from sklearn import preprocessing
def normalize(attributes, target):
'''
Data Normalization.
:param attributes: the data frame of attributes(candidates for features) received from main function
:param target: the data frame of target varia... |
28e32a5e2b3bf56d3f42defda4d04d520364d144 | parlak/An-Introduction-to-Interactive-Programming-in-Python- | /Rock-paper-scissors-lizard-Spock.py | 1,461 | 4.0625 | 4 | # Rock-paper-scissors-lizard-Spock
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
# helper functions
def number_to_name(number):
if number == 0:
... |
864b676fbc74522541658bec2bc88d3af97b4598 | csojinb/6.001_psets | /ps1.3.py | 1,208 | 4.3125 | 4 | import math
STARTING_BALANCE = float(raw_input('Please give the starting balance: '))
INTEREST_RATE = float(raw_input('Please give the annual interest'
'rate (decimal): '))
MONTHLY_INTEREST_RATE = INTEREST_RATE/12
balance = STARTING_BALANCE
monthly_payment_lower_bound = STARTING_BALAN... |
762750b5a14f9c781c95c510757901f689edaa2e | zachdj/graph-search | /SearchNode.py | 1,148 | 3.875 | 4 | from Path import Path
"""
A SearchNode object represents a node in the graph but keeps track of the parent node and the cost to jump from parent to child
node should be a pygraphml Node object
parent should be another search node
cost should be the weight of the (parent, child) edge
"""
class SearchNo... |
315cb6441f6ad2ed630ccaa8c87955815bddc2ea | PavlenkoAlexandr/PyHW-1.2 | /albums & tracks.py | 1,647 | 3.8125 | 4 | class Track:
def __init__(self, name, duration):
self.name = name
self.duration = duration
def show(self):
print(f'{self.name} - {self.duration} мин')
class Album:
def __init__(self, groop_name, album_name):
self.groop_name = groop_name
self.album_name = album_nam... |
c4044683c5532d1be600a21627ced4c59185aae1 | nyongja/Programmers | /Level2/124나라의숫자.py | 272 | 3.828125 | 4 | def solution(n):
answer = ''
while n :
if n % 3 != 0 : # 3으로 안나누어떨어지면
answer += str(n % 3)
n //= 3
else :
answer += "4"
n = n // 3 - 1
return answer[::-1]
print(solution(12))
|
f8ca24ccc21e3401ebc698b28149fe8093f1ef59 | nyongja/Programmers | /KAKAO/2018 KAKAO BUILD RECRUITMENT/friends_4block.py | 2,542 | 3.59375 | 4 | """
아이디어 설명
왼쪽 위 블록부터 순서대로 오른쪽, 아래쪽, 대각선 블록 모두가 같은 블록이면 소문자로 바꿈 -> 삭제될 블록을 의미
한바퀴 다 돈 후 열을 기준으로 소문자가 아닌 블록들만 정리(남아있는 블록) -> 즉, 아래에서 남아있는 블록들 차례대로 쌓기 (빈 칸은 .으로 채움)
.인 블록을 제외하고 다시 처음부터 끝까지 돌면서 같은 블록이 있는지 count
"""
dx = [0, 1, 1] # 오른쪽, 아래쪽, 대각선
dy = [1, 0, 1]
def search(x, y, board, m, n) :
for i in range(3) :
... |
a5d3956b66d347f10b0f25c9c1a9203c73b3dcad | daniyalnawaz-heek/decrypt_with_reverse | /decrypt_by_reverse.py | 261 | 4.0625 | 4 |
message=str(input("Enter the text"))
#cipher text is stored in this variable
translated = ''
#for loop for iteration
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print("The cipher text is : ", translated) |
34d82fea24acedd37a6e7a090fb644de95c0b402 | allhaillee/pytrend | /trendclass.py | 1,207 | 3.625 | 4 | """
pytrends library practice 2
Mainly focus on Object oriented programming
class object file
version : 0.1
Author : Hailey Lee
"""
from pytrends.request import TrendReq
class trendclass():
def __init__(self,timef, kwlist=None , keyword = None, df):
#initialize the object with constructor
self.... |
d588955e9e5ce1ccb89558e3769984ca794d7b93 | edenuis/Python | /Code Challenges/productList.py | 1,498 | 3.921875 | 4 | #Challenge 1: Given an array of integers, return a new array such that each
# element at index i of the new array is the product of all the
# numbers in the original array except the one at i.
#Idea: One pass - Retrieve total product; Another pass to do division
def productList(numbers):
... |
db3b2d74227002ac3fb74f8809b9e6fd86289da2 | edenuis/Python | /Code Challenges/consandcdr.py | 478 | 3.78125 | 4 | #Challenge: cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns
# the first and last element of that pair. For example,
# car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(f):
def left(a, b)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.