text stringlengths 37 1.41M |
|---|
def Sets(x,y,z):
if (z == 1):
g=set(x).union(y)
print ("Your Answer is = " ,g)
if (z == 2):
g=set(x).intersection(y)
print ("Your Answer is = " ,g)
if (z == 3):
g=set(x).difference(y)
print ("Your Answer is = " ,g)
if (z == 4):
print("Enter U set elements... |
def display_matrix(x,l):
a=0
for i in range(0,len(l)):
print(" ",l[i],end="|")
a=a+1
if(a== (x)):
print(end="\n")
a=0
def conv1(a,w):
temp=[]
count=0
t=[]
for i in a:
count = count +1
t.append(i)
if(c... |
from Structures import Stack, Queue, PriorityQueue
from Node import *
# Tree Search Algorithms
def treeSearch(problem, ds):
ds.append(Node(problem.initial))
while not ds.isEmpty():
node = ds.pop()
if problem.isGoal(node.state):
return node
ds.extend(node.expand(problem))
... |
tree = [1,2,3,4,5]
def children(i):
l,r = (i*2) + 1, (i*2)+2
if l >= len(tree):
l = None
if r >= len(tree):
r = None
return l, r
def parent(i):
if i%2:
return (i-1)/2
else:
return (i-2)/2
def in_order(ni):
li , ri = children(ni)
print("{}{}: li-{} ri-{}... |
from collections import defaultdict
tree = [10, 0, 25, -1, 21, 16, 32]
class Node(object):
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
self.value = value
def children(i):
return (i*2) + 1, (i*2) +2
# Generates tree from array
def gen_tree(i... |
tree = [0, 1, 2, 3, 4, 5, 6]
"""
0
/ \
1 2
/ \ / \
3 4 5 6
"""
def children(i):
l = (i * 2) + 1
l = l if l < len(tree) else None
r = (i * 2) + 2
r = r if r < len(tree) else None
return l, r
def parent(i):
if (i % 2):
... |
""" Efficient calculation of factorials"""
def is_even(n):
return n % 2 == 0
def efficient_factorial(n):
"""
This method of calculating the factorial by reducing the multiplications by half.
As we know multiplication is the costlier operation redcing it by half adds a lot of
performace benifits
... |
# not correct
x = [3,4,-1,0,6,2,3]
results = []
n = len(x)
i = 0
j = 1
local_res = []
for i in range(n):
local_res = []
last_data = x[i]
for j in range(i, n):
if last_data <= x[j]:
local_res.append(x[j])
last_data = x[j]
results.append(local_res)
print(results)
|
def fibgen(n):
res = []
for i in range(1, n+1):
if i <= 2:
out = i
else:
out = res[-1] + res[-2]
res.append(out)
yield out
print([x for x in fibgen(5)])
|
from tkinter import *
from ConsoleCalculator import *
# PLEASE ENSURE YOU HAVE ConsoleCalculator.py AVAILABLE FOR THIS APPLICATION OR THIS WILL NOT WORK:
# https://github.com/marcusvongsykeo/portfolio/blob/master/ConsoleCalculator.py
formula = ""
ans = ""
root = Tk()
root.title("Calculator")
# Define formula field (... |
# Exam Assignment
# Programmer Name: Jin Li
# Date: 1/9/2021
# Course Name and Term: CS X458.05 - Data Structures and Algorithms (EXT Fall 2020)
# Program Title: Simple Demo of google search autocomplete.
# Description: Given an input (prefix), return all words begin with the prefix and the 5 most commonly used ones.
... |
#Works for strings consisting of alphabets only
def mulInv(a,m):
"""Computes modular multiplicative inverse
a mod m"""
t1 = 0
t2 = 1
n = m
if m == 1: return 0
while a>0:
q = m//a
r = m-q*a
m = a
a = r
t = t1 - q * t2
t1 = t2
t2 = t
... |
# Code in file autograd/two_layer_net_autograd.py
import torch
import numpy as np
from torch.autograd import Variable
dtype = torch.FloatTensor
# dtype = torch.cuda.FloatTensor # Uncomment this to run on GPU
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_... |
text = ""
stopword = ""
while True:
line = input()
if line.strip() == stopword:
break
text += "%s ],[" % line
print(text)
|
# Package for getting the current location of the sun
# Requires PyEphem (ephem) and datetime (datetime) libraries
# Author: Tim Krentz
# June 22, 2015
import ephem
import datetime
####################################################################################################
# Method definition: GPS coord. de... |
print('enter with [1,2,3...] brackets')
tup = input()[1:-1].split(',')
#Input required to map out valid n x m or n^2 x n^2 Sudoku Grid
x = input('Enter mapping valid Sudoku eg. 3 for 9 x 9:')
e = input('Enter 9 for 9 x 9 ...12 for 12 x 12:')
f = input('Enter 3 if its a 9 x 9 ... n^2 x n^2:')
x = int(x)
e = int(e)
f... |
friends = ['rachel', 'jace', 'max']
msg_r = f"Hello {friends[0].title()}, it is nice to meet you!" #Each set a variable for the list above
msg_j = f"Hello {friends[1].title()}, it is nice to meet you!" #Drawing from the list in order with a personal message
msg_m = f"Hello {friends[2].title()}, it is nice to meet you!"... |
from Funciones import *
# ---- Menu Principal ------------
#Desde aquí se da inicio al programa
menuPrincipal = int(input("\n\n\t\tSistema de Diagnostico de Enfermedades \n\n 1. Comenzar Diagnostico \n 0. Salir \n\n Elija una Opcion: "))
while menuPrincipal != 0:
if menuPrincipal == 1:
Preguntas(... |
import time
import pandas as pd
import numpy as np
#Creating a dictionary containing the data sources for the three cities
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, ... |
import sqlite3
#create and connect database
conn = sqlite3.connect('Records_db.sqlite')
#create table in database
conn.execute('CREATE TABLE IF NOT EXISTS record_holders(Name text, Country text, Number_of_catches int)')
#inserting the four record holders
conn.execute('INSERT INTO record_holders VALUES("Janne Mustone... |
class LinkedList:
def __init__(self):
self._head = None
@property
def head(self):
return self._head
@head.setter
def head(self, node):
self._head = node
@property
def size(self):
p = self.head
ct = 1
if p == None:
return 0
... |
"""
Author: Drishika Nadella
Date: 20th April 2021
Time: 1432
Email: drishikanadella@gmail.com
"""
import numpy as np
# Defining the global variables
h = 4.135*10**(-15) # Planck's constant in eV/Hz
hb = h/(2*np.pi) # Reduced Planck's constant
def potential(m, E, V):
"""
This function calculates the prob... |
class Stack:
def __init__(self):
self.l = []
def push(self, data):
self.l.append(data)
def pop(self):
if self.empty():
return
self.l.pop()
def top(self):
if self.empty():
return -1
return self.l[-1]
def size(self... |
'''
create linked list by user input
detect and remove cycle using floyd cycle detection algorithm
'''
class Node:
def __init__(self, data):
self.data = data
self.link = None
class LinkedList:
def __init__(self):
self.head = None
# insert node at end
def insert_at_tail(se... |
'''
find smallest path, largest path, floor and ceil path, kth largest path
'''
from collections import defaultdict
from heapq import heappush, heappop
class Edge:
def __init__(self, src, nbr, dist):
self.src = src
self.nbr = nbr
self.dist = dist
spath = ''
sweight = float('inf')
lpath = '... |
'''
https://www.interviewbit.com/problems/paint-house/
You are given a number n, representing the number of houses.
In the next n rows, you are given 3 space separated numbers representing the cost of painting nth house with red or blue or green color.
You are required to calculate and print the minimum cost of paintin... |
class Stack:
def __init__(self):
self.head = None
self.length = 0
class Node:
def __init__(self, data):
self.data = data
self.next = None
def push(self, data):
n = self.Node(data)
n.next = self.head
self.head = n
self... |
'''
create linked list by user input
reverse linked list by pointers (recursively and iteratively)
'''
class Node:
def __init__(self, data):
self.data = data
self.link = None
class LinkedList:
def __init__(self):
self.head = None
# insert node at end
def insert_at_tail(se... |
class Movie:
def __init__(self, book, year):
self.book = book
self.year = year
def printObj(self):
print(self.book, self.year)
def sort_year(obj):
return obj.year
if __name__ == '__main__':
l = []
l.append(Movie('a', 1996))
l.append(Movie('b', 2000))
l.append(M... |
'''
Bitwise basic operation
1) Get ith bit
2) Set ith bit
3) Clear ith bit
'''
def get_ith_bit(n, i):
mask = 1<<i
print("1") if n&mask else print("0")
def set_ith_bit(n, i):
mask = 1<<i
print(n|mask)
def clear_ith_bit(n, i):
mask = ~(1<<i)
print(n&mask)
def main():
n = int(input(... |
'''
Input a 2D array and print it in wave form.
Input : r = 5, c = 4
matrix = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Output : 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
wave print = 1 5 9 13 17 18 14 10 6 2 3 7 11 15 19 20 16 12 8 4
'''
import numpy as np
def print_matrix(matri... |
import gc
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
# function to find length
def length(self):
temp = self.head
count = 0
while(temp != N... |
class Node:
def __init__(self, data):
self.data = data
self.link = None
class CircularLinkedList:
def __init__(self):
self.head = None
# function to find length of list
def length(self):
temp = self.head
count = 0
while(True):
if self.hea... |
'''
1. You are given a number n, representing the count of coins.
2. You are given n numbers, representing the denominations of n coins.
3. You are given a number "amt".
4. You are required to calculate and print the number of permutations of the n coins using which the amount "amt" can be paid.
Note1 -> You have an in... |
import math
from math import sqrt
#sem a biblioteca nenhuma importada
n = int(input('Digite um número:'))
dobro = n * 2
triplo = n * 3
raiz = n ** (1/2)
print('O dobro de {} vale {}'.format(n, dobro))
print('O triplo de {} vale {}'.format(n, triplo))
print('A raiz quadrada (arredondada) de {} é igual a {:.2f}'.format... |
tempC = float(input('Informe a temperatura em °C:'))
tempF = (tempC * 1.8) + 32
print(f'{tempC}°C é igual a {tempF}°F')
|
numero = int(input('Digite um numero qualquer: '))
if (numero % 2) == 0:
print(f'O número {numero} é PAR')
else:
print(f'O número {numero} é IMPAR')
|
# include argv
from sys import argv
# assign argv contents to variables
script, filename = argv
# open file as specified by argv[1]
txt = open(filename)
# print the contents of the file
print(f"Here's your file {filename}:")
print(txt.read())
# provide a prompt and ask user to repeat the filename
print("Type the fi... |
# -*- coding: utf-8 -*-
import numpy as np
from pandas import Series, DataFrame
print 'Series的索引,默认数字索引可以工作。'
obj = Series(np.arange(4.), index = ['a', 'b', 'c', 'd'])
print obj['b']
print obj[3]
print obj[[1, 3]]
print obj[obj < 2]
print
print 'Series的数组切片'
print obj['b':'c'] # 闭区间
obj['b':'c'] = 5
print obj
prin... |
#! /usr/bin/python3
def digit(n):
if n < 10:
return n
n -= 10
width = 2
amount = 90
start_value = 10
while True:
if n < width*amount:
return int(str(start_value + int(n/width))[n%width])
n -= width*amount
width += 1
amount *= 10
... |
#! /usr/bin/python3
# to time how long it takes your code to run, enter the problem number here
# and then run this file
problem_num = 1
import time, sys, os
if len(sys.argv) == 2:
problem_num = int(sys.argv[1])
module_name = "problem{:03}".format(problem_num)
file_name = module_name + '.py'
if not os.p... |
unicode = {0:9471,1:10102,2:10103,3:10104,4:10105,5:10106,6:10107,7:10108,8:10109,9:10110,10:10111}
x = (input("Insert digits 0-9:"))#0123456789-->any number u can give
num = " "
for i in x:
i=int(i)
i=chr(unicode[i])
num=num+i
print("the result of unicode =%s"%num)#⓿❶❷❸❹❺❻❼❽❾-->%s is must in code
|
import string
import secrets
import os
import sys
alphabet = string.ascii_letters + string.digits
i1 = input("How long should the password be? (number only) ")
i2 = input("Should I export your password to a text file? (y/n)")
bool1 = True if i2 == "y" else False
number = int(i1)
password = ''.join(secrets.choice(alp... |
def try_parse_number_int(str_number):
'''
Try to parse the string to an integer.
Successful parsing - it returns an integer value
Unsuccessful parsing - return None value
'''
try:
number = int(str_number)
return number
except:
return None
def form... |
"""Routes instances to specific methods for classes & their subclasses
Primarily used to concisely define individual methods (i.e. functions) for drawing physical things in the SandboxGame.
Ideally, there would be a view class for each individual thing (each item, each block, each creature, etc.), inheriting
fro... |
from course import Course
class Student(Course):
#Static variable
major="CSE"
def __init__(self, rollno, name):
#Instance variables
self.rollno=rollno
self.name=name
s1=Student(1,"John")
s2=Student(2,"Bill")
#Accessing class variable using class name
print(Student.major)
#Acce... |
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
def fibonacci(n):
if n<=1:
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
n=10
print(factorial(n))
for i in range(n):
print(fibonacci(i)) |
import time
#Create a program that prints out Hello every two seconds.
# while True:
# print("Hello")
# time.sleep(2)
"""Create a program that once executed the programs prints Hello instantly first, then it prints it after 1 second, then after 2, 3, and then the program prints out the message "End of the ... |
def decorator_function(function):
def wrapper_function(*args, **kwargs):
print("addition to existing print")
return function(*args, **kwargs)
return wrapper_function
@decorator_function
def display():
print("-------decorator example---------")
@decorator_function
def display_info(name, ag... |
from abc import ABCMeta,abstractmethod
'''
1.Interface in python
2.Use of metclass in python
3.use of abstract method in python
'''
class Shape(metaclass=ABCMeta):
@abstractmethod
def area():pass
@abstractmethod
def perimeter():pass
class Rectange(Shape):
def __init__(... |
'''
Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
'''
# for i in range(1,6):
# input = ('0000000000000000000000000')
# print(i, input)
'''
# Задача 2
# Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5.
# '''
# sum = 0
... |
# prac project from textbook
inventory = {' rope': 1, ' torch': 1, ' gold coin': 10}
def display_inventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + '' + k)
item_total += v
print("Total number of items: " + str(item_total))
|
#!/usr/bin/python
import random
def convert(a,b):
total = []
add = a%b
if a<=1:
total.append(a)
return total
else:
total.extend(convert(a//b,b))
total.append(add)
return total
def format(given):
if given[0] == 1:
coefficient = ''
else:
coefficient = str(given[0])
total = coeffi... |
#minha ideia é fazer um grafo com o input dado pelo usuário, fazer todas as rotas possivéis e dar print na rota com o menor custo
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[st... |
class testing(object):
def __init__(self, arg1, arg2):
print "arg1 is ", arg1
print "arg2 is ", arg2
# def my_func(arg1, arg2):
# print "arg1 is ", arg1
# print "arg2 is ", arg2
# return 0
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='a test for pa... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
level = []
if root is None:
return level
... |
# vim: set fileencoding=utf_8 :
'''
Check Primality Functions
Exercise 11 (and Solution)
Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you. Take... |
# vim: set fileencoding=utf_8 :
'''
List Overlap
Exercise 5 (and Solution)
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are comm... |
# Task 1
def optimise_single_pickup(corridor):
"""
This function takes in a list of numbers that represent values on a tile in a corridor and a robot is tasked to determine
the maximum possible sum of integers possible as long as it has energy. It starts with energy 0 and is therefore unable
to pick the... |
print("hello")
a = 10
b = 20
sum = a + b
print("sum is:", sum);
# whatever we write in program is by default is part of main
print(__name__) # main
|
# 1.Think of an Object
# Customer is Object
# name, phone, email, gender, address are attributes
# 2. Create its Class
class Customer:
#__init__: constructor, which gets executed when we create object
# self is a reference variable, which holds the hashcode of current object
# name of self can by any na... |
"""
求解f(x, y)=1/(x**2+y**2+2)的最大值点
方法:最陡爬山法
初始点: (1, 1, 0.25)
创新:每次搜索时的步长:
初始步长foot,若新点的函数值小于原值,则foot减半
"""
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits import mplot3d
from matplotlib import animation
plt.style.use('ggplot')
... |
#!/usr/bin/python
from Adafruit_PWM_Servo_Driver import PWM
import time
import sys
pwm = PWM(0x40) # Initialise the PWM device using the default address
pwm.setPWMFreq(600) # Set frequency in Hz
Off = 0 # Min pulse length out of 4096
Lowest = 102 # Min pulse length out of 4096
Low = 1024 # Min pulse length out of... |
from Stack_Node import StackNode
class Stack:
def __init__(self):
self.first = None
def push(self, symbol, value):
stack_node = StackNode(symbol, value)
if self.first is None:
self.first = stack_node
else:
stack_node.set_next(self.first)
se... |
from List import List
from Stack import Stack
class LexicalAnalizer:
def __init__(self, entry):
self.SymbolList = List()
self.ErrorList = List()
self.expression = []
self.print_list = []
self.variables = {}
self.entry = entry
self.row = 0
self.column... |
import random
class BlackJack(object):
#setting starting values for the players
#Creating empty arrays for deck, player_hand and dealer_hand
deck = []
player_hand = []
dealer_hand = []
player_value = 0
dealer_value = 0
def __init__(self):
# making the deck
for suit in ... |
def checkwin(player):
#loop through rows and columns
for c in range(0,3):
#check for horizontal line
if board[c][0] == player and board[c][1] == player and board[c][2] == player:
print "*********\n\n%s wins\n\n*********" % player
playerwin = True
return playerwin
#check for vertical li... |
def interpolation_search(array, element, start_idx, end_idx):
while start_idx <= end_idx and element >= array[start_idx] and element <= array[end_idx]:
if start_idx == end_idx:
if array[start_idx] == element:
return start_idx;
return -1;
# pos = start_idx... |
# A non-empty zero-indexed array A consisting of N integers is given.
# The consecutive elements of array A represent consecutive cars on a road.
#
# Array A contains only 0s and/or 1s:
# 0 represents a car traveling east,
# 1 represents a car traveling west.
#
# The goal is to count passing cars. We say that a pair of... |
from playsound import playsound
import os
def genre(name):
'''
Returns a statement with what genre the user has picked. This will check to make sure the user chose one of
the four genres.
Args:
A string with the user choice of genre.
Returns:
A string clarifying th... |
PARENT = {}
def MAKE_SET(v):
PARENT.update({v : v})
def FIND_SET(u):
if PARENT[u] == u:
return u
else:
return FIND_SET(PARENT[u])
def UNION(u, v):
u_root = FIND_SET(u)
v_root = FIND_SET(v)
PARENT[u_root] = v_root
def SAME(u, v):
return FIND_SET(u) == FIND_SET(v)
MAKE_... |
test_list = [1, 4, 2, 8, 10]
print ("Original list : " + str(test_list))
flag = 0
if(test_list == sorted(test_list)):
flag = 1
if (flag) :
print ("Yes, List is sorted.")
else :
print ("No, List is not sorted.") |
import sys
import re
def read_file(FILE_ONE):
with open(FILE_ONE, 'r') as file_one:
data = file_one.read()
return split_sentence(data)
def convert_file(FILE_ONE):
word_array = []
for word in FILE_ONE:
word = convert_word(word)
word_array.append(word)
return "".join(wo... |
##
# Utils.py
#
# CS 578 - HW1
# Fall 2015 @ Purdue University
#
# @author I-Ta Lee
#
# @date 09/10/2015
#
##
# print out the tree
#
# @param root_node
# - root of tree
# @param depth
# - the depth of the root
# @return None
#
def print_tree(root_node, depth=0):
if root_node.is_leaf:
print "\t" * depth, "(%d... |
from typing import List
from exercise_3.Graph import Graph
class Exercise3:
def __init__(self, problem_text):
self._n = self._parse_n(problem_text)
self._graph_edges = self._parse_graph(problem_text)
def _parse_n(self, problem_text) -> int:
return int(problem_text.split()[0])
d... |
import argparse
from pathlib import Path
from exercise_1.exercise_1 import Exercise1
def write(file, text):
with open(file, "w") as file:
file.write(text)
def read(file):
with open(file, "r") as file:
return file.read()
def validate_file(file):
if not Path(file).exists():
rais... |
'''
Реализовать скрипт, в котором должна быть предусмотрена
функция расчета заработной платы сотрудника. В расчете
необходимо использовать формулу:
(выработка в часах*ставка в час) + премия.
Для выполнения расчета для конкретных значений необходимо
запускать скрипт с параметрами.
'''
def simple_calc():
... |
# Implementing Drawing Shape test with python Drawing Libraries
# Last Edited on : 2/12/2019
# Modified by: Tien Phan
# Import library to be able to use draw tools
import pygame
# this is used to load the console
pygame.init()
# setting the size of the frame or specifying a region of an area
size = [800, 640]
screen... |
#program to find common values between two arrays
import numpy as np
x=np.array([1,2,56,78,90,77,89])
y=np.array([56,78,90])
print(np.intersect1d(x,y)) |
#program to create a 3x3x3 array with random values
import numpy as np
x=np.random.random((3,3,3))
print(x)
|
dog_name = raw_input("Enter your dog's name: ")
city = raw_input("What city do you live in? ")
print "He lives in %s with his dog %s" % (city, dog_name)
|
people = 20
cats = 30
dogs = 15
#if evaluates the condition of the statement that follows the reserved word "if"
#if the statement is True, the list of arguments in the function are executed.
#The following lines are indented because an if-statement is a function. (If not indented
#the line is not associated with the ... |
#This string is printed
print "Mary had a little lamb."
#This string has a formatter variable s (for strings). The string snow is assigned to that variable
print "Its fleece was white as %s." % 'snow'
#This string is printed
print "And everywhere that Mary went."
#The string . is multiplied 10 times and printed in a ro... |
#i = 0
#numbers = []
#def num_list(iter, val):
# i = 0
# numbers = []
# while i < val:
# print "At the top i is %d" % i
# numbers.append(i)
# i = i + iter
# print "Numbers now: ", numbers
# print "At the bottom i is %d" % i
# return numbers
#When using for loop the iterator is already included in the ran... |
# Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número]
n = input("Me fala um número de 0 a 10: ")
print ("O número informado foi", n) |
"""
Nombre: circunferencia.py
Objetivo: Permite calcular el area de una circunferencia
Autor: Antonio Rodriguez
Fecha: 28/07/2020
"""
#Importamos libreria Math
import math
#Funcion para calcular area
def calcularArea(valorRadio):
return math.pi*math.pow(valorRadio,2)
#Modulo principal
def main():
ciclo = 'S'
whil... |
def tree_counter_function(path, index):
if path[index] == "#":
return 1
else:
return 0
def search_path(right, down):
line_index = 0
tree_counter = 0
line_number = 0
with open("Day3.in") as f:
for line in f:
if(line_number % down == 0):
i = lin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 2 07:54:22 2019
@author: mlab
"""
# Pythono3 code to rename multiple
# files in a directory or folder
# importing os module
import os
# Function to rename multiple files
def main():
i = 0
for filename in os.listdir("/me... |
#!/usr/bin/env python
# coding: utf-8
from numpy import genfromtxt
import csv
import numpy as np
import math
import matplotlib.pyplot as plt
def read_csv(filename):
with open(filename, newline='') as f_input:
reader = csv.reader(f_input)
next(reader, None) #skip header
return [list(map(floa... |
class User():
"""A simple attempt to create a user."""
def __init__(self, first_name, last_name, age, city, country):
"""Initialize attributes."""
self.first_name = first_name
self.last_name = last_name
self.age = age
self.city = city
self.country = country
... |
while True:
print(""" Consola de Python
Selecciona una ooción.
CALCULAR AREA DE:
1) Cuadrado
2) Triangulo
3) Circulo
4) Salir
""")
r = input("Escribe tu respuesta: ")
if r == '1':
print("Calcular el área de un cuadrado.")
l1 = float(input("Ingresa el valor del primer lado: "))
l2 ... |
class Tweet:
def __init__(self):
self.image_filepath = ''
self.tweet_text = ''
def attach_image(self, fpath: str):
"""Attach an image to the tweet"""
self.image_filepath = fpath
def attach_text(self, tweet_text: str):
self.tweet_text = tweet_text
de... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 09:40:08 2019
@author: OJO3
"""
"""
x = int(input('enter number 1: '))
y = int(input('enter number 2: '))
if x <= y :
print(x, y)
else:
print (y, x)
"""
"""
name = str(input('Enter your name: '))
age = int(input('Enter your age: '))
if age < 18:
pr... |
import json
from linked_list import Linked_List, Link
from pprint import pprint
def read(filename):
"""So this function takes in a param that is the filename of the file that contains our json info for IPs. Returns a list of links, check the ipv6 field to determine if ipv6 or ipv4"""
with open(filename) as data_fi... |
import turtle # allows us to use the turtles library
from itertools import repeat
#wn = turtle.Screen() # creates a graphics window
alex = turtle.Turtle() # create a turtle named alex
turtle.title(__file__)
#alex.speed("fastest")
#for i in range(4):
for i in repeat(None, 4):
alex.forward(1... |
"""
Forms of income
-salary
-espp
-401k
-yearly comps
-bonus
-stock grants
-rental property
"""
import config as cfg
class IncomeType():
def __init__(self, name, yearly_income, yearly_increase):
self.name = name
self.yearly_income = yearly_income
self.yearly_increase = yea... |
#This is day 3, Control Flow & Logical operators
#Exercise 4 - Pizza Order:
bill = 0
if (size == 'S'):
bill = 15
elif (size == 'M'):
bill = 20
else:
bill = 25
if (add_pepperoni == 'Y'):
if(size == 'S'):
bill += 2
else:
bill += 3
if (extra_cheese == 'Y'):
bill += 1
print(f'Your final bill is: ... |
from turtle import Turtle
from random import randint
GOLD_APPLE = 240, 230, 155
FOOD_COLOR = GOLD_APPLE
class Food(Turtle):
def __init__(self): # Initialize
super().__init__() # get inheritance from Turtle
self.shape("turtle")
self.penup()
self.shapesize(stretch_len=0.5, stretch... |
#This is day 2, understanding data types and string Manipulation
#Exercise 3 - Your Life in weeks:
age = 90 - int(age)
months= age*12
weeks= age*52
days= age*365
# F STRINGS ARE AWESOME!
print(f'You have {days} days, {weeks} weeks, and {months} months left.')
#link to exercise
# https://replit.com/@Lludu/day-2-... |
#create a class, always in Pascal Case ThisIsPasacalCase
#attributes are variables that a class has
#methods are functions that a class can use
class User:
#initalize a class by using def __init__(self) function, you must initialize a class
def __init__(self, user_id, username, name, password):
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.