text stringlengths 5 121k |
|---|
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack()
root.mainloop()
|
def prime3(a):
if a < 2: return False
if a == 2 or a == 3: return True
if a % 2 == 0 or a % 3 == 0: return False
maxDivisor = a**0.5
d, i = 5, 2
while d <= maxDivisor:
if a % d == 0: return False
d += i
i = 6 - i
return True
|
import fileinput
for line in fileinput.input(inplace=True):
print(line.replace('Goodbye London!', 'Hello New York!'), end='')
|
def average(x):
return sum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
|
s = ''
if len(s) == 0:
print("String is empty")
else:
print("String not empty")
|
from collections import deque
class Simplemovingaverage():
def __init__(self, period):
assert period == int(period) and period > 0, "Period must be an integer >0"
self.period = period
self.stream = deque()
def __call__(self, n):
stream = self.stream
stream.append(n) ... |
'''Comments stripped with itertools.takewhile'''
from itertools import takewhile
def stripComments(cs):
'''The lines of the input text, with any
comments (defined as starting with one
of the characters in cs) stripped out.
'''
def go(cs):
return lambda s: ''.join(
takew... |
"abcd".startswith("ab")
"abcd".endswith("zn")
"bb" in "abab"
"ab" in "abab"
loc = "abab".find("bb")
loc = "abab".find("ab")
loc = "abab".find("ab",loc+1)
|
import numpy as np
def calculatePowerLevel(x, y, serialNum):
rackId = x + 10
powerLevel = int(str((rackId * y + serialNum) * rackId)[-3:-2]) - 5
return powerLevel
def findMax(array):
max = 0
maxX = -1
maxY = -1
maxLength = None
for x in range(298):
for y in range(298):
... |
sentenct_list = input().split()
length_of_sentence_list = len(sentenct_list)
sum_of_all_words_lengths = 0
for word in sentenct_list:
length_of_word = len(word)
sum_of_all_words_lengths += length_of_word
average_length_of_words_in_sentence = (sum_of_all_words_lengths/length_of_sentence_list)
print(average_lengt... |
from PIL import Image
from os import listdir
import numpy
def main():
images = [];
for fileName in (listdir("images\\")):
images.append(numpy.array(Image.open("images\\" + fileName)));
stacked = numpy.uint8(numpy.median(images, axis = 0));
output = Image.fromarray(stacked);
output.s... |
ws= input('input X=')
op= input('input +-*/:')
ws2=input('input Y=')
x='the dog'
print(x)
print(int(ws)*int(ws2))
|
n = int(input())
nums = []
s = 0
for i in range (0, n):
number = int(input())
nums.append(number)
s = s+number
print(s) |
values = []
s = 0
for i in range (0, 100):
num = int(input())
values.append(num)
s = s+num
print(s)
|
from threading import Thread,Lock
g_num = 0;
def test():
global g_num
for i in range(1000000):
mutex.acquire()
g_num += 1;
mutex.release()
print(g_num)
def test2():
global g_num
for i in range(1000000):
mutex.acquire()
g_num += 1;
mutex.release()... |
class Dog:
__instance = None
__init_flag = False
def __new__(cls, name):
if cls.__instance:
return cls.__instance
else:
cls.__instance = super().__new__(cls)
print('真正的创建')
return cls.__instance
def __init__(self,new_name):
if ... |
class Tool(object):
num = 0
def __init__(self,new_name):
self.name = new_name
Tool.num += 1
self.num2 = 0
self.num2 += 2
t1 = Tool('t1')
t2 = Tool('t2')
t3 = Tool('t3')
print(Tool.num)
print(t1.num2)
print(t2.num2)
print(t3.num2) |
import numpy as np
def funkcja(n):
macierz=np.zeros((n,n))
for i in range(n):
macierz=macierz+np.diag(np.linspace(2*(i+1),2*(i+1),n-i),i)
if (i!=0):
macierz=macierz+np.diag(np.linspace(2*(i+1),2*(i+1),n-i),-i)
return macierz
n=input("podaj rozmiar tablicy:")
n=int(... |
import numpy as np
a=np.array([9,5,1,4,6,2,7,3,5]).reshape(3,3)
b=np.array([1,6,8,4,11,16,9,5,14,10,15,2,13,3,12,7]).reshape(4,4)
print("Pierwsza tablica: ")
print(a)
print("Najmniejsze wartosci kazdego rzedu: ")
print(a.min(axis=1))
print("Najmniejsza wartosc kazdej kolumy: ")
print(a.min(axis=0))
print("Drug... |
import math
print("funkcja y=ax+b")
a=input("podaj liczbe a: ")
a=int(a)
if a > 0:
print("a jest wieksze od 0 zatem funkcja jest rosnaca ")
if a < 0:
print("a jest mniejsze od 0 zatem funkcja jest malejaca")
if a==0:
print("a jest rowne 0 zatem funkcja jest stala") |
from tkinter import*
import random
class rpsGui:
def __init__(self, parent):
self.name_label = Label(parent, text='Rock Paper Scissor')
self.name_label.grid(row=0,column=0,columnspan=2, pady=10)
self.user_entry = Entry(parent, width=12)
self.user_entry.grid(row=1,column=0,padx=5)
... |
def reverse_fun(n):
for i in range(0, len(n)):
n = n[:i] + n[i:][::-1]
return n
|
def solve(s):
res= [0,0,0,0]
for c in s:
if c.isupper():
res[0] += 1
elif c.islower():
res[1] += 1
elif c.isdigit():
res[2] += 1
else:
res[3] += 1
return res |
def descending_order(num):
sorted_num = sorted([d for d in str(num)],reverse=True)
return int("".join(sorted_num)) |
from collections import Counter
def count(array):
return Counter(array) |
import sys
vsize = int(input())
if (vsize % 2 == 0) or (vsize > 100):
print("invalid")
sys.exit()
for i in range(vsize,0,-1):
for j in range(1,vsize+1):
if i == 1:
if j == (vsize+1)/2:
print("v",end="")
else:
print(".",end="")
else:
... |
score_lists = [40,50,60,70,100]
score_tuple = (40,50,60,70,100)
print("Value and this num")
for i,score in enumerate(score_lists):
print("{0}:{1}".format(i,score))
print("specify start and end point of value 1 to 4")
print("list : {0}".format(score_lists[1:4]))
print("tuple : {0}\n".format(score_tuple[1:4]))
pri... |
print([i for i in range(10)])
print(range(10))
print(list(range(10)))
print([i*3 for i in range(10)])
print(list(map(lambda x:x*3,range(10))))
print([i*3 for i in range(10) if i % 2 == 0])
print(list(filter(lambda i:i%2==0,map(lambda x:x*3,range(10)))))
print([i if i % 2 == 0 else "skip 3" if i == 3 else ... |
class A:
def say_a(self):
print("in A")
def say_hi(self):
print("hi A")
class B:
def say_b(self):
print("in B")
def say_hi(self):
print("hi B")
class C(B,A):
pass
instance_c = C()
instance_c.say_a()
instance_c.say_b()
'''
if exist same instance name in multiple i... |
basevalue=15
for a in range(1,basevalue):
for b in range(1,basevalue) :
if a>=b :
print(repr(b).ljust(1)+"x"+repr(a).ljust(1)+"="+repr(b*a).ljust(3),end=' ')
print('')
|
tabla= int(input("Dame un numero del 1 al 9: "))
if tabla >9 or tabla <1:
print("Este valor no es permitido")
else:
for i in range(1,11):
salida= "{} x {} = {}"
print(salida.format(tabla,i,i*tabla))
|
a= int(input())
b= int(input())
temp = a
a = b
b = temp
print("a",a)
print("b",b) |
while True:
a = int(input("Enter a Number"))
if a>100:
print("COngrats You Have Enter Greater Than 100")
break
else:
print("Wrong Input")
continue |
list = []
def function_add(*args):
sum=0
for i in args:
sum=sum+i
return sum
print("Enter numbers you want to add Enter c for REsult")
while(1):
number = input()
if(number == 'c'):
break
list.append(int(number))
summation = function_add(*list)
print(summation)
|
f = open("Hello.txt","w")
f.write("HEy Pagla")
print(f)
f = open("Hello.txt","a")
a = f.write("Sujal sharma")
print(a) |
import turtle
Roger=turtle
def hexagon():
for i in range(6):
Roger.forward(150)
Roger.right(60)
def octagon():
for i in range(8):
Roger.forward(50)
Roger.left(45)
def octagonLoop():
for i in range(80):
octagon()
Roger.right(5)
def dodecagon():
... |
class ListNode(object):
def __init__(self, val=0, next=None):
self.val=val
self.next=next
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
level, current_max=0,0
check_later=list()
if root:
... |
"""
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is '-' or '+'. Read thi... |
"""
Given a non-empty binary tree, return the average value of the nodes on
each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on
level 2 is 11. Hence return [3, 14.5, 11]... |
countries = ['Finland','Sweden','Denmark','Norway','Iceland']
nums = [1, 2, 3, 4, 5]
new_nums = [n ** 2 for n in nums]
print(new_nums)
country_codes = [c.upper()[:3] for c in countries]
print(country_codes)
countries_with_land = [c for c in countries if 'land' in c]
print(countries_with_land)
countries_without_land =... |
is_raining = False
if is_raining:
print('I have to have my umbrella with me')
else:
print('Go out freely')
a = -5
if a > 0:
print('The value is positive')
elif a == 0:
print('The value is zero')
elif a < 0:
print('This is a negative number')
else:
print('It is something else')
... |
countries = ['Finland','Sweden','Denmark','Norway','Iceland']
print(len(countries))
print(countries[0])
print(countries[1])
print(countries[-1])
print(countries[-2])
nums = [1, 2, 3, 4, 5]
new_nums = []
for i in nums:
new_nums.append(i * i)
print(new_nums)
print(list(range(1, 11, 2)))
all_nums = 0
for i in... |
from sys import exit
from cs50 import get_int
card = get_int("What is your credit card number? \n")
temp = card
alt = 0
adj = 0
while temp > 0:
adj = adj + temp % 10
""" the next line is very messy but start from the innermost bracket and u will understand.
i took the alternate digits, multipli... |
import matplotlib.pyplot as plt
true_avengers = pd.DataFrame()
true_avengers = avengers[avengers["Year"] > 1960]
true_avengers['Year'].hist()
col_death = ["Death1","Death2","Death3","Death4","Death5"]
def convdeath(str):
if str == "YES":
return int(1)
else:
return int(0)
... |
Integer = 0
Float = 0
String = "Mikey"
Boolean = True
Array = [1, 3, 4, 8, 76]
Dictionary = {'Papagayo':'objeto', 'Patilla':'fruta'}
Tuple = (12,25)
Array2 =[]
"""if (Integer <= 10):
print("Si es menor a 10")
if (Boolean):
print("Boolean es VERDADERO!!")
else:
print("Esa Vaina es FALSA!!"... |
number = [0, 9, 6, 5, 4, 3, -7, 1, 2.6]
print("-----------")
print(any(number))
print(all(number))
print("-----------")
print(max(number))
print(min(number))
print("-----------")
print(sorted(number))
print(list(reversed(number)))
print("-----------")
print(len(number))
print(abs(number[6]))
p... |
class user :
def normalFunction(self):
print("this is normal function")
print(self)
@classmethod
def functionWithDecorator(cls):
print("this is function with decorator")
print(cls)
example = user()
example.normalFunction()
print("-------------------------------")
example.functi... |
class users :
activeUsersCount = 0
activeUsersList = []
allowedUsers = ["ali", "hossein" , "iman" , "javad" , "sara"]
def __init__(self , userName , userFamily):
self.name = userName
self.family = userFamily
def login(self):
if self.name not in users.allowedUsers :
... |
print("please enter youre rank ")
rank = int(input())
if rank == 1 :
print("you got the GOLD medal ")
elif rank == 2 :
print("you got the SILVER madal ")
elif rank == 3 :
print("you got the BRONZE medal ")
else :
print("ridi")
|
def factorial (n):
f = 1
while (n >0 ):
f = f * n
n = n - 1
return f
print("Input your number")
n= int(input())
print ("factorial of your input number:", factorial(n))
|
import datetime
class Art:
def __init__(self, artist, title, year, medium, owner):
self.artist = artist
self.title = title
self.year = year
self.medium = medium
self.owner = owner
def __repr__(self):
return f"{self.artist}. \"{self.title}\". {self.year}, {self.medium}. {self.owner.name}, {... |
word = input('Enter the word: ')
arr = list(word)
second_word = []
for index in range(len(arr)-1, -1 , -1):
second_word.append(arr[index])
print(second_word)
reversed = ''.join(second_word)
print(reversed)
def is_palindrome():
if(word == reversed):
return True
else:
return False
print(i... |
def fillBuffer(stepLength, steps):
buffer = [0]
currentPos = 0
for i in range(1, steps + 1):
currentPos = (currentPos + stepLength) % len(buffer)
currentPos += 1
buffer.insert(currentPos, i)
return buffer
def findAfterZero(stepLength, steps):
currentPos = 0
lastChanged = 1
for i in range(1, steps +... |
def followPath(dirList):
x = 0
y = 0
for dir in dirList:
if dir == "n":
y += 1
elif dir == "s":
y -= 1
elif dir == "ne":
x += 1
elif dir == "sw":
x -= 1
elif dir == "nw":
y += 1
x -= 1
elif dir == "se":
y -= 1
x += 1
z = 0 - x - y
d = max(abs(x), abs(y), abs(z))
... |
n= int(input())
svar=""
for i in range(n):
c= input()
c= c.split()
product= int(c[len(c)-1])
c = c[0:len(c)-1]
c.sort(reverse = True, key= int)
if (int(c[0]) + int(c[1])) == product:
svar="Possible"
elif (int(c[0]) / int(c[1])) == product:
svar="Possible"
elif (int(c... |
class BaseNode(object):
"""
This class represents the state of a node along with its score (f, g, h) and expand function
This is the class that should be replaced or subclassed to implement other A* problems
"""
ARC_COST_MULTIPLIER = 1
def __init__(self, **kwargs):
self.parent = kwargs.... |
from point import Point
from base_node import BaseNode
class NavNode(BaseNode):
"""
This is a Node implementation that is specific to the "find shortest path" problem
"""
H_MULTIPLIER = 1
board = None
def __init__(self, position, g=None, h=None, parent=None):
super(NavNode, self).__in... |
import os
import csv
'''
读取文件夹下的csv文件
'''
def readAllFiles(filePath):
file_list = []
fileList = os.listdir(filePath)
for file in fileList:
path = os.path.join(filePath, file)
if os.path.isfile(path):
file = open(path, 'r' , encoding='utf-8')
file_list.append(pat... |
import random
def encrypt_bit(number, p, g, y):
k = random.randint(2, p - 2)
a = pow(g, k, p)
b = number * pow(y, k, p) % p
return a, b
def decrypt_bit(crypto_pair, public_key, private_key):
p, _, _ = public_key
x = private_key
a, b = crypto_pair
decrypted = (b * a ** (p - 1 - x))... |
import math
import random
def karatsuba_multiplication(int1, int2):
"""Karatsuba implementation of integer multiplication."""
if isinstance(int1, int):
int1 = str(int1)
if isinstance(int2, int):
int2 = str(int2)
n_int1 = len(int1)
n_int2 = len(int2)
highest_pow_2 = max(2**ma... |
'''
Write a python program which creates a class named Cone and write a
function calculate_area which calculates the area of the Cone.
'''
import math
class ConeArea:
def __init__(self):
pass
def getArea(self, r, h):
return math.pi*r*(r+math.sqrt(h**2+r**2))
coneArea=ConeArea()
radius=i... |
class ReplaceWordsWithLength:
def __init__(self):
pass
def getNewList(self, words):
newList=[str(len(w)) for w in words]
return newList
replacer=ReplaceWordsWithLength()
newList=replacer.getNewList(['A','Dark','Horse','Rode','Through','The','Mountain'])
print("The new list is given belo... |
def wordSmash (a, b):
return a + b
print (wordSmash ("Cat", "Dog"))
print (wordSmash ("Red", "blue"))
print (wordSmash ("qqqqq", "wwwww")) |
import re
def is_valid_number(token):
return bool(re.fullmatch(r"\s*([+-]?((\d*\.)?\d+))(e[+-]?\d+)?\s*", token))
table = {
"0": True,
" 0.1 ": True,
"abc": False,
"1 a": False,
"2e10": True,
" -90e3 ": True,
" 1e": False,
"e3": False,
" 6e-1": True,
" 99e2.5 ": False,... |
from testy import test
class linklistnode:
def __init__(self, d):
self.data = d
self.next = None
def insert(self, d):
n = linklistnode(self.data)
self.data = d
n.next = self.next
self.next = n
def append(self, d):
n = self
new_node... |
import sys
def find_pattern_fast(pattern, text):
"""
Find all the occurrences of the pattern in the text
and return a list of all positions in the text
where the pattern starts in the text.
"""
s = pattern + '$' + text
borders = prefix_function(s)
matches = []
for i in range(len(pattern) + 1, l... |
import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation
num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high = 3500, size= num_house)
np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low... |
from numpy import *
def rmserr( set1, set2 ):
"""Compute and return RMS error for two sets of equal length involving the same set of samples."""
tot = 0.
for i in range(len(set1)):
tot+= (set1[i] - set2[i])**2
return sqrt(tot/float(len(set1)))
def correl(x,y ):
"""For two data sets x and ... |
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def addNode(self, node):
if node.value < self.value:
if self.left == None:
... |
"""
Created on Thu Aug 30 09:45:16 2018
@author: Rafael Bastardo
"""
def linear_congruences_random_generator(X0=3,a=22695477,b=1,m=2**32,throws=1):
"""Function generates a list of random numbers using linear congruences equation X1=(a*X0+b) mod(m)
Default values: a=22695477,b=1,m=2**32 and X0=3, throws=1"""
... |
n = int(input("Starting Number: "))
num_list = [n]
for i in num_list:
if 1 in num_list:
print("".join(str(num_list).strip("[]")))
elif i % 2 == 0:
num_list.append(int(i / 2))
else:
num_list.append(int(i * 3 + 1))
|
while True:
num = int(input("Integer: "))
if num == 0:
print("Bye")
break
if num % 2 == 0 and num in range(20,201) or num % 2 != 0 and num < 0:
print(num, "passes the test!")
else:
print(num, "fails the test :(")
|
rain = input("Is it currently raining? ")
if rain == "Yes":
print("You should take the bus.")
elif rain == "No":
travel = int(input("How far in km do you need to travel? "))
if travel > 10:
print("You should take the bus.")
elif travel in range(2, 11):
print("You should ride your bike.... |
"""
Convert values from one base to another.
Changed from original spec to specify output base in the input stream
rather than the command line. This makes demonstration easier.
"""
import decimal
import re
import string
import sys
DEBUG = True
def baseString(base):
"""Return a Unicode printable version of a... |
import fractions
def without(iterable, remove_indices):
"""
Returns an iterable for a collection or iterable, which returns all items except the specified indices.
"""
if not hasattr(remove_indices, '__iter__'):
remove_indices = {remove_indices}
else:
remove_indices = set(remove_ind... |
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
dummy = ListNode(-1)
dummy.next = head
last = dummy
fast = dummy
for i in range(n+1):
fast = fast.n... |
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
if root == None:
return True
def dfs(root,low=-sys.maxsize,high=sys.maxsize):
if root == None:
return True
val = root... |
class Solution(object):
def reversePairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def merge(nums,left,mid,right):
res = []
start = left
end = mid + 1
while start <=mid and end <= right:
if nums[star... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset_train=pd.read_csv("Google_Stock_Price_Train.csv")
training_set=dataset_train.iloc[:,1:2].values
from sklearn.preprocessing import MinMaxScaler
sc=MinMaxScaler(feature_range=(0,1))
training_set_scaled=sc.fit_transform(trainin... |
a=[1,3,4,2,4,5,4]
b=[3,5,3,5,6,4,3]
def union(a,b):
return a+b or b+a
print(union(a,b)) |
E = int(input("輸入英文成績:"))
M = int(input("輸入數學成績:"))
if E >= 0 and M >= 0 and E <= 100 and M <= 100:
if E >=90 and M >=90:
print("幹的好,有獎品!")
elif E <=60 and M <=60:
print("幹的好,有處罰!!!")
elif M <=60 or E <=60:
print("幹的好,再加油!!")
else:
print("隨便啦,沒獎品喇")
els... |
matplan = { "Kari Nordmann": ["brod", "egg", "polser"],
"Magda Syversen": ["frokostblanding", "nudler", "burger"],
"Marco Polo": ["oatmeal", "bacon", "taco"]}
person = input("Inquire the food plan for a resident, by typing their name: ")
if person in matplan:
print(matplan[person])
el... |
elements = 5
steder = []
for i in range(0, elements):
steder.append(input("Please enter a travel destination and hit ENTER: "))
klesplagg = []
avreisedatoer = []
for j in range(0, elements):
klesplagg.append(input("Please enter a piece of clothing you're bringing: "))
for k in range(0, elements):
... |
def addisjon(number1, number2):
return number1 + number2
def subtraksjon(number1, number2):
return number1 - number2
def divisjon(number1, number2):
assert(number2 != 0),"Division by 0 is illegal"
return number1/number2
def tommerTilCm(antallTommer):
assert(antallTommer > 0), "Inches mus... |
num_1 = input("First number: ")
num_2 = input("Second number: ")
result = int(num_1) % int(num_2)
print("The result is", result) |
def greeting(name):
"""Display a simple greeting"""
print("Hello, " + name.title() + "!")
user_name = input("What's your name?: ")
greeting(user_name)
def describe_pet(pet_name, animal_type='cat'):
"""Display information about a pet"""
print("\nI have a " + animal_type + ".")
print("My ... |
import unittest
from name_function import format_this_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'."""
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work?"""
formatted_name = format_this_name('janis', 'joplin')
self.asser... |
import kay_func as kf
new_list = ['one', 'two', 'three']
print_list = kf.format_list(new_list)
print(print_list) |
class Dog():
"""A simple class example"""
def __init__(self, name, age):
"""Initializes name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sittin... |
import json
filename = 'testing.json'
my_dict = {}
try:
with open(filename, 'r') as file_obj:
if file_obj.read():
print("I read something")
file_obj.seek(0)
my_dict = json.load(file_obj)
test_value_1 = my_dict['... |
from collections import deque
class UndoRedo:
def __init__(self):
self._stack = deque()
self._index = -1
def append(self, num):
self.pop()
self._stack.append(num)
self._index += 1
def pop(self):
l = len(self._stack)
for i in reversed(range(self._in... |
zipCode=input("Enter zipCode:\n")
if len(zipCode) != 5:
print("Invalid Zip: " + zipCode + "\t...expecting 5 digit zip")
exit()
elif (zipCode.isnumeric()) == False:
print("Invalid zip: " + zipCode + "\t...expecting numbers only")
exit()
else:
print(zipCode)
print("The Zip Code is:", zipCode... |
def custom_function(n):
for i in range(1,11):
return n , i, n*i
x,y,z = custom_function(5)
def f_name (fname,lname):
return fname+lname
print(f_name("Prasanth","Ala"))
def q3(*args):
a1=args[0]
a2=args[1]
return a1+" "+a2
arg1=input("Q3a Enter fname value:\n")
arg2=input(... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('data/Advertising.csv')
X = np.array([[147, 150, 153, 158, 163, 165, 168, 170, 173, 175, 178, 180, 183]]).T
Y = np.array([[ 49, 50, 51, 54, 58, 59, 60, 62, 63, 64, 66, 67, 68]]).T
X = np.array([data.values[:, 2]]).T... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def load_dataset(path):
data = pd.read_csv(path, index_col=None)
data = data.sample(frac=1)
labels = list(set(data.values[:, 5]))
X_train = data.values[:100, :]
X_test = data.values[101:, :]
class_1 = X_train[[i fo... |
class Board:
def __init__(self, canvas=None):
self.wide = 355
self.height = 710
self.g = 9.809
self.item = None
self.canvas = canvas
self.loss = 0.55
def paint(self, root):
if self.canvas is None:
return
board = self.canvas(root, bg='... |
def reverseString(string):
'''Returns a string in reverse order'''
print(string[::-1])
reverseString('hi i am chrys') |
import os
from os import path
'''
A small utility to count all the files in a given master folder (main_dir)
- folders donot get added to count
to use (in terminal locally) -
1. go to count_files folder (cd ~/path/to/count_files)
2. type python3 -c "from count_files import main;main('/home/user/path/to/disire... |
def stringapp ():
mainstring = "return List.of("
for i in range (1,601):
i = str(i)
appendstr = ", new rList(" + '"' + "Brijesh" + i + '")'
mainstring = mainstring+appendstr
return mainstring
h=stringapp()
print(h) |
__author__ = "Pär-Love Palm, Felix Steimle, Jakob Wadman, Veit Wörner"
__credits__ = ["Pär-Love Palm", "Felix Steimle", "Jakob Wadman", "Veit Wörner"]
__license__ = "GPL"
__version__ = "0.9b"
__maintainer__ = "Veit Wörner"
__email__ = "veit@student.chalmers.se"
__status__ = "Production"
import numpy as np
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.