text stringlengths 37 1.41M |
|---|
from typing import List
# Name: Number Of Rectangles That Can Form The Largest Square
# Link: https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/
# Difficulty: Easy
# Method: Find max and count
# Time: O(n)
# Space: O(1)
class Solution:
def countGoodRectangles(self, rectangles: L... |
from typing import List
class Solution:
def reconstructMatrix(
self, upper: int, lower: int, colsum: List[int]
) -> List[List[int]]:
n = len(colsum)
up = [0 for _ in range(n)]
down = [0 for _ in range(n)]
for i in range(n):
x = colsum[i]
... |
from collections import defaultdict
from typing import List
# Name: Number of Connected Components in an Undirected Graph
# Link: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
# Method: DFS from every node to n
# Time: O(n)
# Space: O(n + e)
# Difficulty: Medium
# Note: n = nr of... |
from typing import List
# Name: Minimum Size Subarray Sum
# Link: https://leetcode.com/problems/minimum-size-subarray-sum/
# Method: Sliding window, once target sum is passed, reduce from left side as much as possible
# Time: O(n)
# Space: O(1)
# Difficulty: Medium
class Solution:
def minSubArrayLen(sel... |
#!/bin/python3
import math
import os
import random
import re
import sys
def equal(orignal_arr):
results = []
for i in range(5):
minim = min(orignal_arr)-i
results.append(actualEqual(orignal_arr, minim))
print(results)
return min(results)
def actualEqual(original_a... |
from typing import List
# Name: Unique Email Addresses
# Link: https://leetcode.com/problems/unique-email-addresses/
# Method: Process email, store in set
# Time: O(n)
# Space: O(n)
# Difficulty: Easy
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
return len(set(map(self.simplify_em... |
from typing import List
# Name: House Robber
# Link: https://leetcode.com/problems/house-robber/
# Method: Dynamic programming, max of prev 2 days
# Time: O(n)
# Space: O(1)
# Difficulty: Medium
class Solution:
def rob(self, nums: List[int]) -> int:
rob_prev = 0
rob_max = 0
for x in nums:... |
from functools import lru_cache
class Solution:
zero_ways = 0
def numWays(self, steps: int, arrLen: int) -> int:
@lru_cache(None)
def step(poz: int, steps: int):
if poz < 0 or steps < 0 or poz >= arrLen or steps < poz:
return 0
elif poz == st... |
import pygame
class Text_input:
#Initilisation
def __init__(self, origin, width, height, font, box_colour, text_colour, function, border = 0.05, password = False):
# Copy Args to name space
self.font = font
self.origin = origin
self.widt... |
import sys
from random import randint
n=int(sys.argv[1])
ganador=randint(0,36)
if n==ganador:
print("El numero ganado es",ganador)
print("Premio")
else:
print("El numero ganado es",ganador)
|
def same_digits(a, b):
"""
Implement same_digits, which takes two positive integers. It returns whether they both become
the same number after replacing each sequence of a digit repeated consecutively with only one of that
digit. For example, in 12222321, the sequence 2222 would be replaced by only 2, l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 23 14:22:58 2018
@author: jcarraascootarola
"""
import numpy as np
import random
class SigmoidNeuron:
def __init__(self, initLearningRate,numberOfInputs):
self.lastOutput=0
self.bias = random.uniform(-2.0, 2.0)
... |
import sys
import csv
import math
import operator
#it first reads the text file input2
with open("input2.txt") as f:
content = f.readlines()
i=0
numcase=float(content[i])
#check number of votes
#input of votes and candidate orders returning the vote % the highest
def check(votes,cand_order):
total={}
fo... |
#This is a comment from RAD416
students = ['aas731',
'acw438',
'agb344',
'ajm777',
'ak4706',
'ak4728',
'am5801',
'cbj238',
'cnl272',
'efm279',
'gz475',
'hj745',
'hm1273',
'hw1067',
'jj1006',
'jl2684',
'jwr300',
'ke638',
'kll392',
'ks2890',
'kx273',
'lcv232',
'lz1023',
'mam1220',
'rad416',
'rh1328',
'rs4606',
'seltzn... |
# < algorithm >
#1. voter ranks all candidates
#2. gather the #1 candidates and elect candidates who get over half of ballots
#3. if there is no elected candidate, drop the candidates, who get the lowest ballots
# (one or more candidates can be dropped)
#4. Among ballots that elected candidates who are already d... |
# -*- coding: utf-8 -*-
#Haozhe Wang
#Assignment 5
#Problem 1 A
import pandas as pd
import csv
import pylab
import numpy as np
stockfile = pd.read_csv('stocks.dat')#read the file with pandas call function
#print stockfile
apple_stock = stockfile[['month','apple']]
index = apple_stock.set_index('month')
#print index... |
#Aliya Merali
#Assignment 2
#Problem 3
import csv
from collections import defaultdict
incident_log = open('Incidents_grouped_by_Address_and_Zip.csv','r')
borough_log = open('boroughs.csv','r')
zip_log = open('zipCodes.csv','r')
outputFile = open('output_problem3.txt','w')
#Creating a Dict with Zipcodes:No. Incidents... |
######################################################################
#
# tutorial 2 - zipcode class
# September 21th, 2013
#
# Michael Musick
#
######################################################################
class Zipcode(object):
number = None
def __init__(self, zipcode):
self.zipcode = zipcode |
import sys
inputFile = open("input3.txt", "r")
"""
A scenario is a list containing a pair of integers P N denoting the number of
papers P and the number of authors N in each scenario, followed by P + N lines.
Parse the input for integer pairs and splice input into a new list of scenarios
(a list of lists). Define a... |
def main():
f = open('input1.txt', 'r') #open the input file
input = f.readlines() # read the whole file as a list of lines
line_index = 0
line_index2 = int(input[line_index].replace('\n', '')) # this line is to set the number of student in each trip (the number of student is formatted as integer)
... |
#!usr/bin/python
######################################################################
#
# Assignment 2 - Problem 4
# September 25th, 2013
#
# Michael Musick
#
# Description: returns the avergae population of the user specified
# borough
#
# Sample Input: python problem4.py "staten island"
#
#################... |
import sys
inputFile = open('input1.txt', 'r') # open .txt file
inputLines = [] # save lines in a list
for line in inputFile:
inputLines.append(line)
inputFile.close()
"""
Define a function that will take costs (as floats) as input and will print as o... |
import sys
def isJolly(x):
targets = (len(x)-1)*[False]
for i in range(1,len(x)):
diff = abs(int(x[i-1])-int(x[i]))
if diff<len(x) and diff>0 and not targets[diff-1]: #will not crash because first clause will evaluate first
targets[diff-1]=True
else:
print "Not jolly"
return
print "Jolly"
return
... |
class Borough:
name = None
zipcodes = None
populations = 0
populationcount = 0
average = 0
def __init__(self, name):
self.name = name
self.zipcodes = []
def addZipcode(self, zipcode):
self.zipcodes.append(zipcode)
def addPopulation(self, population):
... |
#Kara Leary
#Urban Informatics
#Assignment 2 - Problem 2
import sys
import csv
#initialize variables for zip, population, area, density:
currentZip = 0
currentPop = 0
currentArea = 0
populationDensity = 0
#set up a temporary list to hold unsorted values
temparray = []
with open('zipCodes.csv') as f:
rows = csv.... |
myFile=open('input4.txt','r')#read the input file and put all data into an array
readdata=[]
for line in myFile:
line_lower=line.lower()#change the letters of the data to lowercase
readdata.append(line_lower[:-1])
myFile.close
readdata.append('')#add a space into the end of array to indicate the last case ends
bla... |
#Aliya Merali
#Assignment 2
#Problem 1
import sys
import datetime
from dateutil import parser
logfile = open('log_assignment1.txt','r')
#Set the time limit to compare to from input value as an object in datetime
dateInput = sys.argv[1].split('/')
timeInput = sys.argv[2].split(':')
dateTimeLimit = datetime.datetime(in... |
import sys
inputFile = open('input1.txt', 'r')
inputFile.seek(0)
thisLine = inputFile.readline()
tripList = []
averageList = []
finalList = []
while thisLine != '0\n':
thisTrip = []
numStudents = int(thisLine[:-1])
thisLine = inputFile.readline()
for student in range(0, numStudents):
thisTrip.... |
# !usr/bin/python
######################################################################
#
# Assignment 5 - Problem 1a
# November 24th, 2013
#
# Michael Musick
#
# Description: Plot Apple Stock Prices
#
# Plotting Principles Used:
# Improving Vision, Principle 1 - Reduce Clutter:
# This was ma... |
"""
Note that this program accepts input on the command line *without* quotation marks.
For example, one would type
$ python problem1.py 10 20
and receive an output of
10 20 21
"""
import sys
input = (sys.argv)
input.pop(0)
first_parameter = int(input[0])
second_parameter = int(input[1])
"""
The following func... |
import sys
max = 0
def test(n):
if (n % 2 == 0):
n = n/2
else:
n = 3*n + 1
return n
def cycle(n):
global max
count = 1
while n!= 1:
n = test(n)
count += 1
if (count > max):
max = count
i = int(sys.argv[1])
j = int(sys.argv[2])
for n in range(i, j+1):
#print "Calculating Cycle of "+str... |
# A script to take in a file of zipcodes with populations, calculate the density
# and output those to a file, ignoring any zipcodes without a population figure
# output is likely population per decimal degree, though it's not clear from the
# source file what the units are.
from _collections import defaultdict
zipc... |
#!usr/bin/python
# Assignment 1 - Problem 2
# September 18th, 2013
####################################
#
# sample input:
# python problem2.py 6 1 -3 -6 -4 -3
#
###################################
import sys # lib to get terminal input
# print len(sys.argv) # test print
# put the user supplied arguments into a lis... |
#Katherine Elliott
#ke638
#Assignment 3 Problem 3
inputFile = open("input3.txt", "r")
num_scenarios = int(inputFile.readline())
for n in range (0, num_scenarios):
PN = inputFile.readline().split()
P = int(PN[0])
N = int(PN[1])
papers = []
for i in range (0, P):
papers.append(inputFile.r... |
import sys
import numpy
import matplotlib.pyplot as plt
from sklearn import cross_validation, linear_model, datasets
from random import shuffle
"""
First we open the text file and save the lines to the list input_lines
"""
inputfile = open('labeled_data.csv', 'r')
input_lines = []
for line in inputfile:
input_l... |
import numpy
import matplotlib.pyplot as plt
"""
The lists of values that we'll graph are:
[13519.178949317729, 13247.82770615588, 13164.52846434755, 13405.996537917486, 14109.84815164765]
[1515.2051976713724, 1536.1593441442926, 1662.8911854362129, 1925.7478724867913, 3262.5729874720264]
[13492.142190458173, 13118.85... |
#!usr/bin/python
######################################################################
#
# Assignment 2 - Problem 2
# September 21th, 2013
#
# Michael Musick
#
# Description:
#
######################################################################
dbFile = open('zipCodes.csv', 'r')
# create a dictionary
zipDict... |
import sys
import borough as boroughClass
boroughInput =sys.argv[0]
boroughInput =boroughInput.title()
boroughName= open ('boroughs.csv','r')
zippop= open('zipCodes.csv','r')
#setting the input as part of the boroughClass
boroughObj= borough(boroughInput)
#add the list of the zip codes to the boroughClass
boroughDict=... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 15:18:57 2013
@author: yz1897
"""
import sys
# this solution should be faster in c, but in after i test
#in python, the it get a little slower...
def Longest_Cycle(i,j):
longest=0
deleted=[-1 for k in range(j-i+1)]
for n in range(j,i-1... |
import sys
import math
input = open('input2.txt','r')
value1 = input.readlines()
value1 = value1[2:]
break_arr = []
break_arr.append(0)
z = 0
for call in value1:
if call == "\n":
break_arr.append(z+1)
z = z + 1
break_arr.append(len(value1))
def candidates(x, win1): # Getting the list of candidate... |
import sys
import csv
class Borough:
name = None
zipcodes = None
numOfZip=None
population=None
def __init__(self, name):
self.name = name
self.zipcodes = []
self.numOfZip=0
self.population=0
def addZipcode(self, zip):
self.zipcodes.append(zip)
se... |
#!/usr/local/bin/python
#Warren Reed
#Principles of Urban Informatics
#Assignment 2, Problem 3
"""
Creating ZipCodes Population Dictionary with key as zipcode and value
as the population of that zipcode
"""
Pop_File = open('zipCodes_tr.csv','r')
population_lines = []
for line in Pop_File:
population_lines.appen... |
#!/usr/local/bin/python
#Warren Reed
#Principles of Urban Informatics
#Assignment 4, Problem 1
#Connects to MySQL and creates three tables to store the boroughs.csv, zipCodes, and incidents table.
import MySQLdb
import csv
def incidentsToSql(cur,db):
incidents_csv = csv.reader(open('Incidents_grouped_by_Address_... |
#Nathan Seltzer
#Homework 5
#Problem1c.py
#import the neccessary modules and rename them
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
#the following import form pylab will allow me to use the subplot function
from pylab import *
#same as previous annotations
f = open('stocks.d... |
# Awais Malik
# Assignment 2
# Problem 4
import sys
import csv
zipFile = open('zipCodes.csv','r')
zipcodeList = csv.reader(zipFile)
boroughFile = open('boroughs.csv','r')
boroughList = csv.reader(boroughFile)
boroughName = sys.argv[1].lower()
zip = {}
for line in boroughList:
zip[line[0]] = [line[1]]
... |
#!/usr/local/bin/python
#Warren Reed
#Principles of Urban Informatics
#Assignment 4, Problem 2
#Connects to MySQL and computes the population density for a given zipcode
import MySQLdb
import sys
def main():
inputZipcode = sys.argv[1]
db = MySQLdb.connect(host="localhost", # your host, usually localhost
... |
def find_location(string,matrix): # find the location of keyword
location=[float("inf"),float("inf")]
lineNum=len(matrix)
colNum=len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j].lower()==string[0].lower():
lStr=string[0].low... |
# TIM LEAVEY
# SUPERHERO APP
# This program does NOT used prepared statements, meaning it's vulnerable to SQL injections.
# This was intentional as a lesson in what NOT to do. ;)
import sys
import sqlite3
# Initial welcome display for user
print('Welcome to the superheroes archive!')
print('1. Superheroes')
print('2... |
from datetime import date
from lib.colors import red, green
iteration_start = date(2021, 6, 16)
iteration_end = date(2021, 9, 22)
iteration_diff = iteration_end - iteration_start
number_of_sprints = int(iteration_diff.days / 14)
days_into_iteration = int((date.today() - iteration_start).days)
current_sprint = int((day... |
num=int(input("Enter 3 digit number "))
n1=num%10
n2=num//10%10
n3=num//100
print(f"{n1}{n2}{n3}")
|
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from scipy.stats import pearsonr
if __name__ == "__main__":
boston = datasets.load_boston()
boston = pd.DataFrame(data=boston.data, columns=boston.feature_names)
print(boston)
correlation, _ = pearsonr(boston["TAX"], bost... |
from tkinter import *
from PIL import Image, ImageTk
from datastorage import Insert_user
import sqlite3
conn = sqlite3.connect("users.db")
c = conn.cursor()
def credentials():
global font
log = Tk()
log.geometry("500x600")
log.title("Fundit")
log.configure(background="white")
log.resizable(width=False, heigh... |
from pieces import Piece
import board
class Rook(Piece):
def __init__(self, color, type):
Piece.__init__(self, color, type)
def __str__(self):
if(self.color == "W"):
return "R"
else:
return "r"
def scan(self):
availMoves = []
... |
import pygame
from pygame.locals import *
from random import choice
from copy import deepcopy
NAME_OF_THE_GAME = "Tetris"
BLOCK_SIZE = 30
def coord_in_px(coord):
return (coord[0] * BLOCK_SIZE,
coord[1] * BLOCK_SIZE)
DRAW_SPOTLIGHT = True # the spotlight is a guide the width of the player that extends... |
# initialize
my_dict = {}
# add item
my_dict['name'] = 'brian'
my_dict['state'] = 'florida'
my_dict['age'] = 37
# access item
print my_dict['name']
# change item
my_dict['name'] = 'engineer man'
# remove item by index
del my_dict['state']
# iterate
for k, v in my_dict.iteritems():
print k, '=>', v
|
import numpy as np
import matplotlib.pyplot as plt
# https://towardsdatascience.com/understanding-the-3-most-common-loss-functions-for-machine-learning-regression-23e0ef3e14d3
# MSE loss function
def mse_loss(y_pred, y_true):
squared_error = (y_pred - y_true) ** 2
sum_squared_error = np.sum(squared_error)
... |
def exam_model():
# introduction
print ('Welcome to the grade caluclator for you English, Science and Maths exams')
print ('type you scores in and find out your grades')
name=raw_input ('What is you name: ')
english_score= input ('What was your exam score for English: ')
maths_score=input ('What was your exam ... |
import random
stuff = ['water', 'food', 'sword']
party = ['you']
pos_x = 2
pos_y = 2
you_hp = 15.0
map_dungeon = '''
----------------
| |__
| main room |__ outside
== | |
-----... |
#python3 programe for bubble sort
def bubbleSort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if swapped == False:... |
#Python3 programe for deleting node from binary tree
#Class for binary tree Node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#Print inorder of binary tree
def inorder(node):
if not node:
return
inorder(node.left)
print(node.... |
n = int(input("Introduzca un número positivo mayor o igual a 0: ")) #SOLICITA VALOR
for i in range (1,n+1,1): #REPETIR N VECES
print ("*",end="") #IMPRIMIR * SIN SALTO DE LINEA |
#! python3
# zipBackup.py - Copies an entire folder and its contents into a ZIP file where the file name increments each time
import zipfile, os
def backupToZip(folder):
#Back up entire folder to ZIP
folder = os.path.abspath(folder)
#Calculate version number
number = 1
while True:
zipFi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# cw-miesiące.py
#
def main(args):
nazwy = ['styczen', 'luty', 'marzec', 'kwiecen', 'maj', 'czerwiec', 'lipiec', 'sierpien', 'wrzesien', 'pazdziernik', 'listopad', 'grudzien']
while 1 > 0:
numer = int(input("Podaj numer miesiąca: "))
if 1 > numer > 12:
... |
#Python 3.6.8
#author Karan Joshi
from bs4 import BeautifulSoup
import pandas
from selenium import webdriver # Use https://github.com/mozilla/geckodriver/releases to install geckodriver on your python console
import time
driver=webdriver.Firefox() # Instantiating browser object
page=driver.get("https://yourstory.co... |
def palindrome(input):
if input == "".join(reversed(input)):
return True
return False
if __name__ == "__main__":
user_in = input("Enter a string: ")
print(palindrome(user_in)) |
'''
Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number.
'''
def getShortestSubArray(input_arr, k):
shortest_length = -1
left_side = 0
right_side = 0
cur_sum = input_arr[0]
while right_side < len(input_arr):
if left_side > right_side:
... |
'''
Longest Substring Which contains K Unique Characters
'''
def getLongestSubString(input_str):
# Use a hashmap to store the index of each character, if finding duplicate the left side of window will start from there
left_side = 0
right_side = 0
max_length = 1
max_left = 0
max_right = 0
... |
def integer_to_english_words(num):
ret = ""
billion = 1000000000
million = 1000000
thousand = 1000
n_to_english = {
1: 'One',
2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine',
10: '... |
'''
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
'''
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
water = 0
left = 0
right = len(height) - 1
water = 0
while left < right:
if height[left]... |
#Advent of Code 2019 Day 1 Part 2: The Tyranny of the Rocket Equation
fuelReq = []
def fuelCalc(mass):
mass = int(mass)
return mass//3-2
filepath = 'Day1.txt'
with open (filepath) as masses:
for mass in masses:
fuel = fuelCalc(mass)
fuelTotal = fuel
while fuel > 0:
fuel ... |
from .exceptions import *
import random
# Complete with your own, just for fun :)
LIST_OF_WORDS = []
def _get_random_word(list_of_words):
if list_of_words == []:
raise InvalidListOfWordsException
else:
return random.choice(list_of_words)
def _mask_word(word):
if len(word) == 0:
... |
#! /usr/bin/env python3
def fuel(amt):
return (amt//3) - 2
def all_fuel(amt):
num = fuel(amt)
sub = 0
while num > 0:
sub += num
num = fuel(num)
return sub
total = 0
with open("input") as f:
for line in f:
total += all_fuel(int(line))
print(total)
|
# Multiples
# Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
number = range(0,100)
for i in number:
if i%2!=0:
print i
# Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000.
number = range(... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import random
def play():
a = random.randint(0,20) #a adalah bilangan random yg akan ditebak
#print("contoh angka random: ",a)
score = 100
b=11 #b adalah angka yg akan ditebak, b=11 inisiasi awal aja
tebaka... |
#!/usr/local/bin/python3
# Python class to implement a Kalman Filter
import numpy as np
import matplotlib.pyplot as plt
from random import random
from math import *
class kalman():
# Init assuming 2d problem with no control input or process noise
def __init__(self, t0, dx):
self.t = t0
# Me... |
l = [1,2,3]
l.append(4)
l.count(2)
x = [1,2,3]
x.append([4,5])
# appends the entire element to the list, list in a list
# if you want to add to the list, use extend
x.extend([4,5])
l.index(2)
# two arguments: index, object
l.insert(2,'inserted')
ele = l.pop()
# pop always last element, but can add index
l.remove... |
class Animal():
def __init__(self):
print('Animal created')
def who_am_i(self):
print('I am an animal')
def eat(self):
print('I am eating')
#myanimal = Animal()
#print(myanimal.eat())
class Dog(Animal):
#Derived class
def __init__(self):
Animal.__init__(self)
print('Dog created')
... |
def myfunc():
print('Hello World')
def myfunc(Name):
print('Hello {}'.format(Name))
def myfunc(s):
if s == True:
return 'Hello'
if s == False:
return 'Goodbye'
def myfunc(x, y, z):
if z == True:
return x
if z == False:
return y
def myfunc(a, b):
return a+b... |
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposit of {amount} accepted.")
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
print(f"Withdraw... |
"""
Write a Python program that matches
a string that has an a followed by three 'b'.
"""
import re
def is_match(text):
pattern = ("ab{3}")
if re.search(pattern, text):
return "Match found!"
else:
return "Match not found"
print(is_match("a")) |
"""
you get a sorted list and need to find the first and last appearence of a certain number in the list and return the indices
example if input is 1, 3, 3, 5, 7, 8, 9, 9, 15
if asked for 9 the indicie range is 6-9
lets do it in sub-linear time
"""
#this is binary search to solve it
class Range:
def Get... |
#this is for adding a functionality for the stack which will return the maximum number
class Max(object):
def __init__(self):
self.stack = []
self.maxs = []
def push(self, val):
self.stack.append(val);
if self.maxs and self.maxs[-1] > val:
self.maxs.appe... |
'''Creating the functionality for the application
In this file, we are going to create the functionality for our application. There are multiple functionality.
Functionalities:
1. signup
2. login
3. add_events
4. show_events
5. remove_events
6. add_participants
7. show_participants
8. remove_participants
'... |
# 18. Read in some text from a corpus, tokenize it, and print the list of all wh-word types that occur. (wh-words in English are used in questions, relative clauses and exclamations: who, which, what, and so on.) Print them in order. Are any words duplicated in this list, because of the presence of case distinctions or... |
list = [2, 4, 6, 8 ,10]
for item in list[0:3]:
print(item)
list2 = ["Gustavo", "Costa"]
for name in list2:
if not name == "Gustavo":
print(name) |
#!/usr/bin/env python3
import numpy as np
import cv2
import matplotlib.pyplot as plt
from VO import MonoVo as VO
import os
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',
'dog', 'horse', 'motorbike', 'person', 'potte... |
x = input("enter list 1:")
y = input("enter list 2: ")
comb = len(x) + len(y)
if comb % 3 == 0 and comb % 5 == 0:
print("fizzbuzz")
elif comb % 3 == 0:
print("Fizz")
elif comb % 5 == 0:
print("Buzz")
else:
print(comb)
|
class dog:
species = "mamal"
def __init__(self, sound_made):
self.sound_made = sound_made
def sound(self):
print(self.sound_made)
def bite(self):
self.sound_made()
print("bite")
def identify_yourself():
print("i am a" + self.species)
my_dog = dog(... |
txt = str(input("Enter any word: "))
text = txt[1::]
print(txt)
text = text + txt[0]
cyrus = ("ay")
print(text + "ay") |
# tuples
# tuples are immutable
# tuples are ordered collection of data
# tuples can store any data type
# you cannot change(add or delete) values from tuple once it created
# but can add, delete data from list which is present inside tuples
mixed = (1,2,3,4,5,'six')
# no append, no pop, no insert, no remove
# only co... |
# check empty or not
# important
name = input("enter name = ")
if name: # true is string is not empty
print(f"your name is {name}")
else:
print("you did'nt type anything") |
# fromkeys() - used to create dictionaries :-
# d = {'name' : 'unknown', 'age' : 'unknown'}
# d = dict.fromkeys(['name', 'age', 'dob'], 'unknown')
# print(d)
# get() method (useful):- to handls errors we use get() method
d = {'name' : 'harshit', 'age' : 24}
# print(d['dob']) # gives error because 'dob' key is not p... |
# sum : 1 to 10 (or any number)
total = 0
i = 1 # i = 2
while i <= 10:
total = total + i
i = i + 1
print(total)
# total = 0 + 1 |
# will discuss three problems in existing
# then we will solve them using getter , setter decorator
class Phone:
def __init__(self, brand, model_name, price):
self.brand = brand
self.model_name = model_name
self._price = max(price,0)
@property
def complete_specific(self):... |
. center(lenght of string, '*')
. replace(" " , "_") # replace ' ' by '_'
. replace("is" , "was" , 1) # replace 1 'is' if 2 then replaces two 'is
. find("is")) # finds the position of is o/p = 4'
. find("is",skip the first 'is')
. str()
. split(",")
. len() ... |
# common elements finder function
# define a function which takes two lists as input and return a list
# which conatins common elemetns of both lists
# example
# input ---> [1,2,5,8], [1,2,7,6]
# output ---> [1,2]
def common_elements(list1, list2):
common_list = []
for i in list1:
if i in list2:
... |
# compare list
# == , is
fruits1 = ['orange', 'apple', 'pear']
fruits3 = ['orange', 'apple', 'pear']
fruits2 = ['banana', 'kiwi', 'apple', 'banana']
print(fruits1 == fruits3) # values are same
print(fruits1 is fruits3) # false |
# some more mehods to add data in out list
# insert method
# how to join(concatenate) two list
# extend method
# difference between append and extend methods
fruits1 = ['mango', 'orange']
# fruits1.insert(1, "grapes")
# print(fruits1)
fruits2 = ["grapes", "apple"]
# fruits = fruits1 + fruits2
# print(fruits)
fruits1... |
# lambda expressions (anonymous function)
def add(a,b):
return a+b
add2 = lambda a,b : a+b
print(add2(2,3))
# built in, map , reduce
multiply = lambda a,b : a*b
print(multiply(2,3)) |
# class methods
# difference between class methods and instance methods
class Person:
count_instance = 0 # class variable / class attribute
def __init__(self, first_name):
Person.count_instance = Person.count_instance + 1
self.first_name = first_name
@classmethod
def count_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.