text stringlengths 37 1.41M |
|---|
from admin_functions import *
def manage_books_and_authors():
valid = 0
while(valid == 0):
print('''Books and authors: what would you like to do:
1) Add Book
2) Delete Book
3) Edit Book
4) Add Author
5) Delete Author
6) Update Author
Or Enter to go back to admin menu
''')
choice = in... |
import unittest
from quince.components import Deck, Card
class TestDeck(unittest.TestCase):
def test_constructor(self):
"""Takes a Card class and builds a deck of 40 Cards"""
deck = Deck(Card)
self.assertEqual(40, len(deck.cards()))
# Assert that there are no duplicate cards in th... |
"""
The Card object represents a Card.
Each card has a value and a suit.
"""
from os import path, getcwd
from PIL import Image
SETENTA_SCORING = [11.0, 4.0, 6.0, 8.0, 10.0, 14.0, 17.5, 1, 1, 1]
class Card(object):
"""
The Card object represents a Card.
Each card has a value and a suit.
"""
def _... |
# 菜鸟教程 http://www.runoob.com/python/att-string-format.html
# 不设置指定位置,按默认顺序
str1 = "{} {}".format("hello", "world")
print(str1)
# 设置指定位置
str2 = "{0} {1}".format("hello", "world")
print(str2)
# 设置指定位置
str3 = "{1} {0} {1}".format("hello", "world")
print(str3)
|
def stack():
s=[]
return(s)
def push(s,data):
s.append(data)
def pop(s):
data=s.pop()
return(data)
def peek(s):
return(s[len(s)-1])
def isEmpty(s):
return (s==[])
def size(s):
return (len(s))
def balik(teks):
a=stack()
hasil =''
for i in r... |
#Crie um programa que leia uma FRASE qualquer
#e diga se ela é um PALÍNDROMO, desconsiderando os espaços
# Exemplos de PALÍNDROMOS
# APOS A SOPA
# A SACADA DA CASA
# A TORRE DA DERROTA
# O LOBO AMA O BOLO
# ANOTARAM A DATA DA MARATONA
frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
ju... |
from random import randint
from time import sleep
import emoji
print('{:=^100}'.format("\033[1;31;m Play Jokempô \033[m" + emoji.emojize("\033[1;31;m :sunglasses: \033[m", use_aliases=True)))
print("""Suas opções:
[0] PEDRA
[1] PAPEL
[2] TESOURA
""")
lista = ['PEDRA', 'PAPEL', 'TESOURA']
computador = randint(0, 2)
jo... |
sal_atual = float(input('Digite o salário atual: '))
sal_novo = sal_atual + (sal_atual * 15 / 100)
print('O salário de R${:.2f} com 15% de aumento será de R${:.2f}'.format(sal_atual, sal_novo))
|
#Refaça o DESAFIO 009, mostrando a tabuada de um número
#que o usuário escolher, só que agora utilizando um laço for.
#r = 0
#n = int(input('Digite um número para ver sua tabuada: '))
#for c in range(1, 11):
# r = n*c
# print('{}x{}={}'.format(n, c, r))
#Usando apenas 3 linhas
num = int(input('Digite um número pa... |
import datetime
import pafy
from selenium import webdriver
driver = webdriver.Chrome(r"C:\projects\Eclipse\chromedriver.exe")
# using pafy to get duration of youtube video
# return int - seconds of youtube video duration
def get_duration(url):
video = pafy.new(url)
with open("result.txt", 'a', encoding='utf-8... |
mdp = input("Entrez un mot de passe (min 8 caractères) : ")
mdp_trop_court = "votre mot de passe est trop court."
if(len(mdp)==0):
print(mdp_trop_court)
elif(len(mdp)<8 and not mdp.isdigit()):
mdp_trop_court = mdp_trop_court.capitalize()
print(mdp_trop_court)
elif (mdp.isdigit()):
print("Votre m... |
import numpy as np
import scipy.optimize as opt # para la funcion de gradiente
from matplotlib import pyplot as plt # para dibujar las graficas
from valsLoader import *
from dataReader import save_csv
# g(X*Ot) = h(x)
def sigmoid(Z):
return 1/(1+np.exp(-Z))
def dSigmoid(Z):
return sigmoid(Z)*(... |
"""2048 game
hussein suleman
25 april 2014"""
# random number generator
import random
# grid utility routines
import util
# grid value merging routines
import push
def add_block (grid):
"""add a random number to a random location on the grid"""
# set distributon of number possibilities
options = [2,2,2,2,... |
import json
def _dict_traverse(d, level, max_level, show_values, show_levels):
if level > max_level:
return ""
accum = ""
keys = d.keys()
for k in keys:
key_str = f'{" " * level}"{k}"'
if isinstance(d[k], str):
d_val = f'"{d[k]}"'
elif isinstanc... |
#manikantakintali6@gmail.com
number=int(Input())
if (number>0):
print('Positive')
elif ('Number<0')
print('Negative')
elif:
prin('Zero')
|
"""
Exercise 3
Using the same CelestialBody class, create a factory method called make_earth.
This method returns a CelestialBody object for planet Earth. Earth is 149,600,000 km
from the Sun, has a diameter of 12,756.3 km, and has one moon.
Expected Output
The factory method should return a CelestialBody object.
This ... |
# Recursion Exercise 5
# Write a recursive function called get_max that takes a list of numbers as a parameter.
# Return the largest number in the list.
# Expected Output
# If the function call is get_max([1, 2, 3, 4, 5]), then the function would return 5
# If the function call is get_max([11, 22, 3, 41, 15]), then the... |
#One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given TWO strings, write a function to check if THEY are ONE edit (or zero edits) away.
#EXAMPLE
#pale, ple -> true
#pales, pale -> true
#pale, bale -> true
#pale, bae -> false
#... |
"""
Given two arrays, write a function to compute their intersection.
"""
def intersect(nums1, nums2):
d = {}
for n in nums1:
d[n] = d.get(n, 0) + 1
out = []
for n in nums2:
if n in d and d[n] > 0:
out.append(n)
d[n] -= 1
return out
|
"""
Given an array consisting of n integers, find the contiguous subarray of given length k that has the
maximum average value. And you need to output the maximum average value.
"""
def findMaxAverage(nums, k):
_sum = 0
for i in range(k):
_sum += nums[i]
_max = _sum / (k + 0.0)
i = 0
j = i ... |
class Node:
def __init__(self, v=None, l=None, r=None):
self.key = v
self.lc = l
self.rc = r
def add(root, new_node):
if root is None:
root = new_node
else:
if new_node.key < root.key:
if not root.lc:
root.lc = new_node
else:
... |
"""
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
"""
def minimumTotal(triangle):
if len(triangle) == 0:
return 0
if len(triangle[0]) == 0:
return 0
i = len(triangle) - 2
while i >= 0:
for j in range(... |
"""
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
prove that at least one duplicate number must exist. Assume that there is only one duplicate number,
find the duplicate one
"""
def findDuplicate(nums):
for i in range(len(nums)):
if nums[abs(nums[i])] < 0:... |
# problem: https://www.hackerrank.com/challenges/funny-string
t = int(input().strip())
out_string = ""
for test in range(t):
s = list(map(ord, list(input().strip())))
f = list(reversed(s))
for i in range(1, len(s)):
if abs(s[i] - s[i - 1]) != abs(f[i] - f[i - 1]):
out_string += "Not Fun... |
"""
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
"""
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.left = left
self.right = right
def sortedArraytoBST(nums):
root = _sortedArraytoBST(nums, 0, len(nums) - 1, None)... |
# Dijkstra's algorithm implemented for a graph represented using a dict of adjacent nodes
# Dijkstra's algorithm is used to find the shortest path to any node from a single source
class Graph:
def __init__(self):
self.g = dict()
def add(self, s, e, w):
self.add_aux(s, e, w)
self.add_au... |
# task: given an array with negative and positive numbers, find a subarray such that its sum is maximized
# simple solution that does not keep track of the start and end indices
def maximum_subarray_simple(lst):
cur_max = 0
global_max = -float("inf")
for val in lst:
cur_max += val
if cur_ma... |
"""
Given a Binary Search Tree and a target number, return true if there exist two elements in
the BST such that their sum is equal to the given target.
"""
import unittest
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right =... |
# task: given a binary tree, write a function to check if the given tree is a valid binary search tree
class Node:
def __init__(self, v=None, l=None, r=None):
self.key = v
self.lc = l
self.rc = r
def is_BST(tree):
if not tree:
return True
if not tree.lc and not tree.rc:
... |
"""
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
"""
def totalHammingDistance(nums):
return sum(b.count('0') * b.count('1') for b in zip(*map('{:032b}'.f... |
# task: given a binary tree, swap all children
class Node:
def __init__(self, v, l=None, r=None):
self.key = v
self.lc = l
self.rc = r
def swap(tree):
if not tree:
return tree
q = [tree]
while q:
cur_node = q.pop(0)
cur_node.lc, cur_node.rc = cur_node.rc... |
#task: given a pointer to some node that has a valid next node, delete itself from the linkedlist without
# an access to previous nodes.
# e.g) a -> b -> c -> d -> .
# you are given a pointer to node 'c', but no other previous elements
# turn the linked list into
# a -> b -> d -> .
class Node:
... |
#task: given two linked lists each of which represents a string. Return 0 if they are the same,
# 1 if the first string is lexicographically greater than the second, -1 if the second is
# lexicographically less than the second.
class Node:
def __init__(self, v=None, n=None):
self.key = v
... |
"""
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
"""
def plusOne(digits):
"""
:type dig... |
"""
Given a binary tree, return the inorder traversal of its nodes' values.
"""
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
def inorderTraversal(root, iterative=True):
lst = []
if not iterative:
_rec... |
# task: given a list of N coins, their values, and the total mass S, Find the minimum number of coins the sum of which is S.
def minimum_coins(coins, S):
if not coins:
return 0
|
"""
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
"""
def generateMatrix(n):
matrix = [[0 for i in range(n)] for j in range(n)]
i = j = 0
n = 1
directio... |
#task: given a sorted linked list, insert a new node so that the sorted order is retained
class Node:
def __init__(self, v=None, n=None):
self.key = v
self.next = n
def insert(head, v):
if not head:
return Node(v)
if not head.next:
if v < head.key:
return Node(v... |
# Completed
# Problem: https://leetcode.com/problems/reverse-integer/#/description
def reverseAux(x, neg, acc=0):
if x == 0:
if neg:
return acc * -1
else:
return acc
else:
new_x = x // 10
cur_digit = x % 10
return reverseAux(new_x, neg, (acc * 10)... |
# task: given two string, determine if the strings are at most one edits from each other
# 'edit' refers to a deletion, insertion or replacement
def one_away(src, s):
if abs(len(src) - len(s)) > 1:
return False
if len(src) == len(s):
diff = False
for i, j in zip(src, s):
... |
# task: given a pointer to a node in a binary search tree, write an algorithm to return the node containing the
# next largest element
class Node:
def __init__(self, key=None, left_child=None, right_child=None, parent=None):
self.k = key
self.lc = left_child
self.rc = right_child
... |
"""
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5,... |
"""
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s
elements are subset of nums2. Find all the next greater numbers for nums1's
elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number
to its right in nums2. If it does not exi... |
"""
Reverse a singly linked list
"""
import unittest
class ListNode(object):
def __init__(self, x, next=None):
self.val = x
self.next = next
def create_LL(lst):
if not lst:
return None
root = ListNode(lst[0])
cur = root
for i in range(1, len(lst)):
cur.next = ListN... |
"""
Given a positive integer num, write a function which returns True if num is a perfect square else False.
"""
def isPerfectSquare(num):
if num <= 0:
return False
base = 1
increment = 3
while base < num:
base += increment
increment += 2
return base == num
|
"""
Given a binary tree, check whether it is a mirror of
itself (ie, symmetric around its center).
"""
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
def isSymmetric(root):
if not root:
return True
retu... |
"""
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area i... |
"""
Unfinished, taken help from book solution
"""
import string
import random
def process_file(filename, skip_header):
hist = {}
fp = file(filename)
if skip_header:
skip_gutenberg_header(fp)
for line in fp:
process_line(line, hist)
return hist
def skip_gutenberg_header(fp):
... |
# python3
from collections import namedtuple
from typing import List
from unittest import TestCase
Loot = namedtuple('Loot', 'value weight')
def get_optimal_value(cap: int, loots: List[Loot]) -> float:
optimal = 0.0
loots = sorted(loots, key=lambda x: x.value / x.weight, reverse=True)
while cap > 0 and ... |
# python3
from collections import namedtuple
from sys import stdin
from typing import List
from unittest import TestCase
test = namedtuple('test', 'seq expected')
def number_of_inversions(seq: List[int], buf: List[int], left: int, right: int) -> int:
count = 0
if right - left <= 1:
return count
a... |
# python3
def naive_gcd(a: int, b: int) -> int:
current_gcd = 1
for d in range(2, min(a, b) + 1):
if a % d == 0 and b % d == 0:
if d > current_gcd:
current_gcd = d
return current_gcd
def fast_gcd(a: int, b: int) -> int:
if b == 0:
return a
if a < b:
... |
# python3
from sys import stdin
from typing import List
from unittest import TestCase
def compute_min_refills(distance: int, tank: int, points: List[int]) -> int:
points.insert(0, 0)
if distance != points[-1]:
points.append(distance)
num_refills = current_refill = 0
destination = len(points) ... |
# python3
from sys import stdin
from typing import List
from unittest import TestCase
def max_dot_product(profits: List[int], clicks: List[int]) -> int:
profits = sorted(profits, reverse=True)
clicks = sorted(clicks, reverse=True)
res = 0
for i in range(len(profits)):
res += profits[i] * click... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 24 01:29:55 2016
@author: sergeys04
Program that prints the sum of the numbers in s
"""
s = '2.3456,98.12,654.23,1.21'
string = ''
total = 0
for x in s:
if x != ',':
string = string + x
elif x == ',':
total = total + float(string)
string... |
#binary search
def binary_search(array,value):
left = 0
right = len(array)
while left <= right:
middle = (left+right) // 2
if value == array[middle]:
return middle
elif value > array[middle]:
left = middle + 1
elif value < array[middle]:
... |
import random
import turtle
turtle.shape('turtle')
for i in range(100):
turn = random.randint(-360, 360)
forward_t = random.randint(30, 100)
turtle.forward(forward_t)
turtle.left(turn)
|
import string
import os
def system_drives():
""" Find the different drives located in the system
Args:
Does not take any arguments
Returns:
available_drives: A list of all available drives in the system
"""
# Runs a list through all uppercase alphabets and stores v... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 12:51:35 2019
@author: owner
"""
list=[1,20,-1,0,1000]
#EX1:
for x in list:
print(x)
#EX2:
print(sum(list))
#EX3:
print(max(list))
#EX4:
x= set(list)
#EX5:
print("Empty") if (len(list)==0) else print("Not Empty")
#EX6:
tuple=(1,2,3,"Hi",... |
def begin():
print("装饰开始:瓜子板凳备好,坐等[生成]")
def end():
print("装饰结束:瓜子嗑完了,板凳坐歪了,撤!")
def wrapper_counter_generator(func):
# 接受func的所有参数
def wrapper(*args, **kwargs):
# 处理前
begin()
# 执行处理
result = func(*args, **kwargs)
# 处理后
end()
# 返回处理结果
r... |
# -.- coding: latin-1 -.-
from __future__ import print_function
from math import sqrt
'''
Amicable Numbers
Problem 21
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b a... |
"""
Problem Statement:
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 N.
"""
from __future__ import print_function
N = 10
N_limit = 101
while N < N_limit:
# raw_input = input("请输入一个大于3... |
s=0
a=int(input("Введите число:"))
while a!=0:
s+=a
a = int(input("Введите число:"))
print(s) |
# -*- coding:utf-8 -*-
# @time : 2019-12-17 14:43
# @author : xulei
# @project: Fluent_Python
import math
from array import array
import itertools
import numbers
class Vector:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self)... |
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
stack = [-1]
ans = 0
heights.append(0)
for i in range(len(heights)):
while stack[-1] >= 0 and heights[stack[-1]] > heights[i]:
x = stack.pop()
... |
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
s = [root]
res = []
while s:
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def rob(self, root: TreeNode) -> int:
cache = {}
def done(node: TreeNode, flag: bool):
if node is None:
... |
from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
iIndex = []
jIndex = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
... |
"""The n queens puzzle."""
import sys
class NQueens:
"""Generate all valid solutions for the n queens puzzle"""
def __init__(self, size):
# Store the puzzle (problem) size and the number of valid solutions
self.size = size
self.solutions = 0
self.solve()
def solve(self):
... |
def calc_angle(h, m):
hour_step_angle = 30
# reference for measuring tha angles is the "12" hour
minute_angle = m * 6
hour_angle = (h % 12) * hour_step_angle + (m / 60) * hour_step_angle
angle = abs(minute_angle - hour_angle)
return angle if angle <= 180 else 360 - angle
print(calc_angle(3, ... |
# Given an array containing only positive integers,
# return if you can pick two integers from the array which cuts the array
# into three pieces such that the sum of elements in all pieces is equal.
# Example 1:
#
# Input: array = [2, 4, 5, 3, 3, 9, 2, 2, 2]
#
# Output: true
#
# Explanation: choosing the number 5 and... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 12:03:42 2021
@author: quantum
"""
import nltk
import re
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
paragraph='''Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus.... |
import sys
import time
from board import Board
from priorityQueue import priority_queue
from board import Spot as heuristics
class BFS:
def __init__(self, start):
self.start = start
self.visited = []
self.nodes_visited = 0
self.space = 0
def search(self):
queue = [(sel... |
# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
#
# Note:
#
# The solution set must not contain duplicate triplets.
#
# Example:
#
#
# Given array nums = [-1, 0, 1, 2, -1, -4],
#
# A solution set is:... |
# Given a 32-bit signed integer, reverse digits of an integer.
#
# Example 1:
#
#
# Input: 123
# Output: 321
#
#
# Example 2:
#
#
# Input: -123
# Output: -321
#
#
# Example 3:
#
#
# Input: 120
# Output: 21
#
#
# Note:
# Assume we are dealing with an environment which could only store integers within the 32-b... |
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
#
# Note: For the purpose of this problem, we define empty string as valid palindrome.
#
# Example 1:
#
#
# Input: "A man, a plan, a canal: Panama"
# Output: true
#
#
# Example 2:
#
#
# Input: "race a c... |
# -*- coding:utf-8 -*-
# Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
#
# Example:
#
#
# Input: 38
# Output: 2
# Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
# Since 2 has only one digit, return it.
#
#
# Follow up:
# Could you ... |
# -*- coding:utf-8 -*-
# Reverse bits of a given 32 bits unsigned integer.
#
# Example:
#
#
# Input: 43261596
# Output: 964176192
# Explanation: 43261596 represented in binary as 00000010100101000001111010011100,
# return 964176192 represented in binary as 00111001011110000010100101000000.
#
#
# F... |
#
# Given an integer, write a function to determine if it is a power of three.
#
#
# Follow up:
# Could you do it without using any loop / recursion?
#
#
# Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.
class Solution:
def isPowerOfThree(self, n):
... |
# filename : var.py
i=5
print i
i = i+1
print i
s = '''this is a multi-line string
this is the second line'''
print s
print \
i
s = 'this is a string. \
this continues the string'
print s
s = 'this is a string \
this continues the string'
print s
print "this is the first sentence. \
this is the second sentence."
... |
import sqlite3
import time
class Ürün():
def __init__(self,urun,adet,marka,fiyat):
self.urun = urun
self.adet = adet
self.marka = marka
self.fiyat = fiyat
def __str__(self):
return "Ürün: {}\nAdet: {}\nMarka: {}\nFiyat: {} Tl\n".format(self.urun,self.adet,self.marka,self... |
"""
fibonacci serisi yeni bir sayıyı önceki iki sayının toplamı şeklinde oluşturulur.
1,1,2,3,5,8,13,21,34.....
"""
a = 1
b = 1
fibonacci = [a, b]
for i in range(10):
a , b = b, a + b
print("a:", a,"b", b)
fibonacci.append(b)
print(fibonacci)
|
import math
class Vector(list):
def length(self):
return math.sqrt(sum(i**2 for i in self))
def dot(self, vec):
return sum([i * j for (i, j) in zip(self, vec)])
def euclidDist(self, vec):
return math.sqrt(sum([(i-j)**2 for (i, j) in zip(self, vec)]))
def manhattanDist(self, v... |
import random
print(
'''Hey there!
Welcome to CERO.
To play the game, type '?p' or 'play'.
To know about the rules, type '?h' or 'help'.
'''
)
cards = [
"b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b10",
"c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
"r1", "r2", "r3", "r4", "r5... |
import pandas as pd
import matplotlib.pyplot as plt
def generate_histogram(column, title, range, labels):
plt.figure(figsize=(12, 8))
x = df[df[column].notnull()][column]
bins = int(range[1] - range[0])
plt.hist(x, bins, facecolor='green', alpha=0.75, range=range)
plt.title(title)
plt.xlabel(l... |
def fayyaz(itemList):
itemList[0] = "Pulaoo"
for i in itemList:
print("Buying "+i)
myItems = ["Briyani","Anday wala burger","Nihari","Lassi"]
print(myItems)
fayyaz(myItems[:])
print(myItems) |
def myfunction(x):
return x * 3
def doubler(f):
def g(z):
return z + f(6)
return g
myfunc = doubler(myfunction)
print(myfunc)
print(myfunc(2))
|
marks = 39
if marks >= 40 and marks < 50:
print("D")
elif marks >= 50 and marks <60:
print("C")
elif marks >= 60 and marks <70:
print("B")
elif marks >= 70 and marks < 80:
print("A")
elif marks >= 80:
print("A+")
else:
print("Failed")
|
players = ['charles', 'martina', 'michael',
'florence', 'eli',"1",
"2","3","4"]
print(players)
for p in players[::2]:
print(p.title())
|
stu1 = {'name':'Qasim',
'email':'abc@gmail.com',
'age':20,
23:"hello",
True:"working",
2.5:"new",
4:True}
print(stu1)
print(stu1['name'])
stu1['name'] = 'Inzamam'
print(stu1['name']) |
# # 재귀 함수
# def factorial(n):
# if n == 0:
# return 1
# else:
# return n*factorial(n-1)
# print("1! : {}".format(factorial(1)))
# print("2! : {}".format(factorial(2)))
# print("3! : {}".format(factorial(3)))
# print("4! : {}".format(factorial(4)))
# print("5! : {}".format(factorial(5)))
# prin... |
#! /usr/bin/python
from PIL import Image
import sys
def get_main_color(file):
img = Image.open(file)
colors = img.getcolors(256*1024) #put a higher value if there are many colors in your image
max_occurence, most_present = 0, 0
try:
for c in colors:
if c[0] > max_occurence:
... |
#!/usr/bin/python3
'''Advent of Code 2018 Day 24 solution'''
import re
import math
import copy
from typing import Tuple, TextIO, List, Callable
class Unit: # pylint: disable=too-many-instance-attributes
'''Represents a unit group'''
count = 0
hp = 0
attack = 0
attacktype = ''
initiative = 0
... |
#!/usr/bin/python3
'''Advent of Code 2018 Day 4 solution'''
from typing import Tuple, List, DefaultDict, TextIO
import re
import datetime
import operator
from collections import defaultdict
InputData = List[Tuple[datetime.datetime, str]]
def runsolution(values: InputData) -> Tuple[int, int]:
'''Run solution - both... |
#!/usr/bin/python3
'''Sequence finder code'''
from typing import List, Optional, Tuple
def checksequence(numbers: List[int]) -> Optional[Tuple[int, int]]:
'''Check to see if a sequence has started repeating.
Simple check - does not actually verify contents of loop'''
if len([n for n in numbers if n == ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def do(word):
odd_letters = ""
even_letters = ""
for i in range(len(word)):
if i%2==0:
even_letters = even_letters+word[i]
elif i%2==1:
odd_letters = odd_letters+word[i]
return "{} {}".format(... |
x = -2
y = -1111
if x < 0 and y < 0:
print('mindkettő negatív')
if x < 0 or y < 0:
print('van köztük negatív')
if not x <= 0:
print('x pozitív') |
szám = 1
while szám <= 10:
if szám % 2 == 0:
print(szám)
szám = szám + 1
print("vége") |
import os
#declarar variables
valor1,valor2,valor3,valor4=0,0,0,0
#INPUT
valor1=int(os.sys.argv[1])
valor2=int(os.sys.argv[2])
valor3=int(os.sys.argv[3])
valor4=int(os.sys.argv[4])
#PROCESSING
total =int(valor1 + valor2 + valor3 + valor4)
#OUTPUT
print ( " ############################################# " )
print ( " ... |
import os
#BOLETA DE VENTA DE ELECTRODOMESTICOS
#DECLARAR VARIABLES
empresa,cliente,radio,costo_radio,tv,costo_tv = "","",0,0.0,0,0.0
#INPUT
empresa=os.sys.argv[1]
cliente=os.sys.argv[2]
radio=int(os.sys.argv[3])
costo_radio=float(os.sys.argv[4])
tv=int(os.sys.argv[5])
costo_tv=float(os.sys.argv[6])
#PROCESSING
total_... |
import os
#VOLUMEN DE UNA ESFERA
#DECLARAR VARIABLES
pi,radio,angulo=0.0,0,0
#INPUT
pi=float(os.sys.argv[1])
radio=int(os.sys.argv[2])
angulo=int(os.sys.argv[3])
#PROCESSING
volumen =(round(4/3*pi*(radio**3)*angulo,2))
#VERIFICADOR
volumen_correcto=(volumen>=50)
#OUTPUT
print("pi es: " + str(pi))
print("El radio es... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.