text stringlengths 5 121k |
|---|
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(s):
for i in s:
if i in punctuation_chars:
s=s.replace(i,"")
return s
positive_words = []
with open("positive_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
... |
palabras = ["hola","juan","curso","programacion","universidad"]
"""
conteo_cars = []
for p in palabras:
cnt_cars = len(p)
conteo_cars.append(cnt_cars)
"""
conteo_cars = list(map(len,palabras))
print(conteo_cars) |
x=[3,2,6,5,1,2,5,4,8,7,6]
y=x[:]
x.sort();
print(x);
y.sort(reverse = True);
print(y) |
"""
Created on Mon Oct 19 17:05:52 2015
@author: scdavis6
"""
import sqlite3 as lite
import pandas as pd
con = lite.connect('/Users/scdavis6/getting_started.db')
join_query = "SELECT name, state, year, warm_month, cold_month FROM cities INNER JOIN weather ON name = city;"
joined = pd.read_sql(join_query, con)
joi... |
"""
For this list [1, 2, 3] return [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
"""
list = [1, 2, 3]
list1 = []
list2 = []
list3 = []
for x in range(1, len(list)+1):
list1.append(x)
list2.append(2*x)
list3.append(3*x)
print([list1, list2, list3])
"""
Using List Comprehensions
"""
print([[x, 2*x, 3*x] for x in r... |
"""
@Author: Brady Miner
This program will display a temperature conversion table for degrees Celsius to Fahrenheit from 0-100 degrees
in multiples of 10.
"""
print("\nCelsius to Fahrenheit")
print("Conversion Table\n")
print("Celsius\t Fahrenheit")
for celsius in range(0, 101, 10):
fahrenheit = (celsius... |
def getNumbers(n):
for x in range(n):
yield x
print(getNumbers(9))
g = getNumbers(10)
print(g.__next__())
print(g.__next__())
print(g.__next__()) |
"""
File Name: generator.py
Name:Nahia Akter
Student#: 301106956
Date: 23/08/2020
File description: Generates and displays sentences chooding random words from files
"""
import random
def getWords(filename):
files = open(filename)
temp_list = list()
for each_line in files:
each_line = each_line.st... |
def find_gcd(a, b):
if b == 0:
return a
else:
return find_gcd(b, a % b)
def solutions(N, M):
return N // find_gcd(N, M)
print(solutions(10, 4)) |
class Person:
def __init__(self, name = "Anonymouse", umur = 0):
self.__umur = umur
self.__name = name
def getName(self):
return self.__name
def getUmur(self):
return self.__umur
def perkenalkan_diri(self):
return "Saya adalah " + self.__name + ",... |
def file_to_list(path):
completeName = path
f = open(completeName, "r")
vocab_list = []
while True:
word = f.readline()
vocab_list.append(word.rstrip())
if not word:
break
f.close()
return vocab_list
|
import sys
class node():
def __init__(self,d=None,n=None):
self.data=d
self.next=n
class linked_list(node):
def __init__(self,r=None,l=0):
self.length=l
self.root=r
def add(self,d):
new_node=node()
new_node.data=d
if (self.root==None... |
from os.path import isfile
from sqlite3 import connect
file_name = 'tasks.db'
class Database:
"""Connector for ``Database`` to create and modify.
>>> Database
``create_db`` - creates a database named 'tasks.db' with table as 'tasks'
``downloader`` - gets item and category stored in the table 'tasks... |
import operator
d = {'a': 100, 'b': 200, 'c': 300, 'd': 400, }
print('Original dictionary :' ,d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in de... |
import requests
import json
import properties
'''
News article object to contain all relevant information from api
'''
class newsArticle:
imageUrl = ""
title = ""
description = ""
author = ""
def __init__(self, imageUrl, title, description, author):
self.imageUrl = imageUrl
self.title = title
self.descript... |
a = {move: 1 for move in ['K', 'U']}
a = 3
b = 'string'
c = True
print(a, b, c)
a = 3
if a == 3:
print('a value is ', a)
|
def printTriangle(incr, base, a_center):
for y in range(4):
etoiles = base + (y*incr)
print((etoiles*"*").center(a_center))
def printSapin(height):
center = ((1+(( height-1)*2))+( height*2)) + 2*( height*2)
for y in range(1, height+1):
printTriangle(y*2, 1+((y-1)*2), center)
pr... |
import re
cadena = 'Estoy trabajando con Python en domingo y Semana Santa'
busqueda = 'domingo'
if print(re.search(busqueda, cadena)) is not None:
print(f'Se ha encontrado el termino {busqueda}')
else:
print(f'No se ha encontrado el termino {busqueda}')
|
import random
class Dice:
def roll(self):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
result = (dice1, dice2)
return result
game = Dice()
print(game.roll())
|
'''
Leetcode- 122. Best Time to Buy and Sell Stock II - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Time complexity - O(N)
Space complexity - O(1)
Approach - We need to find the peak and valleys in an given array
'''
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if le... |
class Solution(object):
"""
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"... |
import random
MIN_LIMIT = -1
MAX_LIMIT = 1
def create_point(min_limit=MIN_LIMIT, max_limit=MAX_LIMIT):
point = {"x": random.randint(min_limit, max_limit),
"y": random.randint(min_limit, max_limit)}
return point
def create_triangle(points_name_str: str) -> dict:
return {key: create_point() f... |
import string
import random
print(string.ascii_lowercase)
value = random.randint(10, 20)
my_list = [1, 2, 3, 10, 20, 30]
my_str = 'qwerty'
choice_from_list = random.choice(my_str)
print(value, choice_from_list)
from random import randint, choice
my_str = 'qwerty'
choice_from_list = choice(my_str)
value = rand... |
import os
fo=open("Test.txt","w")
fo.write("Create a file")
fo.flush()
fo.close()
print("done")
mid=input(":")
fo=open("Test.txt","r")
str=fo.read(5)
print("read the line : ",str)
fo.close()
print("done")
mid=input("change the file name right?:")
os.rename("Test.txt","change.txt")
fo=open("change.txt","r")
print(... |
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
for i in range(len(usernames)):
usernames[i] = usernames[i].lower().replace(' ', '_')
print(usernames) |
def party_planner(cookies, people):
num_each = cookies // people
leftovers = cookies % people
return(num_each, leftovers)
num_each, leftover = party_planner(100,'g')
print("Number of cookies each: {}".format(num_each))
print("Number of cookies left: {}".format(leftover))
|
a = {"Name": "Glenn", "DOB": 1987}
b = []
c = ()
d = {0, 1}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
myDict = {}
print(myDict)
myDict["Name"] = "Glenn"
myDict["DOB"] = 1987
myDict["Age"] = 2019 - myDict["DOB"]
print(myDict)
def get_data():
name = input("What is your name: ")
year = input("... |
def party_planner(cookies, people):
leftovers = None
num_each = None
try:
num_each = cookies // people
leftovers = cookies % people
except ZeroDivisionError:
print("Oops, you entered 0 people will be attending.")
print("Please enter a good number of people for a party.")... |
starting = 0
ending = 20
current = starting
step = 6
while current < ending:
if current + step > ending:
break
if current % 2:
continue
current += step
print(current)
|
countries = ['India', 'Germany', 'France', 'Thailand', 'Georgia']
print(countries)
print(sorted(countries))
print(countries)
x = sorted(countries)
x.reverse()
print(x)
print(countries)
countries.reverse()
print(countries)
countries.reverse()
print(countries)
countries.sort()
print(countries)
countries.sort(reverse=True... |
name = "\nPlease enter a name: "
guests_book = 'guests_book.txt'
with open(guests_book, 'a') as gs:
while True:
names = input(name)
if names == 'stop':
break
else:
print(f"Hello, {names.title()}!")
gs.write(f"Hello, {names.title()}!\n")()
|
pizzas = ['Cheese', 'Barbeque', 'Lisitsa']
for pizza in pizzas:
print("I like " + pizza + " pizza")
print("I really love pizza!\n")
animals = ['dog', 'cat', 'cow']
for animal in animals:
print("A " + animal.title() + " gives a milk to its babies!")
print("Any of these animals would make a great pet!\n")
friend_... |
def mutliplesof3and5(n):
if(n%3==0 or n%5==0):
return 1
else:
return 0
def sum(n):
temp=0
for i in range(3,n):
if(mutliplesof3and5(i)):
temp=temp+i
return temp
n=5
sum(n) |
import numpy as np
import cv2
img = cv2.imread('lena.jpg', 1)
img = cv2.line(img, (0, 0), (255, 255), (255, 0, 0), 5)
img = cv2.arrowedLine(img, (255, 255), (400, 400), (255, 0, 0), 5)
img = cv2.rectangle(img, (50, 50), (200, 200), (100, 100, 100), 5)
img = cv2.circle(img, (200, 200), 20, (120, 120, 1... |
import sys
MAX_DIGITS = 5
def genfonts(prefix, width, height):
yoffset = height - 2
for charindex in range(10):
char = chr(65 + charindex);
for numdigits in range(2, MAX_DIGITS+1):
spritewidth = width * numdigits
xoffset = int(spritewidth / 2)
for digit in range(1, numdigits+1):
patchwidth = s... |
import os, shutil
def main():
print('Enter input directory path')
folder1 = input()
print('Enter New File Prefix')
prefix = input()
print('Enter output directory path')
folder2 = input()
os.chdir(folder1)
i = 34
for root, dirs, files in ... |
def Average_Atomic_Mass():
isotopes = input("How many isotopes?")
average = 0
for x in range(1,int(isotopes) + 1):
mass = input("What is the isotope %s's mass in amu?" % x)
percent = input("How abundant is it in %?")
average += (float(mass)*(float(percent)/100))
print("%s ... |
def main():
print("This is the functions.py file.")
for i in inclusive_range(0,25,1):
print(i, end = ' ')
def inclusive_range (start,stop,step):
i = start
while(i < stop):
yield i
i += step
if __name__ == "__main__":
main()
|
def reverse(s):
return s[::-1]
def reverse5(s):
s1 = ''
length = len(s) - 1
while length >= 0:
s1 = s1 + s[length]
length = length - 1
return s1 |
'''Table of Contents
What are Strings?
Indexing
Negative Indexing
Slicing
Stride
Concatenate Strings
Escape Sequences
String Operations
'''
"Michael Jackson"
'Michael Jackson'
'1 2 3 4 5 6 '
'@#2_#]&*^%$'
name = "Michael Jackson"
print(name, "length:", len(name))
print(name[0])
print(n... |
'''Table of Contents
About the Dataset
Viewing Data and Accessing Data with pandas
'''
'''About the Dataset
The table has one row for each album and several columns
artist - Name of the artist
album - Name of the album
released_year - Year the album was released
length_min_sec - Length of the album (hours,... |
print((2*9)+(10*5))
a = 5
print(a)
a = a*5
print(a)
two_dogs = 2
|
my_stuff = {"key1" : "value1", "key2" : "value2"}
print(my_stuff["key2"])
print(my_stuff)
my_dict = {"key1" : 123, "key2" : "value2", "key3" : {'123' : [1,2,"grabme"]}}
print(my_dict["key3"]['123'][2])
print((my_dict["key3"]['123'][2]).upper())
my_diet = {'bfast' : "milk" , "lunch" : "oats"}
my_diet['lunch'] =... |
import random
import time
from os import system, name
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def game():
words = ["banana", "grape", "orange", "mango", "cherry", "apple", "pear", "peach"]
strikes = int(7)
play = True
while play:
... |
def beg():
b = int(input('how many integers?\n'))
if b == 0:
print("sorry not allowed")
quit()
a = [int(x) for x in input('Please enter the values now\n').split(' ')]
if len(a) == b:
return a
else:
print('incorrect amount of values within sequence')
def gr... |
def reto1(palabra):
cantidad = len(palabra)
i = 0
correcto = 0
num = cantidad
while i<cantidad:
num-=1
if palabra[num] == palabra[i]:
correcto+=1
i+=1
if correcto == cantidad:
result = True
else:
result = False
print(result)
reto1("ojo")
def reto2(numero):
... |
from sklearn.impute import KNNImputer
from utils import *
import matplotlib.pyplot as plt
def knn_impute_by_user(matrix, valid_data, k):
""" Fill in the missing values using k-Nearest Neighbors based on
student similarity. Return the accuracy on valid_data.
See https://scikit-learn.org/stable/modules/gen... |
import sqlite_manager as db
def createNewDB(database, rooms):
'''
This function initializes a new database.
A new gameSave database will be created with the required tables. rooms number of
stock rooms then get inserted into the database. The database name also gets added to the
gameFilePaths.txt file.
... |
def fib(n):
if n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fastFib(n):
a, b = 0, 1
for k in range(n):
a, b = b, a+b
return a
print(fastFib(45)) |
def make_matrix(rows, column):
"""
>>> make_matrix(3,5)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> make_matrix(4,2)
[[0, 0], [0, 0], [0, 0], [0, 0]]
>>> m = make_matrix(4,2)
>>> m[1][1] = 7
>>> m
[[0, 0], [0, 7], [0, 0], [0, 0]]
"""
matrix = []
for i in rang... |
"""
Author: Nathan Dunne
Date last modified: 16/11/2018
Purpose: Create a data frame from a data set, format and sort said data frame and display
data frame as a table.
"""
import pandas
from tabulate import tabulate
class DataFrameDisplayFormat:
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""Out of the R&D Spends and Marketing spends, which yields better profit?
With the assumption that the location of the startup hold now significance.
A Caveat to Linear Regressions:
1. Linearity
2. Homoscedasticity
3. Multivari... |
from time import time
times = []
for i in range(10):
times += [time()]
delta = []
old = ""
for elem in times:
print("Time:", elem)
if old == "":
res = "No delta"
else:
res = elem - old
print("Delta:", res)
old = elem
|
def optimal_path(grid):
n = len(grid)
record = []
for i in range(n):
row = []
for j in range(n):
row.append(-1)
record.append(row)
record[0][0] = grid[0][0]
def sum_path(i,j):
if record[i][j] != -1:
return record[i][j]
if i < 0 or i... |
from pprint import PrettyPrinter
pp = PrettyPrinter()
class DisjointSet:
def __init__(self):
self.universe = ['a','b','c','d','e']
self.PARENT = {}
for item in self.universe:
self.PARENT[item] = item
self.PARENT[self.universe[3]] = self.universe[1]
self.GRAPH = ... |
def b_search(nums, search_item, start, end):
if end < start:
return -1
k = int((end-start)/2) + start
y = search_item
if nums[k] < y and k == end:
return k
elif nums[k] < y and y <= nums[k+1]:
return k
elif y < nums[k]:
return b_search(nums, search_item, start, k-... |
from queue import PriorityQueue
def count_subarrays(arr):
n = len(arr)
result = [1] * n
stack = []
for i, v in enumerate(arr):
if not stack:
result[i] += i
else:
while stack and stack[-1][0] < v:
stack.pop()
if stack:
... |
class Graph:
def __init__(self):
self.nodes = {}
def __repr__(self):
return str(self.nodes)
def addEdge(self, src, tgt):
self.nodes.setdefault(src,[]).append(tgt)
self.nodes.setdefault(tgt,[])
def bfs(self, root):
queue = [root]
vi... |
"""
a Rectangle
"""
from anchor import Anchor
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self.bbox = None
self.norm_bbox = None
self.calc_bbox(Anchor())
self.normalize_bbox()
def calc_bbox(self, anchor):
... |
list1 = [2, 5, 4, 1, 6]
list2 = [1, 6, 2, 3, 5]
print ("The first list is : "+ str(list1))
print ("The second list is : "+ str(list2))
if len(list1) == len(list2):
print ("Length of the lists are same")
else :
print ("Length of the lists are not same")
|
fn=input("enter filename")
f=fn.split(".")
print("extension of file is;"+ f[-1]) |
from pyclbr import Class
name = "Daryl"
print(f"Hello, {name}!")
i = 28
f = 2.8
b = False
n = None
x = 28
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
coordinates = (10.0,20.0)
names = ["Alice", "Bob", "Charlie"]
for i in range(5):
print(i... |
from tkinter import *
import random
from tkinter import messagebox
root = Tk()
root.geometry("500x500")
root.title("Generate Your Numbers")
numb_ans = StringVar()
numb_ent = StringVar()
mylist = []
mynewlist = [numb_ent]
ent_numb = Entry(root, textvariable=numb_ent)
ent_numb.place(x=50, y=25)
Label(root, textvariabl... |
class Ball:
def __init__(self, color="unknown", circunf=0, material="unknown"):
self.color = color
self.circunf = circunf
self.material = material
def trocaCor(self):
troca = input("Deseja mudar a cor atual {}? [sim/nao]".format(self.color))
troca = tr... |
class BurrowsWheelerTransform:
"""Transforming a string using Burrows-Wheeler Transform"""
def __init__(self):
pass
def bwt(self,f):
"""Applies Burrows-Wheeler transform to input string.
Args:
f (File): The file object where each line is a '0' or '1'.
Return... |
"""
December 3, Advent of Code 2015 (Jonas Nockert / @lemonad)
"""
from common.puzzlesolver import PuzzleSolver
class Solver(PuzzleSolver):
@classmethod
def make_move(cls, move, pos):
if move == '^':
pos = (pos[0], pos[1] + 1)
elif move == 'v':
pos = (pos[0], pos[1] -... |
my_file = "my_phone_book.txt"
def add_entry(first_name, last_name, phone_number):
entry = first_name + "," + last_name + "," + phone_number + "\n"
with open(my_file, "a") as file_handler:
file_handler.write(entry)
def get_list_from_file(file_name):
phone_book_list = []
with open(file_na... |
numbers = [10, 8, 4, 5, 6, 9, 2, 3, 0, 7, 2, 6, 6]
min_item = numbers[0]
max_item = numbers[0]
for num in numbers:
if min_item > num:
min_item = num
if max_item < num:
max_item = num
print("Minimum Number : ", min_item)
print("Maximum Number : ", max_item) |
def is_prime(x):
i=1
while i<x:
if x%i==0:
if i!=x and i!=1:
return False
i=i+1
return True
print(is_prime(5191))
|
import split
import operator
def readFile(fileIn):
content=""
for line in fileIn :
content+=line
return content
def wordCount(contents):
wordcount={}
for word in split.tsplit(contents,(' ','.','!',',','"','\n','?')):
if word != '':
if word not in wordcount:
... |
import sys
def fib(n):
n = int(n)
if n <= 1:
return 1
return fib(n-1)+ fib(n-2)
if __name__ == '__main__':
import pdb; pdb.set_trace()
print(fib(sys.argv[-1]))
|
"""
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
"""
class Solution:
... |
"""
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
"""
class TwoSu... |
"""
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"""
class Solution:
def singleNumber(self, A):
res = 0
for n in A:
... |
"""
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,... |
class stack:
def __init__(self):
self.s = []
def push(self, val):
self.s.append(val)
def pop(self):
return self.s.pop()
def top(self):
return self.s[-1]
class MinStack:
def __init__(self):
self.s = stack()
self.min_s = stack()
def push(self... |
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution:
def cloneGraph(self, node):
if node is None:
return None
new_nodes = {}
parent = {node : None}
self.dfs(node, new_nodes, parent)
... |
"""
e.g. 12 : return [ [1, 12], [2, 2, 3], [2, 6], [3, 4] ]
"""
def factors_of_num(num):
res = []
list_aux = []
helper(num, res, list_aux)
return res
def helper(num, res, list_aux):
if num == 1:
if len(list_aux) < 2:
list_aux.append(num)
res.append(list_aux[:])
... |
"""
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
T is "ece" which its length is 3.
"""
import collections
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s):
if s is None:
return 0
if len(s) =... |
"""
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
A... |
"""
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequenc... |
"""
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (... |
class Graph:
def __init__(self, vertices = [], Adj = {}):
self.vertices = vertices
self.Adj = Adj
def itervertices(self):
return self.vertices
def neighbors(self, v):
return self.Adj[v]
class DFSResult:
def __init__(self):
self.parent = {}
self.st... |
"""
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
"""
class ... |
"""
A peak element is an element that is greater than its neighbors.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
"""
class Solution:
def findPeakElement(self, num):
if len(num) == 0:
return None
if len(num) ==... |
"""
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
"""
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
... |
cuts = [[-5, 5], [-5, 5], [-5, 5]]
f = "x**2 - 2*x + y**2 + 4*y + z**2 - 8*z + 21"
def findExtr(f, c):
cuts = c
k = len(cuts)
m = 5
d = cuts[0][1] - cuts[0][0]
h = d / m
min = None
e = 0.0001
while (h > e):
grid = []
for i in range(m):
x =... |
import matplotlib.pyplot as plt
from random import randint as rnd
amountOfDice = int(input('Hur många tärningar vill du kasta?'))
amount = int(input('Hur många gånger vill du kasta?'))
amountOfSides = int(input('Hur många sidor ska tärningarna ha?'))
sum = []
frequency = []
plt.plot(sum, frequency[amountOfDice... |
"""Terminator."""
import rospy
from PiBot import PiBot
robot = PiBot()
count = int()
robot.get_leftmost_line_sensor()
robot.get_rightmost_line_sensor()
def counting(count):
"""Counting."""
if count == 3:
print("Turning Right")
robot.set_right_wheel_speed(-30)
robot.set_left_wheel_spee... |
import threading
import numpy as np
import global_var
from math import floor
class VisualConvolutionThread(threading.Thread):
def run(self):
def start_animation():
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
... |
weight = input('Enter your weight in pounds: ')
height = input('Enter your height in inches: ')
weight_float = float(weight)
height_float = float(height)
BMI = (5734 * weight_float) / (height_float**2.5)
print("Your BMI is: ", BMI)
weight_kg = weight_float * .453592
height_meters = height_float * .0254
BMI = ... |
s=input()
a=''
for x in s:
if x.islower():
a=a+x.upper()
elif x.isupper():
a=a+x.lower()
print(a)
|
a=input()
if((a>='a' and a<='z') or (a>='A' and a<='Z')):
print ("Alphabet")
else:
print("No")
|
s=input()
a=''
for x in s:
a = a + chr(ord(x) + 3)
print(a)
|
a=int(input())
b=0
c=a
while (a>0):
d=a%10
b=b+(d**3)
a=a//10
if (b==c):
print ("yes")
else:
print ("no")
|
""" Remove rows from a tabular file. """
from hed.tools.remodeling.operations.base_op import BaseOp
class RemoveRowsOp(BaseOp):
""" Remove rows from a tabular file.
Required remodeling parameters:
- **column_name** (*str*): The name of column to be tested.
- **remove_values**... |
class queue_item():
def __init__(self):
self.data = None
self.next = None
class queue():
def __init__(self):
self.head= None
def enqueue(self, data):
new_item = queue_item()
new_item.data = data
new_item.next = self.head
self.head = new_... |
total_amount = float(input("Enter the total amount: "))
tip_percentage_amount = float(input("Enter the tip percentage amount: "))
def tip_amount(total_amount, tip_percentage_amount):
tip = total_amount * tip_percentage_amount / 100
print("$" + str(tip))
return tip
tip_amount(total_amount, tip_percent... |
def fib(n):
print(f'calculando fib de {n}')
if n <= 1:
return n
else:
return fib(n - 2) + fib(n - 1)
print(fib(7))
|
class Mamifero(object):
def __init__(self, cor_de_pelo, genero, andar):
self.cor_de_pelo = cor_de_pelo
self.genero = genero
self.num_de_patas = andar
def falar(self):
print(f'ola sou um {self.genero} mamifero e sei falar')
def andar(self):
print(f'estou andando sobre {self.num_de_patas}')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.