text stringlengths 37 1.41M |
|---|
tup=(1,2,3,4,5,6,7,8,9,10)
def print_even(tup):
for i in range(10):
if tup[i] % 2 ==0:
print(tup[i])
print_even(tup)
|
a=int(input())
class gen():
def gent(self,a):
n=1
while n<=a:
if n % 7 == 0:
yield n
n+=1
obj=gen()
obj.gent(a)
for i in obj.gent(a):
print(i)
|
print("number of lines want to capilatize")
t=int(input())
ls=[]
# tr=''
for i in range (t):
a=input()
# tr=a.split(" ")
ls.append(a)
for item in ls:
print(item.upper()) |
def dic_val():
lis=[]
for c in range (21):
lis.append(c*c)
# for c in range (5):
# print(dic[c],end=" ")
return lis
print(dic_val()) |
S = 'chungus'
def revstr(S):
if len(S) == 1 :
return S
else :
return S[-1] + revstr(S[:-1])
print(revstr(S)) |
iterable_here = "Andy Rulz"
for variable_here in iterable_here:
print(variable_here) #actions here
print("Is shorthand for:")
it = iter(iterable_here)
while True:
try:
variable_here = next(it) #declare variable_here
except StopIteration:
break #break out of the loop if we're done
prin... |
f = open('filelooper.txt', 'w')
f.write("Hi there. \n\
I am a competer. \n\
Are you a human or a computer?")
f.close()
f = open('filelooper.txt')
temp = 'start'
while temp != '':
temp = f.read(3)
print(temp)
print("\n**\n")
f.close()
#seek(0) ---> sets the file's current position at the offset
|
import random, time
def draw_to_screen(content):
print("\n"*50)
print(content)
time.sleep(0.2)
def noise_bars(n, w):
result = ""
list_of_numbers = []
for i in range(n):
list_of_numbers.append(random.randint(1,w))
while len(list_of_numbers) > 0:
next_number = list_of_number... |
total = 1
def hundredforward (n):
if n < 100:
global total
total = total * n
return hundredforward(n+3)
else:
return total
print(hundredforward(1)) |
people = [{"name":"Andy", "rel_stat":"married"}, {"name":"Sara", "rel_stat":"married"}, {"name":"Simone", "rel_stat":"single"}]
print("Count married people")
print(list(map(lambda x: x["rel_stat"], people)))
print(list(map(lambda x: 1 if x["rel_stat"] == "married" else 0, people)))
print(sum(map(lambda x: 1 if x["re... |
n = input("Pick a number please: ")
for i in range (1, n+1):
print (i*i) |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
import re
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area cod... |
import math
def is_leap_year(year):
if year%4 !=0:
return False
elif year%100 !=0:
return True
elif year%400 !=0:
return False
else:
return True
def days_between_dates(birth_date,current_date):
"""Calculates the age in days based on the values provided
Args:
... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self, head=None):
self.head = head
def append(self, value):
if self.head is None:
self.head = Node(v... |
import math
import random
import scripting.py
def main():
print(math.pow(2,3))
def generate_password():
try:
word_list=[]
with open('words_list.txt','r') as f:
for line in f:
word_list.append(line.strip('\n'))
password_list=random.... |
#!/usr/bin/python3
"""
Given an array A of N numbers (integers), you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].
... |
#!/usr/bin/python3
"""
Given a list of numbers (integers), find second maximum and second minimum in this list.
Input Format:
The first line contains numbers separated by a space.
Output Format:
Print second maximum and second minimum separated by a space
Example:
Input:
1 2 3 4 5
Output:
4 2
"""
ls = list(map(i... |
#!/usr/bin/python3
"""
You are provided with the number of rows (R) and columns (C). Your task is to generate the matrix having R rows and C columns such that all the numbers are in increasing order starting from 1 in row wise manner.
Input Format:
The first line contain two numbers R and C separated by a space.
Out... |
#!/usr/bin/python3
"""
Write a program to convert a square matrix into a lower triangular matrix.
Input Format:
The first line of the input contains an integer number n which represents the
number of rows and the number of columns.
From the second line, take n lines input with each line containing n integer elements... |
import math
from abc import abstractmethod
from utils import Vector, Position
GRAVITAIONAL_CONSTANT = .001
class Object:
def __init__(self, radius, density, position, velocity=Vector(), colour=(0,0,255)):
self.__radius = radius
self.__density = density
self.position = position
sel... |
for tc in range(1, int(input())+1):
n = int(input())
list1 = list(map(int, input().split()))
list1.sort()
list2 = list1[::-1]
result = []
for i in range(5):
result.append(list2[i])
result.append(list1[i])
print('#{}'.format(tc), end = ' ')
for i in result:
print... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 20:31:08 2020
@author: 86158
"""
#import n, start the loop
temp=input('please input a positive integer:')
n = int(temp)
print(n,"-")
while n>1 :
#judge n even or odd, give different operations
#if the number is even
if n%2==0:
n=n/2
print(n,"-")
#i... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 21:25:14 2020
@author: 86158
"""
#input necessary library
import pandas as pd
#input 3 protein sequence
human='MLSRAVCGTSRQLAPVLAYLGSRQKHSLPDLPYDYGALEPHINAQIMQLHHSKHHAAYVNNLNVTEEKYQEALAKGDVTAQIALQPALKFNGGGHINHSIFWTNLSPNGGGEPKGELLEAIKRDFGSFDKFKEKLTAASVGVQGSGWGWLGFNKERGH... |
import random
import dicts
class WordFactory(object):
def element(self, type):
if type == "SimpleWord": return SimpleWord()
elif type == "Password": return Password()
elif type == "Noun": return Noun()
elif type == "Verb": return Verb()
elif type == "Adjective": return Adje... |
def chartoint (c):
return ord(c) - ord("A") + 10 if c.isalpha() else int(c)
def baseConversion(numStr,radix):
result=0
for i,char in enumerate(reversed(numStr)):
res = chartoint(char)
if res>radix:
return -1
result = result + res * radix ** i
return result
print baseConversion('AF',16)
|
valor = float(input('Qual o valor da casa? '))
sal = float(input('Qual o seu salário? '))
anos = int(input('Em quantos anos pagará a casa? '))
pres = valor / (anos * 12)
if pres > (0.3 * sal):
print('Empréstimo negado. A prestação seria de R${:.2f}.'.format(pres))
else:
print('Empréstimo aprovado')
|
pro = float(input('Qual o valor do produto? '))
print('''Formas de pagamento:
[ 1 ] à vista: dinheiro ou cheque
[ 2 ] à vista, no cartão
[ 3 ] 2x no cartão
[ 4 ] 3x ou mais no cartão''')
meio = int(input('Qual o meio de pagamento? '))
if meio == 1:
print('O valor fica R${}.'.format(pro -(pro*0.1)))
elif meio == 2:
... |
nome = input('Digite o nome: ').strip()
print('Seu nome tem Silva? {}'.format())
# in é um operador do python, não um método.
print('silva' in nome.lower()) |
#nome = input('Digite seu nome completo: ').strip()
#n = nome.split()
#print('Seu primeiro nome é {}'.format(n[0]))
#print('Seu último nome é {}'.format(n[len(n)-1]))
#print('{}'.format(nome[:5]))
print(19 // 2)
print(19 % 2) |
#!/usr/bin/python3.6
# --coding:Utf- -
import pymysql
import pandas as pd
import sys
import site
site.addsitedir('/home/hsaid/Bureau/scripts/python/jeu_video')
from dbHelpers import *
def mysql_to_csv(sql, file_path, con):
'''
The function creates a csv file from the result of SQL
in MySQL database.
'... |
"""节点"""
class Node(object):
def __init__(self, item):
self.elem = item
self.next = None
self.prev = None
"""双向链表"""
class DoubleLinkList(object):
def __init__(self, node=None):
self.__head = node
"""链表是否为空"""
def is_empty(self):
return self.__hea... |
class AQueue:
def __init__(self):
self.in_stack = []
self.out_stack = []
def enqueue(self, value):
self.in_stack.append(value)
def dequeue(self):
if not len(self.out_stack):
while self.in_stack:
self.out_stack.append(self.in_stack.po... |
from contacts.trie import TrieNode
N = int(input())
trie = TrieNode()
for _ in range(N):
instruct, in_str = input().split()
if instruct == "add":
trie.add(in_str)
if instruct == "find":
print(trie.find(in_str))
|
s = input("Enter the String : ")
vowels = 'AEIOUaeiou'
d = {item: s.count(item) for item in s if item in vowels}
print(d) |
s = input("Enter string : ")
print(s.swapcase()) |
import random
import string
st = ''
l = [()]
for i in range(0,6):
if i % 2 == 0:
st += random.choice(string.ascii_letters)
else:
j = random.randrange(0,9,1)
st += str(j)
print(st) |
from sys import argv
def bmi():
print('Name : ', argv[1])
print('Height : ', argv[2])
print('Weight : ', argv[3])
height = float(argv[2])
weight = float(argv[3])
bmivalue = round(weight / (height * height), 1)
return 'Your BMI is ', bmivalue, 'which means you are underweight.' if bmivalue < ... |
n = int(input("Enter the Value:"))
if n in range(1,101):
if n%2 != 0:
print('Weird')
else :
if n in range(2, 5):
print(' Not Weird')
elif n in range(6,11):
print('Weird')
elif n > 10:
print('Not Weird')
else :
print("Invalid Number")
|
s = input('Enter String: ')
t = ''
for i in s:
if i not in t:
t = t+i
print(t)
|
# coding: utf-8
# ## Finite State Machine for Snakes and Ladders game
import random
class State(object):
def __init__(self, ix):
self.index = ix
self.link = None # placeholder, not None if Snake or Ladder
def process(self):
"""Action when landed upon"""
if self.link:
... |
# -*-coding:Utf-8 -*
"""Ce module contient la classe Labyrinthe."""
class Labyrinthe:
"""Classe représentant un labyrinthe."""
def __init__(self,max_largeur,max_hauteur, position_robot, position_sortie,grille):
self.max_largeur = max_largeur
self.max_hauteur = max_hauteur
self.posit... |
number=int(input(''))
list=[]
for i in range(0,number):
newNo=int(input(''))
a=list.append(newNo)
print("Elements are",list[i],i)
|
list=[]
number=input()
for i in range(0,number):
a=input()
list.append(a)
list.sort()
print list
|
x=int(input(""))
y=int(input(""))
temp=x
x=y
y=temp
print(format(x), format(y))
|
def getPrimes(n):
if n % 2 == 0:
nums = list(range(n-1, 3, -2))
else:
nums = list(range(n-2, 3, -2))
curPrime = 3
primes = [2, 3]
while(curPrime*curPrime < n):
removes = set(list(range(curPrime*curPrime, n, 2*curPrime)))
numSet = set(nums)
numSet.dif... |
def numberWordCount():
singles = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
singlesCount = 0
for word in singles:
singlesCount += len(word)
tenCount = len('ten')
multTens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
mult... |
from __future__ import print_function
import math
def findMillthPerm():
numPermsLeft = 1000000
numsLeft = range(10)
numNumsLeft = 10
while numNumsLeft > 1:
nextNumPerms = math.factorial(numNumsLeft-1)
curNumPerms = 0
for i in numsLeft:
if (nextNumPerms... |
import heapq
class ProductTuple:
def __init__(self, _fact1, _fact2):
self.product = _fact1 * _fact2 * -1
self.fact1 = _fact1
self.fact2 = _fact2
def __cmp__(self, other):
return cmp(self.product, other.product)
def addNextProds(heap, fact, topBound):
if(fact == 0): return
... |
'''
Created on October 9, 2019
@author: Brad Bosak
'''
import socket
class CertificateAuthority:
def createCaServer(self):
#Create server socket
caSocket = socket.socket()
#Define port and bind
port = 9501
caSocket.bind(('', port))
caSoc... |
from typing import List
# Runtime: 48 ms, faster than 94.59% of Python3 online submissions for Find Numbers with Even Number of Digits.
def findNumbers(nums: List[int]) -> int:
count = 0
for i in nums:
if len(str(i)) % 2 == 0:
count += 1
return count
print(findNumbers([12, 345, 2, 6,... |
# You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.
#
# Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
#
# The... |
# Description: Given a two parameters of type integer 'N', 'D', return a string of the decimal representation where N is the numerator and D is the denominator. If the decimal has a repeating sequence of digits, indicate the sequence by enclosing it in brackets. Use xxx.0 to denote an integer.
def frick_fractions(N, ... |
from typing import List
# There are N children standing in a line. Each child is assigned a rating value.
#
# You are giving candies to these children subjected to the following requirements:
#
# Each child must have at least one candy.
# Children with a higher rating get more candies than their neighbors.
#
... |
import types
class GameBoard:
def __init__(self, width=5, height=5):
"""Initializes a rectangular gameboard."""
self.width, self.height = width, height
assert 2 <= self.width and 2 <= self.height,\
"Game can't be played on this board's dimension."
self.board = {}
... |
#addwithloop
#sum:1 to 10
total =0
i =1
while i<=10:
total =total+i
i=i+1
print(total) |
#ex_args
def power(num,*args):
if args:
return[i**num for i in args]
else:
"no args"
nums = [1,2,3]
print(power(3,*nums)) |
#join and split
#split
user_info = 'anuj 18'.split()
print(user_info)
#if
user_info1 = 'anuj,18'.split(',')
print(user_info1)
#name , age = input("enter ur name and age").split(',')
#print(name)
#print(age)
#join method
user_info3 = ['anuj', '18']
print(','.join(user_info3)) |
a = int(input("nter no"))
b = int(input("enter no."))
a = a+b
b = a-b
a = a-b
print(a,b)
|
#list inside list
num = [[1,2,3],[4,5,6],[7,8,9]] #2d list
for sublist in num:
for i in sublist:
print(i)
print(num[1][1])
|
#a
def twos_powers(n):
for i in range(n):
x=2**i
yield(x)
# for i in twos_powers(10):
# print(i,end=", ")
# print( )
#b
def reverse_twos_powers(n):
for i in range(n):
x=.5**i
yield(x)
# for i in reverse_twos_powers(10):
# print(i,end=", ") |
def max_two_products(lst):
max1=0
max2=0
for i in lst:
if (max1<i):
max1=i
for j in lst:
if (max2<j and max1!=j):
max2=j
return (max1*max2)
print(max_two_products([11, 3, 4, 9, 2, 7, 8, 10, 5]))
|
def is_BST(BST):
return is_BST_helper(BST.root)[2]
def is_BST_helper(root):
''' Returns a tuple (min, max, bool)'''
if not root.left and not root.right:
return(True,root.item.key,root.item.key)
if root.left and root.right
|
#a
def print_triangle(n):
if n==0:
return 1
else:
print_triangle(n-1)
return("*"*n)
#b
def print_opposite_triangles(n):
if n==0:
return 1
else:
return("*"*n)
print_opposite_triangles(n-1)
return("*"*n)
#c
def print_ruler(n):
if n==0:
re... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head:
return
curLeft = curRight = last = head
... |
input("What is your favorite basketball team?")
if answer == "the warriors":
input("Good, who is your favorite player?")
if answer == "stephen curry":
elif answer == "the spurs":
input("Okay, who is your favorite player?")
elif answer == "the thunder":
input("Okay, who is your favorite player?")
|
# subtract two numbers
answer = int(input("What do you want a to be?"))
answer2 = int(input("What do you want b to be?"))
if answer > answer2:
answer3 = answer-answer2
if answer2 > answer:
answer3 = answer2-answer
print answer3
|
#determine which is least out of three numbers you give.
a = int(input("What do you want a to be?"))
b = int(input("What do you want b to be?"))
c = int(input("What do you want c to be?"))
if a < b < c:
print a
if a < c < b:
print a
if b < a < c:
print b
if b < c < a:
print b
if c < a < b:
print c
if c < b < a:
p... |
# pig latin strings
words = input("HI ZOMBIE.")
words = words.lower()
words = words.split(" ")
output = ""
vowels = [ "a", "e", "i", "o", "u"]
for word in words:
if word[0] in vowels:
output = output+ word + "yay "
else:
start = 0
for letter in list(word):
if letter in vowels:
break
else:
if lett... |
class bankAccount:
def __init__(self, int_rate=0.03, balance=0):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdrew(self, amount):
self.balance -= amount
if self.balance < 0:
p... |
def updateFreq(d, prev, curr):
# if prev is a zero
if prev == 0:
# increment curr in d if it exists
if curr in d:
d[curr] += 1
# add curr to d and set to 1
else:
d[curr] = 1
# return
return
# if value at prev of d is greater than zero
... |
def longestVowelSubsequence(s):
# create vowel with aeiou
vowel = "aeiou"
# set pos to zero
pos = 0
# set length to zero
length = 0
# loop through s
for char in s:
# if pos equals four
if pos == 4:
# if char is char at pos of vowel
if char == vowel... |
from time import time
"""
Find XOR of numbers from the range [L, R]
Naive Approach: Initialize answer as zero, Traverse all numbers from L to R and perform XOR of the numbers one by one with the answer. This would take O(N) time.
Efficient Approach: By following the approach discussed here, we can find the XOR of el... |
def jumpingOnClouds(c):
"""
should start jump at 0
can only jump 1 or 2 index forward
will run in O(n) time
must avoid list items that are 0's
should jump 2 steps forward if there are two consecutive 1's
"""
# initialize jump to zero
jump = 0
# initialize index to zero
index ... |
def find_combinations(n):
# initialize a combo to empty dict
combo = {}
# loop from a range of one to n
for i in range(1, n):
# add the number to dict and set the value to empty set
combo[i] = set()
# loop from current number plus one to n
for j in range(i + 1, n + 1):
... |
r1 = float(input('Informe o tamanho do primeiro lado: '))
r2 = float(input('Informe o tamanho do segundo lado: '))
r3 = float(input('Informe o tamanho do terceiro lado: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('É possível montar um triângulo', end=' ')
if r1 == r2 and r2 == r3:
prin... |
def fatorial(num, show=False):
"""
Calcula o fatorial de um número
:param num: número cujo fatorial será calculado
:param show: mostrar cálculos
:return: resultado do cálculo do fatorial
"""
f = 1
for c in range(num, f-1, -1):
f *= c
if show:
if c > 1:
... |
frase = str(input('Informe sua frase: ')).strip().lower()
aux = "".join(frase.split())
cont = 0
for c in range(0, len(aux)):
if aux[c] == aux[len(aux) - 1 - c]:
cont += 1
if cont == len(aux):
print('A frase informada é um palíndromo')
else:
print('A frase informada não é um palíndromo') |
from datetime import date
ano = int(input('Informe seu ano de nascimento: '))
hoje = date.today().year
idade = hoje - ano
sexo = str(input('Informe seu sexo [M ou F]: ')).lower()
if sexo == 'f' or sexo == 'fem' or sexo == 'feminino':
print('Seu alistamento não é obrigatório.', end=' ')
if idade < 18:
... |
salario = float(input('Informe o salário atual do funcionário: R$'))
print('O salário reajustado com 15% de aumento é R${:.2f}'.format(salario*1.15)) |
n = float(input('Informe o preço: R$'))
print('O produto com 5% de desconto custa R${:.2f}'.format(n*0.95)) |
valor = float(input('Informe o valor da casa: R$'))
salario = float(input('Informe seu salário: R$'))
tempo = int(input('Informe em quantos anos você pretende pagar a casa: '))
parcela = valor / (tempo * 12)
print('Para pagar uma casa de R${:.2f} em {} anos a prestação será de R${:.2f}'.format(valor, tempo, parcela))
... |
def ficha(nome='<desconhecido>', gols=0):
print(f'O jogador {nome} marcou {gols} gol(s) no campeonato')
nome = str(input('Nome do jogador: ')).strip().title()
try:
gols = int(input('Número de gols: '))
if not nome.isalpha():
ficha(gols=gols)
else:
ficha(nome, gols)
except ValueError:
... |
# Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista.
# Caso o número já existe lá dentro, ele não será adicionado. No final serão exibidos todos os valores únicos
# digitados, em ordem crescente.
numero = list()
while True:
n = int(input('Informe um número: '))
i... |
velocidade = int(input('Informe a velocidade do carro (em km/h): '))
if velocidade > 80:
multa = (velocidade - 80) * 7
print('Limite de velocidade excedido!!! Você foi multado em R${:.2f}'.format(multa))
print('Tenha um bom dia e dirija com segurança!') |
from random import randint
from time import sleep
palpites = list()
numeros = list()
print('-'*60)
print(f'{"Gerador de Palpites":^60}')
print('-'*60)
qtd = int(input('Informe quantos palpites você deseja: '))
for q in range(0, qtd):
while True:
num = randint(1, 60)
if num not in numeros:
... |
frase = input('Insira uma frase: ').strip().lower()
print('A letra A aparece {} vez(es) na frase informada'.format(frase.count('a')))
print('A primeira vez ocorre na posição {}'.format(frase.find('a')+1))
print('A última vez ocorre na posição {}'.format(frase.rfind('a')+1))
|
import pandas as pd
import PySimpleGUI as sg
class Import():
"""
This class handles importing of HRM data. Upon initilization it creates a
link to the HRM parent object that stores the HRM data.
"""
def __init__(self, hrm):
self.hrm = hrm
def from_text(self, file_path):
... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
myList = [8, 10, 6, 2, 4] # list to sort
swapped = True # it's a little fake - we need it to enter the while loop
step=0
while swapped:
swapped = False # no swaps so far
for i in range(len(myList) - 1):
if myList[i] > myList[i + 1]:
step+=1
... |
# the first formula
print ("change the value of n in the code to change precesion")
# pi will be the fial value of pi
pi = long long float(0)
# n is the precision
n = 1000000 # this value is changebale
for i in range(n):
# even index elements are positive
if i % 2 == 0:
pi += 4 / (2 * i + 1)
else:
... |
def transpose_matrix(a):
# calculate the transpose of the matrix
t = [[a[j][i] for j in range(len(a))] for i in range(len(a[0]))]
# print transpose of the matrix
for row in t:
print(row)
# uncomment the following lines to test
# a = [[1.2, 1.1, 1.5],
# [2.1, 2.2, 2.3],
# [3.1, 3.2, 3.3]]
#... |
from Adresse import Adresse
from Personne import Personne
from ListePersonnes import ListePersonnes
# test of Adresse class
# creation of three addresses
a1 = Adresse("rue 1", "ville 1", "41000")
a2 = Adresse("rue 2", "ville 2", "42000")
a3 = Adresse("rue 3", "ville 3", "43000")
a4 = Adresse("rue 3", "ville 7", "43000... |
# dict 辞書 イミュータブル型の一意なキーを与える
# empty_dict
# empty_dict = {}
# print(empty_dict)
# {}
# dict1 = {
# "ichigo" : "red and sweet",
# "human" : "ambrose",
# "mike" : "human and cool"
# }
# print(dict1)
# dict()
# lol = [['nissan','skyline'],['mitsubishi','evo']]
# dict_lol = dict(lol)
# print... |
"""
Code Challenge:
dataset: BreadBasket_DMS.csv
Q1. In this code challenge, you are given a dataset which has data and time wise transaction on a bakery retail store.
1. Draw the pie chart of top 15 selling items.
2. Find the associations of items where min support should be 0.0025, min_confidence=0.2, min_lift=3.
3.... |
"""
Code Challenges 02: (House Data)
This is kings house society data.
In particular, we will:
• Use Linear Regression and see the results
• Use Lasso (L1) and see the resuls
• Use Ridge and see the score
"""
#importing
import pandas as pd
import numpy as np
dataset=pd.read_csv("kc_house_data.csv")
dataset.isnull(... |
"""
Q1. (Create a program that fulfills the following specification.)
deliveryfleet.csv
Import deliveryfleet.csv file
Here we need Two driver features: mean distance driven per day (Distance_feature) and the mean percentage of time a driver was >5 mph over the speed limit (speeding_feature).
Perform K-means clu... |
"""
Q2. (Create a program that fulfills the following specification.)
The iris data set consists of 50 samples from each of three species of Iris flower (Iris setosa, Iris virginica and Iris versicolor).
Four features were measured from each sample: the length and the width of the sepals and petals, in centime... |
"""
Code Challenge
Name:
Last Line
Filename:
lastline.py
Problem Statement:
Ask the user for the name of a text file.
Display the final line of that file.
Think of ways in which you can solve this problem,
and how it might relate to your daily work with Python.
"""
input1=raw_input("en... |
# Interactive Guess the Number Game
"""
Challenge 1
The computer will think of a random number from 1 to 10 as secret number
Then ask you ( Player ) to guess the number and store as guess number
Compare the guess number with the secret number
If the player guesses the right number he wins,
... |
"""
Code Challenge
Name:
Pattern Builder
Filename:
pattern.py
Problem Statement:
Write a Python program to construct the following pattern.
Take input from User.
Input:
5
Output:
Below is the output of execution of this program.
*
* *
* * *
* * * *
... |
if __name__ == '__main__':
kv = lambda x, t, i: t(x.split(":")[i])
dic = lambda a: dict([(kv(x, str, 0), kv(x, int, 1)) for x in a.split(",")])
d = dic("语文:80,数学:82,英语:90,物理:85,化学:88,美术:80")
s = 0
for v in d.values():
s += v
print("总分为{}, 平均分为{:.1f}".format(s, s / len(d)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.