text stringlengths 37 1.41M |
|---|
from math import inf, sqrt
from heapq import heappop, heappush
def find_path (source_point, destination_point, mesh):
"""
Searches for a path from source_point to destination_point through the mesh
Args:
source_point: starting point of the pathfinder
destination_point: the ultimate goal t... |
class Course:
"""
this is course class for the program
it contains information of each course
Contain parameters:
name -- string -- static
admin -- user(User.py) -- static
term -- string -- static
topic[] -- Topic(Topic.py)
Contain functions:
c... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
_ = int (input())
set_n =set(map(int, input().split()))
_ = int(input())
set_b =set(map(int, input().split()))
new_set=set_n.union(set_b)
print(len(new_set))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import OrderedDict
a_list=OrderedDict()
n = int(input())
for i in range(n):
inp = input()
if type(inp) !=int:
isplit = inp.split()
cost= isplit[-1]
item = isplit[:-1]
item = " ".join(it... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n, x =(map (int, input().split()))
grades_by_subject = []
for _ in range (x):
grades_by_subject.append(map(float, input().split()))
for grades_by_student in zip(*grades_by_subject):
print(sum(grades_by_student)/len(grades_by_subject))
|
from sklearn import datasets
boston = datasets.load_boston()
# This data is similar to a dictionary
# Contains 4 keys
# 1. data: data for all the features
# 2. feature_names: column names
# 3. DESCR: a description of the dataset
# 4. target: the dependent variable/MEDV/median home value in thousands
boston.keys()
#... |
import pickle
import streamlit as st
import math
# loading the trained model
pickle_in = open('classifier.pkl', 'rb')
classifier = pickle.load(pickle_in)
@st.cache()
# defining the function which will make the prediction using the data which the user inputs
def prediction(Gender, Married, Dependents... |
# --*-- encoding:utf-8 --*--
'''
求导数为0时,自变量的值
'''
def f_prime(x_old):
return -2 * x_old + 3
def cal():
x_old = 0 # 导数为0时,x的初始值
x_new = 50 # 导数为0时,x的估计值
eps = 0.4
presision = 0.00001
while abs(x_new - x_old) > presision: # abs 返回绝对值 上一次求导的值减去本次求导的值,如果趋势是0,则认为极值存在
x_old = x_new
... |
import random
class Card(object):
def __init__(self, suit, value, isHidden):
self.suit = suit
self.value = value
self.hidden = isHidden
if (value == 'A'):
self.pointValue = 11
elif (value in ['J', 'Q', 'K']):
self.pointValue = 10
elif (value ... |
import pygame
import random
import Lists
def create_path(length, randomized=True, preset=None):
""" Creates a sequence of Numbers correlating to directions that the Player can follow,
without going back on themselves."""
if randomized:
path = [random.randint(1, 4)]
L = (0, (1, 2, 4), (1, ... |
def main():
lenght = int(input('Lenght: '))
array = [None] * lenght
for i in range(lenght):
array[i] = int(input('Item {}: '.format(i)))
print('Source array: ', array)
for i in range(lenght):
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
... |
from machine import ADC,Pin
from utime import sleep
temp_sensor = ADC(4)
temperature = temp_sensor.read_u16()
to_volts = 3.3 / 65535
temperature = temperature * to_volts
celsius_degrees = 27 - (temperature - 0.706) / 0.001721
print (celsius_degrees)
led = Pin(25, Pin.OUT)
led.on()
message = input("enter text to deciphe... |
import L8_12_test
def run_grader(student_func):
grade_result = dict()
try:
result = L8_12_test.tests(student_func)
correct = result == 0
comment = ""
if result == 0:
comment = ""
elif result == 1:
comment = "There was an error running yo... |
s=str(input("ingrese una letra:"))
a=list("hola mundo")
b=tuple("hola mundo")
c=set("hola mundo")
print(a)
print(b)
print(c)
print("pertenecia de tuplas:",s in a)
print("contaremos cuantas letras o existen en la lista:",a.count("o"))
x=c.copy()
print("la copia del set:",x)
y=a.reverse()
print("la lista inve... |
import csv
MY_FILE = "../data/sample_sfpd_incident_all.csv"
def parse(raw_file, delimiter):
"""Parses a raw CSV file to a JSON-line object."""
parsed_data = []
# Abrir archivo CSV
opened_file = open(raw_file)
# Leer archivo CSV
csv_data = csv.reader(opened_file, delimiter=delimiter)
#... |
mydict={
"Name":"Prathap",
"Place":"Hyderabad",
"Location":"KPHB"
}
#print(mydict['Name'])
#loop
# for x in mydict:
# print(x)
#Get only keys
for x in mydict.keys():
print(x)
print("***********************************")
for x in mydict.values():
print(x)
print("**********************... |
class School:
place="Hyderabad"
location="KPHB"
def addStudent(self):
print("Add Student to the school")
def delStudent(self):
print("deflete student from the school")
obj=School()
obj.addStudent()
obj.delStudent()
print(obj.place)
print(obj.location)
|
num = int(input())
for i in range(num) :
number = input()
if(number[0] == "9" or number[0] == "7" or number[0] == "8") :
if(number.isdigit() == False) :
print("NO")
elif(len(number) == 10) :
print("YES")
else:
print("NO")
else :
print("NO")... |
try:
name = input("Enter your name : ")
income = int(input("Enter your yearly Income : "))
income_per_month = income / 12
print(f"Hello {name}")
print(f"This is your monthly income : {income_per_month}")
#in except you have to specify the type of exception that can generate in your code
except ... |
name = input("Enter your name : ")
last_name = input("Enter your last name : ")
#formatting String in python
result = f'{name} {last_name} is learning python programming'
print(result)
#without String formatting
print("hello " + name + " How are you ?")
print('python\'s course for Bignners') |
num_1 = float (input ())
num_2 = float (input ())
result = num_1 / num_2
print(int(result))
print(result) |
# 7.2.1 Add a 'cow' to the list
list1.append('cow')
list1
# 7.2.2 Add 'chicken' and 'pig'
list1.extend(['chicken', 'pig'])
list1
# 7.2.3 Remove the 'dog'
list1.remove('dog')
list1
# 7.2.4 Remove and return the cat
foo = list1.pop()
print("foo is: " + foo)
list1
|
#A sample dataset for a recommendation engine for coffee
from math import sqrt
class recommendation():
people={
'mathura':{'CCD':2,'Kaapi':5,'Joes':5,'Starbucks':1},
'madhu':{'CCD':1,'Kaapi':5,'Joes':5},
'shroom':{'CCD':3,'Kaapi':5,'Joes':5,'Starbucks':4},
'sam':{'Kaapi':5,'Joes':5},
'mathur':... |
class Solution:
def isMatch(self, string: str, pattern: str) -> bool:
def match(string, pattern):
if not pattern:
return not string
initialMatch = bool(string) and pattern[0] in {string[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
... |
import math
class Solution:
def reverse(self, x: int) -> int:
maxint_32 = 2**31 - 1
minint_32 = -1*(2**31)
negative = True if x < 0 else False
if(negative): x *= -1
if(x < 10):
return x
reversedInt = 0
while x >= 1:
reversedInt *= 10
... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
from scipy.interpolate import splprep, splev
from scipy.optimize import minimize
import time
class LongitudinalController:
'''
Longitudinal Control using a PID Controller
functions:
PID_step()
control()
... |
import json
from copy import deepcopy
class Namespace(dict):
"""
A convenience class that makes a json like dict of (dicts,lists,strings,integers)
looks like a python object allowing syntax sugar like mydict.key1.key2.key4 = 5
this object also looks like a dict so that you can walk items(), keys() o... |
# -------------------------------------------------------------------------------
# Type conversion
# -------------------------------------------------------------------------------
def is_float(string):
"""Check whether string is float.
See also
--------
http://stackoverflow.com/questions/736043/che... |
from sklearn.neighbors import KDTree
import numpy as np
import pandas
from matplotlib import pyplot as plt
class DBSCAN:
"""
Implementation of dbscan clustering algorithm.
"""
NOISE = -1
UNDEFINED = -2
def __init__(self, min_samples=4, eps=0.1, metric="euclidean"):
"""
saves p... |
def add_numbers(num1, num2):
return num1 + num2
def subtract_numbers(num1, num2):
return num1 - num2
def multiply_numbers(num1, num2):
return num1 * num2
def divide_numbers(num1, num2):
return num1 / num2
def main():
print("calculator module 2")
if __name__ == "__main__":
main() |
#!/usr/bin/env python
'''
Author : Jonathan Lurie
Email : lurie.jo@gmail.com
Version : 0.1
Licence : MIT
description : Send a email using python. Based on
https://flenniken.net/blog/send-email-using-python-and-1and1/
'''
import smtplib
from email.mime.text import MIMEText
def sendMai... |
from os import makedev
import sys
def makeNumberNice(number, length):
addon = ""
if(number[0] == '-'):
addon = "-"
number = number.replace("-", "")
while(len(number) < length):
number = "0" + number
number = addon + number
return number
if __name__=="__main__":
#qui... |
import unittest
from count_letters import count_letters
class TestCountLetters(unittest.TestCase):
def test_count_letters_one_letter(self):
self.assertEqual(count_letters("a"),{"a":1})
def test_count_letters_another_letter(self):
self.assertEqual(count_letters("b"),{"b":1})
d... |
# Write a recursive function that takes one parameter: n and adds numbers from 1 to n.
try:
def adder(number):
if number == 1:
return 1
elif number > 1:
return number + adder(number-1)
else:
return number + adder(number+1)
print(adder(9))
except Recur... |
import unittest
from fibonacci import fibonacci
class TestFibonacci(unittest.TestCase):
def test_fibonacci(self):
self.assertEqual(fibonacci(5), 5)
def test_fibonacci_one(self):
self.assertEqual(fibonacci(1), 1)
def test_fibonacci_zero(self):
self.assertEqual(fibonacci(0), 0)
... |
# Write a program that opens a file called "my-file.txt", then prints
# each of lines form the file.
# If the program is unable to read the file (for example it does not exists),
# then it should print an error message like: "Unable to read file: my-file.txt"
my_file = "week-03/day-01/my-file.txt"
def line_printer(file... |
# Write a program that reads a number from the standard input, then draws a
# pyramid like this:
#
#
# *
# ***
# *****
# *******
#
# The pyramid should have as many lines as the number was
a = int(input("Please enter a number: "))
for i in range(1,a+1):
print(" "*(a-i) + "*"*(i*2-1)) |
# Write a program that asks for a number.
# It would ask this many times to enter an integer,
# if all the integers are entered, it should print the sum and average of these
# integers like:
#
# Sum: 22, Average: 4.4
sum_list = []
many = int(input("How many number would you like? "))
while many <= 0:
many = int(inp... |
# Crate a program that draws a chess table like this
#
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
# % % % %
#
a = int(input("Please enter a number: "))
while a <= 0:
a = int(input("Please enter a bigger number: "))
if a > 0:
if a == 1:
print("%")
elif a%2 == 0:
... |
# Write a program that reads a number from the standard input, then draws a
# diamond like this:
#
#
# *
# ***
# *****
# *******
# *****
# ***
# *
#
# The diamond should have as many lines as the number was
a = int(input("Please enter a number: "))
for i in range(1,(a+1)//2+1):
print(" "*((a+1)//2-i)+"*... |
from tkinter import *
root = Tk()
canvas_width = 300
canvas_height = 300
canvas = Canvas(root, width=canvas_width, height=canvas_width)
canvas.pack()
# create a line drawing function that takes 2 parameters:
# the x and y coordinates of the line's starting point
# and draws a line from that point to the center of t... |
# Write a program that asks for 5 integers in a row,
# then it should print the sum and the average of these numbers like:
#
# Sum: 22, Average: 4.4
a = int(input("First number: "))
b = int(input("Second number: "))
c = int(input("Third number: "))
d = int(input("Fourth number: "))
e = int(input("Fifth number: "))
Sum ... |
from tkinter import *
root = Tk()
canvas_width = 300
canvas_height = 300
canvas = Canvas(root, width=canvas_width, height=canvas_width)
canvas.pack()
# reproduce this:
# [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/envelope-star/r2.png]
center = canvas_width//2
def half_envel... |
def main():
j = 0
for i in range(10):
j += i
print("Ends with '!'", end=" Ending...\n")
print("Another", "Example")
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
"""
Python Language Converter(PLC)
Converts Source Code from language A to B
"""
from error import Error
from logger import Logger
from file_path import FilePath
from language import Language
from code_processor import CodeProcessor
# Initialize plc_logger
plc_logger = Logger("PLC")
# Create v... |
from random import randint
valik=input('''Kas soovite istekohta ise valida ("ise") või loosida ("loos")? ''')
if valik == "ise":
asukoht=input('''Kas soovite istuda akna ääres ("aken") või mitte ("muu")? ''')
if asukoht == "aken":
print("Valisite ise. Aknakoht")
else:
print("Valisite ise. V... |
#Soal Satu
""" def find_short(s):
lst = s.split()
shortest = len(lst[0])
for l in lst:
if len(l) < shortest:
shortest = len(l)
return(shortest)
print(find_short("Create new file after this morning")) """
#Soal Dua
""" def persistence(n):
count = 0
product = n
... |
import matplotlib.pyplot as plot
import math
"""
Ce module a été écrit par Pacôme Perrotin en octobre 2021 pour le projet Mazes.
Ce module met à votre disposition des fonctions d'affichages de labyrinthes,
qui utilisent pyplot.
Les fonctions qui vous seront utiles sont draw_tree, draw_square_maze et
draw_hex_maze. ... |
#!/usr/bin/env python3
from re import sub
def check_ch(a, b):
if a.lower() == b.lower():
if (a.isupper() and b.islower()) or (a.islower() and b.isupper()):
return True
return False
def reactor(data):
newdata = ""
for ch in data:
if newdata != "" and check_ch(ch, newdat... |
#!/usr/bin/env python3
from re import findall
def create_boards(data):
boards = []
b = {'nums': set(), 'board': [], 'id': None}
a = []
i = 0
for l in data:
if l != '':
row = list(map(int, findall(r'\d+', l)))
a.append(row)
for j in row:
b... |
#!/usr/bin/env python3
import aocUtils
def part1(data):
_increases = 0
# set first value to curr_val
curr_val = data[0]
# iterate over the remaining values in data, check if they are greater than
# curr_val, and set v as curr_val for the next loop
for v in data[1:]:
if v > curr_val:
... |
#!/usr/bin/env python3
from collections import Counter, defaultdict
def main():
with open('input', 'r') as fp:
data = fp.read()
houses = defaultdict(lambda: 0)
sx = sy = rx = ry = 0
houses[(0, 0)] += 2
odd = True
for step in data:
if odd:
if step is '>':
... |
# Ab aap ek program likhoge jo ki user se ek integer input lega aur fir uska factorial
# print karega. Agar user 3 dalega to 6 print karega, 7 dalega toh 5040 print karega aur
# aise hi dusre numbers ke lie. Note: Abhi ke liye yeh soch lo ki user sirf positive integers
# hi dalega. Negative integers kabhi nahi daleg... |
class Item:
def __init__(self, category = "", condition = 0):
self.category = category
self.condition = condition
def __str__(self):
"""
Stringfy method
Returns:
String: Return default string Hello World!
"""
self.default_str = "Hello... |
'''
Created on Apr 10, 2016
@author: Sameer Adhikari
'''
from string import uppercase
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
answer = ''
while n:
r = (n - 1) % 26
answer = uppercase[r] + answer
... |
'''
Created on Apr 22, 2016
@author: Sameer Adhikari
'''
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n = len(nums)
start = 0
end = n - 1
mididx = None
... |
'''
Created on Apr 10, 2016
@author: Sameer Adhikari
'''
from string import ascii_lowercase
from operator import or_ # logical or
class Solution(object):
def maxProduct(self, words):
"""
:type words: List[str]
:rtype: int
"""
if not words:
return 0
... |
'''
Created on Jul 16, 2016
@author: Sameer Adhikari
'''
class Point(object):
"""
Class that represents a two dimensional point.
"""
def __init__(self, x=0.0, y=0.0):
"""
Create a point, with a default at origin.
Args:
x (float): x-axis coordinate for the point.
... |
'''
Created on May 17, 2016
@author: Sameer Adhikari
'''
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
n1 = x
n2 = 0
while n1 > 0:
n2 = (n2 * 10) + (n1 % 10)
n1 = n1 // 10
pr... |
'''
Created on Feb 28, 2016
@author: Sameer Adhikari
'''
'''
Given a MxN array in the form of list of lists.
array[x][y] == 1 => can step in the cell.
array[x][y] == 0 => cannot step in the cell.
Starting point is array[0][0].
Ending point is array[M-1][N-1].
Only movement is either right or down.
Find all paths from... |
def fib(x):
if x==0 or x==1:
return 1
else:
return fib(x-2)+fib(x-1)
print fib(33)
|
def xbin(x): # return integer as string in binary
if x <= 0:
return "0"
else:
if (x&1 == 0):
s = "0"
else:
s = "1"
x = x >> 1
while (x > 0):
if (x&1 == 0):
s = "0" + s
else:
s = "1" + s
x = x >> 1
return s
print xbin(23)
|
def hi(a, b, c):
if a < b < c:
print '< true'
else:
print '< false'
if a > b > c:
print '> true'
else:
print '> false'
hi(1, 2, 3)
hi(3, 2, 1)
hi(1, 2, 1)
hi(2, 1, 2)
|
# This program is used to invite any customer within 100km of
# Intercom's Dublin office for some food and drinks.
# The GPS coordinates for our Dublin office are 53.339428, -6.257664.
#
# To run the code, please run python invite_customer.py
from invite_customer_helper import get_customer_id_name_list, get_customer_l... |
#!/usr/bin/python
#
# Created by Albert Au Yeung (2010)
#
# An implementation of matrix factorization
#
import numpy as np
###############################################################################
"""
@INPUT:
R : a matrix to be factorized, dimension N x M
P : an initial matrix of dimension N x K... |
import random
def get_special(num_special, my_list):
specials = []
while num_special > 0:
index = random.randint(0,len(my_list) - 1)
while my_list[index] in specials:
index = random.randint(0, len(my_list)-1)
specials.append(my_list[index])
num_special = num_sp... |
# First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
csvpath = os.path.join('..', 'Resources', 'budgetdata.csv')
# defining the variables, and lists
mcount = 0
nettotal = []
months = []
netchangelist = ... |
'''In this Program- we will convert Days to Hours or Minutes.
So user can input two parameters in this format-1:hours or 1:minutes.'''
def days_to_units(num_of_days,conversion_unit):#function for conversion.
if conversion_unit == "hours": # if user input is nimber of days and hours-apply this formula.
... |
person=('Birju Vachhani',21) #tuple packing
(name, age)=person #tuple unpacking
print(name)
print(age)
a=(5,6)
b=(5,7)
#tuple comparison
if a>b:
print('a is bigger')
else:
print('b is bigger')
c=(1,2,3,4,5,6,7)
print(c[1:5]) #tuple slicing
#tuple as dictionary key
d={('birju','vachhani'):1403701160655}
print... |
pattern = 'X-DSPAM-Confidence'
file_name = input('Enter the file name to read from(with extension):')
confidences = list()
try:
with open(file_name) as f:
for line in f:
line_parts = line.strip().split(':')
if line_parts[0] == pattern:
confidences.append(float(line_pa... |
class Employee():
e_count = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.e_count += 1
def get_emp_data(self):
return 'Name: {}\nSalary: {}'.format(self.name,self.salary)
class Qualification():
q_count = 0
def __init__(self,degree,... |
class Circle():
def __init__(self,radius):
self.radius = radius
def area(self):
return 3.14*self.radius**2
#driver code
circle = Circle(10)
print(circle.area())
|
a=float(input("Enter 1st number:"))
b=float(input("Enter 2nd number:"))
while True:
print("Choose operation to perform:")
print("1.Addition\t2.Substraction\t3.Multiplication\n4.Division\t5.Exit")
choice=int(input())
if choice==1: print("Addition: {}".format(a+b))
elif choice==2: print("Substraction:... |
name=input("Enter your name:")
enrl=input("Enter enrollment no.:")
division=input("Enter your Division:")
address=input("Enter your address:")
print("\n\nEntered Details:\n")
print("Name:\t\t\t{}\nEnrollment No.:\t\t{}\nDivision:\t\t{}\nAddress: \t\t{}".format(name,enrl,division,address))
|
#classes.py
class Dog(): #define a class called Dog, notice the capital D
"""a simple attempt to model a dog"""
def __init__(self,name,age): #the __init__ method
"""initialize name and age attributes"""
self.name = name #attributes
self.age = age
def sit(self):
"""simulate a dog sitting in response to a... |
"""
This module implements training and evaluation of a Convolutional Neural Network in PyTorch.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import os
from convnet_py... |
primer=0
segundo=0
a=int((input("introduce enumero entre 0 y 9999")))
if a>10:
print()
else:
primer=a//10
segundo=a-primer*10
print(primer+segundo*10)
|
#3. Dado el fichero de texto números.txt realiza un programa en Python
#que recorra el fichero y sume todos los números pares,
#los números están separados por espacios.
f=open("ejercicio1.txt","r")
r=f.read()
r=r.split()
cont=0
for x in r:
if int(x)%2==0:
cont+=int(x)
print(2*cont)
f.close() |
#!/usr/bin/python3
class Point:
def __init__(self, x, y):
self._x = float(x)
self._y = float(y)
def __repr__(self):
return f'<Point: x{self.x}, y{self.y}>'
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
def __iadd... |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# This example will open a file and read it line by line, process each line,
# and write the processed line to standard out.
# -----------------------------------------------------------------------------
# Open a fil... |
#!/usr/bin/env python3
#
# Replacement for standard UNIX cal utility, supporting date ranges, and
# defaulting to Monday as first day-of-week.
#
# Copyright (C) 2010 Richard Mortier <mort@cantab.net>. All Rights
# Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms o... |
title='Oscillator'
label='Oscillator'
icon='oscillator.png'
description="""<html>The oscillator needs an input (2D), which can be used to start it off from rest. Once it has started, the input can be set to zero. The controlled oscillator also needs a 1D control input that changes the frequency (and direction) of... |
from tkinter import *
from tkinter import messagebox
operator=''
def ClearDisplay():
global operator
operator=''
name.set('')
num.set('')
def namer():
w1.destroy()
from name import w5
def numberr():
w1.destroy()
from number import w2
def email():
w1.destroy()
... |
# 导入psycopg2 包
import psycopg2
# 获取连接
conn = psycopg2.connect(database="postgres", user="postgres",
password="postgres", host="localhost", port="5432")
# 建立游标,用来执行数据库操作
cursor = conn.cursor()
# 执行SQL命令
cursor.execute('DROP TABLE if exists test_conn')
cursor.execute("CREATE TABLE test_conn(id ... |
from tkinter import *
root = Tk()
canvas_width = 800
canvas_height = 400
root.geometry(f"{canvas_width}x{canvas_height}")
root.title("Canvas GUI")
can_widget = Canvas(root,width = canvas_width,height = canvas_height)
# This line goes from the point x1, y1 to x2,y2.
can_widget.create_line(0,0,800,400,fill = "red")
... |
from tkinter import *
root = Tk()
root.geometry("655x444")
def getValue():
print(f"Username is {uservalue.get()}and Password is {passwordValue.get()} ")
#gets is use to get the value.
user = Label(root,text = "Username ")
user.grid() # by default row is 0.
password = Label(root,text = "Password ")
password.g... |
import pandas as pd # Used for dataframes
import matplotlib.pyplot as plt # Used for plotting
import os # Used to get current working directory
def plot_data(df, title="Stock prices", xlabel="Date", ylabel="Price"):
"""Plot stock prices"""
ax = df.plot(title=title, fontsize=8)
ax.set_xlabel(xlabel)
... |
n=5
k=(2*n)-2 #8
for i in range(0,n): #(0,1,2,3,4)
for j in range(0,n-i-1): #(0,1,2,3,4,5,6,7)
print(end=" ")
#k-=2 #k=k-2
for j in range(0,i+1):
print(" + ",end=" ")
print("") |
# Program utilizing the pandas and matplotlib.pyplot to create pivot tables and plots for panel data on countries' population's over time
import pandas as pd
import matplotlib.pyplot as plt
# Read csv data from computer
pop_df = pd.read_csv('C:/Users/Dennzy/Desktop/Development And Growth 582/HW1/population.csv'... |
# -*- coding: utf-8 -*-
from bui.utils.node import Node
class TestNode():
def test_create_node(self):
node = Node()
def test_append_children_to_node(self):
node1, node2 = Node(), Node()
node1.children.append(node2)
assert node1.children[0] == node2
... |
#!/usr/bin/python3
'''
Adapted excerpt from Getting Started with Raspberry Pi by Matt Richardson
Modified by Rui Santos
Complete project details: http://randomnerdtutorials.com
Modified by Chip Fleming 23Sep2019 for valve control
'''
import time
import RPi.GPIO as GPIO
from flask import Flask, render_template, reque... |
# # lambda expression(anonymous function)
# def add(a,b):
# return a+b
# add2=lambda a,b : a+b #no need to assign
# print(add2(2,3))
# # used with built in functions--map,reduce,filter
# mul=lambda m,n :m*n
# print(mul(3,4))
# def is_even(n):
# return n%2==0
# print(is_even(8))
# is_even2=lambda a:a%2==0
# pr... |
age=int(input("Enter ur age "))
# if age>=14:
# print("U r above 14")
# print("u shud die")
# else:
# print("hi u r welcome")
if age>8:
pass |
# # dictionary
# # unordered collection of data in key:value pair
# u={'n':'i','a':24}
# print(u)
# print(type(u))
# # second method
# u=dict(n='i',a=20)
# print(u)
# print(type(u))
# print(u['n'])
# # no index
# ui={'n':'i',
# 'a':20,
# 'fm':['in','incep'],
# 's':['pe','ka']
# }
# print(ui)
# # empty dicti... |
#modify guessing game
import random
win=random.randint(1,100)
a=True
c=0
while a:
guess=int(input("Enter ur guess: "))
c+=1
if guess==win:
print("u won")
a=False
elif guess>win:
print("too high")
else:
print("too low")
print(f"u took {c} chances to win") |
#for in string
name="fuck"
for x in name:
print(x)
for x in range(1,-11,-1):
print(x) |
from functools import wraps
import time
# # first class function/closures
# # decorators
# def sq(a):
# return a**2
# s=sq(7)
# print(s)
# s=sq
# print(s(7))
# print(s.__name__)
# print(sq.__name__)
# print(s)
# print(sq)
# l=[1,2,3,4]
# def sq(a):
# return a**2
# print(map(sq,l))
# print(list(map(sq,l)))
#
# ... |
#string methods
name ="hARSHIT vAsHSISTH"
#1.len() function
print(len(name))
#2.lower() method
print(name.lower())
#3.upper() method
print(name.upper())
#4.title() method
print(name.title())
print(name)
#5.count() method
print(name.count("H"))
print(name.count("h"))
#Exercise 3
name,sc=input("Enter ur name and a singl... |
import unittest
import chess
import random
import string
class SquareTest(unittest.TestCase):
def setUp(self) -> None:
self.rand_col = random.choice(chess.COLUMNS)
self.rand_row = random.choice(chess.ROWS)
self.square = chess.Square(self.rand_col, self.rand_row)
# print('Square at... |
import { SortAlgorithm } from '@mulberrybeacon/sorting/lib/SortAlgorithm';
/**
* Several possible implementations of the Merge Sort algorithm.
*
* @author Eduardo Ferreira
*/
export class MergeSort {
/**
* Top-down version of Merge Sort.
*
* @param {int[]} list List of numbers
* @return {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.