text stringlengths 37 1.41M |
|---|
city_name = "Istanbul, Turkey"
pop_1927 = 691000
pop_2017 = 15029231
pop_change = (pop_2017 - pop_1927) / pop_1927
percentage_gr = pop_change * 100
annual_gr = percentage_gr / (2017 - 1927)
print(annual_gr)
def population_growth(year_one, year_two, population_one, population_two):
growth_rate = (((population_two - ... |
class Circle:
pi = 3.14
def area(self, radius):
return Circle.pi * radius ** 2
circle = Circle()
pizza_area = circle.area(12 / 2)
teaching_table_area = circle.area(36 / 2)
round_room_area = circle.area(11460 / 2)
print(pizza_area)
print(teaching_table_area)
print(round_room_area)
# Constructors
class Cir... |
balances = {"checking": 0, "savings": 0}
def make_deposit(account_type, amount, balances):
print("Time to open your account")
account_type = input("Savings or Checkings?: ")
print("Perfect!, time to make a deposit")
amount = input("How much would you like to deposit?: $")
deposit_status = ""
if... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pandas_datareader.data import DataReader
# Group listings by Sector and Exchange
by_sector_exchange = listings.groupby(['Sector', 'Exchange'])
# Calculate the median market cap
mcap_by_sector_exchange = by_sector_exchange.market_cap_m.med... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from pandas_datareader.data import DataReader
# Select IPOs after 2000
listings = listings[listings['IPO Year'] > 2000]
# Convert IPO Year to integer
listings['IPO Year'] = listings['IPO Year'].astype(int)
# Create a countplot
sns.countplot(x... |
def word_flipper(our_string):
"""
Flip the individual words in a sentence
Args:
our_string(string): Strings to have individual words flip
Returns:
string: String with words flipped
"""
# Method 1 starts************************************
words = our_string.split(" ")
reverse... |
# use f in order to interpolate variables into a string
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
# use the title method to capitalize first letters
print(f"Hello {full_name.title()}")
# .strip() to strip whitespace from a string
einstein = "Albert Einstein"
qu... |
groups = open("input").read().split("\n\n")
count1, count2 = (0,0)
for group in groups:
questions = set([person for person in group.replace("\n","")])
count1 += len(questions)
for group in groups:
list_questions = [set(person) for person in group.split("\n")]
count2 += len(set.intersection(*list_ques... |
def sort(nums):
for i in range(len(nums)-1,0,-1):
for j in range(i):
if nums[j] > nums[j + 1]:
temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
nums = [12, 2, 89, 105, 63, 4, 57, 99];
sort(nums)
print(nums) |
class Animal(object):
def __init__(self,sound,name,age,favourite_color):
self.sound = sound
self.name = name
self.age = age
self.favourite_color = favourite_color
def eat(self,food):
print("Yummy!!" + self.name + "is eating" + food)
def description(self):
print(self.name + " is " + str(self.age) + " year... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import operator
eps = np.finfo(float).eps
########################################################
# Meas Squared Errror
########################################################
def rmse_score(y_true, y_pred):
"""Return the Me... |
#!/usr/bin/env python
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__... |
import datetime
"""
DEFINE LEAP YEAR
The year can be evenly divided by 4;
If the year can be evenly divided by 100, it is NOT a leap year, unless;
The year is also evenly divisible by 400. Then it is a leap year.
"""
def is_leap_year(year):
year = int(year)
is_leap = False
if year % 4 == 0:
if ye... |
#2.Write program to implement Selection sort.
no=[5,6,1,2,3]
l=len(no)
for i in range(l-1):
for j in range(i+1,l):
if no[i]>no[j]:
no[i],no[j]=no[j],no[i]
print(no)
|
#6.Write a python program to generate Fibonacci Numbers upto 100 using generator.
def fibo():
a=0
b=1
while True:
if a>100:
break
yield a
a,b=b,a+b
for i in fibo():
print(i)
|
import numpy as np
import random
import matplotlib.pyplot as plt
import os
'''
ConnectX game.
Author: Max Croci
Date: 21.02.2019
'''
class Board:
variant = 0
n_rows = 0
n_cols = 0
positions = {} #Dictionary of symbols (values) at positions (keys)
available_moves = []#List of available moves
... |
def read(filename):
with open(filename, "r") as f:
data = f.read().split("\n\n")
return data
def count(data):
count_1, count_2 = 0, 0
for item in data:
count_1 += len(set(item.replace("\n", "")))
current = [set(i) for i in item.split()]
count_2 += len(current[0].intersection(*curren... |
#danilo Patrucco
#inf 103
#c to f table
#set variables
celsius = 0
#set max temp as final value
maxtemp = 21
#test = 1
#while celsius is different than maxtemp then loop
#while test == 1:
while celsius != maxtemp:
#compute the temperature
fahrenheit = format((9/5)*celsius+32,'.2f')
print (c... |
#inf 103
#danilo patrucco
# Math Quiz
import random
def main():
in1 = random.randint(1,300)
in2 = random.randint(1,300)
intot = in1 + in2
print (in1,"+",in2)
inanswer = int ( input ("insert result of sum of the values displayed above \t"))
compare(intot,inanswer)
... |
#INF103
#Danilo Patrucco
#read, write, append
'''
test = open ('data_sample.txt','r')
file_content = str(test.readline())
test.close()
print = (file_content)
'''
inFile = open ('data_sample.txt','r')
firstLine = inFile.readline()
fLineStripped = firstLine.strip('\n') # stirp remove leading an trailing edge... |
#import os and csv
import os
import csv
#join path
budget_data = os.path.join("Resources", "budget_data.csv")
#open and read csv
with open(budget_data, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
header= next(csvreader)
#make list to find net profit and loss
prof... |
anoNascimento = int(input("Informe o seu ano de nascimento: "))
idade = 2019 - anoNascimento
if idade >= 16:
print("Você possue idade para votar!")
if idade >= 18:
print("Você possue idade para tirar a CNH!")
|
cotacaoDolar = float(input("Informe a cotação atual do dólar: "))
valor = float(input("Informe ó valor em reais: "))
valorConvertido = valor/cotacaoDolar
print("O valor em dólar é: $", valorConvertido) |
from node import Node
class Input(Node):
def __init__(self):
Node.__init__(self)
def forward(self, value=None):
# Overwrite value if one is passed
if value is not None:
self.value = value
def backward(self):
self.gradients = {self: 0}
for neuron in se... |
// Time Complexity : O(V+E)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.i... |
from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv
import pandas as pd
import numpy as np
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from io import BytesIO, StringIO
import boto3
import selenium
import time
fro... |
c = float(input("Digita la temperatura in °C: "))
f = ((9 * c) /5) + 32
print("-" * 80)
print("La temperatura di {}° C equivale a {}° F".format(c, f))
print("-" * 80)
|
name = str(input("COGNOME / NOME: ").strip())
print("Il tuo COGNOME/NOME contiene Rossi: {}".format("rossi" in name.lower()))
|
from random import randint
from time import sleep
pc = randint(0, 5)
print("-=-"*20)
print("Sto pensando in un numero da 0 a 5...")
print("-=-"*20)
sleep(3)
user = int(input("In quale numero ho pensato, prova a indovinarlo: "))
print("-=-"*20)
if user == pc:
print("Hai vinto, complimenti !!!")
else:
... |
"""Calcolo della velocità in km/h e m/s"""
# dati
dist = float(input("Per quanti km hai corso? "))
min = int(input("In quanti minuti? "))
# elaborazione
m = dist * 1000 # da km a metri
s = min * 60 # da minuti a secondi
v = m / s
# colors
colors = {"clear": "\33[m",
"start": "\33[1;30;... |
n = int(input("Digita un numero: "))
if n%2 == 0:
print("Il numero {} è un numero PARI !!!" .format(n))
else:
print("Il numero {} è un numero DISPARI !!!" .format(n))
|
num = int(input("Digita un numero da 0 a 9999: "))
#n = str(num)
#print("-" * 80)
#print("Unità: {}".format(n[3]))
#print("Decina: {}".format(n[2]))
#print("Centinaia: {}".format(n[1]))
#print("Migliaia: {}".format(n[0]))
#print("-" * 80)
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num /... |
global1 = 34
def cambiar_global(var1):
'''Cambiar una variable global
Esta función debe asignarle a la variable global `global1` el valor que se
le pasa como único argumento posicional.
'''
global global1
global1 = var1
# print(var1)
return global1
pass
#cambiar_global(5)
def anio_b... |
x=int(input("Введите число: "))
def chetn(x):
if x%2==0:
return("Число четное")
else:
return("Число нечетное")
print(chetn(x))
|
import random
x = random.randint(1,4)
value = input("Я загадал число от 1 до 4. Ты думаешь, что это число: ")
if value:
y = float(value)
if x==y:
print("Ты победил!!")
elif x<y:
print("Нет, мое число меньше...Повторите ее раз!")
else:
print("Нет, мое число больше...Повторите ее р... |
x=input("Введите время звонка в минутах:")
y=input("Введите код города: ")
if x:
vrem=float(x)
if y:
kod_gor=int(y)
if kod_gor==343: print("Стоимость звонка в городе Екатеринбург:", 15*vrem)
elif kod_gor==381: print("Стоимость звонка в городе Омск:", 18*vrem)
elif kod_gor==473: p... |
'''This simple program models using OOP the proces of calculating
the cost of a telephone call.
'''
# Needed for computation of call duration, and to determine whether call
# is on- or off-peak.
import datetime
class Call:
'''Model a call with clas params as below:
:param MINIMUM_COST_NEAR : The applicabl... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 10:11:08 2019
@author: Hashim
"""
import itertools
fl = lambda ll: [item for sublist in list2d for item in sublist]
fl(list2d)
'''
# goal is to write a program inputting two lists where the 2nd list element is an exponent to the first list element
power = lambda x,... |
import string
from words import choose_word
from images import IMAGES
import random
'''
Important instruction
* function and variable name snake_case -> is_prime
* contant variable upper case PI
'''
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: word guess by the user
letters_guessed: ... |
print('Welcome')
#print('08-15-2021')
h = float(input("What is your hight?"))
w = float(input('What is your weight?'))
imc = round(w/(h*h),1)
meta = round(float(25*h*h),1)
print('IMC')
print(imc)
if imc > 25.0:
print('Over weight')
print('Your target is: ')
print(f"{meta}Kg")
else:
print('You got it!')
pri... |
"""
Observer pattern implementation.
Any observable object shall inherit from Observable, and an observer from
Observer.
"""
from abc import ABC, abstractmethod
class Observer(ABC):
"""
Observer class needs to be added in Observable container of Observers.
Implement update() to define what happens on Ob... |
#need a list
weight_list= []
#enter weights/print list
for i in range(4):
val = float(input("Enter weight " + str(i+1) + ": "))
weight_list.append(val)
print("Weights:", weight_list)
#calculate total/average and print
total = 0.0
for i in range(len(weight_list)):
total = total + weight_list[i]
average = tot... |
arrow_base_height = int(input('Enter arrow base height:\n'))
arrow_base_width = int(input('Enter arrow base width:\n'))
arrow_head_width = int(input('Enter arrow head width:\n'))
while arrow_head_width <= arrow_base_width:
arrow_head_width = int(input("Enter arrow head width:"))
print
for i in range(arr... |
import collections
def equalizeArray(arr):
arrCount = collections.Counter(arr)
return len(arr)-arrCount.most_common(1)[0][1]
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = equalizeArray(arr)
print(str(result)) |
import random
import data
import distance
import prototype
class clustering:
def __init__(self, data, clusters, centroids, distance=distance.euclidean):
self.data = data
self.clusters = clusters
self.centroids = centroids
self.distance = distance
def source_data_summary(self):
"""
Produces a summary i... |
from collections import deque
class LRU_Cache(object):
def __init__(self, capacity):
# Initialize class variables
self.size = capacity # cache size = queue size
self.hash = {}
self.q = deque()
def get(self, key):
# Retrieve item from provided key. Return -1 if nonexis... |
'''Slice'''
a = [1,12,23,34,45,56, 3, 5, 36, 75, 81, 2]
b = [2, 4, 6, 7, 8, 57 ,89, 9]
'''Print out the 2nd to the 5th elements of list "a"'''
print(a[1:5])
'''Create a list that contains the 4th to the 8th element of "a" and the 1st to the 3rd element of "b"'''
c = a[3:8] + b[0:3]
print(c)
'''Append "a" with the... |
class Solution:
#O(NlogN) time(sort)
#First sort the input array by two attributes:
#(1) height, with reverse order(higher people in front)
#(2) k, with normal order
#Then we insert the sorted array into another array with the rule given.
def reconstructQueue(self, people):
"""
:... |
# 循环语句
# py中所有的计数都是从0开始的
# for i in range(10):
# print(i)
lists = [9, 8, 6, 7, 15, 3, 5, 6, 3, 4, 6, 3]
a = 0
for i in lists:
if i == 6:
del lists[a]
a = a + 1
print(lists)
# count = 10
#
# while count < 0:
# count = count - 1
# print(count)
# 打印:0123456789
# 打印:0 2 4 6 8 10
# a = 0
# w... |
"""This is the simple implementation of a batch gradient descent algorithm.
Partially inspired by https://gist.github.com/marcelcaraciolo/1321575
Written by Sarunas Girdenas, sg325@exeter.ac.uk, July, 2014"""
import numpy as np
import matplotlib.pyplot as plt
# Import some data
Data = np.genfromtxt('some_data_file.t... |
import random
# input
print("Let's play rock, paper, scissors!")
user_choice = input("What do you choose - rock, paper, or scissors?\n")
computer_choice = random.choice(["scissors", "rock", "paper"])
result = ""
# process
if computer_choice == user_choice:
result = "It's a tie game!"
elif user_choice == "rock" ... |
# Initialize for all GPAs
overall_count = 0
overall_points = 0
overall_gpa = 0
grade= ""
active = True
grades = {"A+": 4.2,
"A": 4.0,
"A-": 3.9,
"B+": 3.7,
"B": 3.2,
"B-": 3.0,
"C+": 2.8,
"C": 2.2,
"C-": 2.0,
"D+": 1.8,
"D": 1.2,
"F": 0
}
# Get the first input into variable grade
print("This ... |
import csv
from utils import *
def nameyear(pm):
return pm["County"] + pm["Year"]
def newCounty(pm, withYear):
newCounty = {}
#set county name
newCounty["Name"] = pm["County"]
#set establishment and changeover numbers
newCounty["EstNum"] = 0
newCounty["ChangeNum"] = 0
if isChangeover(pm):
newCounty["ChangeN... |
import random
# greeting = '안녕하세요.'
# for i in range(5):
# print(greeting)
# n = 0
# while n < 5:
# print(greeting)
# n += 1
# tiny_dust = 130
# if tiny_dust >= 150:
# print("매우나쁨")
# elif tiny_dust > 80, 150 <= tiny_dust:
# print("나쁨")
# elif tiny_dust > 30, 80 <= tiny_dust:
# print("보통")
#... |
import nmap
print("*.*.*.*.*.*.*.*.*.*.*.*.*..*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*")
print("<*W*E*L*L*C*O*M*E**T*O**N*A*M*P**S*C*A*N*N*E*R**I*N**P*Y*T*H*O*N*3*_*>")
print("*.*.*.*.*.*.*.*.*.*.*.*.*..*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*")
scanner = nmap.PortScanner()
ip_addr = input("< Enter The IP Ad... |
import pandas as pd
class OpenFiles:
'this class has opens and closes the file to process using pandas library, it has the openfile method which accepts arguments, accepts either(txt,csv,tsv)'
def __init__(self,file_type):
self.file_type = file_type
def open_files(self): ... |
import csv
with open ("oui.csv") as input_csv:
entries = csv.reader(input_csv, delimiter =',')
output_txt = open("oui.txt", "w")
#Create the starting part of the file
output_txt.write("OUI/MA-L\nOrganization\ncompany_id\nOrganization\n\nAddress\n\n")
first = True
for row in entries:
if first:
first = Fals... |
class Employee:
def __init__(self,name,yearsOfExperience,pastEmployers):
self.name = name
self.yearsOfExperience = yearsOfExperience
self.pastEmployers = pastEmployers
def pastEmployers(self):
return(self,pastEmployers)
def yearsOfExperience(self,y):
self,yearsOfExperience = y
def needsPromotion(sel... |
def main():
mylist = ['Tuesday','Wednesday','Friday']
print(mylist)
replacement_day = input("Enter the day: ")
mylist[0] = replacement_day
print(mylist)
remove_day = int(input("Enter the index of the day: "))
del mylist[remove_day]
print(mylist)
if __name__ == "__main__":
main() |
s = input("Enter a string:")
t = ""
for i in s:
if i == " ":
t = t + '_'
else:
t = t+i
print(t)
|
text1 = str(input("Enter your first name:"))
if "Moaksh" in text1:
print("Moaksh Kakkar the great!!")
else:
text2 = str(input("Enter yout second name:"))
space = " "
print(text1 + space + text2)
|
num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
min = num1
if num2 < num1:
min = num2
for i in range(1, min + 1):
if((num1 % i) == 0 and (num2 % i) == 0):
hcf = i
print("HCF of", num1, "and", num2, ":", hcf)
|
str = "Hello, World!"
#str[start: stop:step]
# slicing str
print("Basic slicing")
print("1", str[1:])
print("2", str[:5])
print("3", str[6:10])
print("4", str[-12:-6])
# step string slicing
print("Step string slicing")
print("1", str[:12:2])
# reverse slicing
print("Reverse slicing")
print("1", str[::-1])
|
ask = ("avashah")
odd = 1
empty = ""
for x in ask:
odd = odd + 1
if odd%2 ==0:
empty = empty + ((x.upper()))
else:
empty = empty + ((x.lower()))
print(empty)
ask = ("avashah")
odd = 1
anotherempty = ""
for t in ask:
odd = odd + 1
if odd%2 ==0:
t = t.upper()
if t ==... |
"""
Project: Coffee Machine in Python
Stage #5: On a coffee loop
Description
But just one action isn’t interesting.
Let's improve the program so it can do multiple actions, one after another.
The program should repeatedly ask what the user wants to do.
If the user types "buy", "fill" or "take", then just do what the p... |
"""
Project: Smart Calculator (Python)
Stage #3: Count them all
Description
At this stage, the program should read an unlimited sequence of numbers from the standard input and calculate their sum.
Also, add a /help command to print some information about the program.
Input/Output example
The example below shows input... |
"""
Project: Hangman
Stage #6: Victory!
Add the victory condition
The recent version of the game is not as fun until we don't handle the player's victory.
A player wins when all the letters are guessed and there are still some tries left
(except the player uses his last try and actually guesses the word, he's lucky th... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 25 23:23:12 2017
@author: akhiltayal
"""
# Multiple Linear Regression
# Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def importData(filename):
data = pd.rea... |
users=[
{
"id":0,"name":"Hero"},{
"id":1,"name":"Dunn"
},{
"id":2,"name":"Sue"
},{
"id":3,"name":"Chi"
},{
"id":4,"name":"Clive"
},
{
"id":5,"name":"Devin"
},
{
"id":6,"name":"Klein"
},
]
#now wants to map them to the friendship pairs
friendsip_pairs=[(0... |
# 单行注释1
print("abc") # 单行注释2
'''
多行注释
'''
"""
多行注释
"""
if True:
print("true")
else:
print("false")
if True:
print("Answer")
print("True")
else:
print("Answer")
# print ("False") # 缩进不一致,会导致运行错误
# 变量声明,前面不能有空格
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
#a = b = c = ... |
def mergeSort(a):
n=len(a)
if n<=1:
return a
L=mergeSort(a[:round(n/2)])
R=mergeSort(a[round(n/2):])
return merge(L,R)
def merge(L,R):
i=0
j=0
newA=[]
while i<len(L) and j< len(R):
if L[i]<R[j]:
newA.append(R[j])
j+=1
els... |
"""
Algorithms for finding shortest distance between set of points
"""
import math
def e_distance(point1, point2):
"""Calculates the euclidian distance betweeb two points"""
return math.sqrt((point1[0] - point2[0]) ** 2 +
(point1[1] - point2[1]) ** 2)
def brute_force(points_list):
... |
def union(set1, set2):
"""
Returns the union of two sets.
Arguments:
set1 -- The first set of the union.
set2 -- The second set of the union.
Returns:
A new set containing all the elements of set1 and set2.
"""
res = set1.copy()
for item in set2:
res.add(item)
retur... |
"""
Simple graph distionary representation and calculation
"""
import random
import dpa_trial
import upa_trial
EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])}
EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]),
3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
EX_GRAPH2 = {0: set([1, 4, 5]),... |
# -*- coding: utf-8 -*-
import command
class NothingToUndoException(Exception):
def __init__(self):
super(NothingToUndoException, self).__init__("There is command to undo.")
class NothingToRedoException(Exception):
def __init__(self):
super(NothingToRedoException, self).__init__("There is no... |
sifre1 = input("Lütfen yeni şifrenizi giriniz:")
sifre2 = input("Lütfen şifrenizi tekrar giriniz:")
if(sifre1 == sifre2):
if(len(sifre1) < 4):
print("Şifreniz 4 karakterden daha büyük olmalıdır")
else:
print("Şifreniz değiştirildi.")
else:
print("Şifreleriniz uyuşmamaktadır.")
|
int_codes = []
relative_base = 0
def get_int_code(position: int) -> int:
global int_codes
if position >= len(int_codes):
for num in range(len(int_codes), position + 2):
int_codes.append(0)
return int_codes[position]
def set_int_code(position: int, value: int):
global int_codes
... |
from collections import deque
class TransitionMemory():
def __init__(self, num_steps):
self.t_deque = deque(maxlen=num_steps)
# this function formats all transitions in memory, returns the list of them, and resets self.t_deque to an empty deque, resetting the instance to its starting state
def flush(self):
# ... |
"""
Desafio 015 - Aluguel de carros
Faça um algoritmo que : Pergunte a quantidade de Km percorridos
e quantidade de dias alugado, Calcule o valor a pagar
Diaria R$60 Km rodado R$0.15
Passos
1- Verificar quantidade de Km percorrido
2- Verificar quantidade de Dias alugado
3 - Calcular valor a ser pago
4 ... |
#Dissecando uma váriavel : Fazer um programa que leia algo -
# pelo teclado e mostre na tela o seu:
#Tipo primitivo e todas informações possíveis
a = input('Digite algo: ')
print(" o tipo primitivo desse valor é" , type(a))
print('Só tem espaços?', a.isspace())
print('is numeric?', a.isnumeric())
print('é alfabetico?... |
import csv
import os
# Adopted from course materials
electioncsv = os.path.join("Resources", "election_data.csv")
# Declare and initialize variables and lists
totalvotes = 0
candidates = []
candidatesvotes = []
Khanvotes = 0
Khanpercent = 0
Correyvotes = 0
Correypercent = 0
Livotes = 0
Lipercent = 0
OTooleyvotes = 0
... |
def prepare_puzzle(puzzle):
return [int(n) for n in puzzle[0].split(',')]
def get_number_spoken(puzzle, nth):
history = {n: i+1 for i, n in enumerate(puzzle)}
last_number = puzzle[-1]
prev_number = -1
for turn in range(len(puzzle)+1, nth+1):
last_number = 0 if prev_number == -1 else (turn-1... |
def prepare_puzzle(puzzle):
return [parse_exp(exp.replace(' ', '')) for exp in puzzle]
def parse_exp(exp):
result = []
i = 0
while i < len(exp):
if exp[i] == '(':
i, exp_start, open_parentheses = i+1, i+1, 0
while exp[i] != ')' or open_parentheses > 0:
if... |
def prepare_puzzle(puzzle):
return puzzle
def count_trees(puzzle, right, down = 1):
trees = 0
n = 0
for line in puzzle[1::down]:
n += right
n %= len(line)
if line[n] == '#':
trees += 1
return trees
def solve_part1(puzzle):
return count_trees(puzzle, 3)
def ... |
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import time
from enum import Enum, auto
from json.decoder import JSONDecodeError
from typing import Dict, List, Optional, Union
class ValidationError(Exception):
"""
Exception used to signal that it was not possibl... |
import random
#Empty list that will hold the generated Characters
generated_characters=[]
#loop through 100 to generate 100 rows
for each in range(100):
#Generate characters for each row
generated_characters.append(" ".join(random.choice("AGCT") for each in range(12)))
#Opens or creates a file, greenshoe.csv, ... |
# 12. Write a ship battle game, which is similar to ex.8, except it takes 1 integer as an order of matrix,
# randomly generates index (x, y) and checks user input (2 integers).
# (tip: use var1, var2 = raw_input("Enter two numbers here: ").split())
# *Visualize the game.
import random
board = []
for x in r... |
#!/usr/bin/python
import mraa
import time
"""
This script demonstrates the usage of mraa library for configuring and
using a GPIO as input port
setup:
The LED is connected port D5 and button is connected to port D6
Demo:
start the application in the command line by using following command:
python button.py
Press t... |
text="hello hai hai hai hai hello hello"
#o/p hello:3 hai :4
#print word count
words=text.split(" ")
#print(words)
dict={}
#dict[word]=1##hello id that word not in dict
#dict[word]+=1 #if that word not in dictionary
for word in words:#"hello" 1st check then hai etc
if(word not in dict):
dict[word]=1
... |
#class---design pattern,plan,template,blueprint
#object---real world entity
#reference
#create class using "class"
#class classname
class Person:
#attribute of person self.name,self.age,self.gender
def set_person(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
... |
lst=[6,6,8,9,4,2,3]#otput is [7,7,9,10,3,1,2]
#if num>5 num+1 else num<5 num-1
out=[]
for num in lst:
if(num>5):
out.append(num+1)
else:
out.append(num-1)
print(out)
|
#example pgm
# 1 2 3 4
# 5 6 7 8
# 9 10 11 12
# pgm
#cnt=1
#for i in range(1,13):
# print(i, end="\t")
# if(cnt==4):
# print()
# cnt=1
# else:
# cnt+=1
#nested for loop pgm
#*
#* *
#* * *
#* * * *...........
for row in range(1,5):
for col in range(0,row):
print("*",end=" ")
print()
... |
num=int(input("number"))
if(num>0):
print("+ve")
elif(num<0):
print("_ve")
elif(num==0):
print("zero") |
num1=int(input("Enter the day:"))
num1=int(input("Enter the month:"))
num1=int(input("Enter the year:")) |
n1=10
n2=3
add=n1+n2
sub=n1-n2
div=n1/n2
mul=n1*n2
flr=n1//n2
mod=n1%n2
print("addition:",add)
print("subsraction:",sub)
print("division:",div)
print("Multiplication:",mul)
print("mod:",mod)
print("floor:",flr) |
import collections as c
class Node:
def __init__(self, char = ""):
self.char = char
self.children = []
self.last = False
def isNext(self, char):
for i, child in enumerate(self.children):
if child.char == char:
return i
def addChar(self, char):
... |
from fenics import *
import sys
import math
def print_message (ndiv,h):
print("*********************************************************************")
print("Solving Poisson equation using %d divisions -- h = %g" % (ndiv,h))
print("*********************************************************************")
def solve_p... |
import random
from playsound import playsound
def gameWin(comp, you):
if comp == you:
return None
elif comp == 'r':
if you == 's':
return False
elif you == 'p':
return True
elif comp == 'p':
if you == 'r':
return False
elif you... |
i = 1
sum = 0
while i <= 10:
user = int(raw_input("enter your number"))
sum = sum + user
average = sum / i
i = i + 1
print (average)
|
user = int(raw_input("enter your number"))
if user > 0:
print "positive umber h",user
else:
print "nagative h",user |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.