text stringlengths 37 1.41M |
|---|
word=input("Enter a world: ")
word=word.lower()
vowel_count=0
consonant_count=0
vowels="aeiou"
for letter in range(len(word)):
if (vowels.find(word[letter]) != -1):
vowel_count+=1
else:
consonant_count+=1
print(word, "has", vowel_count, "vowels and", consonant_count, "consonants.")
|
nums=[1,3,5,7,9,10]
def multiply(nums):
for a in nums:
print(a*5)
multiply(nums) |
# class MyClass:
# x=5
# y=10;
# z=20;
# a=30;
# print(MyClass)
#
# myObj = MyClass()
#
# print(myObj.z)
class Person :
def __init__(self,fname,lname):
self.fname = fname
self.lname = lname
def fullName(self):
print(self.fname +" "+self.lname)
person2 = Person("Murali","... |
x = 1
y = 2.8
# z = x//y
x =5 ;
x **= 4
print(x)
# a = 27
# b = a % 4
# print(b)
# x = x+y
# x+=y
# x = x - y
# x-=y
# ** Exponentation
# // Floor Division
# print(z)
# print(x)
# print(type(y))
# print(type(x)) |
###########################################################################################################################################################
#-PROGRAM 1
numbers = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 95... |
# The program to find the different part of the sentence between #
# two files which are your targets. You should tell the program #
# hint which is the first of the word of the sentence. #
# #
... |
# Library for Use by FactorModelMOOC.ipynb.
"""
This file applies to Week2.
Python and Machine Learning for Asset Management by EDHEC Business School.
on Coursera
-----------
Week 1 - Introducing the fundamentals of machine learning
Week 2 - Machine learning techniques for robust estimation of factor models
Comm... |
# -*-coding:Latin-1 -*
import os
nb_u = input("Tapez un nombre pour obtenir sa table de multiplication"" ")
nb = int(nb_u)
MAX_u = input("Tapez le chiffre maximal pour lequel vous voulez obtenir sa table de multiplication"" ")
MAX = int(MAX_u)
def table_multiplication(nb, MAX):
i = -1
while i<MAX:
pr... |
#!/usr/bin/python
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # Zaehlweise der GPIO Pins auf dem Raspberry
GPIO.setup(2, GPIO.IN) # Pin 3 als Eingang - Button 1
GPIO.setup(3, GPIO.IN) # Pin 4 als Eingang - Button 2
# store button state in these variables, 0 means button is pressed
button1 = 1
button2 =... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 8 13:08:34 2019
@author: Harsh Anand
"""
"""
Code Challenge
Name:
Bricks
Filename:
bricks.py
Problem Statement:
We want to make a row of bricks that is target inches long.
We have a number of small bricks (1 inch each) and big bricks (5 inches e... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 9 16:26:02 2019
@author: Harsh Anand
"""
"""
Two words are anagrams if you can rearrange the letters of one to spell the second.
For example, the following words are anagrams:
['abets', 'baste', 'bates', 'beast', 'beats', 'betas', 'tabes']
Hint: How can you tell qu... |
"""
Code Challenge 1
Write a python code to insert records to a mongo/sqlite/MySQL database
named db_University for 10 students with fields like
Student_Name, Student_Age, Student_Roll_no, Student_Branch.
"""
import mysql.connector
from pandas import DataFrame
# connect to MySQL server along with Database name
c... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 14:10:31 2019
@author: Harsh Anand
"""
# Print all the numbers from 1 to 10 using condition in while loop
i=1
while(i<11):
print(i)
i+=1
#Print all the numbers from 1 to 10 using while True loop
x=1
while(True):
print(x)
x+=1
if x==11:
br... |
'''
Q1. Human Activity Recognition
Human Activity Recognition with Smartphones
(Recordings of 30 study participants performing activities of daily living)
(Click Here To Download Dataset): https://github.com/K-Vaid/Python-Codes/blob/master/Human_activity_recog.zip
In an experiment with a group of 30 volunteers with... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 8 16:23:22 2019
@author: Harsh Anand
"""
"""
Code Challenge
Name:
Unlucky 13
Filename:
unlucky.py
Problem Statement:
Return the sum of the numbers in the array, returning 0 for an empty array.
Except the number 13 is very unlucky, so it does no... |
r = int(input('Enter r:'))
gotr = r * 2
mohit = gotr * 3.14
masahat = r ** 2 * 3.14
print('gotr:', gotr, 'mohit:', mohit, 'masahat:', masahat)
|
def fact(num):
if num == 1:
return 1
else:
return(num*fact(num-1))
val = int(input("Enter any number "))
print("The required factorial is ", fact(val)) |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
dict1 = {21: "FTP", 22: "SSH", 23: "telnet", 80: "http"}
newdict = dict([(value, key) for key, value in dict1.items()])
print(dict1)
print()
print("keys: values")
for i in newdict:
print(i, " : ", newdict[i])
# In[11]:
list1 = [(1,2),(3,4),(4,5),(5,6)]
l... |
def insertion(numbers):
for i in range(1, len(numbers)):
j = i
#While loop to check if previous element is larger
#If previous element is smaller, continue traversing
while j > 0 and numbers[j-1] > numbers[j]:
#Swap elements, decrement j
... |
# _*_ coding: utf-8 _*_
"""题目:打印出如下图案(菱形):
*
***
*****
*******
*****
***
*
"""
def diamond(n):
for i in range(1, 2*n):
print(' ' * abs(i - n) + '*' * (2 * (n - abs(i -n)) -1))
diamond(7) |
# -*- coding: UTF-8 -*-
"""两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵:
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]"""
import numpy
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
def matrixadd(x, y):
L1 = []
for i in range(len(x)):
... |
# _*_ coding: utf-8 _*_
"""题目:利用递归方法求5!。"""
def fact(n):
def f(n, s):
if n == 1:
return s
s *= n
return f(n-1, s)
return f(n, 1)
print(fact(5)) |
starting_nums = [2,15,0,9,1,20]
number_spoken = []
last_spoken = []
nums = dict()
nums[1] = [1,2,3]
#30000000
for i in range(0,30000000):
if i < len(starting_nums):
number_spoken.append(starting_nums[i])
else:
previous_number = number_spoken[i-1]
locations = []
for i in range... |
for letra in "hola!":
print("estamos en la letra: ", letra )
palabras = ["hola", "python", "pythondiario"]
for i in palabras:
print(i, len(i))
vuelta = 1
while vuelta < 10:
print("vuelta" + str(vuelta))
vuelta = vuelta + 1
for vuelta in range(1, 10):
print("vuelta" + str(vuelta))
|
nota1 = int(input("Nota del primer parcial?"))
nota2 = int(input("Nota del segundo parcial?"))
nota3 = int(input("Nota del tercer parcial?"))
nota_Final = (nota1 + nota2 + nota3)/3
print(nota_Final)
|
partidos_g = int(input("cuantos partidos ganados? "))
partidos_p = int(input("Cuantos partidos perdidos? "))
partidos_emp = int(input("Cuantos partidos perdidos? "))
total = (partidos_g*3)+(partidos_emp*1)
print("El equipo tuvo un total de ", total, "puntos")
|
import time
def brute_force(elements):
if len(elements) == 0:
return [[]]
first_element = elements[0]
# Copy the array without first element
rest = elements[1:]
combs_without_first = brute_force(rest)
combs_with_first = []
for comb in combs_without_first:
comb_with_first ... |
from random import randint
bilTebak = randint (0,100)
print ("Halo... Nama saya Mr. Komputer :D")
print ("Saya telah memilih bilangan secara acak dari 0 - 100")
print ("Coba tebak, bilangan berapakah itu?? :)))")
while True :
bilAnda = int ( input ("Silahkan masukkan tebakkan Anda :"))
if (bilAnda > 0) and (... |
print ("Program input nama mahasiswa")
status = True
a = []
while (status == True):
namaMhs = str ( input ("Masukkan nama mahasiswa/i : "))
a.append(namaMhs)
konfirmasi = input ("Apakah Anda ingin menambahkan lagi? (y/n) : ")
a.sort()
if (konfirmasi != 'y'):
print()
for data in a:
... |
class Loja(object):
def __init__(self, estoque, caixa):
self.estoque = estoque
self.caixa = caixa
self.aluguelHora = 5
self.aluguelDia = 25
self.aluguelSemana = 100
self.aluguelFamilia = 0
def receberPedido(self, tipoAluguel, qtdeBike, periodo):
... |
"""
This module contains functionality to retrieve the information needed to communicate with the ETC lwm2m server.
Use it to obtain the lwm2m host name, identity, secret key, and endpoint.
"""
import http
import binascii
GET_LWM2M_SECURITY_INFO = 'GET_LWM2M_SECURITY_INFO'
class RetVals:
'''
Defines a s... |
'''This file contains all the functions responsible for mashing the various analysis results into
the format that the result that the rest of the project is expecting (two keyword lists with tuples
of keyword and weight).
This is what implements the actual analyse function that we export in __init__.py
'''
import nlt... |
# Logistic Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Importing the dataset
featured_data = pd.read_excel('survey - USSD among FIsher women - final.xlsx')
X = featured_data[['age','Education','Average Per day sales','Operate SM... |
#program to print if the year is leap or not
'''year = int(input("Enter the year : "))
if year% 4 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
#progran to print multiplication table intered by the user
a = int(input("Enter number for which the table is required : "))
for i in ra... |
def search(arr, n):
while len(arr) > 0:
midpoint = len(arr) / 2
if arr[midpoint] == n:
return True
elif arr[midpoint] > n:
arr = arr[:midpoint]
else:
arr = arr[(midpoint + 1):]
return False
print search([1, 2, 3, 4, 5], 1)
print search([1, 2,... |
#With a single integer as the input, generate the following until a = x [series of numbers as shown in below examples]
a=int(input("enter a number"))
num=1
lst=[]
while len(lst)<a:
if(num%2 !=0):
lst.append(num)
num+=1
print(lst)
|
# A queue based on two stacks
class MyQueue(object):
def __init__(self):
self.vals = [[], []]
def enqueue(self, val):
self.vals[0].append(val)
def _move(self):
while len(self.vals[0]) > 0:
self.vals[1].append(self.vals[0].pop())
def dequeue(self):
... |
from collections import defaultdict
def _count_paths(x, y, obstacles, memo=None):
if memo is None:
memo = defaultdict(int)
if obstacles is not None and (x, y) in obstacles:
return 0
if (x, y) in memo:
return memo[(x, y)]
elif x == 0 and y == 0:
memo[(x, y)] = 1
... |
def _compress_intervals(intervals):
if len(intervals) == 1:
return intervals
else:
cur = intervals[0]
rest = _compress_intervals(intervals[1:])
if cur[1] >= rest[0][0] and cur[1] < rest[0][1]:
if cur[0] < rest[0][0]:
rest[0][0] = cur[0]
else:
... |
class SetOfStacks(object):
def __init__(self, capacity=10):
self.stack_set = [[]]
self.cur = 0
self.capacity = capacity
def push(self, val):
if len(self.stack_set[self.cur]) >= self.capacity:
self.stack_set.append([])
self.cur += 1
self.stack_set[... |
# Given two sorted arrays, A and B, with A having enough buffer at the end to hold B, merges B into A in sorted order.
def merge_sorted_arrays(A, B):
cur_A = len(A) - len(B) - 1
cur_B = len(B) - 1
cur = len(A) - 1
while cur_A >= 0 and cur_B >= 0:
if A[cur_A] > B[cur_B]:
A[cur] = A[... |
class TowersOfHanoi(object):
'''Implementation of Towers of Hanoi using lists as stacks.'''
def __init__(self, num_disks):
# Declare three stacks to represent the three rods
self.towers = [[], [], []]
# Initialize first rod with disks. Numbers represent disk size
# with large... |
def _paint_fill(screen, x, y, color, new_color):
if x >= 0 and x < len(screen) and y >= 0 and y < len(screen[0]) and screen[x][y] == color:
screen[x][y] = new_color
_paint_fill(screen, x - 1, y, color, new_color)
_paint_fill(screen, x + 1, y, color, new_color)
_paint_fill(screen, x, ... |
#!/usr/bin/env python3
# created by: Ryan Walsh
# created on: November 2020
# this program calculates numbers inserted by user
def main():
# this program calculates numbers inserted by user
# input
first_number = int(input("Enter the first number:"))
second_number = int(input("Enter the second numbe... |
#! /usr/bin/env python3
#-*- conding utf-8 -*-
from PIL import Image
import os
"""
This module contain the function:
-black_and_white :
Transform the image passed as parameter in a black and white Image,
also called greyscale
"""
def black_and_white(img):
"""
for each pixel of the img the average ... |
import cs50
import csv
from sys import argv, exit
if len(argv) != 2:
print("Usage: python3 import.py characters.csv")
exit(1)
db = cs50.SQL("sqlite:///students.db")
the_characters = []
with open(argv[1], "r") as the_characters_csv:
the_characters_reader = csv.DictReader(the_characters_csv)
for row i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# python library for google earth plot
#
# author: Atsushi Sakai
#
# Copyright (c): 2015 Atsushi Sakai
#
# License : GPL Software License Agreement
import simplekml
import pandas
import math
class googleearthplot(object):
def __init__(self):
self.kml = si... |
import numpy as np
import cv2 as cv
img = cv.imread("D:\Code\MyCode\img\logo.png")
print(img.shape)
res = cv.resize(img,None,fx=2, fy=2, interpolation = cv.INTER_CUBIC)
print(res.shape)
#或者
height, width = img.shape[:2]
res = cv.resize(img,(2*width, 2*height), interpolation = cv.INTER_CUBIC)
print(res.shape)
|
def F(x):
if x == 0:
l = 1
elif x == 1:
l = 3
elif x ==2:
l = 2
else:
l = F(x-1)*F(x-3)
return l |
def main():
tupla = (3, 4, 'Não')
tupla2 = 3, 4, 6, 'Sim', True
print(tupla)
print(tupla2)
#vc usa tupla pra retornar valores que precisam de uma maior quantidade de retorno.
main() |
class Carro(object):
tipo = None
def __init__(self, caminho):
self.caminho = caminho
def andar(self):
print('Andando pela', self.caminho)
class Fusca(Carro):
tipo = "Fusca"
def correr(self):
super(Fusca, self).andar()
class Ferrari(Carro):
tipo = "Ferrari"
... |
delattr(object, name)
This is a relative of setattr(). The arguments are an object and a string.
The string must be the name of one of the object’s attributes. The function
deletes the named attribute, provided the object allows it. For example,
delattr(x, 'foobar') is equivalent to del x.foobar.
|
""" filter(function,iterable)¶
Construct a list from those elements of iterable for which function returns
true. iterable may be either a sequence, a container which supports
iteration, or an iterator. If iterable is a string or a tuple, the result
also has that type; otherwise it is always a list. If ... |
xrange(start,stop[,step])
This function is very similar to range(), but returns an xrange object
instead of a list. This is an opaque sequence type which yields the same
values as the corresponding list, without actually storing them all
simultaneously. The advantage of xrange() over range() is minima... |
list([iterable])
Return a list whose items are the same and in the same order as iterable‘s
items. iterable may be either a sequence, a container that supports
iteration, or an iterator object. If iterable is already a list, a copy is
made and returned, similar to iterable[:]. For instance, list('abc')... |
""" repr(object)
The str() function is meant to return representations of values which are fairly
human-readable, while repr() is meant to generate representations which can be
read by the interpreter (or will force a SyntaxError if there is no equivalent
syntax)
Return a string containing a printable represe... |
with open('file.txt', 'r') as f:
# do stuff with f
pass
"""
Python allows putting multiple open() statements in a single with.
You comma-separate them.
"""
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
pass
"""
The argument mode points to a string beginning with one o... |
hex(x)
Convert an integer number (of any size) to a lowercase hexadecimal string
prefixed with “0x”, for example: >>>
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(1L)
'0x1L'
If x is not a Python int or long object, it has to define an __index__()
method that returns an in... |
def lineformater(phrase):
intro = ("who","why","why","how")
if phrase.startswith(intro):
return f"{phrase.capitalize()}?"
else :
return f"{phrase.capitalize()}."
fineline = []
while True:
user_input = input("say to format")
if user_input == "\end":
break
else:... |
def jogar():
print("*********************************")
print("***Bem vindo ao jogo da Forca!***")
print("*********************************")
palavra_secreta = "python"
letras_acertadas = ["_","_","_","_","_","_"]
enforcou = False
acertou = False
print("A palavra secreta contem... |
# This is the number we'll find the factorial of - change it to test your code!
number = 6
# We'll start with the product equal to the number
product = number
# TODO: Write a for loop that calculates the factorial of our number
for i in range(1,number,1):
product = product*i
# TODO: print the factorial of your nu... |
from tkinter import *
from tkinter import messagebox
from random import randint
"""
MINE SWEEPER GAME
"""
class initialScreen():
"""
initial screen
"""
def __init__(window):
window.root = Tk()
window.root.title("Start Game")
window.root.grid()
window.finish = ... |
def calculatePie(n):
pie =0
i =1
for i in range(n):
x =4*i*i
y= 4*i*i -1
z=float(x)/float(y)
if(i==1):
pie =1
pie =pie*z
else:
pie =pie*z
newpie=2*pie
print newpie
calculatePie(5... |
#!/usr/bin/env python3
'''
an async routine called wait_n that takes in 2 int
arguments (in this order): n and max_delay. You will
spawn wait_random n times with the specified max_delay
'''
import random
import asyncio
from typing import List
wait_random = __import__('0-basic_async_syntax').wait_random
async def wa... |
import sys
import random
from collections import deque
class Node:
def __init__(self, state, parent, path_length, dir):
self.parent = parent
self.path_length = path_length
self.state = state
self.dir = dir
def get_parent(self):
return self.parent
de... |
""" Methods to add UTC datetimes"""
import pandas as pd
def add_utc_datetime(df: pd.DataFrame) -> pd.DataFrame:
"""
Make 'settlement_period_start_utc' from 'Settlement Day' and 'Settlement Period'
settlement_period_start_utc is the datetime with utc timezone of the settle period
:param df: datafrom... |
#!/usr/bin/env python
# coding=utf-8
__author__ = 'chenfengyuan'
def find(arr: list, start, value):
for i in range(start, len(arr)):
if arr[i] == value:
return i
else:
return None
|
#Anthony Barrante
#ITP 100
#Area of a Circle Calculator
#This program calculates the area of a circle using the mathematical formula:
#Area=3.14*radius^2
Radius = float(input("Please enter the radius of the circle: "))
Area = float(3.14*Radius*Radius)
print("Using the radius ",Radius, "the area of the ci... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic list exercises
# D. Given a list of numbers, return a list where
de... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
# 打印list:
names = ['小明','小红','小石']
for name in names:
print(name)
# 打印数字 0 - 9
for x in range(10):
print(x) |
from tkinter import *
root = Tk()
i = 0
operand = ''
x = ''
def insert(text):
global i
screen.insert(i,text)
i += 1
def operate(operator):
global operand
global x
operand = operator
x = screen.get()
screen.delete(0,END)
def execute():
global operand
glo... |
# ------------------------------------------------------------------------ #
# Title: Assignment 07
# Description: Demo of pickling and error handling
# ChangeLog (Who,When,What):
# JEmbury, 12/1/19,Created started script
# ------------------------------------------------------------------------ #
import pickle... |
#CH09-Lab01 가위, 바위, 보 게임
import random
def match(c, m):
if c == m :
return '비겼습니다.'
elif match_table[c] == m:
return '졌습니다.'
else:
return '이겼습니다.'
rps_dic = {1:'가위', 2:'바위', 3:'보'}
match_table = {'가위':'보', '바위':'가위', '보':'바위'}
computer = rps_dic[random.randint(... |
#CH02-08. 지역 변수와 전역 변수
##################################################################
##원의 면적을 계산
def calculate_area( ):
result = 3.14 * r **2
return result
r = float(input("원의 반지름: "))
area = calculate_area( )
print(area)
|
#CH03-05 연산자의 우선순위
##################################################################
#사용자로부터 3개의 수를 입력받아서 평균을 출력
x = int(input("첫 번째 수: "))
y = int(input("두 번째 수: "))
z = int(input("세 번째 수: "))
avg = (x + y + z) / 3
print("평균 =", avg)
|
#CH07-05. 리스트 항목 삭제하기
##################################################################
##방법3: 리스트에서 pop( )을 이하여 항목을 삭제
cart=['사과', '세제', '화장지', '치약']
item = cart.pop( )
print(cart)
print(item)
|
#CH06-Lab05 범인 찾기 게임
import random
score = 0
while True :
room = random.randint(1, 3)
n = int(input("방 번호를 입력 하세요: "))
if n == room :
print("범인 체포!")
score += 10
break
elif n > 3 :
print(n,"번 방은 없습니다.")
else:
print("범인이 없습니다.")
scor... |
#CH10-Lab03 평균 강수량 통계
import csv
# 입력 파일 출력 파일 열기
infile = open("D:\\weather_input.csv", "r")
data = csv.reader(infile)
count = 0
sum = 0
for line in data :
count += 1
sum += float(line[2])
print("강원도 2009년 01월 부터 2019년 09월까지의 총 강수량: ", sum)
print("강원도 2009년 01월 부터 2019년 09월까지의 평균 강수량: ", sum... |
#CH02-08 수 입력받기
##################################################################
##정수 2개 입력받기
##x = int(input("첫 번째 정수를 입력하시오: "))
##y = int(input("두 번째 정수를 입력하시오: "))
##sum = x + y
##print(x, "과", y, "의 합은", sum, "입니다.")
###################################################################
##사용자로부터 2개의 ... |
#CH03-Lab03 두 점 사이의 거리 구하기
x1 = int(input("x1: "))
y1 = int(input("y1: "))
x2 = int(input("x2: "))
y2 = int(input("y2: "))
print("두 점 사이의 거리=", ((x2-x1)**2 + (y2-y1)**2)**0.5)
|
#CH06-006. 조건 제어 반복을 좀 더 이해시켜 줄 예제
##################################################################
##1부터 100까지의 합을 구하는 프로그램
count = 1
sum = 0
while count <= 100 :
sum = sum + count
count = count + 1
print("1부터 100까지의 합은",sum,"입니다.")
|
import re
def adverbe(word):
if word[-4:] == "ment":
return 1
return 0
def split_to_word(text):
separtion_punctuation = re.compile('[\s]+')
text = separtion_punctuation.split(text)
return text
def open_file(file):
file_ = open(file, 'r')
content = file_.read()
liste = spli... |
class Solution:
def isValid(self, s: str) -> bool:
#뚜껑과 그릇이 딱 만나는 순간에도 같아야한다
stack = []
for char in s:
if char == "(" or char == "{" or char == "[":
stack.append(char)
if char == ")" : #testcase ")"때문에
if not stack or stack[-1]... |
# 1. Ce valoare o sa contina variabila a după execuția codului ?
a = 10
a += len(str(a))
print(a)
#Raspuns a = 12
######################################################################################################
# 2. Codul de mai jos conține o eroare, modificați codul astfel încît programul să funcționze corect.
#... |
t#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 2 02:51:42 2019
@author: utkarsh
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20.0, 10.0)
# Reading Data
data = pd.read_csv('./dataSet/headbrain.csv')
print(data.shape)
data.head()... |
# -*- coding: utf-8 -*-
# scatter plot
2D scatter plot
iris.plot(kind='scatter', x='sepal_length', y='sepal_width') ;
plt.show()
# 2-D Scatter plot with color-coding for each flower type/class.
# Here 'sns' corresponds to seaborn.
sns.set_style("whitegrid");
sns.FacetGrid(iris, hue="species", size=4) \
.map... |
def collect_by_value(obj, val_fn, only_values=False):
"""
Collect values in an arbitrary structure. Values can be strings or numbers.
Takes:
obj(iterable): arbitrary structure to scan
val_fn(function): function to use against values
include_key(bool): Collect the key as well
Re... |
#Cómo se visualizaría en consola la respuesta
cadena = 'En una zarzamorera estaba una mariposa zarzarrosa y alicantosa.'
diccionario = {'Salvador Caracuel': 144}
b = cadena.split('po')
for i in b:
if i in diccionario:
diccionario[i] *= 78
else:
diccionario[i] = 98
print(diccionario)
'''
RPTA:
{'sa zarzarrosa... |
matriz = [
['A', 'B', 'C', 'D'],
['E', 'F', 'G', 'H'],
['I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P'],
]
for num in range(1,5):
x = num % 2
if x == 0:
print(matriz[x][num % 2])
'''
RPTA:
A
A
'''
|
#Criar um algoritmo em PYTHON que leia o destino do passageiro, se a viagem inclui retorno (ida e volta) e informar o preço da passagem conforme a tabela a seguir:
#1-Região Norte, 2-Região Nordeste, 3-Região Centro-Oeste, 4-Região Sul
#Entrada de dados
print("Digite um dos valores abaixo para selecionar a região\... |
#Escreva um algoritmo em PYTHON que leia uma temperatura em gruas centígrados e apresente a temperatura convertida em graus Fahrenheit.
#A fórmula de conversão é: F = (9 * C + 160) / 5
#Onde F é a temperatura em Fahrenheit e C é a temperatura em centígrados
#Entrada de dados
C = float(input("Digite a temperatur... |
#2)Uma P.G. (progressão geométrica) fica determinada pela sua razão (q) e pelo primeiro termo (a1). Escreva um algoritmo em PORTUGOL que seja capaz de determinar
#qualquer termo de uma P.G., dado a razão e o primeiro termo.
#Entrada de dados
a1 = int(input("Digite o valor do primeiro termo: "))
q = int(input(... |
#Antes de o racionamento de energia ser decretado, quase ninguém falava em quilowatts; mas, agora, todos incorporaram essa palavra em seu vocabulário. Sabendose
#que 100 quilowatts de energia custa um sétimo do salário mínimo, fazer um algoritmo em PYTHON que receba o valor do salário mínimo e a quantidade de quilowat... |
from Pilha import Pilha
class Backtracking:
def __init__(self,inicio,objetivo):
self.inicio = inicio
self.inicio.visitado = True
self.objetivo = objetivo
self.fronteira = Pilha(16)
self.fronteira.empilhar(inicio)
self.achou = False
def buscar(... |
class Pilha:
def __init__(self,tamanho):
self.tamanho = tamanho
self.letras = [None] * self.tamanho
self.topo = -1
def empilhar(self,letras):
if not Pilha.pilhaCheia(self):
self.topo += 1
self.letras[self.topo] = letras
else:
... |
#Criar um algoritmo em PYTHON que efetue o cálculo do salário líquido de um professor. Os dados fornecidos serão: valor da hora aula, número de aulas dadas no
#mês e percentual de desconto do INSS.
#Entrada de dados
valorHora = float(input("Digite o valor da hora aula: "))
#implementação de segurança garantindo... |
import math
print(" COMPUTER ORGANIZATION ")
print(" END SEMESTER ASSIGNMENT ")
def read(address1,bits_in_B,bits_in_Cl,cache):
l1=len(address1)
extra_tag_length=int(l1-bits_in_B-bits_in_Cl)
i2=32-l1
tag=""
for i in range(i2):
tag+="0"
f... |
adapters = []
f = open("input.txt", "r")
for line in f.readlines():
strippedLine = line.strip()
print(strippedLine)
adapters.append(int(strippedLine))
adapters.sort(reverse=True)
adaptersMap = {}
endJolt = adapters[0]
endNode = {"jolt": endJolt - 3, "chains": {}, "from": {}}
adaptersMap[endJolt] = endNode... |
# f = open("exampleInput.txt", "r")
f = open("input.txt", "r")
cardPublicKey = 0
doorPublicKey = 0
for line in f.readlines():
strippedLine = line.strip()
print(strippedLine)
if cardPublicKey == 0:
cardPublicKey = int(strippedLine)
else:
doorPublicKey = int(strippedLine)
print(cardPublic... |
import re
def moveDir(pos, dir, value):
if (dir == 0):
pos[0] = pos[0] + value
elif (dir == 180):
pos[0] = pos[0] - value
elif (dir == 90):
pos[1] = pos[1] + value
elif (dir == 270):
pos[1] = pos[1] - value
def rotateVec(vec, degrees):
if (degrees == 0):
#no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.