text stringlengths 37 1.41M |
|---|
import turtle
esquerda = int(input('Esquerda:'))
topo = int(input('Topo:'))
largura = int(input('Largura:'))
altura = int(input('Altura:'))
x = int(input('X:'))
y = int(input('Y:'))
if (x > esquerda) or x < esquerda and x < esquerda - largura:
print('Não colide')
elif x >= esquerda - largura and x <= esquerda:
... |
import string
def is_pangram(sentence):
for letter in string.ascii_lowercase:
if letter in sentence.lower():
pass
else:
return False
return True |
'''Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3'''
n=input()
l=0
d=0
for i in n:
if i.isalpha():
l+=1
elif i.isdigit():
d+=1
print... |
'''Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.
Example: If the following n is given as input to the program:
10
Then, the output of the program should be:
0,2,4,6,8,10
In case of input data being supplied to the question, it shou... |
'''Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 _ C _ D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.For example Let us assume the following com... |
'''Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
'''
import random
n=random.sample([i for i in range(100,201) if i%2==0],5)
print(n) |
'''Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9'''
n=input()
u=0
l=0
for i in n:
if i.islower():
l+=1
elif i.isup... |
'''Define a function which can generate a dictionary where the keys are numbers
between 1 and 20 (both included) and the values are square of keys.
The function should just print the keys only.'''
def dict_print():
dict1={i:i**2 for i in range(1,21)}
for i in dict1:
print(i)
return dict1
dict_prin... |
'''Please write a program which count and print the numbers of each character in a string input by console.
Example: If the following string is given as input to the program:
abcdefgabc
Then, the output of the program should be:
a,2
c,2
b,2
e,1
d,1
g,1
f,1'''
n=[i for i in input()]
dict1={i:n.count(i) for i in n}
for i... |
'''Please write a program to randomly print a integer number between 7 and 15 inclusive.'''
import random
n=random.randint(7,15)
print(n) |
'''Define a function that can accept two strings as input and concatenate them and then print it in console.'''
cnct=lambda s,s1:s+s1
print(cnct(input(),input())) |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 17:01:10 2019
@author: Vidya
Solution to Project Euler problem 2
https://projecteuler.net/problem=2
Problem Statement :
>>>>>>>>>>>
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms w... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 13 16:47:02 2019
@author: Vidya
Solution to Project Euler problem 16
https://projecteuler.net/problem=16
Problem Statement :
>>>>>>>>>>> Power digit sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number... |
#!/usr/local/bin/python
"""
tokenizer in python (albeit a (very) long one
outputs similar to shell script
"""
import os
import re
import subprocess
import sys
import tempfile
if len(sys.argv) < 2:
print("Error! No argument given. Need the filename for the command.")
sys.exit(1)
lines = open(sys.argv[1], 'r').rea... |
"""
Name:Matthew Coutts
Class: CMSPC 462 - FA 2020
Project 2 - Create a BT and a BST and implement functions
Date: October 15th, 2020
"""
from big_o import big_o
import time ##first we import the time function
BSTtime = [] # this will hold our time for the function BST
BT_Time = [] # this will hold our time for th... |
"""
*** BaSuZ3 ***
This problem was asked by Airbnb.
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
Follow-up... |
"""
*** BaSuZ3 ***
This problem was asked by Apple.
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
"""
# Solución / Solution - class, function, etc.
def agrega_uwus(texto, uwu = 'uwu'):
"""
Acá se coloca la descripción de la función (lo que se muestra... |
#!/usr/bin/env python3
if __name__ == '__main__':
# Text in Python is represented as things called strings. You can use single or double quotes to assign a string.
#
a = 'This is a string.'
b = "This is also a string."
c = "So's this, and it has an appostrophe."
d = str()
print(a, b, c)
... |
import overload
print("===================")
print("print(overload.foo())")
print(overload.foo())
print("===================")
print("overload.foo(4, 3.0)")
overload.foo(4, 3.0)
print("===================")
print("print(overload.foo(0, 3.0, 56, 2.0))")
print(overload.foo(0, 3.0, 56, 2.0))
print("===... |
from constants import *
color = [BLUE, RED, GREEN, WHITE, YELLOW, VIOLET, AQUA]
def text_objects(text, font, color):
"""
Sets up text format and returns it
:param str text: text to format
:param font: Font
:param color: Color of text
"""
text_surface = font.render(text, True, color)
... |
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
"""
@author: Henrique Igai Wang
Class that represents each item of customer's cart
"""
from classes.item_class import Item
class Cart:
def __init__(self):
self.productList = []
def __str__(self):
string = ""
productList = self.g... |
def login():
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "1234":
return True
else:
return False
def showMenu():
print(15*"-" + "Menu" + 15*"-")
print("1. Vat Calculator")
print("2. Price Calculator... |
__author__ = 'isaac'
"""
Written By: Gil Rael
The following program prints the A Friday - Fridays that are scheduled days off in 2017,
The program takes the hard coded first A Friday that is a scheduled day off in January 2017
and then calculates the other A Fridays in 2017 based on this initial date.
Planning
Mo... |
server = []
while True:
sname = input("Please enter any server ")
if sname in server:
print(sname,"Server Exist in our inventory")
else:
print(sname,"Server not found")
print("to add --",sname,"enter 'y': or exit (press any other key:)")
i = input()
if i == 'y' :
server.append(snam... |
#my_list = [2,3,4,5,6,8,10]
my_list = input("ENTER YOUR LIST ")
my_list=list(my_list)
print(type(my_list))
print "MY ORIGINAL LIST IS" ,my_list
for i in range(len(my_list)):
if ((my_list[i] % 2) == 0 ):
print( str(my_list[i]) + " -->element is even")
print('TESTING')
else:
print( str(my_... |
import unittest
from domain.car import Car
class TestCar(unittest.TestCase):
def test_create(self):
car=Car("C1",2007,780)
self.assertEqual(car.get_fuel(),"C1")
self.assertEqual(car.get_year(),2007)
self.assertEqual(car.get_price(),780)
... |
#! python3
# incidentParser.py - parses incident data from the Boca Police Department and cleans it up.
import re
import csv
raw_incident_file = "bocaIncidents.csv"
headers = ['type', 'date', 'address'];
def main():
parse_rows();
write_new_file();
print(*parsed_rows, sep='\n')
parsed_rows = []
def par... |
def main():
num=0
print('Loop 1:')
while num < 6:
print(num)
num += 1
print('\nLoop 2:')
for num in range(6):
print(num)
print('\nLoop 3:')
for num in range(0,6):
print(num)
print('\nLoop 4:')
for num in range(1,11,2):
print(num)
print(... |
import math
user_name = input("What is your name? ")
# old way with concatenation:
greeting = "Hello, " + user_name + "!"
# or with string formatting:
greeting = "Hello, {0}!".format(user_name)
# new way with f-string:
greeting = f"Hello, {user_name}!"
print (greeting)
# format specification is also available:
pi_state... |
import random
def get_rand_nums(low,high,num):
for number in range(num):
yield random.randint(low,high)
print('First time through:')
for num in get_rand_nums(1,100,5):
print(num)
print('Second time through:')
for num in get_rand_nums(1,100,5):
print(num) |
from random import randint
def roll_dice():
return (randint(1,6), randint(1,6), randint(1,6))
def play():
n=0
while True:
n+=1
r = roll_dice()
print('{}: {},{},{}'.format(n, r[0], r[1], r[2]))
if r[0] == r[1] == r[2]:
print('Wow! Triples!')
input()
def ... |
#problem 1
def initialLetterCount(wordList):
dict = {}
for word in wordList:
firstLetter = word[0]
if firstLetter not in dict:
dict[firstLetter] = 1
else: ... |
Sum = 0
#This Function calculates the sum of the square of each digitt of any number
def sumOfSquares(a):
global Sum
Sum =(a%10)**2 + Sum
if a == 0:
a = Sum
Sum = 0
return a
a = a/10
return sumOfSquares(a)
def isHappy(a):
if sumOfSquares(a) == 4:... |
import random
min = 1
max = 6
roll_again = "y"
while roll_again is "y":
print("rolling the dices...")
print("the values are")
print(random.randint(min,max))
print(random.randint(1,6))
roll_again = input("roll the dices again? ")
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
carry = 0
p = l1
q = l2
curr = dummy = ListNode(0)
whi... |
"""
===================================================
Introduction to Machine Learning (67577)
===================================================
Skeleton for the decision tree classifier with real-values features.
Training algorithm: CART
Author: Noga Zaslavsky
Edited: Yoav Wald, May 2018
"""
import numpy as n... |
def play_quiz():
print("Determining your Patronus....")
print("When chosing your answer, please put the letter that is in brackets.")
print(" ")
print(" ")
print("You enter the woods, and see a small, shapeless light hovering before you.")
print("As you try to get closer to it, the shapeless li... |
#!/usr/bin/env python3
'''matriz é uma lista com três elementos,
onde cada elemento é uma linha da matriz. '''
matriz = [[1,2,3], [4,5,6], 6,7,8]
print(matriz[1])
'''O primeiro índice seleciona a linha,
e o segundo índice seleciona a coluna.'''
print(matriz[1][1]) |
#!/usr/bin/env python3
# Exemplo de composicao
import math
# from raio import area
# from calcula_distancia import distancia
def area(raio):
return math.pi * raio**2
def distancia(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dquadrado = dx**2 + dy**2
resultado = math.sqrt(dquadrado)
return r... |
#!/usr/bin/env python3
def valorAbs(x):
if x == 0:
return 0
elif x < 0:
return -x
elif x > 0:
return x
print(valorAbs(2))
print(valorAbs(-1))
print(valorAbs(0)) |
#!/usr/bin/env python3
def imprime_dobrado(nome):
print (nome, nome)
def concatDupla(part1 , part2):
concat = part1 + part2
imprime_dobrado(concat)
#Esta função recebe dois argumentos, concatena-os, e então
# imprime o resultado duas vezes.
# Podemos chamar a função com duas strings:
canto1 = 'Pie Jes... |
#!/usr/bin/env python3
"""O Teorema de Pitágoras diz que: “a soma dos quadrados dos catetos é igual
ao quadrado da hipotenusa.”"""
import math
def calculaHipotenusa(x, y):
z = x**2 + y**2
hipo = math.sqrt(z)
return hipo
print(calculaHipotenusa(9,12)) |
#!/usr/bin/env python3
import string
fruta = 'banana'
indice = str.find(fruta, 'na', 3)
print(f'posicao: {indice}') |
#!/usr/bin/env python3
def imprimeMultiplos(n, altura): # altura refere-se a tabuada nesse caso.
i = 1
while i <= altura:
print (n, 'x', i, '=', n*i, '\t',)
i = i + 1
print()
# teste da funcao imprimeMultiplos
# imprimeMultiplos(3, 2)
def imprimeTabMult(altura): # altura nesse caso ref... |
#!/usr/bin/env python3
def compara(x, y):
if x > y:
return 1
elif x == y:
return 0
else:
return -1
print(compara(1,2))
print(compara(3,2))
print(compara(3,3)) |
""" Display url using the default browser.
by frost (passion-xbmc.org)
"""
# Modules General
import webbrowser
from traceback import print_exc
# Modules XBMC
import xbmc
def notification( header="", message="", sleep=5000, icon="DefaultIconInfo.png" ):
""" Will display a notification dialog with the specifi... |
# Import random library
import random as Random
# Create function that takes in a parameter for the fruits array and the number of fruits requested
def pick_fruits(fruits, num_fruits=3):
# Set the value of the fruits array to the value returned by the get avalible fruits functtion
fruits = get_avalible_fruits(... |
import numpy as np
import pandas as pd
# drop() method has inplace=False as default
def df_drop_column() :
old_data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Height': [5.1, 6.2, 5.1, 5.2],
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
old_frame = pd.DataFrame(old_data)
address =... |
#Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
thistuple = ("apple", "banana", "cherry")
print(thistuple)
thattuple = tuple(("honda", "maruti", "hyundai"))
print("tuple created using constructor ", thattuple)
print("Count : ",len(thistuple))
for x in thistuple:
print(x)
if... |
global solved
AllPuzzles = []
with open ('sudoku.txt') as file:
for line in file:
if line[0] == "G":
AllPuzzles.append([])
else:
AllPuzzles[-1].append(line.strip())
class Square():
def __init__(self, number, row, column, box):
self.number = number
self.r... |
#PF-Exer-18
def get_count(num_list):
count=0
for i in range(0,len(num_list)-1):
if(num_list[i]==num_list[i+1]):
count=count+1
# Write your logic here
return count
#provide different values in list and test your program
num_list=[1,1,5,100,-20,-20,6,0,0]
print(get_co... |
def find_common_characters(msg1,msg2):
a=''
for i in range(0,len(msg1)):
for j in range(0,len(msg2)):
if(msg1[i]==msg2[j]):
if(msg1[i]!=" "):
if msg1[i] not in str(a):
a=a+msg1[i]
if(a==''):
a=-1
... |
#PF-Tryout
def generate_next_date(date,month,year):
#Start writing your code here
if(month==1 or month==3 or month ==5 or month ==7 or month==8 or month==10):
if(date>=1 and date<=30):
next_date=date+1
next_month=month
next_year=year
else:
... |
#goal of this tryout is to create a function from scratch and invoke it for the given problem
def convert_temp(temp):
sign=temp[-1]
temp=int(temp[0:-1])
if(sign=="C" or sign=="c"):
tempval=(temp*(9/5)+32)
tempval=str(tempval)+"F"
elif(sign=="F" or sign=="f"):
tempval=((te... |
# CSV = comma seperated variables
# very common output for spreadsheet programs
import csv
# Open the file
data = open('example.csv',encoding='utf-8')
# csv.reader
csv_data = csv.reader(data,delimiter=',',quotechar='"')
# reformat it into a python object list of lists
data_lines = list(csv_data)
# print(data_lines[0])
... |
class Player:
def display(self):
print('Name :', self.name)
print('Level:', self.level)
p1 = Player()
p1.name = 'Daikon'
p1.level = 1
p1.display()
p2 = Player()
p2.name = 'Ninjin'
p2.level = 2
p2.display()
|
def find(c):
if(d.__getitem__(c)==None):
return False
else:
d.__setattr__(c,(d.__getitem__(c)+1))
def Encrypt():
endata = ""
for i in range(len(data)):
c = chr((ord(data[i]) + int(key1)) % 128)
if (ord(c) <= 31 and ord(c) >= 0):
endata += chr(ord(c) + 32)
e... |
def Encrypt():
endata=""
for i in range(len(data)):
c=chr((ord(data[i])+int(key1)) %256)
if(ord(c) <=31 and ord(c) >=0):
endata+=chr(ord(c)+32)
else:
endata+=c
return endata
def Decrypt():
dedata=""
for i in range(len(endata)):
if(ord(endata[i])-int(key2) <=31 and ord(endata[i])-int(key2) >=... |
def solution(arr, divisor):
possible_divide = []
for i in arr:
if i % divisor == 0:
possible_divide.append(i)
if len(possible_divide) == 0:
possible_divide.append(-1)
return possible_divide
else:
possible_divide.sort()
return possible_divid... |
"""
Entradas
venta en galones--->float--->gal
precio por litro--->float--->precio
Salidas
venta en litros--->float--->lts
total venta--->float--->total
"""
print("COBRO GASOLINERIA")
gal=float(input ("Ingrese la venta en galones: "))
lts=(gal*3.785)
total=(lts*50000)
print("El total de la venta es: "+str(total)) |
"""
en una tienda efectúan un descuento a los clientes dependiendo del monto de la compra. El descuento se efectúa con base en el siguiente criterio:
a. Si el monto es inferior a $50.000 COP, no hay descuento.
b. Si está comprendido entre $50.000 COP y $100.000 COP inclusive, se hace un descuento del 5%
c. Si está comp... |
"""
Entradas
Capital
Salidas
Ganancia
La razon es un dato conocido, no se toma como entrada
"""
cap=int (input("Ingrese el valor del capital invertido: "))
ganancia=(cap*0.02)
print("La ganancia mensual es de: "+str(ganancia)) |
""""
entradas
lectura actual--->float--->lact
lectura anterior--->float--->lant
valor kw--->float--->kwh
salidas
consumo--->float--->cons
total factura-->float--->total
"""
print("FACTURA DE ENERGIA ELECTRICA")
lact=float(input ("Digite lectura actual: "))
lant=float(input ("Digite lectura anterior: "))
kwh=float(inpu... |
"""
Entradas
numero de estudiantes--->int--->est
numero de mujeres-->int--->numm
numero de hombres--->int--->numh
Salidas
Porcentaje de hombres--->float--->ph
porcentaje de mujeres--->float--->pm
"""
est=int(input("Introduzca el número de estudiantes: "))
numm=int(input("¿Cuantas mujeres hay en el grupo? "))
numh=int(... |
import random
class Cell:
"""A single cell in a maze"""
def __init__(self, row, col):
self.visited = False
self.left = True
self.right = True
self.up = True
self.down = True
self.row = row
self.col = col
def get_all_neighbors(self, maze):
"... |
'''
Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
Каждое слово состоит из латинских букв в ниж... |
# usr/bin/env python
# -*- coding:utf-8 -*-
def quick(arr):
if len(arr) in (0,1):
return arr
p=arr[-1]
l=[x for x in arr[:-1] if x <= p]
r=[x for x in arr[:-1] if x > p]
return quick(l) + [p] + quick(r)
li=[9,1,6,4,9,2,7,4,5,3,8]
print(li)
print(quick(li))
# 名称 平均計算時間 最悪計算時間 メモ... |
# usr/bin/env python
# -*- coding:utf-8 -*-
def insert(arr):
for i in range(1,len(arr)):
for j in range(i,0,-1):
if arr[j] >= arr[j-1]:
break
else:
arr[j],arr[j-1]=arr[j-1],arr[j]
return arr
li=[9,1,6,4,9,2,7,4,5,3,8]
print(li)
print(insert(li))
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 09:46:08 2019
@author: Lily Amsellem
"""
import math
import numpy as np
import numpy.random as random
import scipy.special as special
import matplotlib.pyplot as plt
"""
x is the stock
D is the demand
o is the order
v is the quantity sold at an... |
while(True):
print("Press q to quit")
a = input("enter a number")
if a == "q":
break
try:
a =int(a)
if a > 6:
print("Enterd number is greater then 6")
except Exception as e:
print(e)
print("Thanks for playing this game") |
# def func(a):
# return a+5
'''
#Lambda Functions: is a function like we make function using "def" keyword.
Functions created using an expression using lambda keyword.
syntax : lambda arguments : expressions
--> Ek hi line m function define krte h
'''
func = lambda a: a+5
x = 566
print... |
# This is an illustration of the random walk diffusion model of atoms.
# It is assumed that the atoms are diffusing upwards as shown in the output figure of this script.
# We consider 3 atoms viz. A, B and C.
import numpy as np
import matplotlib.pyplot as plt
import math
# For tracing a random path for atom 1.
series... |
def unique():
list=[]
n=int(input("Enter the length of the list : "))
while(n!=0):
num=int(input("Enter the number: "))
list.append(num)
n=n-1
print(set(x for x in list if list.count(x)==1))
unique()
|
class Character:
name = ''
power = 0
energy = 100
def eat(self, food=5):
while self.energy != 100:
if self.energy < 100:
print('\nУ вас сейчас меньше 100% энергии.')
eat_food = input('Вы можете подкрепиться(да или нет)')
if eat_food ==... |
#Exercise 19
#Given a string return the odd characters of a string based on the index
def oddCharacters(word):
oddList = []
for i in range(1,len(word)):
if i%2 != 0:
oddList.append(word[i])
oddStr = ''.join(oddList)
return oddStr
print(oddCharacters('Hallo'))
|
#Exercise 13
#When using bottom down approach we start the the smallest deetails as we build to a bigger picture
#part one-->check if first letter is capital
def is1stcapital(string):
string_list = [i for i in string]
return string_list[0].isupper()
#part 2 -->We then capitalize each first letter
def... |
#Exercise 4
#Indicates the amount of change to give
#The change is divided in groups of twenties,ten, fives, ones, quarters, dimes, nickels and pennies
#user inputs cost of item
cost_of_item = 65.64#float(input('Enter the cost of item >'))
#user inputs amount given
amount_given = 100.00#float(input('How much ... |
class Function:
def __init__(self,id,argList,compoundInstr):
self.compoundInstr=compoundInstr
self.id=id
self.argList=argList
class Memory:
def __init__(self, name): # memory name
self.name=name
self.map={}
def has_key(self, name): # variable name
return (... |
'''
Created on May 7, 2015
https://www.hackerrank.com/contests/projecteuler/challenges/euler003
@author: Chocolate
'''
def prime(n):
i = 2
#print n;
while (n % i != 0 and i*i< n):
i += 1
#print "In While",i
if (i*i < n):
#print "In if",i;
return prime (n / i)
else:
... |
#####Rules_variables
#* Cannot start with any number
#* #Cannot be used at the beginning of a variable name
#* !Cannot be used at the beginning of a variable name
#* There can be no symbol at the beginning of the variable
#* Variables must be one word, not two words
#* If two words _ it must be used
#* To know the pos... |
a=int(input("Sayi giriniz:"))
if(a%2==0):
print("Sayi çifttir.")
else:
print("Sayi tektir.") |
#liste'den liste2'yi oluşturalım.
liste1 = [1,2,3,4,5]
liste2 = list() #veya liste2=[] ikiside boş liste oluşturur.
for i in liste1:
liste2.append(i) #liste2'ye liste1'in elemanlarını ekledik.
print(liste2) |
for i in range(1,100):
if(i%2==0):
print(i)
print("------")
for j in range(1,100):
if(j%2==1):#(j%2!=0)
print(j) |
liste=[1,2,3,4,5]
print(liste)
for i in range(6,25):
liste.append(i)
print(liste) |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
loansData = pd.read_csv('https://spark-public.s3.amazonaws.com/dataanalysis/loansData.csv')
# FICO DATA
# loansData['FICO.Range'][0:5]
# Returns as follow:
# 81174 735-739
# 99592 715-719
# 80059 690-694
# 15... |
import requests
from bs4 import BeautifulSoup
import bs4
continent_links = ['https://en.wikipedia.org/wiki/List_of_airlines_of_Africa',
'https://en.wikipedia.org/wiki/List_of_airlines_of_the_Americas',
'https://en.wikipedia.org/wiki/List_of_airlines_of_Asia',
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 18:08:29 2018
@author: soojunghong
@about : Building POS tagger
@reference : https://nlpforhackers.io/training-pos-tagger/
"""
from nltk import word_tokenize, pos_tag
print pos_tag(word_tokenize("I am Soojung, I am learning NLP"))
#----------... |
# 27 移除元素
# https://leetcode-cn.com/problems/remove-element/
def removeElement(nums, val):
k = 0 # 不等元素索引
for i in range(len(nums)):
if (nums[i] != val):
if (i != k): # 防止所有元素都是非零元素(特殊用例)-》自己与自己交换
nums[k], nums[i] = nums[i], nums[k]
k += 1
return k
# 优化-》
... |
# Creator: Lusemar Oliveira
# Description: Project 4 - Grocery List
# Date: 10/27/2020
# Class: COP1000
# Variable declarations
test = None
# Logic
while True:
groceryList = open("grocery.dat", "r") # Open File for Reading data
print ("Here is your currently Grocery List: " + "\n")
for row in groceryList:
... |
#Assignment 5.2
Numbers = []
while True :
sval = input('Enter a number: ')
if sval == 'done' :
break
try:
fval = float(sval)
except:
print('Invalid input')
continue
Numbers.append(fval)
Minimum = int(min(Numbers))
Maximum = int(max(Numbers))
print('... |
"""This is the player class"""
import pygame
import random
# Local imports
import resources
pygame.font.init()
COLORS = resources.COLORS
NAME_FONT = pygame.font.SysFont("comicsans", 20)
SCORE_FONT = pygame.font.SysFont("comicsans", 30)
WIN_WIDTH = 1400
WIN_HEIGHT = 800
class Player:
size = 20
thickness =... |
def add_data(list_values):
with open('iris.csv','a') as f:
f.write(','.join(list_values)+'\n')
def delete_data(list_values):
import pandas as pd
iris=pd.read_csv('iris.csv',header=None)
data=iris.loc[(iris[0]==list_values[0]) & (iris[1]==list_values[1]) & (iris[2]==list_values[2]) & (iris[3]==list_values[3... |
"""
Prediction File
------------
Author: Guilherme M. Toso
File: prediction.py
Date: Jul 16, 2021
Description:
This is the prediction page. Where the user can input data and it will return the house price prediction.
"""
# Dependencies
import os
import streamlit as st
from apps.domain.data_clean import Cle... |
#!/usr/bin/env python
# encoding: utf-8
# the same as 1001, but I stuck in this for hours...
def get_number(n):
if n % 2 == 0:
return n / 2
else:
return (3 * n + 1) / 2
n = int(input())
number_list = [int(i) for i in input().split()]
data = number_list[:]
for i in data:
while not i == 1:... |
def pares(dimension):
i=1
pares=0
while i<=dimension:
if i % 2==0:
print(i,end=" ")
if i % 2==0:
pares=pares+1
if i==dimension:
print("\n\n La cantidad de pares son " + str(pares))
break;#Sale del flujo de ejecución del ciclo
#Incrementar contador en el ciclo
i=i+1
rango=int(... |
from operaciones_mate_intermedio import menu2
#Menu de operaciones
def menu():
print("************************************************************")
print("* *")
print("* ELIJA UNA OPCIÓN *")
print("* ... |
#Prueba con cadenas
while True:
nombreUsuario=input("\nIntroduce tu nombre de usuario >")
while nombreUsuario.isalpha()==False:
print("\n debe ingresar una cadena ")
nombreUsuario=input("\nIntroduce tu nombre de usuario >")
#Mostrar opciones de cadenas
print("\n El nombre es " + nombreUsuario.upper())#C... |
#Uso del continue en un ciclo
nombre="Angel Fabricio González"
contador=0
for i in nombre:
if i==" ":
continue#El continue omite el resto de código desde que se aplica
contador+=1
print("\n La cantidad de letras de " + nombre + " son: " + str(contador))
|
#importar clase para la raiz cuadradra
import math
def menu2():
print("* 5)Raíz cuadrada *")
print("* 6)Potencia *")
print("* 7)Salir *")
print("********************************... |
def mensaje():
print("Estoy aprendiendo python")
print("esto es fácil")
def multiplicacion(n1,n2):
return n1*n2
#Llamar a la función
mensaje()
#Llamar otra ves a la función mensaje
mensaje()
#llamar a función multiplicación
numero1=5.5
numero2=3
print(multiplicacion(numero1,numero2))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.