text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Tim Petersen
10/30/18
Bubble Sort
Best Case: O(n)
Average Case: O(n^2)
Worst Case: O(n^2)
Space Complexity: O(1)
Stability: Yes
"""
def BubbleSort(arr):
"""
Goes through the array and swaps adjacent items
If goes through array and does not swaps it stops
"""
whil... |
# 1. Pedir dos números por teclado e imprimir la suma de ambos.
n1 = int(input("Digite el Primer valor: "))
n2 = int(input("Digite el Segundo valor: "))
suma = n1 + n2
print (suma) |
N = int(input())
Nnew = 0
while N > 0:
Nnew = Nnew * 10 + N % 10
if N >= 10:
N = N // 10
else:
N = 0
print(Nnew)
|
from math import sqrt
x = int(input())
if x == 0:
quit()
n = 0
sumx2 = 0
sumx = 0
s = 0
while x != 0:
n += 1
sumx2 = sumx2 + x**2
sumx = sumx + x
x = int(input())
s = sumx / n
print(sqrt((sumx2 - 2 * s * sumx + n * (s**2)) / (n - 1)))
|
symbol_table = {
"R0":0,
"R0":1,
"R0":2,
"R0":3,
"R0":4,
"R0":5,
"R0":6,
"R0":7,
"R0":8,
"R0":9,
"R0":10,
"R0":11,
"R0":12,
"R0":13,
"R0":14,
"R0":15,
"SP":0,
"LCL":1,
"ARG":2,
"THIS":3,
"THAT":4,
"SCREEN":16384,
"KBD":24576
}
def addEntry(symbol, address):
symbol_table[symbol] = address
def c... |
#Binary search O(logn)
def binarysearch(ar,a):
first=0
last=len(ar)-1
flag=0
mid=0
while first<last and flag==0:
mid = (first + last) / 2
if(ar[mid]==a):
flag=1
else:
if a<ar[mid]:
last=mid-1
else:
first=mid... |
#This code shows the use of input() function in Python 2
print "Enter a number"
x=input()
print "The integer value is ",x
#This part shows typecasting and conversion
print "Enter a string"
y=int(raw_input())
print "The value is ",y
print "Enter a float"
print int(17.4) |
#This code explains if and elif
print "Enter a number:"
x=input()
if (x%2==0):
if (x>10):
print "The number is even and greater than 10"
else:
print "The number is even but not greater than 10"
elif (x%2!=0):
print "The number is odd" |
#This code introduces the concept of list in python
a=[]
print a
b=[1,2,3,4]
print b
print type(b)
print b[1]
b[1]=5
print b[1]
c=[2,3,'anything',5.5]
print c |
#Second example of function
def div(x,y):
if(x>=y):
if(x%y==0):
print "x is divisible by y "
else:
print "x is not divisible by y "
else:
print "The divisor is bigger than the dividend"
div(6,3)
div(6,4)
div(6,5)
print "***********************"
#Rev... |
# thisone is like your scipts w/ argv
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
# this just takes one arg
def print_one(arg1):
pr... |
# Standard Dictionary
mystuff = {'apple':'I AM APPLES!'}
print(mystuff['apple'])
# Module way
import mystuffmodule
mystuffmodule.apple()
print(mystuffmodule.tangerine)
# Class way
from mystuffclass import MyStuff
thing = MyStuff()
thing.apple()
print(thing.tangerine)
print('-'*10)
### Official ex40 Code
class Song:... |
from math import *
c = 3*(10**8)
pi = 3.1415
def comprimento_de_onda():
comprimento = float(input("Digite o comprimento de onda: "))
print()
print("Escolha a unidade de medida :")
print("1 - [nm]")
print("2 - [µm]")
print("3 - [mm]")
print("4 - [m]")
print("5 - [km]")
opcao = int(i... |
"""
Shaan Khan
CNT4713: Assignment 2, Basic Python Programming
"""
class Assignment2:
# Task1: Constructor
def __init__(self, age):
self.age = age
# Task 2: Birth Year
def tellBirthYear(self, currentYear: int):
print("Your birth year is", (currentYear - self.age))
# ... |
users={'Nijo':'nkppp','Sam':'cppp'}
while True:
p=input("Enter q to exit or 1 to continue:")
if p.lower() =='q':
break
username=input("Enter your Username:")
if username in users:
print("This user name already exits")
else:
pass_1=input("Enter your password:")
pass_2=input("Confirm your passwo... |
def find_student(db):
p = 0
st = input("Please enter name of student: ")
for rec in db:
for tmp in rec[1]:
if (tmp[0]==st):
p = 1
print("%10s" % "GROUP", "%7s" % "ID", "%5s" % "AGE")
print("%10s" % rec[0], "%7d" % tmp[1], "%5s" % tmp[2])
... |
import numpy as np
import timeit
from SortingString import *
def BubbleSort(n, direction): #2 аргументи - масив чисел та напрям
comparisons = 0 # к-сть порівнянь
exchanges = 0 # к-сть обмінів
len_n = len(n)
for i in range(len_n):
for j in range(0, len_n - 1 - i): # починаємо перевірки ... |
print("Soal\nAnda disuruh memasukan gaji bulanan selama sebulan, setiap bulan 10% dari gaji anda gunakan untuk persepuluhan.\ndari sisa uang 50% digunakan untuk kebutuhan sehari-hari dan 30% anda gunakan untuk kebutuhan tidak terduga, lalu dari sisa uang yang tersisa anda gunakan tabungan.")
gaji = int(input("Masukan ... |
from turtle import Screen, Turtle
from paddle import Paddle
from ball import Ball
from scoreboard import ScoreBoard
import time
screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong by Bunny")
screen.tracer(0)
right_paddle = Paddle(350, 0)
left_paddle = Paddle(-... |
#!/usr/bin/env python3
import unittest
from binary_to_decimal_and_back_converter import binary_to_decimal, decimal_to_binary, \
decimal_to_hexadecimal, decimal_to_octal
class Test(unittest.TestCase):
def test_binary_to_decimal(self):
self.assertEqual(binary_to_decimal(1000101011), 555)
def test... |
#!/usr/bin/env python3
import unittest
from latin_squares import is_latin_square
class Test(unittest.TestCase):
def test_is_latin_square(self):
self.assertTrue(is_latin_square(5, "1234551234451233451223451"))
self.assertFalse(is_latin_square(4, "1234132423414321"))
if __name__ == "__main__":
... |
#!/usr/bin/env python3
"""Reverse a string.
Title:
Reverse a String
Description:
Develop a program that has the user enter a string.
Your program should reverse the string and print it out.
"""
def reverse(string: str) -> str:
"""Return the string reversed."""
reversed_string = ""
for index in range(len... |
#!/usr/bin/env python3
"""Lookup a country of an IP address.
Title:
Country from IP Lookup
Description:
Enter an IP address and find the country that IP is registered in.
"""
import urllib.request
import json
import tkinter as tk
from tkinter import ttk
API_URL = "https://ipapi.co/"
API_FORMAT = "/json"
class Main... |
#!/usr/bin/env python3
"""
Title:
Roman to Arabic numeral converter
Description:
Create a program that converts Roman numbers (such as MCMLIV)
to Arabic numbers (1954) and back.
Roman numerals are read from left to right,
as you add or subtract the value of each symbol.
If a value is lower than the following value, it... |
#!/usr/bin/env python3
"""A pig latin translator.
Title:
Pig Latin
Description:
Pig Latin is a game of alterations played on the English language game.
To create the pig latin form of a word
the initial consonant sound is transposed to the end of the word
and an 'ay' is affixed.
Example: "banana" would yield 'ananaba... |
#!/usr/bin/env python3
"""Encrypt text using the Vigenère Cipher.
Title:
Vigenère Cipher
Description:
Make a program to accept some plaintext and a key from the user
and use them to perform a Vigenère Cipher and output the result.
More info on Vigenère Ciphers:
https://en.m.wikipedia.org/wiki/Vigenère_cipher
Bonus po... |
#!/usr/bin/env python3
"""
Title:
MD5 Hash Generator
Description:
Make an MD5 hash code generator for strings and files.
MD5 is a widely used hash function algorithm that produces a 128 bit hash value.
Submitted by JoFo
"""
import hashlib
import os
def hash_string(string: str) -> str:
hash_object = hashlib.md5()... |
#!/usr/bin/env python3
"""Calculate the number of days between two dates.
Title:
Number of Days
Description:
Your program should take two string inputs from the user
in the format (dd/mm/yyyy)
and calculate the number of days between those two dates.
Submitted by Kanishk
"""
DAYS_IN_A_MONTH = [31, 28, 31, 30, 31, 30,... |
#!/usr/bin/env python3
"""A minimalistic launcher program.
Title:
Quick Launcher
Description:
A utility program that allows the user to assign various programs
to icons on a toolbar.
Then by clicking the buttons
they can quickly launch the programs with parameters etc.
Much like Windows quick launch.
"""
import os
im... |
#!/usr/bin/env python3
"""A tax calculator for the command line.
Title:
Tax Calculator
Description:
Develop a program that asks the user to enter a cost
and either a country or state tax.
It then returns the tax plus the total cost with tax.
"""
def get_tax(base_cost: float, tax_rate: float) -> float:
"""Return... |
"""
用RNN对评论进行二值分类的问题
先获取25000条评论数据,这里库里面就进行了整数对应,把每个单词映射到一个整数上
因为序列一般长度都不一样,所以要先进行一个sequence.pad_sequences(input_train, maxlen=maxlen),把长的去掉,短的补充
然后就送入训练层了
第一层是一个embedding
然后是rnn
最后接一个dense
问题:32的batch是什么,和后面的batch没有冲突吗?
"""
from keras.datasets import imdb
import matplotlib.pyplot as plt
from keras import models
f... |
import pygame
import os
class Paddle(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, images, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the bl... |
brownie =5
chococookie=15
croissant= 3
print(f''' Menu
------------------------------
Brownie - $ {brownie}
Croissant - $ {croissant}
chococookie - $ {chococookie}''')
print('/'*30)
bill =0
order=input("Kindly place your Order:\n").lower()
if order =='brownie':
bill += ... |
# Past and Present
# Below, the Current Date and Time has been stored in a variable.
# from datetime import datetime
# today = datetime.now()
# Find the Date exactly before 100 days and after 200 days.
# The Final Result should only display the Date and not the Time
from datetime import *
today=datetime.now(... |
number=int(input("enter which tables you want to display :\n"))
i=1
while(i<=10):
print(f'{number} X {i} = {number*i}')
i += 1 |
import random
Cscore=0
Pscore=0
for x in range (5):
S=int(input("enter a number (1-5)"))
print(f"Round {x+1} ")
S1=int(input("PLease guess any number between 1 to 5"))
if S1 == S:
print("player 1 won!!!!!!")
Pscore += 1
else:
Cscore += 1
print("player 2 ... |
word=input("Enter a word \n")
lowercase=word.lower()
vowel_dic={}
for i in "aeiou":
count=lowercase.count(i)
vowel_dic[i]=count
for i ,j in vowel_dic.items():
print(f"{i} : {j}") |
class Employee():
__age=int()
__company=str()
def __init__(self):
print('Конструктор базового класса без параметров')
def __init__(self,age='',company=''):
self.__age=age
self.__company=company
print('Конструктор базового класса')
def __del__ (self):
print(... |
#!/usr/bin/env python
def check_horizontal(player, moves):
for i in range(0, 3):
if moves[i][0] == player and moves[i][1] == player and moves[i][2] == player:
return "'%s' wins (horizontal)." % player
def check_vertical(player, moves):
for i in range(0, 3):
if moves[0][i] == player and moves[1][i] =... |
#!/usr/bin/env python
def generateNumber(start, end, step):
lst = []
if step > 0:
end += 1
else:
end -= 1
for i in range(start, end, step):
lst.append(i)
return lst
print generateNumber(2, 10, 2)
print generateNumber(10, 10, 1)
print generateNumber(20, 0, -3)
print generateNumber(15, 6, -2)
|
import unittest
class unitest(unittest.TestCase):
def testEmptyString(self):
s = ""
ans = ""
self.assertEqual(Solution().longestPalindrome(s),ans);
def testCase1(self):
s = "cbbd"
ans = "bb"
self.assertEqual(Solution().longestPalindrome(s),ans);
def testCase2... |
animals = ['dog', 'cat', 'horse']
for i in animals:
print(i)
print(i + " can be a great pet.")
print('These ' + i + ' have a common thing that they follow their masters.')
print(i)
|
# r is for read only
file = open("employees.txt", "r")
# print(file.readlines())
for employee in file.readlines():
print(employee)
file.close()
# a is to add to an already existing file
file = open("employees.txt", "a")
file.write("Franco")
file.write("\nKelly")
file.close()
# w can create a new file
fil... |
name = "Alex"
age = "24"
print("Hello " + name + " are you " + age + "?")
print("Monkey \nAcademy")
print("\" hello.... \" the girl said")
# change string to all upper or lower (string.upper())
s = "HELLO HOW ARE YOU DOING TODAY";
print(s.lower())
# find length of string
x = len(s)
print(x)
# Select specified in... |
# 9. Найти максимальный элемент среди минимальных элементов столбцов матрицы.
# Примечание: попытайтесь решить задания без использования функций max, min, sum, sorted и их аналогов,
# в том числе написанных самостоятельно.
array = [[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[4, 3, 4, 4, 4],
[1, 2, 3,... |
a = 5
b = 6
c = a & b
d = a | b
e = a << 2
f = a >> 2
print(f'Результа побитового "И": {c}')
print(f'Результа побитового "ИЛИ": {d}')
print(f'Результа побитового сдвига "в лево": {e}')
print(f'Результа побитового сдвига "в право": {f}') |
items = int(input('Введите число: '))
item = int(input('Какое число ищем: '))
i = len(str(items))
itr = iter(str(items))
i, s = len(str(items)), 0
while i>0:
i -= 1
t = int(next(itr))
if t == item:
s += 1
print(f'найдено {s} повторов')
|
mobiles={
"galaxy":{"frontcam":"12px","rearcam":"30px","ram":4,"price":20000},
"galaxy1":{"frontcam":"10px","rearcam":"20px","ram":4,"price":30000}
}
mobilename=input("enter mobile name")
spec=input("enter specification")
# print(mobile[mobilename][spec]) -->error
if mobilename in mobiles:
print(mobiles[mob... |
import re
rule="[a-k][369][a-zA-Z]*"
var_name=input("enter variable name")
matcher=re.fullmatch(rule,var_name)
if matcher==None:
print("invalid variable")
else:
print("valid variable name") |
no1=int(input("enter num1"))
no2=int(input("enter num2"))
try:
res=no1/no2
print(res)
except Exception as e:
print(e.args)
print("database transaction")
print("file operation") |
lst=[2,4,6,7,8,9]
even=list(filter(lambda num:num%2==0,lst))
print(even)
# print name starting with a
names=["akhil","harsha","anu","shirin","kavya"]
name_a=list(filter(lambda name:name[0]=="a",names))
print(name_a)
# print detail of students with mca
class Student:
def __init__(self,rlno,name,course,total):
... |
prices ={}
stock = {}
prices["banana"] = 4
prices["apple"] = 2
prices["orange"] = 1.5
prices["pear"] = 3
stock["banana"] = 6
stock["apple"] = 0
stock["orange"] = 32
stock["pear"] = 15
for k,i in prices.items():
print(k)
print('price :',prices[k])
print('stock :',stock[k])
total = 0
for k in prices:
to... |
n = int(input("Nhap so:"))
# tong = n
# for i in range(n):
# tong += i
# print("Tong la:",tong)
a = range(n+1)
print("Tong la:",sum(a))
|
numb_list = [10,2,-5,4]
numb_list_sorted = []
# while numb_list != []:
while True:
minn = min(numb_list)
numb_list_sorted.append(minn)
numb_list.remove(minn)
if len(numb_list) == 0:
break
print(numb_list_sorted)
|
def abs(n):
if n>=0:
return n
else:
return abs(-n)
def factorial(n):
if n<=0:
return 1
else:
return n*factorial(n-1)
def fibo(a):
if a==0:
return 0
elif a==1:
return 1
else:
return (fibo(a-1)+fibo(a-2))
def po... |
#Create Rectangle and Square classes with a method called calculate_perimeter that calculates the perimeter
#of the shapes they represent.
#Create Rectangle and Square objects and call the method on both of them
#Define a method in your Square class called change_size that allows you to pass in a number that increases... |
# A recursive algorithm must have a base case
# A recursive algotithm must change its state and move towards the base case
# A recursive algorithm must call itself, recursively
def bottles_of_beer(bob):
""" Prints 99 Bottles of Beer on the wall lyrics/
:param bob: Must be a positive integer.
"""
if... |
from tkinter import *
from tkinter.font import *
import time
import math
class Timer:
def __init__(self, wnd, ms, call):
self.__wnd = wnd
self.__ms = ms
self.__call = call
self.__running = False
def start(self):
if not self.__running:
self.__wnd.after(0, sel... |
from tkinter import *
from tkinter.font import *
# create the main window
root = Tk()
paned_window = PanedWindow(root, background="#a0ffa0")
# create font
ftiTimes = Font(family='Times', size=24, weight=BOLD)
# create a listbox for demo.
lb = Listbox(paned_window,
activestyle='dotbox',
bg=... |
import re
def cleanWords(text):
words = re.findall('[a-zA-Z]+', text)
words = map(lambda x: x.lower(), words)
return words
if __name__ == '__main__':
print cleanWords("Hi, how are you? 777")
|
#Command Line arguments sys.argv
import sys
argumentsCount=len(sys.argv)
script=sys.argv[0]
if argumentsCount>1:
print("{} arguments passed on command line".format(argumentsCount))
print("The first argument is always the python script that you ran in command line: \'{}\'".format(script))
print("Here is the ... |
#The goal of this exercise is to convert a string to a new string where each character in the new string is '('
#if that character appears only once in the original string, or ')' if that character appears more than once in the original string.
#Ignore capitalization when determining if a character is a duplicate.
#Ex... |
#There is an array with some numbers. All numbers are equal except for one. Try to find it!
#findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
#findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
#It’s guaranteed that array contains more than 3 numbers.
#The tests contain some very huge arrays, so think about performance.
def find_uniq(arr)... |
#Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
#Examples
#pig_it('Pig latin is cool') # igPay atinlay siay oolcay
#pig_it('Hello world !') # elloHay orldway !
punctation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
def pig_it(s):
resul... |
x1, y1 = map(float, input())
x2, y2 = map(float, input())
x3, y3 = map(float, input())
ans = (y2 - y1) / (x2 - x1) * x3 - (y2 - y1) * x1 / (x2 - x1) + y1
if ans > y3:
print('above')
else:
print('under') |
import pickle
from os.path import exists
book = []
#open the file where the phone numbers will be saved in a write mode
class Entry(object):
def __init__(this, name, cell,home):
this.name = name
this.cell = cell
this.home = home
def retrieve(this,name):
print "%s cell # : %s" ... |
import matplotlib.pyplot as plot
import math
def y1(x):
return x+10
def y2(x):
return x-10
def y3(x):
return 100
xs = range(0,101)
yy = []
yg = []
yr = []
for x in xs:
yy.append(y1(x))
yg.append(y2(x))
yr.append(y3(x))
plot.xlim(0,100)
plot.ylim(0,100)
plot.plot(xs,yr,xs,yy,xs,yg)
plot.f... |
# Sa se scrie o functie care sa returneze o lista cu primele n numere din sirul lui Fibonacci.
def Fibonacci(n):
fib = [1,1]
for i in range(2 , n):
fib.append(fib[i - 1] + fib[i - 2])
return fib
print(Fibonacci(15))
|
# Write a function that returns the largest prime number from a string given as a parameter
# or -1 if the character string contains no prime number.
# Ex: input: 'ahsfaisd35biaishai23isisvdshcbsi271cidsbfsd97sidsda'; output: 271
def isPrime(number):
number = int(number)
if number > 1:
for i in ... |
# -*- coding: utf-8 -*-
# =============================================================================
# @author: yeowny
# woon young, YEO
# ywy317391@gmail.com
# https://github.com/yeowny
# =============================================================================
'''
https://programmers.co.kr/learn/co... |
# -*- coding: utf-8 -*-
# =============================================================================
# @author: yeowny
# woon young, YEO
# ywy317391@gmail.com
# https://github.com/yeowny
# =============================================================================
'''
https://programmers.co.kr/learn/co... |
# -*- coding: utf-8 -*-
# =============================================================================
# @author: yeowny
# woon young, YEO
# ywy317391@gmail.com
# https://github.com/yeowny
# =============================================================================
'''
https://programmers.co.kr/learn/co... |
# Problem 1
# hexcolor = re.findall([A-Fa-f0-9]{6}], website)
# Problem 2
# 1. Import modules
# 2. Assign the given website to a variable
# 3. Open the website
# 4. .read the website and assign it to a variable
# 5. Use .findall to create a pattern to find the wins
# 6. Use .findall to create a pattern to find the l... |
##headers = ['Name', 'Age', 'Hometown']
##
##
##data = []
##
##while len(data) < 5:
## name = input('Please enter a name: ')
## age = input('Please enter an age: ')
## hometown = input('Please enter a hometown: ')
## lst = [int(age), name, hometown]
## data.append(lst)
##
##sorted_lst = sorte... |
"""
Домашнее задание №1
Условный оператор: Сравнение строк
* Написать функцию, которая принимает на вход две строки
* Проверить, является ли то, что передано функции, строками.
Если нет - вернуть 0
* Если строки одинаковые, вернуть 1
* Если строки разные и первая длиннее, вернуть 2
* Если строки разные и вторая с... |
# * Your task is to create a Python script that analyzes the records to calculate each of the following:
# * The total number of months included in the dataset
# * The net total amount of "Profit/Losses" over the entire period
# * Calculate the changes in "Profit/Losses" over the entire period, then find the a... |
file1 = open("data.txt", "r")
file_string = file1.read()
list1 = file_string.split("\n")
list_of_lists = []
for i in list1:
city = i.split(",")
city_population = [city[0], city[1]]
list_of_lists.append(city_population)
print(list_of_lists)
conurbation = ["Belo Horizonte", "Contagem", "Betim", "Ibirite",... |
from random import randint
r=randint(1,10)
n=5
while(n>=1):
a=int(input("Number:"))
if(a==r):
print("Win")
break
else:
n=n-1
print("Try Again") |
n=int(input("Enter a Multiplicand Number:"))
m=int(input("Enter a Multiplier Number Range: "))
for i in range(1,(m+1)):
print(n,'x',i,'=',n*i) |
n=int(input())
a=1
if(n>=1):
for i in range(1,n+1):
a=a*i
print(a) |
l=int(input())
b=int(input())
print("Perimeter:",2*(l+b)) |
p=int(input("Principal:"))
r=int(input("Rate:"))
t=int(input("Time:"))
print("Simple Interest:",(p*r*t)/100) |
amt=int(input("Enter Amount:"))
n2000=n500=n200=n100=n50=n10=n5=0
if(amt>=2000):
n2000=int(amt/2000)
amt=int(amt-(n2000*2000))
if(amt>=500):
n500=int(amt/500)
amt=int(amt-(n500*500))
if(amt>=200):
n200=int(amt/200)
amt=int(amt-(n200*200))
if(amt>=100):
n100=int(amt/100)
amt=... |
def thirdMaxElemnt(nums):
#create a set to hold maximum numbers
max_nums = set()
#Loop through as you store maximum numbers and delete the minimum values and retain only 3 values at any time
for item in nums:
max_nums.add(item)
if len(max_nums) > 3:
max_nums.remove(min(max_nums))
#return the... |
#Inspired by https://leetcode.com/problems/binary-search/
#Nums must strictly be increasing
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
pivot = left + (right - left) // 2
if nums[pivot] == target:
return pivot
if target < nums[pivot]:
right = right - 1
e... |
import pandas
import config
def to_yes_or_no(value):
return 'N' if value == 0 else 'Y'
def get_data():
# Carregando dados do CSV
cardio = pandas.read_csv(config.DATA_PATH + 'cardio_train.csv', sep=';')
# Removendo coluna de ID
cardio = cardio.drop('id', axis=1)
# Convertendo coluna classif... |
# a=int(input("enter a value"))
# i=1
# while i <=10:
# print(i,"*",a,"=",i*a)
# i+=1
# n = int(input("enter a number"))
# sum = 0
# for i in range(n+1):
# sum=sum+i
# # print(sum)
# print(sum)
# n=int(input("enter a no"))
# sum=0
# i=0
# while i<=n:
# sum=sum+i
# i=i+1
# print(sum)
min=int(in... |
print("greatest of two numbers")
a=int(input("enter a number"))
b=int(input("enter another number"))
if a>b:
print("a is greater than b",a)
elif a==b:
print("a and b are equal",a,b)
else:
print("b is greater than a",b)
|
numbers=[1,3,5,6,4,7,9,8]
even=[n for n in numbers if n%2==0]
odd=[n for n in numbers if n%2!=0]
print(even)
print(odd) |
punctuation= '`.,!-@#$%^&*()_+/'
my_str=input("enter string")
no_punc=""
for char in my_str:
if char not in punctuation:
no_punc=no_punc+char
print(no_punc) |
def fib(n):
if n<=1:
return 1
else:
return fib(n-1) + fib(n-2)
num=int(input("enter number"))
print("fibanocci series")
for i in range(num):
print(fib(i)) |
c = set()
num=int(input("enter size of set "))
for i in range (num):
n = int(input("enter numbers"))
c.add(n)
print(c)
|
# x='[abc]' ---either a b or c
# x='[^abc]' except abc
# x='[a-z]' a to z
# x='[A-Z]' A to Z
# x='[a-zA-Z]' both lower and upper are checked
# x='[0-9]' check digits
# x='[^a-zA-Z0-9]' special symbols
# x='\s' check space
# x='\d' check the digits
# x='\D' except digits
# x='\w' all words except special charecters
... |
class Calc:
res=0
def add(self,num1,num2):
self.num1=num1
self.num2=num2
res=self.num1+self.num2
print(res)
def sub(self,num1,num2):
res=self.num1-self.num2
print(res)
def mult(self,num1,num2):
res=self.num1*self.num2
print(res)
def div... |
def fact(x):
if x==0:
return 1
# elif x==0:
# return 1
else:
return x * fact(x-1)
num = int(input("enter number"))
print("faxtorial of",num, "is",fact(num))
|
# a=input("enter string")
# print("first letter is",a[0])
f=lambda n:n[0]
print(f("Hello"))
#
# add=lambda x,y:x+y
# print(add(9,5)) |
# quantifires
# x='a+' a including group
# x='a*' count including zero number of a
# x='a?' count a as each including zero no or a
# x='a{2}' 2 no of a position
# x='a{2,3}' minimum 2 a and maximum 3 a
# x='^a' check starting with a
# x='a$' check ending with a
# import re
# x="a+"
# r="aaa abc aaaa cga"
# matc... |
no1=int(input("enter number 1"))
no2=int(input("enter number 2"))
no3=int(input("enter number 3"))
if no1>no2 and no1>no3:
print("number 1 is greater", no1)
elif no2>no1 and no2>no3:
print("number 2 is greater",no2)
elif no1==no3==no2:
print("equal numbers")
else:
print("number 3 greater",no3)
|
# CMPT 120
# Lab 3: A program used to compute a user given number for the term in the
# fibonnaci sequence.
# Jack Mullane
# 10/7/2019
def main():
num = int(input("Enter a number for the fibonnaci sequence: "))
result = fibonacci(num)
print(result)
def fibonacci(num):
if num < 0:
return
... |
l = [1, 2, 3]
l.append(4)
print(l)
print(l.count(10))
print(l.count(1))
x = [1, 2, 3]
x.append([4, 5])
print(x)
x = [1, 2, 3]
x.extend([4, 5])
print(x)
print(l)
print(l.index(2))
# If dont exist is a ValueError
l.insert(2, 'inserted')
print(l)
ele = l.pop()
print(ele)
print(l.pop(0))
l.remove('inserted')
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.