text stringlengths 37 1.41M |
|---|
"""
Solution for 1281. Subtract the Product and Sum of Digits of an Integer
https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
"""
class Solution:
"""
Runtime: 28 ms, faster than 100.00% of Python3 online submissions for Subtract the Product and Sum of Digits of an Integer.
Memor... |
"""
Solution for 493. Reverse Pairs
https://leetcode.com/problems/reverse-pairs/
"""
from typing import List
import bisect
class Solution:
"""
Runtime: 2248 ms, faster than 29.86% of Python3 online submissions for Reverse Pairs.
Memory Usage: 20.7 MB, less than 33.33% of Python3 online submissions for Reve... |
"""
Solution for 1324. Print Words Vertically
https://leetcode.com/problems/print-words-vertically/
"""
from itertools import zip_longest
from typing import List
class Solution:
"""
Runtime: 20 ms, faster than 100.00% of Python3 online submissions for Print Words Vertically.
Memory Usage: 12.8 MB, less than 100.... |
"""
Solution for 1009. Complement of Base 10 Integer
https://leetcode.com/problems/complement-of-base-10-integer/
"""
import math
class Solution:
"""
Runtime: 32 ms, faster than 97.46% of Python3 online submissions for Complement of Base 10
Integer.
Memory Usage: 13.1 MB, less than 62.77% of Python... |
"""
Solution for 746. Min Cost Climbing Stairs
https://leetcode.com/problems/min-cost-climbing-stairs/
"""
class Solution(object):
"""
Runtime: 44 ms, faster than 89.58% of Python3 online submissions for Min Cost Climbing Stairs.
Memory Usage: 13.3 MB, less than 7.01% of Python3 online submissions for Min ... |
"""
Solution for 378. Kth Smallest Element in a Sorted Matrix
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
"""
import heapq
class Solution:
"""
Runtime: 240 ms, faster than 51.62% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix.
Memory Usage: 20.1 MB, les... |
"""
Solution for 515. Find Largest Value in Each Tree Row
https://leetcode.com/problems/find-largest-value-in-each-tree-row/
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
... |
"""
Solution for 841. Keys and Rooms
https://leetcode.com/problems/keys-and-rooms/
"""
class Solution:
"""
Runtime: 48 ms, faster than 35.36% of Python3 online submissions for Keys and Rooms.
Memory Usage: 13.4 MB, less than 14.52% of Python3 online submissions for Keys and Rooms.
"""
def canVisitAl... |
"""
Solution for Value equal to index value
https://practice.geeksforgeeks.org/problems/value-equal-to-index-value/0
"""
# code
def solve(array):
"""
Given an array of positive integers. Your task is to find that element whose value is equal to that of its index value.
Input:
The first line of input c... |
"""
Solution for 226. Invert Binary Tree
https://leetcode.com/problems/invert-binary-tree/
"""
# Definition for a binary tree node.
class TreeNode:
"""
Node object for a BT
"""
def __init__(self, x):
"""
Initialization method for a Node object
Args:
x: integer value ... |
"""
Solution for 848. Shifting Letters
https://leetcode.com/problems/shifting-letters/
"""
class Solution(object):
"""
Runtime: 168 ms, faster than 85.39% of Python online submissions for Shifting Letters.
Memory Usage: 14.5 MB, less than 33.33% of Python online submissions for Shifting Letters.
"""
... |
"""
Solution for 1277. Count Square Submatrices with All Ones
https://leetcode.com/problems/count-square-submatrices-with-all-ones/
"""
from typing import List
class Solution:
"""
Runtime: 644 ms, faster than 87.10% of Python3 online submissions for Count Square Submatrices with All Ones.
Memory Usage: 14.9 MB, ... |
"""
Solution for 289. Game of Life
https://leetcode.com/problems/game-of-life/
"""
import collections
from copy import deepcopy
from typing import List
class Solution:
"""
Runtime: 40 ms, faster than 66.29% of Python3 online submissions for Game of Life.
Memory Usage: 13.8 MB, less than 10.00% of Python3 o... |
"""
Solution for 389. Find the Difference
https://leetcode.com/problems/find-the-difference/
"""
from collections import Counter
class Solution:
"""
Runtime: 36 ms, faster than 97.86% of Python3 online submissions for Find the Difference.
Memory Usage: 13.3 MB, less than 13.13% of Python3 online submission... |
"""
Solution for 19. Remove Nth Node From End of List
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
"""
# Definition for singly-linked list.
class ListNode:
"""
Node object for a linked-list
"""
def __init__(self, x):
"""
Initialization method for a Node
Args:
... |
"""
Solution for 1209. Remove All Adjacent Duplicates in String II
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/
"""
class Solution(object):
"""
Runtime: 148 ms, faster than 100.00% of Python online submissions for Remove All Adjacent Duplicates in String II.
Memory Usage: 13.3 ... |
"""
Solution for 39. Combination Sum
https://leetcode.com/problems/combination-sum/
"""
class Solution:
"""
Runtime: 96 ms, faster than 52.91% of Python3 online submissions for Combination Sum.
Memory Usage: 13.1 MB, less than 5.14% of Python3 online submissions for Combination Sum.
"""
def combina... |
"""
Solution for 452. Minimum Number of Arrows to Burst Balloons
https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/
"""
class Solution:
"""
Runtime: 504 ms, faster than 20.75% of Python3 online submissions for Minimum Number of Arrows to Burst Balloons.
Memory Usage: 19.3 MB, less th... |
"""
Solution for 325. Maximum Size Subarray Sum Equals k
https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/
"""
from typing import List
class Solution:
"""
Runtime: 116 ms, faster than 95.36% of Python3 online submissions for Maximum Size Subarray Sum Equals k.
Memory Usage: 15.8 MB, less than 100... |
"""
Solution for 809. Expressive Words
https://leetcode.com/problems/expressive-words/
"""
from itertools import groupby
from typing import List
class Solution:
"""
Runtime: 48 ms, faster than 89.27% of Python3 online submissions for Expressive Words.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online su... |
"""
Solution for 836. Rectangle Overlap
https://leetcode.com/problems/rectangle-overlap/
"""
class Solution:
"""
Runtime: 36 ms, faster than 68.28% of Python3 online submissions for Rectangle Overlap.
Memory Usage: 13.8 MB, less than 8.33% of Python3 online submissions for Rectangle Overlap.
"""
def... |
# This is the code to choose the mode of play
print("")
print("Enter 1 to play with computer.")
print("Enter 2 to play with another player.")
print("")
ch = int(input("Choose the mode of play: "))
# This function takes the user choice and then import the python files to proceed
def choices(ch):
if c... |
#!/usr/bin/env python3
strs=(1,2,3,4,5)
def list_numbers(numbers):
#print (numbers[::])
n=(len(numbers))
x=['{:d}']*n
nlist = (', '.join(x))
return '"The numbers are: '+nlist+'"'
my_numbers=list_numbers(strs)
print (my_numbers.format(*strs))
|
from Tetromino import *
from Button import TextButton
import pygame
import numpy as np
pygame.init()
class SideBoard:
"""
Everything that has to do with things around the game board
"""
# Place of tetrominos on specific index
PLACE_TETROMINOS = [2, 2]
def __init__(self, size_per_block, board)... |
class PathPlanner():
"""Construct a PathPlanner Object"""
def __init__(self, M, start=None, goal=None):
""" """
self.map = M
self.start = start
self.goal = goal
self.closedSet = self.create_closedSet() if goal != None and start != None else None
self.openSet = se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 14:41:15 2021
@author: mollybair
"""
# Objectives: Show examples of list comprehensions, and how to deal with
# different python object types
import pandas as pd
# Problem 1: Take a list of strings and convert them into plural words.
singular... |
import math
import warnings
from fermulerpy.elementary import gcd as gcd_helper
def gcd(*args):
"""
Returns Greatest Common Divisor of Multiple Integers
Parameters
----------
*args : tuple
tuple of integers
return : int
returns an integer gcd
"""
if(len(args)<2):
... |
import math
from fermulerpy.elementary import (isCoprime , euler_function , prime_divisors)
def order(a , m):
"""
Returns order of a modulo m
order of a modulo m is the smallest positive integer t such that a^t ≡ 1 (mod m)
Parameters
----------
a : int
denotes positive integer a in a... |
import csv
def fix():
# open old csv
r = csv.reader(open('pos_superlemmata_original.csv'))
lines = list(r)
# fill in missing values using values from line above
for i in range(1, len(lines)):
previous_line = lines[i-1]
current_line = lines[i]
if current_line[2] =... |
# Pets class getters and setters
class Pet:
def __init__(self, n, a, h, p):
self.name = n
self.age = a
self.hunger = h
self.playful = p
def getName(self):
return self.name
def getAge(self):
return self.age
def getHunger(self):
return self.hunger... |
import matplotlib.pyplot as plt
plt.plot([i**2 for i in range(10)])
plt.show()
### Homework 2 ###
# Exercise 1
'''
Tic-tac-toe (or noughts and crosses) is a simple strategy game in which two
players take turns placing a mark on a 3x3 board, attempting to make a row,
column, or diagonal of three with their mark. In th... |
#Made By HarveyGW
def anagramchk(word,chkword):
for letter in word:
if letter in chkword:
chkword = chkword.replace(letter,'',1)
else:
return 0
return 1
wordin = input("Enter Anagram: ")
f=open('Dictionary.txt', 'r')
for line in f:
line=line.strip()
if len(line)>=3:
if anagramchk(line... |
#include <bits/stdc++.h>
using namespace std;
// Function for printing the optimal
// parenthesization of a matrix chain product
void printParenthesis(int i, int j, int n, int* bracket,
char& name)
{
// If only one matrix left in current segment
if (i == j) {
cout << name++;
... |
from __future__ import print_function
import math
import random
def print_matrix( matrix ):
for c in range (len(matrix)):
for r in range (len(matrix[c])):
print(matrix[r][c], end=' ')
print("\n", end='')
print("\n", end='')
def ident( matrix ):
m = []
fo... |
import math
def generate_binary_strings(n):
# Credit to: https://gist.github.com/kevinwuhoo/2424597
# 2^(n-1) 2^n - 1 inclusive
bin_arr = range(0, int(math.pow(2, n)))
bin_arr = [bin(i)[2:] for i in bin_arr]
# Prepending 0's to binary strings
max_len = len(max(bin_arr, key=len))
bin_arr =... |
from coord import coordinates
from typing import Callable, Tuple
import math
def get_distance(coord:Tuple[int,int]) -> float:
i,j = coord
x1, y1 = coordinates[i]
x2, y2 = coordinates[j]
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
# path = [5, 13, 2, 20, 26, 14, 17, 16, 21, 9, 22, 6, 1, 1... |
# coding: utf-8
# In[338]:
#Creating a matrix
def read():
a = int(input('Enter number of rows '))
b = int(input('Enter number of columns '))
matrix = []
for i in range(a):
print('Enter row {}'.format(i+1))
m = input()
m = list(map(int, m.split()))
matrix.append(m)
... |
#!/usr/bin/env python
# coding: utf-8
# # Introduction
#
# Classical mechanics is a topic which has been taught intensively over
# several centuries. It is, with its many variants and ways of
# presenting the educational material, normally the first **real** physics
# course many of us meet and it lays the foundation... |
from math import sin, pi
import numpy as np
from sympy import Symbol, integrate
import matplotlib.pyplot as plt
# function for the trapezoidal rule
def Trapez(a,b,f,n):
h = (b-a)/float(n)
s = 0
x = a
for i in range(1,n,1):
x = x+h
s = s+ f(x)
s = 0.5*(f(a)+f(b)) +s
return h*s
# function ... |
import unittest
from answer.maximum_number_of_words_you_can_type import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.text = [
'hello world',
'leet code',
'leet code',
]
self.brokenLetters = [
'ad',
'lt',
... |
import unittest
from answer.number_of_strings_that_appear_as_substrings_in_word import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.patterns = [
["a", "abc", "bc", "d"],
["a", "b", "c"],
["a", "a", "a"],
]
self.word = [
... |
class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower()
# 模範解答
# https://leetcode.com/problems/to-lower-case/discuss/342980/Python-One-Liner
'''
class Solution:
def toLowerCase(self, str: str) -> str:
# chr(): ある Unicode コードポイントの文字を return
# chr(97) -> 'a' を return
... |
from typing import List
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
for i in range(left, right + 1):
s = str(i)
if '0' not in s:
self_dividing = True
for divide in s:
i... |
from typing import List
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
str1 = str2 = ''
for w in word1:
str1 += w
for w in word2:
str2 += w
if str1 == str2:
return True
return False
# 模範解答
... |
import unittest
from answer.shuffle_the_array import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.nums = [
[2, 5, 1, 3, 4, 7],
[1, 2, 3, 4, 4, 3, 2, 1],
[1, 1, 2, 2]
]
self.ns = [
3,
4,
2
... |
import unittest
from answer.merge_strings_alternately import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.word1 = [
'abc',
'ab',
'abcd',
]
self.word2 = [
'pqr',
'pqrs',
'pq',
]
... |
import unittest
from answer.height_checker import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.heights = [
[1, 1, 4, 2, 1, 3],
[5, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
]
self.answers = [
3,
5,
0,
... |
import unittest
from answer.merge_two_binary_trees import Solution, TreeNode
class TestSolution(unittest.TestCase):
def setUp(self):
self.root1 = [
TreeNode(1, TreeNode(3, TreeNode(5), None), TreeNode(2, None, None)),
TreeNode(1),
]
self.root2 = [
TreeN... |
from typing import List
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
result = []
for n in nums:
count = 0
for target in range(len(nums)):
if n > nums[target]:
count += 1
result += [count]... |
import unittest
from answer.minimum_number_of_operations_to_move_all_balls_to_each_box import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.boxes = [
'110',
'001011',
]
self.answers = [
[1, 1, 3],
[11, 8, 5, 4, 3, 4],
... |
import unittest
from answer.generate_a_string_with_characters_that_have_odd_counts import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.n = [
4,
2,
7,
]
def solution(self, i):
s = Solution()
result = s.generateTheStr... |
import unittest
from answer.concatenation_of_array import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.nums = [
[1, 2, 1],
[1, 3, 2, 1],
]
self.answers = [
[1, 2, 1, 1, 2, 1],
[1, 3, 2, 1, 1, 3, 2, 1],
]
... |
import unittest
from answer.check_if_numbers_are_ascending_in_a_sentence import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.s = [
"1 box has 3 blue 4 red 6 green and 12 yellow marbles",
"hello world 5 x 5",
"sunset is at 7 51 pm overnight lows... |
import pygates
lg = pygates.Gates
number1 = input("Please write the first variable. \n-> ")
while number1 != "1" and number1 != "0":
number1 = input("Please write the first variable in boolean format. \n-> ")
if number1 == "1" or number1 == "0":
break
else:
print("Input must ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Wang Yan
@ide: PyCharm
@Time : 2019/9/23 21:20
"""
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
result = ''
if 1 <= num <= 3:
result = result + 'I'*num
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author:Wang Yan
@ide:PyCharm
@time:2019/11/30 12:13
"""
import pandas as pd
data = {'animal': ['cat', 'dog', 'cat', 'lion'],
'foot': [2, 3, 5, 3],
'scale': ['big', 'small', 'big', 'small']
}
data_learn = pd.DataFrame(data)
print(data_learn)
# 完整... |
"""
This project is created to compute square sides
Github: https://github.com/misha2956/lab1_z3/
"""
from math import sqrt
def get_base_and_side_len(side_a: float, side_b: float, side_c: float) -> tuple:
"""
This function finds side and base length of a triagle
>>> get_base_and_side_len(2, 2, 3)
(3... |
def reverse(array):
temp = 0
for i in range(len(array)/2):
temp = array[i]
array[i] = array[-i-1]
array[-i-1] = temp
def main():
'''
the input could is a string:
bahia
'''
array = list(raw_input())
reverse(array)
print("".join(array))
if __name__ == '__main_... |
# Load Modules
import os
import csv
# Define path variables
file_name = "budget_data.csv"
path = "Resources"
file = os.path.join(path, file_name)
# Define calculation variables
total_months = 0
net_total = 0
previous_budget = 0
average_change = 0
greatest_increase = 0
greatest_decrease = 0
greatest_increase_date = ""... |
from pandigital import is_1_x_pandigital
import math
import itertools
def is_prime(p):
"""
A primality test.
>>> [is_prime(n) for n in (857, 859, 863, 877, 881, 883, 887, 907, 911)]
[True, True, True, True, True, True, True, True, True]
>>> is_prime(861)
False
>>> [is_prime(n) for n in ... |
from eratosthenes import sieve
# This will factorize up until some large number.
s = sieve(1000000)
def p_factorize(n):
"""
Return prime factors as an ordered list.
>>> p_factorize(857)
[857]
>>> p_factorize(646)
[2, 17, 19]
>>> p_factorize(644)
[2, 2, 7, 23]
>>> p_factorize(1... |
def divide_to_accuracy(x, y, digits):
"""
x / y to digits accuracy.
:x an integer
:y an integer
:digits the number of digits after the decimal point
Return a string representing the accuracy.
"""
accumulator = ''
# Implement grade school division algorithm?
quotient, remainder =... |
import random
print(random.randint(5, 20)) # line 1
'''
What was the smallest number you could have seen, what was the largest?
lowest: 5
highest: 20
'''
print(random.randrange(3, 10, 2)) # line 2
'''
What was the smallest number you could have seen, what was the largest?
Could this code produce a 4?
lowest: 3
highe... |
import matplotlib.pyplot as plt
from random_walk import RandomWalk
if __name__ == "__main__":
# Make a random walk.
rw = RandomWalk()
rw.fill_walk()
# Plot the point in the walk.
plt.style.use('classic')
fig, ax = plt.subplots(figsize=(5, 3), dpi=256)
point_numbers = range(rw.num_points)
... |
from functools import *
# use of partial
def f(a,b,c,d):
print 1000*a + 100*b + 10*c + d
g=partial(f,4,3,2)
g(1)
#packing unpacking
def unpack(*args):
print args
def pack(a,b,c):
print a,b,c
unpack([1,2,3,4])
args1=[1,2,3]
pack(*args1)
#character to interger
s='0'
print ord(s)
#sorted() doesn't sort... |
from functools import reduce
l1=[1,2,3]
l2=[]
multiply_result= reduce((lambda x,y : x*y),l1)
for i in l1:
l2.append(multiply_result/i)
#print l2 |
# -*- coding: utf-8 -*-
class Man:
def __init__(self,name,age,telephone):
self.name=name
self.age=age
self.telephone=telephone
def getName(self):
return self.name
def getAge(self):
return self.age
def getPhone(self):
return self.telephone
chuc=Man('chuc',... |
def binary_array_to_number(arr):
lenght = len(arr) - 1
n = 0
for i in arr:
n += (i * 2 ** lenght)
lenght-=1
return n
binary_array_to_number([1, 1, 1, 1]) |
'''a = [1, 2, 3]
b = set(a)
print(b)
for i in range(len(a)):
print(a[i])
print(a[2])
'''
'''
c = {1,2,3}
d = {2,3,4}
x = set(c|d)
y = x
print(x)
print(y<=x)
'''
c = [
{'hello', 'buffer'},
{'hello', 'good'},
{'hello', 'buffer'}
]
newx = set({'hello', 'good'})
if newx in c:
print('hello')
a = frozen... |
# '''
# Linked List hash table key/value pair
# '''
class LinkedPair:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
# '''
# Fill this in
# Resizing hash table
# '''
class HashTable:
def __init__(self, capacity):
self.capacity = capacity
... |
"""
- Author: Haoxin Lin
- E-mail: linhx36@outlook.com
- Date: 2020.10.28
- Brief: A Decision Tree class. Decision Tree is constructed with Queue
instead of recursive algorithm, which aims to control the number of nodes.
"""
# -*- coding: utf-8 -*-
import re
import numpy as np
from graphviz import Digraph
class Que... |
"""
- Author: Haoxin Lin
- E-mail: linhx36@outlook.com
- Date: 2020/11/23
- Brief: K-means Algorithm
"""
import numpy as np
class Kmeans():
""" Cluster Algorithm -- K-means """
def __init__(self, k):
self.k = k # parameter of K-means
def cluster(self, xs):
""" k-means al... |
groundShippingFlat = 20.00
premiumGroundShipping = 125.00
# Ground Shipping
def cost_of_ground_shipping(weight):
if (weight <= 2.0):
cost = weight * 1.50 + groundShippingFlat
return(cost)
elif (weight <= 6.0):
cost = weight * 3.00 + groundShippingFlat
return(cost)
elif (weight <= 10.0):
cost =... |
'''
Define a function called 'anti_vowel' that takes one string, 'text',
as input and returns the text with all of the vowels removed.
For example: anti_vowel("Hey You!") should return "Hy Y!".
Don't count Y as a vowel.
Make sure to remove lowercase and uppercase vowels.
'''
def anti_vowel(text):
vowels = ["a", ... |
pyg = 'ay'
# Let's put in a debug switch:
debug = raw_input("Enter 'y' for debug messages:")
# Getting user input:
original = raw_input('Enter a word:')
# Let's make sure that we apply our efforts only to appropriate alphabetic inputs:
if len(original) > 0 and original.isalpha():
word = original.lower()
firs... |
a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def binarysearch(list, value, left_edge, right_edge):
if left_edge <= right_edge:
middle = left_edge + (right_edge - 1) // 2
if list[middle] == value:
return middle
elif list[middle] < value:
return binarysearch(list, value, middle + 1, right_... |
from bs4 import BeautifulSoup
import urllib.request
import requests
# setting URL destination
url = "https://www.reddit.com/r/BabyYoda"
# retrieving HTML payload from the website
response = requests.get(url)
# checking response.status_code (if you get 502, try rerunning the code)
if response.status_code !... |
import sys
import re
def to_float(n):
try:
d = float(n)
except ValueError:
try:
d = float(n.replace(',', '.'))
print('В английском дробная часть отделяется точкой\n')
except ValueError:
print('Некорректный ввод, программа будет завершена.')
... |
players = ['charles', 'martina', 'michale', 'florence', 'eli']
print(players[0:3]) #todo 打印前三个值
print(players[1:4]) #todo 从第二个列表值打印到第三个列表中的值
print(players[:4]) #todo 没有指定头,则从初始开始打印至索引尾
print(players[2:])
print(players[-3:]) #todo 输出列表末尾的三个元素
#!便利切片
print('\n')
print("Here are the first three players on my team:")... |
from random import choice, shuffle
domino_set = []
double = [[x, y] for x in range(7) for y in range(7) if x == y]
for x in range(7):
for y in range(x, 7):
domino_set.append([x, y])
shuffle(domino_set)
def distribute(domino):
computer_d = []
player_d = []
domino_dup = domino
for k in ra... |
#!/usr/bin/python
import turtle
import sys
# creates a graphics window and a turtle
my_turtle = turtle.Turtle()
my_drawing = turtle.Screen()
# This function defines the default for the turtle (width of pen, color..)
def init_turtle():
my_turtle.width(3)
my_turtle.color('#00ffff')
my_drawing.bgcolor('#9400d3... |
import unittest
from todict import todict
class ToDictTest(unittest.TestCase):
def test_one_key(self):
input_list = ['user1', 'user2', 'user3']
input_key = 'name'
expected_output = [
dict(name='user1'),
dict(name='user2'),
dict(name='user3')
]
... |
# CIT590 - HW1 Lunar Lander game
# Pimkhuan(Pim) Hannanta-anan
# Due 9/6/16
play = 1
while play == 1:
# Initiate parameters
alt = 100 # altitude, unit m
vel = 0 # velocity, unit m/s
fuel_rem = 50 # remaining fuel, unit L
fuel_const = 1.5 # fuel burning constant
... |
def sort_asc(x):
from copy import deepcopy
x=deepcopy(x)
for n in range(len(x)):
for i in range(len(x)-1):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
return x
def fib(n):
prev, curr = 0, 1
res=[]
for i in range(n):
res.append(prev + curr)
... |
import math
# Sieve of Eratosthenes to calculate prime numbers up to a given N
# http://www.cut-the-knot.org/Curriculum/Arithmetic/Eratosthenes.shtml
N = 2000000
# write all integers from 1 through N in order
# remove 0 and 1 from the list
all_num_boolean_list = [True] * N
# index 0 is "1"
all_num_boolean_list[0] = F... |
n = 13195
# determines the largest prime factor of the input integer
# largest_factor represents our current largest factor
# smallest_divisor will help calculate whether the current largest factor is prime
# if largest_factor is equal to smallest_divisor, it is a prime number
def lpf(largest_factor):
# the smal... |
import cryptocode
import os
incrupt_key = '''/A?D(G+KbPeShVmYq3t6w9z$C&E)H@McQfTjWnZr4u7x!A%D*G-JaNdRgUkXp2s5v8y/B?E(H+MbPeShVmYq3t6w9z$C&F)J@NcRfUjWnZr4u7x!A%D*G-KaPdSgVkYp2s5v8y/B?E(H+MbQeThWmZq4t6w9z$C&F)J@NcRfUjXn2r5u8x!A%D*G-KaPdSgVkYp3s6v9y$B?E(H+MbQeThWmZq4t7w!z%C*F)J@NcRfUjXn2r5u8x/A?D(G+KaPdSgVkYp3s6v9y$... |
class Robot:
"""Represents a robot, with a name."""
# Class variable, counting robots
population = 0
def __init__(self, name):
"""Initialize data"""
self.name = name
print("Initializing {}".format(self.name))
#When a robot is created the robot population increases
... |
#!/usr/bin/python3
from sys import argv, exit
if len(argv) == 2:
number = argv[1]
if (number.isdigit()):
number = int(number)
if number < 4:
print("N must be at least 4")
exit(1)
else:
print("N must be a number")
exit(1)
'''
1. Colocamos reina en 0... |
#!/usr/bin/env python
"""Copyright 2018 Pavlin "Fanatique" Nikolov
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... |
aprovado=0
recuperacao=0
reprovado=0
notasala=0
print 'informe o numero de alunos da sala'
alunos=input()
for i in range (1, alunos+1):
print 'Digite as notas do aluno ',i
n1=input()
n2=input()
nf=(n1+n2)/2.0
notasala=notasala+nf
if nf>=7:
aprovado=aprovado + 1
if 3<=nf<7:
recuperacao=r... |
def media(x1, x2, x3):
if x3 == 'a' or x3 == 'A':
resultado = (x1 + x2) / 2.0
if x3 == 'p' or x3 == 'P':
resultado = ((x1 * 2) + (x2 * 3)) / 5.0
return resultado
for i in range(20):
print 'Digite a primeira nota'
a = input()
print 'Digite a segunda nota'
b = input()... |
print 'Digite a base do triangulo'
b=input()
print 'Digite a altura do triangulo'
h=input()
while b<0:
print 'Digite a base do triangulo; numero maior que 0'
b=input()
while h<0:
print 'Digite a altura do triangulo; numero maior que 0'
h=input()
print 'Area do triangulo: ', (b*h)/2
|
l1=[0,1]
print 'Digite a qunatidade de valores da lista'
a=input()
for i in range (2,a):
if i%2==0:
l1.append(0)
else:
l1.append(1)
print l1
|
print 'Digite o raio da circunferencia'
r = input()
a = (r ** 2) * 3.1416
print 'Area da Circunferencia: ' + str(a)
|
import math
print 'Calcule ax^2+bx+c=0'
print 'Digite o valor de ax^2'
a = input()
print 'Digite o valor do bx'
b = input()
print 'Digite o valor de c'
c = input()
k = b ** 2 - 4 * a * c
x1 = (-b+math.sqrt(k))/(2.0*a)
x2 = (-b-math.sqrt(k))/(2.0*a)
if k < 0:
print 'Nao possui raizes naturais'
if k == ... |
m1=[]
DiagonalP=[]
DiagonalS=[]
print 'Digite a quantidade de linhas da matriz'
linhas=input()
print 'Digite a quantidade de colunas da matriz'
colunas=input()
if linhas!=colunas:
print 'Nao existe diagonal principal nem secundaria, pois nao e uma matriz quadratica'
else:
for i in range (linhas):
m1.append([])
fo... |
print 'Digite o nome do primeiro canditado'
n1 = raw_input()
print 'Digite o numero de votos do primeiro canditado'
a = input()
print 'Digite o nome do segundo canditado'
n2 = raw_input()
print 'Digite o numero de votos do segundo canditado'
b = input()
print 'Digite o nome do terceiro canditado'
n3 = raw_inpu... |
print 'Digite o numero inteiro'
a = input()
if a % 2 == 0:
print 'O numero e par'
else:
print 'O numero e impar' |
print 'Digite o valor da hora aula'
a=input()
print 'numero de aulas dadas no mes'
b=input()
print 'percentual de desconto do INSS'
c=input()
bruto=a*b
desconto=(bruto*c)/100.0
liquido=bruto-desconto
print 'Salario Bruto ' + str(bruto)
print 'Desconto ' + str(desconto)
print 'Salario Liquido ' + str(liquido)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.