text stringlengths 5 121k |
|---|
import numpy as np
import pandas as pd
df=pd.read_csv('pupils.csv')
df.head()
df.sample(5)
len(df)
df.columns
df.info()
df = pd.read_csv(fname, parse_dates=['time'])
df.to_csv('pupils2.csv', index = False)
df[2:6]
df['Name']
df[['Name','Age']][2:6]
df.loc[2]
df.loc[2:2]
df.loc[2:6]
df.loc[2:6:2]
df.loc[2:... |
import numpy as np
def corrupt_mnist_img(rng, img, value):
"""Corrupt a single MNIST image.
Note that the image itself is MODIFIED.
:param rng: instance of numpy.random.RandomState
:param img: image to modify. ndarray or compatible
:param value: pixel value to use for corrupting the image
:r... |
class Monster():
def __init__(self, name, tax_num, monster_type):
self.name = name.title()
self.tax_num = tax_num
self.monster_type = monster_type.title()
|
import requests
import json
print('Enter your Search:')
search=input()
url="https://api.tvmaze.com/singlesearch/shows?q="+search
response = requests.get(url,timeout=6)
if response.status_code==200:
data= json.loads(response.text)
print('Show Name: '+data['name'])
print('Language: '+data['language'])
p... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([1,8])
ypoints = np.array([3,300])
plt.plot(xpoints,ypoints)
plt.show()
|
numero=int(input("ingrese un numero: "))
factorial = 1
for n in range(1, (numero+1)):
factorial = factorial * n
print ("El factorial de {0} es: {1}".format(numero, factorial))
|
import datetime
import re
import string
import os
"""
We opened input file in readmode and then applying pattern on each line and
if pattern found
apply "linemodification()" function on each line.
linemodifcation function apply regular expression on line and find all the oc... |
print ("hello world " + str(2 * 6) + " goodbye")
var1 = 1.23 ** 1.23
print ("var1 " + str(var1))
var2 = "This is var2 "
var3 = 2 * 3 / 4.0
var4 = "This is var3 "
print (var4 + str(var3))
|
print("---Welcome to Posh's Gift Shop---")
print("----Please Login into System----")
usernameInput = input("Username : ")
passwordInput = input("Password : ")
if usernameInput == "Thammanoon" and passwordInput == "6116" :
print("Welcome!")
print("---Total Goods List---")
print(" 1. Floral Candle : 44... |
""""
utility functions for working with DataFrames
"""
import pandas as pd
import numpy as np
df_null = pd.DataFrame([1, 2, 3, 4, 5, 6, 7, 8, 9, np.NaN, 0, 0])
df_random = pd.DataFrame(np.random.randn(100, 3))
df_random_column = df_random[0]
|
'''
File: Loops.py
Name: Mohammed A. Frakso
Date: 12/01/2020
Course: DSC_510 - Introduction to Programming
Desc: This program will contain a variety of loops and functions:
The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user.
Define a functio... |
import string
def add_word (words, wordcount):
if words not in wordcount: wordcount[words] = 1
else: wordcount[words] = wordcount[words] +1
def process_line (eachline, wordcount):
eachline = eachline.translate(str.maketrans('', '', string.punctuation))
eachlinewords = eachline.spli... |
class WeatherDisplay:
def __init__(self, desc, city, country, temp, feels_like, min_temp, max_temp, lat, lon, wind):
""" Initialize the model variables """
self._desc = desc
self._city = city
self._country = country
self._temp = temp
self._feels_like = feels_like
self._min_temp = mi... |
"""Desc: This program will prompt the user for an arithmetic operation.
It wil then perform the operation and prompt the user for another arithmetic until the user types none."""
def performCalculation (x):
userNum_input = int(input('What is your first number?'))
userNum_input2 = int(input('What is your... |
'''
File: NERALLA_DSC510_WEEK10.py
Name: Ravindra Neralla
Course:DSC510-T303
Date:02/23/2020
Description: This program is to create a simple cash register program.
The program will have one class called CashRegister.
The program will have an instance method called addItem which takes one parameter for price. The method... |
def welcome_screen():
"""Print welcome screen"""
print("Welcome to Fiber Optics One.")
print("Please tell us the name of your company")
def compute_cost(Cable_Length,CableCostPerFoot):
"""Compute cable cost"""
return float(Cable_Length) * CableCostPerFoot
welcome_screen()
... |
import sys
temperature = []
number = []
count = 0
while number != 'go':
try:
number = int(input('Enter a temperature or to run program enter go:'))
temperature.append(number)
count = count + 1
except ValueError:
print('The highest temperature is:... |
import string
def add_word(words, summary):
"""Add each word to the dictionary. If exist, increment the count by 1.
Args:
Parameters are the word and a dictionary.
Returns:
No return value.
"""
for word in words:
if word not in summa... |
'''
File: lists.py
Name: Mohammed A. Frakso
Date: 19/01/2020
Course: DSC_510 - Introduction to Programming
Desc: This program will work with lists:
The program will contains a list of temperatures, it will populate the list based upon user input.
The program will determine the number of temperatures in the prog... |
cost_per_feet_above_100feet = 0.80
cost_per_feet_above_250feet = 0.70
cost_per_feet_above_500feet = 0.50
length_above_100 = 100.0
length_above_250 = 250.0
length_above_500 = 500.0
def calculate_cost(cost, feet):
return cost * feet
class FiberCostCalculator:
def __init__(self, company_name="", num_o... |
def print_values(temperatures):
length: int = len(temperatures)
print('There are total %d temperature values ' % length)
print('The lowest temperature is %g and the highest temperature is %g' % (min(temperatures), max(temperatures)))
def main():
print("Welcome to temperature calcula... |
import datetime
def price_of_cable(length_of_fiber_cable: int):
if 100 < length_of_fiber_cable <= 250 :
return 0.80
elif 250 < length_of_fiber_cable <= 500 :
return 0.70
elif length_of_fiber_cable > 500 :
return 0.50
else :
return 0.87
def... |
print('Welcome to the fiber optic installation cost calculator.')
companyName = input('Please input company name.\n')
fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n')
fiberOpticCost = 0
if float(fiberOpticLength) > 499:
fiberOpticCost = .50
elif float(fiber... |
print('Welcome to the ABC Cabling Company')
companyName = input('What is the name of you company?\n')
feet = float(input('How any feet of fiber optic cable do you need installed?\n'))
cost = float(feet*0.87)
print("********Receipt********")
print('Thank you for choosing ABC Cable Company.\n')
print('Custome... |
print('Welcome to the fiber optic installation cost calculator.')
companyName = input('Please input company name.\n')
fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n')
fiberOpticCost = 0
if float(fiberOpticLength) > 499:
fiberOpticCost = .50
elif flo... |
print('Welcome to the fiber optic installation cost calculator.')
companyName = input('Please input company name.\n')
fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n')
fiberOpticCost = .87
totalCost = float(fiberOpticLength) * float(fiberOpticCost)
prin... |
import requests
import textwrap
from urllib.error import HTTPError
from urllib.error import URLError
url = 'https://api.chucknorris.io/jokes/random'
def welcome_message():
print('------------------------------------------------')
print('----------Welcome to Chuck Norris Joke-... |
'''
File: DSC510-Week 5 Nguyen.py
Name: Chau Nguyen
Date: 1/12/2020
Course: DSC_510 Intro to Programming
Desc: This program helps implement variety of loops and functions.
The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user.
'''
def performCa... |
s=sum([20,40,10])
print('The sum of the container is:', s)
|
import numpy as num
arr1=num.array([4,7,9])
arr2=arr1
print(arr1)
print(arr2)
|
from typing import List
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
count = 0
for i in range(0, len(nums)):
curr = 0
j = i + 1
while curr <= k:
curr += nums[j]
j += 1
if (curr == k):
... |
class Employee:
def __init__(self, empid, isengineer):
self.empid = empid
self.isengineer = isengineer
self.reportees = []
def orgmodification(root):
node = root
newreportees = []
for emp in root.reportees:
newreportees += orgmodification(emp)
if ... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
current = dummy
while l1 and l2:
if l1.val < l2.val:
... |
import functools
"能将被装饰丢失的元数据弄回来,装饰到闭包中"
class Kongjian():
@staticmethod
def upper_sugar(func):
"""
俺是一个装饰器,我使用闭包会定义一个函数,并返回这个函数对象本身
:param func: 初始函数对象
:return: 处理后的函数对象
"""
@functools.wraps(func)
def temp():
return func().upper()
... |
def gcd(a, b):
while b != 0:
(a, b) = (b, a % b)
return a
print(gcd(10, 25))
|
for_low = ""
x = 1
y = 1
p = True
n = "(N)orth"
s = "(S)outh"
e = "(E)ast"
w = "(W)est"
while True:
if y == 1:
change = n + "."
for_low = "n"
if x == 1 and y == 2:
change = n + " or " + e + " or " + s + "."
for_low = "nes"
if x == 2 and y == 2:
change = s + "... |
from Prisoner import Prisoner
"""
TitForTat: a Prisoner who copies their opponent's last choice.
"""
class TitForTat(Prisoner):
"""
This strategy requires remembering the opponent's
last choice, so the class overrides the constructor
to initialize a field to store this information. The
value i... |
"""
Prisoner superclass
"""
class Prisoner():
"""
Constructor. Called once at the start of each match.
If needed, override this method to initialize any
auxiliary data you want to use to determine your
Prisoner's strategy. This data will persist between
rounds of a match but not between match... |
import zipper
def zip_shapefile_simple():
try:
input_shapefile = "C:\\Temp\\Shapefiles\\test.shp"
shape_zipper = zipper.ShapefileZipper()
results = shape_zipper.zip_shapefile(input_shapefile)
if len(results) > 1:
print("SUCCESS... |
import sys
from games import Assano, Triominos
GAMES = {"assano": Assano,
"triominos": Triominos}
def usage():
print("Usage: {} [-h] <game> [<saved data>]".format(sys.argv[0]))
print("Start new game or resume using saved data file.")
print("\nAvailable games:")
for g in GAMES:
pr... |
import turtle
bob = turtle.Turtle()
bob.speed(11)
bob.shape("turtle")
for times in range(300):
bob.forward(times)
bob.right(190)
bob.forward(40)
bob.forward(times)
bob.circle(30)
bob.color("green")
bob.pencolor("yellow")
|
"""
Created on Tue Mar 16 19:11:30 2021
@author: Yeison David Aguirre
"""
def f_titulo():
print("calculo valor factura")
def f_despedida():
print("..... ADIOS ...")
def f_valorfactura():
ve_nomArt = ""
ve_canArt = 0
ve_valUniArt= 0.0
cons_porIva= 0.19
vps_netP... |
def sumdigit(num) :
if int(num/10) == 0 :
return num
return num%10 + sumdigit(int(num/10))
def main() :
num = int(input("Enter any number : "))
sumd = sumdigit(num)
print("Sum of digit of {} is {} ".format(num,sumd))
if __name__ == "__main__" :
main() |
class Base1 :
def __init__(self):
self.i = 10
self.j = 20
print("Inside Base Constructor")
def fun(self) :
print("Inside Base1 fun")
class Base2 :
def __init__(self):
self.x = 30
self.y = 40
print("Inside Base Constructor")
def fun(sel... |
def primeFactors(num) :
i = 2
while (i <= num ) :
if num % i == 0 :
print(i,end=" ")
num = int(num/i)
i = 1
i+=1
print()
def primeFactorsR(num,i) :
if i >= num :
print(i)
return
if (num%i == 0) :
prin... |
import time
import threading
class SumArray :
def add(self,arr,name,lock) :
lock.acquire()
total = 0
for ele in arr :
total += ele
print(f"Running total {name}: ",total)
time.sleep(0.5)
lock.release()
return total
class PThread... |
def isPrime (num) :
for i in range(2,num) :
if num % i == 0 :
return False
return True
def main() :
num = int(input("Enter any number : "))
if isPrime(num) == True :
print("{} is prime number ".format(num))
else :
print("{} is not prime number ".form... |
def demo() :
pass
import functionFile
def main() :
value1 = int(input("Enter num1 : "))
value2 = int(input("Enter num2 : "))
addition = functionFile.add(value1,value2)
subtraction = functionFile.sub(value1 ,value2)
print("Addition of {} and {} is {}".format(value1,value2,addition))
p... |
def student(name, roll, address, marks):
print("Name : ", name)
print("roll : ", roll)
print("address : ", address)
print("marks : ", marks)
def computer(ram, processor, HDD):
print("RAM size : ", ram)
print("processor : ", processor)
print("Hard disk ... |
def fibo(num) :
if num == 0 or num == 1 :
return 1
return fibo(num-1) + fibo(num-2)
def main() :
n = int(input("Enter term to find : "))
print(fibo(n))
if __name__ == "__main__" :
main() |
class Demo :
x=10
y=20
def __init__(self):
print("Inside __init__ (constructor)")
self.i = 30
self.j = 40
def __del__ (self) :
print("Inside destructor ")
def fun(self) :
print("Inside fun")
def main() :
... |
def addition(num1, num2):
ans = num1+num2
return ans
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2)
print("Addition : ",ans)
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2) ... |
def isPalindrome(str) :
if len(str)==0 or len(str)==1 :
return True
if str[0] == str[-1] :
return isPalindrome(str[1:-1])
else :
return False
str = input("Enter string : " )
if isPalindrome(str) == True :
print("Palindrome")
else :
print("Not Palindrome") |
class Demo :
def add(self,no1,no2) :
return no1+no2
def add(self,no1,no2,no3) :
return no1+no2+no3
obj = Demo()
print(obj.add(10,20))
print(obj.add(10,20,30))
|
def no_c(my_string):
if my_string is None:
return
my_list = list(my_string)
for counter in range(len(my_list)):
if my_list[counter] is "c" or my_list[counter] is "C":
my_list[counter] = ""
return(''.join(my_list))
|
def print_matrix_integer(matrix=[[]]):
for row in range(0, len(matrix)):
for line in range(0, len(matrix[row])):
if line == (len(matrix[row]) - 1):
print("{:d}".format(matrix[row][line]), end="")
else:
print("{:d}".format(matrix[row][line]), end=" ")
... |
def simple_delete(a_dictionary, key=""):
if key in a_dictionary:
for counter in a_dictionary:
if counter is key:
del a_dictionary[counter]
return a_dictionary
return a_dictionary
|
def inherits_from(obj, a_class):
"""returns boolean if obj is a subclass of a_class"""
return(issubclass(type(obj), a_class) and type(obj) != a_class)
|
from typing import Optional
class ListNode:
...
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
def helper(
node: ListNode, start: Optional[ListNode], a: int, b: int
) -> ListNode:
reverse_head = node if a == 0 else start
... |
from collections import deque
from typing import Iterable, List, Tuple
class Solution:
def floodFill(
self, image: List[List[int]], sr: int, sc: int, newColor: int
) -> List[List[int]]:
if not image or not image[0]:
return image
limits = len(image), len(image[0])
o... |
from typing import List
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix or not matrix[0]:
return 0
largest = 0
histogram = [0 for _ in range(len(matrix[0]))]
for row in matrix:
for col_index, value in enumerate(row)... |
from collections import Counter
def find_substring(s: str, pattern: str):
pattern_counts = Counter(pattern)
begin = 0
remaining = set(pattern_counts.keys())
best = None
for end, character in enumerate(s):
if character not in pattern_counts:
continue
pattern_counts[char... |
from typing import List
class UnionFind:
def __init__(self, n: int) -> None:
self.uf = list(range(n))
self.lengths = [1] * n
self.components = n
def find(self, i: int) -> int:
if i != self.uf[i]:
self.uf[i] = self.find(self.uf[i])
return self.uf[i]
def... |
class TreeNode:
...
class Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
if root1 is None and root2 is None:
return True
elif root1 is None or root2 is None or root1.val != root2.val:
return False
return (
self.flipEqu... |
from collections import deque
from typing import Iterable, List
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
deadends = set(deadends)
if "0000" in deadends or target in deadends:
return -1
queue = deque([("0000", 0)])
deadends.add("0000"... |
from dataclasses import dataclass, field
from typing import Dict, Optional
TERMINAL = "*"
@dataclass
class TrieNode:
value: str
children: Dict[str, "TrieNode"] = field(default_factory=dict)
class Trie:
def __init__(self):
self.root = TrieNode(TERMINAL)
def insert(self, word: str) -> None:
... |
class Solution:
def shortestWay(self, source: str, target: str) -> int:
source_i = 0
target_i = 0
result = 0
source_chars = set(source)
while target_i < len(target):
if target[target_i] not in source_chars:
return -1
if target[target_... |
from typing import List
def search_bitonic_array(arr: List[int], key: int) -> int:
max_index = binary_search_for_max_index(arr)
return max(
binary_search_exact(arr, key, 0, max_index),
binary_search_exact(arr, key, max_index, len(arr) - 1, True),
)
def binary_search_exact(
arr: List[... |
from typing import List
def make_squares(arr: List[int]) -> List[int]:
squares = []
if not arr:
return squares
left = len(arr) // 2
right = left + 1
while left >= 0 or right < len(arr):
if left >= 0 and (right == len(arr) or abs(arr[left]) < abs(arr[right])):
squares.a... |
class Solution:
def isValid(self, s: str) -> bool:
stack = []
bracket_map = {
")": "(",
"}": "{",
"]": "[",
}
open_brackets = {"(", "[", "{"}
for character in s:
if character in open_brackets:
stack.append(chara... |
from collections import deque
from typing import Iterable, List, Tuple
class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
if not grid or not grid[0]:
return 0
memo = {}
target = len(grid) - 1, len(grid[0]) - 1
queue = deque([(0, 0, 0, k)])
... |
from collections import deque
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
queue = deque([0])
visited = set()
while queue:
start = queue.popleft()
if start in visited:
... |
from typing import Optional
class Node:
...
def find_cycle_start(head: Node) -> Optional[Node]:
fast = head
slow = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if fast != slow:
re... |
from typing import List
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
def place_in_correct_position(value: int) -> None:
while nums[value - 1] not in (value, None):
temp = nums[value - 1]
nums[value - 1] = value
... |
def count_trees(n: int) -> int:
def helper(n: int) -> int:
if n <= 1:
return 1
count = 0
for i in range(n):
count += helper(i - 0) * helper(n - i - 1)
return count
if n < 1:
return 0
return helper(n)
def main():
print("Total trees: " + ... |
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
elif len(needle) > len(haystack):
return -1
target_hash = 0
for i, character in enumerate(needle):
target_hash += ord(character) << (8 * i)
curre... |
from typing import List, Optional, Set, Tuple
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[Tuple[int]]:
return list(get_combination(candidates, target))
def get_combination(
candidates: List[int],
target: int,
current_sum: int = 0,
current_combo: ... |
from collections import deque
from typing import List
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
if not nums:
return []
result = []
window = deque()
def monotonic_append_with_index(i: int) -> None:
while window and nu... |
from typing import List
class FenwickTree:
def __init__(self, array: List[int]) -> None:
self._data = [0] + array[:]
for i, value in enumerate(self._data):
j = i + get_least_significant_bit_value(i)
if j < len(self._data):
self._data[j] += value
def pre... |
from typing import List
def solve_knapsack(profits: List[int], weights: List[int], capacity: int):
def helper(cap: int, current: int) -> int:
if cap < 0:
return 0
elif cap == 0:
return current
best = current
for weight, profit in zip(weights, profits):
... |
"""
Created on Sun Sep 1 21:24:56 2019
@author: ORCAS_ISLAM
"""
People_invitation={}
class Party(object):
def __init__(self , invitation):
self.friend=[]
self.invitation=invitation
def add_friend(self ,f):
self.friend.append(f.getName())
def del_friend(self , f... |
miLista=[1,2,3]
for item in miLista:
print(item)
for item in [4,5,6]:
print(item)
for i in "pepito":
print(i)
for i in range(5):
print (i)
for i in range(5,15,2):
print (f"valor de i: {i}")
|
class Coche():
def __init__(self):
self.largo=2500
self.ancho=1000
self.__ruedas=4
self.enMarcha=True
ventanillas=6
def arrancar(self,arrancamos):
if arrancamos==True:
print("ya esta arrancado")
else:
self.enMarcha=True
... |
miTupla=("item1", 18, "item3")
print(miTupla)
print(miTupla.index("item3"))
miLista=list(miTupla)
print (miLista)
miLista.append(7)
miTupla2=tuple(miLista)
print (miTupla2)
print("item1" in miTupla)
print(miTupla.count(18))
print(len(miTupla2))
miTupla3=("pepe", 13,3,2010)
nombre, dia, mes, anyo = miTupla3
print... |
import unittest
class Math_Dojo:
def __init__(self):
self.result = 0
def add(self, *x):
self.result += sum(x)
return self
def subtract(self, *x):
self.result -= sum(x)
return self
class Math_Dojo_Tests(unittest.TestCase):
def setUp(self):
print... |
import os
import sys
os.system("color e0")
word = input("Give me a word/phrase to turn into a password of at least 10 characters please:\n\n--->")
word = word.lower()
count = len(word)
if count >= 10:
for i in word:
if "e" in word:
word = word.replace("e", "3")
if "a" in ... |
import webbrowser
import time
import sys
import os
os.system("color 3")
tabs = []
end = False
print("""
Here is a list of websites I can open up for you:
1. frederick.blackboard.com
2. hackthebox.eu
3. bugcrowd.com
4. netacad.com
5. overthewire.org
6. Other
""")
done = "NO"
while done == "NO":
... |
def myfunc(a,b):
return sum((a,b))*0.05
print(myfunc(40,60))
def myfunc(a,b,c=0,d=0):
return sum((a,b,c,d))*0.05
print(myfunc(40,60,100))
def myfunc(*args):
print(args)
return sum(args)*0.05
print(myfunc(34,67,34,234))
def myfunc(**kwargs):
print(kwargs)
if 'fruit' in kwargs:
... |
if True:
print("It is True")
hungry = True
if hungry:
print("feed me")
else:
print("i not hungry")
location = "Bank"
if location == "Auto Shop":
print("Cars are cool")
elif location == "Bank":
print("Money is cool")
elif location == "Store":
print("Let go shopping")
else:
print(... |
def newterm(j, size):
if (j < size):
print(end=r"& ")
def printsym(nl, nc=1, sym='a', t='b'):
matrix_style = '{' + t + 'matrix' + '}'
print(end=r"\begin")
print(matrix_style)
for i in range(1, nl+1):
for j in range(1, nc+1):
if(nl == 1)... |
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")
print("Python")
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
print("Lan... |
names = ['aaa', 'bbbb', 'cccc', 'dddd', 'eeeeeee']
great = []
def show_magicians(list):
"""
"""
while list:
current_item = list.pop()
print(current_item)
def make_great(list, great):
while list:
current_item = "Great " + list.pop()
great.append(current_item)... |
usernames = ['apple_27', 'guyonwheels21', 'admin', 'jellybean', 'bananas_23']
for username in usernames:
if username == 'admin':
print("Hello admin, would you like to see a staus report?")
else:
print("Hello " + username + ", thank you for loging in again.")
|
names = ['aaa', 'bbbb', 'cccc', 'dddd', 'eeeeeee']
def show_magicians(list):
"""
"""
while list:
current_item = list.pop()
print(current_item)
show_magicians(names[:])
|
from random import randint
from math import sqrt
DESCRIPTION = 'Answer "yes" if given number is prime. Otherwise answer "no".'
def is_prime(number):
if number % 2 == 0:
return number == 2
d = 3
sqrt_number = sqrt(number)
while d <= sqrt_number and number % d != 0:
d += 2
return d... |
def minimumCheck(applyList):
minWage = applyList[0][0]
minPpl = 1
jobPref = 1
for i in range(len(applyList)):
pplWage = applyList[i][0]
pplJob = 1
for j in range(len(applyList[i])):
if applyList[i][j]<minWage:
minWage = applyList[i][j]
... |
import math
class Circle2D:
def __init__(self,r):
self.__rad = r
@property
def rad(self):
return self.__rad
@rad.setter
def rad(self, r): self.__rad = r
def computerArea(self):
return math.pi*self.__rad**2
def computerCircumferrence(self):
... |
class MessageLengthError(Exception):
def __init__(self, msg):
super().__init__(msg)
def hello(msg):
if len(msg) < 3:
raise MessageLengthError("Length of msg should be >= 3")
print("Hello " + msg)
hello("world")
obj = 123
try:
hello(obj)
except TypeError as err:
print("Error occured, hand... |
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __lt__(self, p2):
if isinstance(p2, Point):
print("Point(%d, %d) < Point(%d, %d)" % (self.x, self.y, p2.x, p2.y))
if (self.x <= p2.x) and (self.y <= p2.y):
return True
... |
class FailedError(Exception):
def __init__(self):
super().__init__()
class ExcellentError(Exception):
def __init__(self):
super().__init__()
def calc_grade(n1,n2,n3):
avg = int((n1 + n2 + n3)/3)
if avg == 0:
raise FailedError()
if avg >= 75:
raise ExcellentE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.