text stringlengths 5 121k |
|---|
import pandas as pd
import tweepy
def get_all_tweets(screen_name, number_to_grab = 50):
"""Gather a user's last 3240 tweets (the most that twitter will allow).
To switch to a different number of tweets comment out while lop and switch
count = 200 to count - number_to_grab."""
consumer_key = "... |
import random
print("PASSWORD GENERATOR")
print("==================")
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_.,?0123456789'
number = int(input("Number of passwords to be generated : "))
length = int(input("Password Length : "))
print("Here are your passwords : ")
for pwd in range(num... |
my_name = 'Darkeox'
my_age = 35
my_height = 185
my_weight = 75
my_eyes = 'Dark Brown'
my_teeth = 'White'
my_hair = 'Black'
print("Let's talk about %s." % my_name)
print("He's %d centimeters tall." % my_height)
print("He's %d kilos heavy." % my_weight)
print("Actually, that's not too heavy.")
print("He's got %s e... |
numbers = []
def count_numbers(count):
count += 1
for i in range(0, count):
numbers.append(i)
return 0
count_numbers(int(input("Enter the number you want to count to: ")))
print("The numbers: ")
for num in numbers:
print(num)
|
import random
verbs = input('Number of verbs: ')
adverbs = input('Number of adverbs: ')
nouns = input('Number of nouns: ')
adjk = input('Number of adjectives: ')
f = open("adj.txt", "r")
m = f.readlines()
l = []
n = []
for x in range(int(adjk)):
for i in range(0, len(m)-1):
x = m[i]
z = le... |
menu1={"ข้าวไข่ข้น":35,"ข้าวไก่ย่างเทอริยากิ":45,"ยากิโซบะ":65,"ซาชิมิ":89}
menuList = []
print(menu1)
while True :
menuName = input("please Enter to Menu")
if(menuName.lower() == "exit"):
break
else:
menuList.append([menuName,menu1[menuName]])
def showBill():
print("------... |
day = 14
month = 2
year = 2012
print("%d.%02d.%d" % (day, month, year))
print("%d-%02d-%d" % (year, month, day))
print("%d/%d/%d" % (year, day, month))
|
"""Create three different variables: the first variable should use all lower case characters with
underscore ( _ ) as the word separator. The second variable should use all upper case characters
with underscore as the word separator. The third variable should use numbers, letters, and
underscores, but still be a va... |
"""
Similar to lesson3, exercise4 write a function that normalizes a MAC address to the following
format:
01:23:45:67:89:AB
This function should handle the lower-case to upper-case conversion.
It should also handle converting from '0000.aaaa.bbbb' and from '00-00-aa-aa-bb-bb' formats.
The function should have one... |
"""
Dictionary:
1. Normal variable holds 1 value; dictionary holds collection of key-value pairs; all keys must be distinct but values may be repeated
2. {} - curly bracket
3. Unordered
4. Mutable
5. uses Hashing internally
6. Functions:
1. dict[] : returns value at specified index
2. len() ... |
import util
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def calc_grad(X, Y, theta):
"""Compute the gradient of the loss with respect to theta."""
count, _ = X.shape
probs = 1. / (1 + np.exp(-X.dot(theta)))
grad = (Y - probs).dot(X)
return grad
d... |
plaintext = input('Enter the plain text:-')
alphabets = 'abcdefghijklmnopqrstuvwxyz'
alphabetc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cipher = ''
dicipher = ''
key = input('Enter the key Size:-')
for c in plaintext:
if c in alphabets:
cipher += alphabets[(alphabets.index(c)+int(key))%(len(alphabets))]
else:
cipher += a... |
from datetime import datetime
from toolz.dicttoolz import assoc
def read(db, shop_id):
shop = fetch_shop(db, shop_id)
if shop:
return shop.get('stock_quantities')
else:
return 'error, no shop with that id exists.'
def update(db, shop_id):
date_input_str = input('Enter the date of tod... |
def is_plalindrome(string):
string = list(string)
length = len(string)
left = 0
right = length - 1
while left < right:
if string[left] != string[right]:
return False
left += 1
right -= 1
return True |
"""
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conve... |
name = input("What is your name?")
age = int(input(f"How old are you, {name}"))
if age >= 18:
print("You can vote")
else:
print(f"Come back in {18 - age} years") |
text = "This is awesome."
print(text[8:])
print(text[0:4])
print(text[0:14:2])
print(text[0::2])
print(text[::-1])
print("Hello " * 10)
print("Hello " * 10 + "World!")
print("awe" in text) |
def inherits_from(obj, a_class):
""" Function that returns True if the object is an instance
of a class that inherited
"""
return not (type(obj) == a_class) and isinstance(obj, a_class)
|
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
def testing_max_integer(self):
"""
testing with assetEquals the max_integer function
self: object
"""
self.assertEqual(max_i... |
def uppercase(str):
for i in range(0, len(str)):
upp = ord(str[i])
print("{:c}".format(upp - 32 if upp > 95 else upp), end="")
print("{:s}".format("\n"), end="")
|
from pals.srp import SRPClient, SRPServer, SRPSession
I = 'me@here.com'
P = 'p@$$W0RD'
server = SRPServer()
client = SRPClient(I, P)
server.add_user(I, P)
session = SRPSession(client, server)
session.handshake()
session.validate()
'''
SIMPLIFIED:
0. create user on server
1. start session - public ephemeral ke... |
'''
why in god's name does this work
I gotta go back to math class
what is a modular inverse even
I need to go redo c39 and focus on egcd + invmod
edit 6/12:
Oh, this works because with an exponent of 3 RSA
is just encryption is just cubing a number mod
the public encryption modulus:
c = m ** 3 % n
... and th... |
n=int(input("enter n"))
a=[]
for i in range(0,n):
b=int(input())
a.append(b)
s=a[0]
for i in a:
s=s|i
print(s)
|
n=input("Enter the n:")
for i in n:
if(n.count(i)>1):
print("yes")
break
else:
print("no")
|
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if not ints:
return (None,None)
min_number = ints[0]
max_number = ints[0]
for x in ints[1:]:
if x > max_num... |
n=int(input("enter num"))
a=0
b=1
for i in range(1,n+1):
print(a)
s=a+b
a=b
b=s
|
class LibraryMember:
def __init__(self, name, user_id, messages):
self.name = name
self.user_id = user_id
self.borrowed = []
self.messages = messages
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_... |
class Assignment:
def _init_(self, assignment1, assignment2):
self.assignment = assignment1
self.assignment = assignment2
class Module:
def __init__(self, module1, module2, module3):
self.module1 = module1
self.module2 = module2
self.module3 = module3
class Student:
... |
class Book:
def __init__(self, isbn, library_member, book_damages, title, author):
self.isbn = isbn
self.library_member = library_member
self.book_damages = book_damages
self.title = title
self.author = author
def get_isbn(self):
return self.isbn
d... |
i = 1
while (i <=5):
print("*****")
i +=1
i = int(input("How big is the square? "))
|
n = 0
print(f"You have {n} coins")
answer = "yes"
while answer == "yes":
n += 1
print(f"You have {n} coins")
answer = input("Do you want another (yes/no)? ")
|
temp = float(input('Temperature in C? '))
cel = temp * 9 / 5 + 32
if cel == int(cel):
print(f'Temperature in F is: {cel}')
else:
print(f'Temperature in F is: {int(cel)}')
|
def fibonacci(n):
a = 0
b = 1
if n <= 0:
print("Please enter a number > 0")
exit()
elif n == 1:
return b
else:
for i in range(2,n):
c = a + b
a = b
b = c
return c
print(fibonacci(10))
|
"""
Example for inverting an image. PCV 1.3, Graylevel transforms.
"""
from PIL import Image
from numpy import *
im = array(Image.open('empire.jpg').convert('L'))
im2 = 255 - im
pil_im = Image.fromarray(im2)
pil_im.save('empire_inverted.jpg')
|
def pgcd(a,b) :
while a%b != 0 :
a, b = b, a%b
return b
print(pgcd( 120, 36)) |
__author__ = 'Hernan Y.Ke'
import scrabble
longest=""
for word in scrabble.wordlist:
if list(word) == list(word[::-1]) and len(word) > len(longest):
longest=word
print(longest) |
import pandas as pd
analyze = pd.read_csv('combined_clean.csv')
analyze['dup'] = analyze.Exposure.duplicated(keep=False) & analyze.Exposure.notna()
same_exposure = analyze[analyze['dup'] == True]
same_exposure.to_csv('same_exposure.csv')
advanced = analyze[analyze['Economic Development Status'] ==... |
from collections import Counter
f = open("inputs/Day6.txt", "r")
columns = []
for line in f:
if len(columns) is 0:
for char in line:
if char is not '\n':
columns.append([char])
else:
for index, char in enumerate(line):
if char is not '\n':
... |
from collections import Counter
startRow = ".^.^..^......^^^^^...^^^...^...^....^^.^...^.^^^^....^...^^.^^^...^^^^.^^.^.^^..^.^^^..^^^^^^.^^^..^"
rowLength = len(startRow)
trap = "^"
safe = "."
def check(left, center, right):
if center is trap:
if left is trap and right is safe:
return trap
... |
import copy
def swap(char):
if char is "1":
return "0"
else:
return "1"
def dragon(data, length):
a = data
while len(a) < length:
b = a
b = b[::-1]
b = "".join(map(lambda c: swap(c), b))
a = a + "0" + b
return a
def check(data):
result = ""
... |
from __future__ import print_function
"""Handles parsing and correction of config file for the program"""
import ConfigParser
def check_boolean(section, variable, value, default=False):
"""Check that a config variable is a proper boolean"""
if value in (0, 1, "True", "False"):
return bool(value)
... |
import os
import sys
class String_comparator:
"""
Class String comparator to compare two strings and
return which is greater, less or equal than the other one.
Attributes:
string_1: String 1
string_2: String 2
"""
def __init__(self, s1, s2):
"""
Class constr... |
def mike():
for i in range(0,1):
print("Choose your own adventure")
print("Dad's trip to work")
print("-*-*-*-*-*-*-*-*-*-*-*-*")
print("Lisa gone, Mike could finally start a new adventure.")
print("Should he?")
response_1 = raw_input("Reply: (Y)es (N)o: ")
if response_1.lower == "y":... |
from random import choice
name = ["jack","jill","qwerty","Anuj","Aditya"]
winner = choice(name)
print(winner) |
active = True
print("if you want to quit type quit")
while active:
message = input("Enter your message: ")
if message == 'quit':
active = False
else:
print(message)
|
message = ''
while message != 'quit':
message = input('hi : ')
if message != 'quit':
print(message)
elif message == 'quit':
print('quiting...')
print('Quited') |
user_want = {}
poll_active = True
while poll_active:
name = input('Enter your name: ')
want = input('if you visit one place in the world where you visit? ')
repeat = input('waant to know others wnats (yes,no)? ')
user_want[name] = want
if repeat == 'no':
poll... |
name = input("Enter your username: ")
passcode = input("Enter you password: ")
name = name.upper()
def webdata():
webdata= input("Enter the key word : ")
user_passwords = {
'youtube' : 'subscribe',
'twitter' : 'qwerty',
}
print(user_passwords.... |
with open('C:/Users/Owner/Desktop/rosalind_fibd.txt') as input_data:
n,m = map(int, input_data.read().split())
Rabbits = [1]+[0]*(m-1)
for year in range(1, n):
Bunnies = 0
for j in range(1,m):
Bunnies += Rabbits[(year-j-1)%m]
Rabbits[(year)%m] = Bunnies
Total_Rabbits = sum(Rabbi... |
def canyoudriveacar():
x = input(" what is your name ")
y = int(input(" what is your age "))
if y >= 18:
return" You are eligble to drive a car"
else:
return" You can not eligble drive a car"
print(canyoudriveacar())
def leapyear():
x = int(input(" which year is going on "))
... |
import datetime
a = datetime.date.today()
b = datetime.date(2017,6,27)
c = a - b
s = datetime.timedelta(days = 7)
z=c/s
print(z)
|
import numpy as np
arr = np.array([1,2,3,4,5,6,7,8,9,10])
newarr = arr.reshape(5,2)
print(newarr)
print(newarr+10) |
def findMaxAndMin(sequence):
if len(sequence) < 2:
print("Please create a sequence of at least 2 numbers.")
minNum = sequence
maxNum = sequence
return minNum, maxNum
elif len(sequence) == 2:
sequence.sort()
return sequence[0], se... |
moves=0
fails=0
lives=3
lock=['S', 'S', 'N', 'W', 'E', 'S']
flag=True
lockRecord=0
while flag:
play=input("You are in the magic maze. Which way (N,S,E,W) do you want to go?: ")
moves +=1
lockRecord +=1
if moves <= (len(lock)-1):
if play != lock[lockRecord - 1]:
lockRecord=0
... |
while True:
name = input("Name: ")
if name == "" or name==" ":
print("one for you, one for me")
raise Exception("meaningful message required, you need to put a name")
else:
print(f"{name} : one for {name}, one for me") |
def sum(*arg):
tot=0
for i in arg:
if i>0:
tot +=i
return tot
print(sum(1,2,3,-4,-5,9))
|
def display(*args):
print(args)
Tup=(1,2,3,4,5,6)
Tup1=(7,8,9,10,11,12)
display(Tup,Tup1)
|
import random
n = int(random.random() * 10)
i = int(input("Please enter your number: "))
attempts = 1
while True:
attempts += 1
if attempts == 3:
print("max number of attempts reached.")
break
if i > n:
print("Enter lesser")
elif i < n:
print("Enter higher")
else:... |
def is_compliant(psswrd:str)->bool:
return len(psswrd)>=8 and any(chr.isdigit() for chr in psswrd)
def main():
psswrd=input("Password: ")
if is_compliant(psswrd):
print("OK")
else:
print("Wrong")
if __name__ == '__main__':
main() |
import re
def rgb(r, g, b):
for i in [r,g,b]:
if r > 255: r = 255
elif r < 0: r = 0
elif g > 255: g = 255
elif g < 0: g = 0
elif b > 255: b = 255
elif b < 0: b = 0
t = "#{:02x}{:02x}{:02x}".format(r,g, b)
result = re.findall('[a-z0-9]', t)
result1 = ''.join(result)
return res... |
def tuner(frequency, seenbefore, tuned):
with open('input.txt', "r") as inputfile:
while tuned == False:
inputline = inputfile.readline()
if inputline == "":
return frequency, seenbefore, tuned
direction = str(inputline[0])
... |
"""Here are the tests with string"""
def test_string_length_and_space(string_prepare, random_number):
"""Test checks the length of string, depending on random text length,
and that string does not start with a space"""
assert len(string_prepare) == 22 + random_number
assert not string_prepare.startswi... |
"""
Trie Implementation
Kyle Schmidt
Insight Data Engineering Coding Challenge
"""
from typing import Optional, Tuple
class Node(dict):
def __init__(self, label: Optional[str]=None):
"""
Node class representing a value in the Trie class.
Node inherits from dict providing dictionary funct... |
import random
from words import words
class Hangman:
def __init__(self):
self.word = random.choice(words)
self.display = ['_' for letter in self.word]
self.guesses = 0
def show(self):
display = ' '.join(self.display)
print(f'the word is: {display}')
def get_wo... |
for i in range(1,6):
for x in range(i):
print("*",end=" ")
print("\n")
|
'''
Create a queue data structure. The queue
should be a class with methods 'enqueue' and 'dequeue'.
--- Examples
q = Queue()
q.enqueue(1)
q.dequeue() # returns 1;
'''
class Queue:
''' A rudimentary queue '''
def __init__(self):
self.lst = []
def enqueue(self, elem):
self.ls... |
class Queue:
def __init__(self):
self.data = []
def enqueue(self, elem):
self.data.insert(0, elem)
def dequeue(self):
try:
return self.data.pop()
except:
return None
def peek(self):
try:
return self.data[-1]
excep... |
import re
from abc import ABC
from abc import abstractmethod
class Validatable(ABC):
@abstractmethod
def validate(self, item):
pass
class Validator(ABC):
def __init__(self, *validators):
self.__validators = validators
def validate(self, item):
return all(map(lambda x: x.val... |
from plotspikes import plotspikes
from matplotlib import pyplot as plt
import numpy as np
def main():
"""Example how to use plotspikes"""
plt.figure(0, figsize=(15,3))
np.random.seed(22)
xsignal = 20 * np.arange(100)
ysignal = 6. + np.cumsum(np.random.randn(100))
plt.plot(xsignal, y... |
board = [ [5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
... |
import sklearn
from sklearn.preprocessing import StandardScalar
sc_X = StandardScalar()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
|
import numpy as np
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums1.extend(nums2)
nums1.sort()
return np.median(nums1)
nums1 = [1, 2]
nums2 = [3,4]
myS... |
class ListNode(self,x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self,l1,l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
numbers=[0,0]
for i in range(2):
idx = 0
if i == 0:
... |
class Solution:
def sortColors(self,nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
r = 0
w = 0
b = len(nums)-1
while w <= b:
if nums[w] == 0:
nums[r], nums[w... |
'''
%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)
'''
name = "John Cenna"
age = 30
pr... |
import csv
import sys
try:
with open('sample09.csv', 'w', encoding='utf8') as csvfile:
writer = csv.writer(csvfile, lineterminator='\n')
writer.writerow(["a","b","c"])
writer.writerow(['あ','い','う'])
with open('sample09.csv', 'r', encoding='utf8') a... |
from tkinter import *
import random
root = Tk()
root.geometry("300x350")
root.title("Rolling Dice")
photo = PhotoImage(file = "dice5.png")
root.iconphoto(False, photo)
header = Label(root, text="Hello..!!", font="Times 25 bold")
header.pack(pady=10)
dice = ['dice1.png','dice2.png','dice3.png','dice4.png','dice5.png... |
from module.utils import snaptogrid
from math import cos,sin,radians
def poly(radius, sides,a,s,ggg):
x = []
y = []
i = 1
if s == 4 :
i2 = 45+90
elif s == 8:
i2 = 22.5
while i < sides + 1 :
x.append(snaptogrid(radius*cos(radians(a+i2)),g... |
'''
你需要管理大量数据,使用零基础和非负ID来使每个数据项都是唯一的!
因此,需要一个方法来计算下一个新数据项返回最小的未使用ID...
注意:给定的已使用ID数组可能未排序。出于测试原因,可能存在重复的ID,但你无需查找或删除它们!
def next_id(arr):
#your code here
测试用例:
verify.assert_equals(next_id([0,1,2,3,4,5,6,7,8,9,10]), 11)
verify.assert_equals(next_id([5,4,3,2,1]), 0)
verify.assert_equals(next_id([0,1,2,3,5]), 4... |
import os
def rename_files():
file_list = os.listdir(r"C:\Users\shahid\Downloads\Compressed\prank")
save_path = os.getcwd()
print("Current Working Directory is"+save_path)
os.chdir(r"C:\Users\shahid\Downloads\Compressed\prank")
for fil... |
import mysql.connector;
print("establish connection with mysql now");
con = mysql.connector.connect(host="localhost",
database="employee",
user="root",
password="");
print("connection mydb",con);
eno=input("enter employee... |
import random as rn
import numpy as np
import matplotlib.pyplot as plt
import sys
def main():
print("-- Central Limit Theorem Demonstration --\n")
dim = int(raw_input("Sample Size: "))
N = int(raw_input("N Random Samples: "))
b = int(raw_input("# Bars in Histogram: "))
Plot_Data(Gaussian_Distrib... |
class Servicio:
def __init__(self,nombre,servidor):
self.nombre=nombre
self.servidor=servidor
def __str__(self):
return "Soy el servicio: "+self.nombre +", disponible en el servidor: "+self.servidor
un_servicio=Servicio("Google","google.es")
print(un_... |
class Solution:
def hIndex(self, citations: List[int]) -> int:
n = len(citations)
counts = [0]*(n+1)
for item in citations:
if item>=n:
counts[n]+=1
else:
counts[item]+=1
papers = 0
for i in range(n,-1,-1):
... |
"""
@Time : 2020/4/19 16:32
@Author : LiuYanZhe
@File : test1.py
@Software: PyCharm
@Description:
"""
import numpy as np
from scipy.optimize import minimize
import pandas as pd
def test_zip():
np1 = np.random.rand(5, 2)
print(np1)
for a, b, c in zip([np1[:, 0], np1[:, 1]], ['red', 'blac... |
"""
@Time : 2020/5/6 17:08
@Author : LiuYanZhe
@File : test_data.py
@Software: PyCharm
@Description: 关于数据的测试
"""
import pandas as pd
import numpy as np
def test_pd1():
df = pd.read_csv('../data/History_country_2020_05_06.csv')
list1 = df[df.name == '突尼斯'].index.tolist()
df2 = df.iloc[list1[0]:list1[len... |
def insertion_sorting(array):
for index in range(1,len(array)):
sorting_part=array[0:index+1]
unsorting_part=array[index+1:]
temp=array[index]
i=index-1
while(((i>0 or i==0) and array[i]>temp)):
sorting_part[i+1]=sorting_part[i]
sorting_part[i]=temp
... |
def cost_ground_ship(weight):
flat_charge = 20.00
if weight <= 2:
return flat_charge + 1.50 * weight
elif 2 < weight <= 6:
return flat_charge + 3.00 * weight
elif 6 < weight <= 10:
return flat_charge + 4.00 * weight
else:
return flat_charge + 4.75 * weight
def cost_drone_ship... |
import numpy
from numpy import *
a = []
for i in range(1,6):
print(i)
a.append(i)
print(a)
a.append("hello")
print(a)
|
from visual import sphere,color
count = 3
R=0.3
for x in range(-count,count+1):
for y in range(-count,count+1):
for z in range(-count,count+1):
if ((x+y+z)%2) == 0:
sphere(pos=[x,y,z],radius=R,color=color.green)
else:
sphere(pos=[x,y,z],radius=R,colo... |
def StartDynamic(No,message = "Jay Ganesh"):
iCnt = 0
while iCnt < No:
print(message)
iCnt = iCnt + 1
def main():
print("How many times do you want output:")
no = int(input())
print("Enter a message you want to print:")
msg = input()
StartDynamic(no,msg)
Star... |
def main():
name = input("Enter the name of file:")
fobj = open(name,"w")
str = input("Enter the data you want to write in file")
fobj.write(str)
if __name__ == '__main__':
main()
|
def main():
no1 = int(input("Enter first number: "))
no2 = int(input("Enter second number: "))
ans = no1 / no2
print("Divison is: ",ans)
if __name__ == '__main__':
main()
|
def main():
no1 = int(input("Enter first number: "))
no2 = int(input("Enter second number: "))
try:
ans = no1 / no2
except Exception as eobj:
print("Exception occurs:",eobj)
else:
print("Divison is: ",ans)
if __name__ == '__main__':
main()
|
import MrvellousNumber as mn
def main():
no = int(input("Enter a number:"))
bRet = m.chkEven(no)
if bRet == True:
print("No {} is even".format(no))
else:
print("No {} is odd".format(no))
if __name__ == "__main__":
main()
|
def DisplayL(list):
iCnt = 0
for iCnt in range(len(list)):
print(list[iCnt])
def main():
arr = [10,20,30,40,50]
print(arr)
print(arr[3])
Brr =[10,"Manali",66.48,"Pune"]
print(Brr)
DisplayL(arr)
if __name__ == "__main__":
main()
|
import sys
from math import sin, cos, acos, radians, sqrt, pi
import json
from control.util import get_abs_path
USAGE = '%s lat lon' % sys.argv[0]
IN_FILE = get_abs_path('stations.json')
def get_angle(lat1, lon1, lat2, lon2):
return acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(lon2 - lon1))
... |
import copy
'''
SHALLOW COPY METHOD
'''
old_list = [[1,2,3],[4,5,6],[7,8,9]]
new_list=copy.copy(old_list)
print ("old_list",old_list)
print ("new_list",new_list,"\n")
old_list.append([999])
print ("old_list",old_list)
print ("new_list",new_list,"\n")
old_list[1][0]="x"
... |
a = []
b = []
c = []
def move(n, x, y, z):
if n > 0:
move(n - 1, x, z, y)
z.append(x.pop())
print('Move:', a, b, c,sep='\n')
move(n - 1, y, x, z)
def main():
global a
a = [3, 2, 1]
print(a, b, c,sep='\n')
move(3, a, b, c)
if __name__ == '__main__':
main()
|
from abc import ABC, abstractmethod
from p6_2 import Stack
from p6_3 import Queue
class A(ABC):
@abstractmethod
def add(self, x):
pass
@abstractmethod
def pop(self):
pass
@abstractmethod
def empty(self):
pass
class AStack(A):
def __init__(self, n):
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.