text stringlengths 37 1.41M |
|---|
'''
Faça um programa que calcule e mostre a área
de um quadrado. Sabe-se que: A = lado * lado.
'''
lado = float(input('Digite o tamanho do lado'))
A = lado * lado
print('A área do quadrado é: ')
print(A)
|
''' Q2
Crie um programa que preencha uma matriz 2x4 com
números inteiros, calcule e mostre:
■ a quantidade de elementos entre 12 e 20 em cada linha;
■ a média dos elementos pares da matriz.
matriz = []
for i in range(2):
linha = []
for j in range(4):
linha.append(int(input('Inserir: ')))
print(linh... |
# Өгөгдсөн тоо эерег тэгш тоо бол true үгүй бол false гэж хэвлэ.
def EeregTegshToo(n):
if n>0 and n%2==0:
return True
else: return False
n = int(input())
print(EeregTegshToo(n)) |
"""Hasan Qadri, 903138378, hqadri6@gatech.edu, I worked on this assignment alone,
using only this semester's course materials.
for seconds in timer(60)
"""
"""
def avoidWalls():
for x in range(timer(60)):
while getIR() != 1 or getObstacle('center') == 0:
forward(3,3)
if getIR() == ... |
def DFS_help(graph, v, visited):
visited[v] = True
successors = graph.get_successors(v)
for i in successors:
if not visited[i]:
DFS_help(graph, i, visited)
def connected(graph):
n = graph.get_order()
visited = [False] * n
for i in range(n):
if len(graph.get_successo... |
import requests
#This code uses Datamuse API
def get_concepts_from_item(source):
"""
use Datamuse API to get related words for given word
:param source: a word which related words are generated from
:return: list of related words
"""
source = source.lower()
myList = []
obj = requests.... |
words = {}
text = {"This is a collection"}
print(text)
check_for_word = text.split()
for word in check_for_word:
frequency = words.get(word, 0)
words[word] = frequency + 1 |
#Example 1
result = 0
basket_items = {'pears': 5, 'grapes': 19, 'kites': 3, 'sandwiches': 8, 'bananas': 4}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
# Your previous solution here
for key, value in basket_items.items():
for fruit in fruits:
if key == fruit:
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 19:53:55 2018
@author: Marina
"""
# Browse the complete list of string methods at:
# https://docs.python.org/3/library/stdtypes.html#string-methods
# and try them out here
name="Marina Lenza"
print(name.capitalize())
print(name.isalnum())
print(name.isspace())
print(n... |
multiples_3 = [x*3 for x in range(1,21)]
print(multiples_3) |
""""
This script is serverd as a practise of Algorithm and data structure learning in Python
"""
# def FindSecondMini(input_list):
# if not isinstance(input_list, list):
# raise ValueError("input must be list type!")
# if len(input_list)==0:
# return None
# if len(input_list)==1:
# ... |
"""Generates data in the form of a dictionary with x and y.
shape of x as (200,2), 2 numbers based on make_moons from sklearn
shape of y as (200,2) multiclass labels for x"""
import numpy as np
from time import time
np.random.seed(int(time())) # is this for make_moons?
import sklearn.datasets as datasets
x,y = datasets... |
#! /usr/bin/env python3
from __future__ import annotations
from abc import ABC, abstractmethod
class Creator(ABC):
"""
The creator class declares the factory method
"""
@abstractmethod
def factory_method(self):
"""
Note that the Creator may also provide some default
implem... |
from player import Player
from mechanics import Move, Result
# Has equal chance of choosing split/steal
class RandomPlayer(Player):
def __init__(self):
super().__init__()
def action(self):
return self.random_action()
# Always split
class NicePlayer(Player):
def __init__(sel... |
from enum import Enum
class Move(Enum):
ROCK = 1
PAPER = 2
SCISSORS = 3
class Strategy(Enum):
STEP0 = 0
STEP1 = 1
STEP2 = -1
class Result(Enum):
WIN = 1
TIE = 0
LOSE = -1
# ROCK beats SCISSORS; PAPER beats ROCK; SCISSORS beat PAPER
MATCHUP = {1: 3, 2: 1, 3: 2}
# Return 1 if move... |
#https://projecteuler.net/problem=3
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
import math
def listprimes(num):
primes = []
for posnum in range(3, int(math.sqrt(num)), 2):
print('checking', posnum)
if num % posnum == 0:
... |
"""Solution to problem 22 on Project Euler"""
# https://projecteuler.net/problem=22
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names,
# begin by sorting it into alphabetical order. Then working out the alphabetical value for each name,
# multiply t... |
def ordenador():
x=input("dime un numero")
cifras=0
while x>0:
x=x/10
cifras=cifras+1
print cifras
ordenador()
|
def sumador_acumulador():
n=input("Dime hasta que numero quieres sumar")
suma=0
for cont in range (1,n+1,1):
suma=suma+cont
print"suma=",suma
sumador_acumulador()
|
import pandas
## @package CSV
# Documentation for the module CSV
#
# More details.
# Documentation for the CSV Class
#
# More details.
class CSV:
## Variable of the csv's route.
_route = "../Others/"
## The constructor.
# @param self The object pointer.
# @param name The CSV name to be lo... |
import cv2
print ("whats with that smile")
train_face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
smile_detector = cv2.CascadeClassifier("haarcascade_smile.xml")
#grab video cam feed
webcam = cv2.VideoCapture(0)
#show current webcam frame
while True:
succesful_webcam_read,f... |
s = input()
if "1"*7 in s or '0'*7 in s:
print("YES")
else:
print("NO") |
import math
def isPrime(a):
if a==1 or a==2:
return True
for i in range(2,int(math.sqrt(a))+1):
if a%i==0:
return False
return True
def gcd(a,b):
if b==0:
return a
gcd(b, a%b)
test = int(input())
for t in range(test):
n = int(input())
l = list(map(int, input().split()))
flag = True
for i in range(1,n... |
def lessthan(n):
i=1
while(1):
if(n<pow(2,i)):
return i-1
i+=1
tc=int(input())
for i in range(tc):
n=int(input())
if(n==1):
print("0")
elif(n==2 or n==3):
print("1")
else:
res=lessthan(n)
if(res%4==2):
... |
from os import system
print("1: Set Alarm for 6:00 am")
print("2: Turn off Zach Light")
print("3: Turn on Zach Light")
print("4: Stop")
for i in range(0,10):
number = input("Input your number here: ")
if (number == 1):
system("say Alexa, set an alarm for 6 in the morning")
if (number == 2):
system... |
from os import system as sys
global command
command = ""
while (True):
print("Edit\nView\nRun")
editing = raw_input("What do you want to do? ")
if editing == "Edit":
command = "vim "
print("You can now Edit")
elif editing == "edit":
command = "vim "
print("You can no... |
worker = {
'name': 'Michal',
'nazwisko': 'Znaj',
'wiek': 21,
'dzieci': ['Jas' , 'Zosia'],
'rodzice': ['Anna' , 'Robert']
}
print(worker)
print(worker['dzieci'])
print ('Dziecko 1: ' + str(worker["dzieci"][0]))
print ('Dziecko 2: ' + str(worker["dzieci"][1]))
worker['height'] = 180
worker['w... |
# -*- coding: UTF-8 -*-
#
# Merge Sort Algorithm
# The All ▲lgorithms library for python
#
# Contributed by: Carlos Abraham Hernandez
# Github: @abranhe
#
def merge_sort(arr):
if len(arr) == 1:
return arr
left = merge_sort(arr[:(len(arr)//2)])
right = merge_sort(arr[(len(arr)//2):])
out = []
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""
The following are generic functions that are used
for grouping purposes
"""
#used to mine frequency patterns from non-numeric attributes
#ex: country frequency, frequency of weapon type and sub weapon type, etc
def freq_grouping(df, attribut... |
print('1. Reverse the order of the items in an array.')
a=[1,2,3,4,5]
print(a)
a.reverse()
print(a)
print()
print('2. Get the number of occurrences of var b in array a.')
a=[1,1,2,2,2,2,3,3,3]
print(a)
b=2
print(b)
a.count(2)
print('The number of occurrences of var b in array a is:')
print(a.count(2))
print()
print('3.... |
import re
from itertools import imap
# Magic ASCII number
A = 97
# Can't have these
bad = re.compile(r'i|o|l')
# Must have two pairs
pairs = re.compile(r'([a-z])\1.*([a-z])\2')
# Check if we have a sequence of type 'abc'
def has_sequence(password):
# Switch chars to numbers
nums = map(ord, password)
# T... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author coolharsh55
# Harshvardhan J. Pandit
# LOGIC
# Given a point (x,y), we need to find the number that occurs
# at that point. To do that, we need to find the diagonal that it belongs to.
# Each diagonal has (i in 1 to x +y-1)∑i numbers.
# Given (x,y), it occurs somewhe... |
import re
inp = 'XXXXXXXX'
# This is a little complicated, we find a digit and capture all of its
# repetitions, in the second capture group we have the single digit itself
repeating_digits = re.compile(r'((\d)\2*)')
for i in range(0,50):
new_input = ''
# Unpack into the total match and the single digit.
... |
import numpy as np
import cv2
'''
The Process of Canny edge detection algorithm can be broken down to 5 different steps:
1. Apply Gaussian filter to smooth the image in order to remove the noise
2. Find the intensity gradients of the image
(cite: from Wikipedia for reference)
'''
def edge_detection():
# Step 1... |
#!/usr/bin/env python2
"""
Masked wordcloud
================
Using a mask you can generate wordclouds in arbitrary shapes.
"""
from os import path
import numpy as np
from PIL import Image
from wordcloud import WordCloud
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'article.txt')).read(... |
def twoSum(nums: List[int], target: int) -> List[int]:
map = {}
for index in range(len(nums)):
if target - nums[index] not in map:
map[nums[index]] = index
else:
return [index, map[target - nums[index]]]
print(twoSum([2, 7, 3], 9))
|
cs = 3 #次数
while cs > 0:
password = input('请输入密码:')
cs = cs - 1
if password =='a123456':
print('登录成功')
break
elif cs > 0: #3-cs>0
print('密码错误,您还有', cs, '次机会')
else:
print('密码错误,您已经没有机会了,请您改天再试试吧')
|
"""
Uso: Comparacion 2
Creador: Andrés Hernández Mata
Version: 1.0.0
Python: 3.9.1
Fecha: 15 Junio 2021
"""
calif_parcial = int( input("Parcial: ") )
CALIF_APROB = 70
print( calif_parcial, type(calif_parcial) )
print( CALIF_APROB, type(CALIF_APROB) )
print(calif_parcial > CALIF_APROB)
print( str(calif_parcial) ... |
"""
Uso: Comparacion 4
Creador: Andrés Hernández Mata
Version: 1.0.0
Python: 3.9.1
Fecha: 15 Junio 2021
"""
def es_bool(str):
if str == "true":
return True
elif str == "false":
return False
else:
print('Respuesta incorrcta intenta con "TRUE" o "FALSE" ')
tiene_efectivo = es_bool( input("Tiene efectivo: ")... |
#!/usr/bin/env python2.5
# a simple script that takes a surface form (word)
# as input and runs the kimmo recognizer on it
# using spanish.yaml as the configuration file.
from kimmo import *
import sys
k = KimmoRuleSet.load('spanish.yaml')
if len(sys.argv[1:]) == 0:
print "usage: %s <word> [<trace>]" %(sys.argv[0... |
name= raw_input("Enter the name of your macro:\n")
name = name.upper().lstrip().rstrip()
macro_file = file("macros.txt","a")
macro = raw_input("Enter the instructions for the macro (separated by a semicolon):\n")
macro = macro.lstrip().rstrip()
lines = macro.split(";")
string = ""
for line in lines:
string = str... |
import math
def power(x,n=2):
s=1
while n>0:
n=n-1
s=s*x
return s
def enroll(name, gender, age=6, city='Beijing'):
print('name: ',name)
print('gender: ',gender)
print('age: ',age)
print('city: ',city)
print()
#n =power(5,3)
#print(n)
#m=power(4)
#print(m)
#s = enr... |
from pathlib import Path
import csv
budget_data = Path("budget_data.csv")
with open('budget_data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
csv_header = next(csv_reader)
months = 0
total_return = 0
value = 0
change = 0
profits = []
dates = []
... |
# -*- coding: utf-8 -*-
# Programa em Python para gerar a frase de destino, começando a partir
# de frase aleatória usando algoritmo genético
# Referencia: https://www.geeksforgeeks.org/genetic-algorithms/
import random
# Número de indivíduos em cada geração
POPULATION_SIZE = 100
# Genes válidos
GENES = '''abcdefgh... |
# =============================================================================
# Foydalanuvchidan aylaning radiusini qabul qilib olib,
# uning radiusini, diametrini, perimetri va yuzini
# lug'at ko'rinishida qaytaruvchi funksiya yozing
# =============================================================================
... |
# =============================================================================
# from datetime import *
# # now=datetime.now()
# # time=datetime.now().time()
# # print(now.second,now.minute,now.hour)
# # print(time)
# # print('today:'+str(date.today()))
# # tomorrow=date(2021,10,2)
# # print('tomorrow:'+str(tomorrow))... |
print("We gonna create a list of products for market")
products={}
i=1
while True :
product=input(f"Please enter {i}-product's name':")
value=int(input(f"Please enter {product}'s price':"))
products[product]=value
i+=1
msg=input("Do you want again?(yes/no)")
if msg!='yes'... |
class Student:
def __init__(self,name,surname,born):
self.name = name
self.surname=surname
self.born=born
def get_know(self):
print(f"{self.name} {self.surname} was born in {self.born}")
def get_name(self):
"""Talabaning ismini qaytaradi"""
return self.name
... |
# from math import sqrt
# nums = list(range(11)) # 0 dan 10 gacha numbers_list ro'yxati
# square_root = list(map(sqrt,nums))
# numbers_list = list(range(11))
# def daraja2(x):
# """Berilgan sonning kvadratini qaytaruvchi funksiya"""
# return x*x
# print(list(map(daraja2,numbers_list)))
# def numbers(x):... |
from abc import ABC, abstractmethod
from typing import List
import random
class SModel(ABC):
"""
The Strategy interface declares operations common to all supported versions
of some algorithm.
The Context uses this interface to call the algorithm defined by Concrete
Strategies.
"""
@abstra... |
#ax^2+bx+c=0
import math
print("entrez les coefficients :")
a=input("a = :")
b=input("b = :")
c= input("c= :")
a=float(a)
b=float(b)
c=float(c)
if a!= :
d=b*b-4*a*c
D=float(d)
if D>0:
x1=(-b-math.sqrt(D))/2*a
x2=(-b+math.sqrt(D))/2*a
print("l'équation a deuxx solutions : ",x1,x2)
... |
import math
a=int (input("entrez un nombre : "))
b=False
for i in range(2,int(math.sqrt(a))):
if a%i==0:
b=True
if b:
print(a, " est un nombre premier")
else :
print(a, " n'est pas un nombre premier") |
ageUser=input("Donnz votre age: ")
try:
ageUser=int(ageUser)
except:
print("L'age indiqué est erroné")
else:
'''ce qui se passe en cas de reussite'''
print("Tu as ",ageUser, "ans")
finally:
print("Fin programme...") |
# write your code here
import random
def dinner():
print("Enter the number of friends joining (including you):")
number = int(input())
print()
if number > 0:
dictionary = create(number)
bill = pay(dictionary)
lucky(dictionary, bill)
print(dictionary)
else:
p... |
from typing import List
from .algorithm import Algorithm
from .result import Result
class Simple(Algorithm):
@property
def name(self) -> str:
return "Simple"
def solve(self, coefitients: List[float], value: float) -> Result:
solution = 0
additions_count = 0
multiply_count ... |
def validateInteger(n,val,x):
s = str(val)
if s.isdecimal() or s[1:].isdecimal() :
li =-(2**n)
ls = (2**n)+x
print(li,val,ls)
if li <= val and val <= ls:
return None
return {'Type':"numeric",'Descripción':"Valor entero fuera del rango establecido"}
def beforePo... |
#CREATE A DICTIONARY TO STORE THE SYMBOLS AND A COUNTER FOR THE INDEX
symbolTable=dict()
#CREATE A NEW SYMBOL AND STORE IT INTO THE SYMBOL TABLE, INCREASE COUNTER BY 1
def add_symbol(name_,type_,value_,row_,column_,ambit_):
symbolTable[name_]=[type_,value_,row_,column_,ambit_]
#SEARCH A SYMBOL WITH name_ IF IS... |
class Heap(object):
"""
Une heap est une structure de données sous forme d'arbre.
https://en.wikipedia.org/wiki/Heap_(data_structure)
"""
def insert(self, value: int) -> None:
"""
Ajoute une valeur dans l'arbre
"""
pass
def find_min(self) -> int:
""... |
class A:
def __init__(self, val=0):
self.val = val
def add(self, x):
self.val += x
def print_val(self):
print(self.val)
a = A()
b = A(2)
c = A(4)
a.add(2)
b.add(2)
a.print_val()
b.print_val()
c.print_val() |
def test_substring(full_string, substring):
assert substring in full_string, f"expected '{substring}' to be substring of '{full_string}'"
test_substring('full_string', 'string')
#s = 'My Name is Julia'
#if 'Name' in s:
# print('Substring found') |
seq1 = 'ATGTTATAG'
#print every 3
for i in range(0,len(seq1),3):
print(i, seq1[i])#indexing
#or you could do
print(seq1[0::3])
#print first 3, next 3, so on
for i in range(0,len(seq1),3):
print(seq1[i:i+3]) #slicing
|
try:
num = int(input("Choose a number: "))
print(10/num)
except ZeroDivisionError:
print("Can't divide by 0")
except ValueError:
print("Please input a valid number")
|
"""
IS 590PR - Programming for Analytics & Data Processing
Final Project- Goalkeeper Success Rate Simulation
Authors:
Samuel John
Salonee Shah
Claire Wu
"""
from random import choice, randint
from collections import Counter
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class Player:
"""
... |
def factorial(i):
if i>1 :
return i*factorial(i-1)
else :
return 1
i=int(input())
print(factorial(i)) |
import socket
import select
serversIP = ["192.168.0.101", "192.168.0.102", "192.168.0.103"]
serversSockets = []
clientsOpenedSockets = []
requestsQueue = []
isServerAvailable = {}
handledConnections = {}
def peekServer(serversList, msg):
if msg[0] == "P" or msg[0] == "V":
for s in serversList[0:2]:... |
import math
def check_decimal(num):
if(num==1):
return False
for i in range(2,int(math.sqrt(num))+1):
if(num%i==0):
return False
return True
if __name__=="__main__":
count=int(input())
result=0
numbers=[int(i) for i in input().split()]
for i in numbers:
if... |
def zero_count_Combination(n,m):
f_num = 1
two_count = 0
five_count = 0
for i in range(m+1, n + 1):
while (i % 2 == 0):
two_count += 1
i=int(i/2)
while (i % 5 == 0):
five_count +=1
i = int(i / 5)
for i in range(2,n-m+1):
while (... |
'''Write a Python function to implement the quick sort algorithm over a singly linked list.
The input of your function should be a reference pointing to the first node of a linked list,
and the output of your function should also be a reference to the first node of a linked
list, in which the data have been sorted into... |
for i in range(1, int(input()) + 1):
exercise = input().split()
if int(exercise[2]) > int(exercise[1]):
result = -1
elif int(exercise[2]) < int(exercise[0]):
result = int(exercise[0]) - int(exercise[2])
else:
result = 0
print("#%d %d" % (i, result)) |
from random import randint
numbers = []
# 수 생성
while len(numbers) < 3:
new_number = randint(0, 9)
while new_number in numbers:
new_number = randint(0, 9)
numbers.append(new_number)
print("0과 9 사이의 서로 다른 세 숫자를 랜덤한 순서로 뽑았습니다.")
# 숫자 입력받기
strike = 0
tries = 0
while strike < 3:
# 초기화
strike... |
text = input()
def uppercase():
return text.upper()
print(uppercase()) |
#!/usr/bin/env python
# From: http://people.ds.cam.ac.uk/mcj33/themagpi/The-MagPi-issue-29-en.pdf
from Tkinter import *
window = Tk()
window.title('GUI Tkinter 1')
window.geometry("300x250") # w x h
window.resizable(0,0)
#define labels
box1 = Label(window,text="Entry 1: ")
#place the label in the window object
box1.g... |
count=0
temp=str=""
strs=[]
while str!="q":
str=input(f"请输入第{count + 1}个单词(输入q结束): ")
strs.append(str)
count+=1
print(f"排序前的结果为: {strs}")
print("-"*20+"\n")
for index,value in strs:
print(f"index:{index}")
print(f"value:{value}") |
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# for bicycle in bicycles:
# if bicycle == 'cannondale':
# print(bicycle.upper())
# else:
# print(bicycle)
# print("a" == "A")
#检查多个条件
# condition_1 and condition_2
#检查列表中特定值
# print('trek' in bicycles)
# age = 12
#
# if age<4:
# ... |
# with open('pi_digits.txt') as file_object:
# contents = file_object.read()
# print(contents) #末尾会多出一个空行,read()到达文件末尾会返回一个空字符串,形成空行,可用rstrip()消除
#可用相对路径和绝对路径,绝对路径可以存储在一个变量中再引用,因为太长不方便
#linux下用 / ,windows下用 \
file_name = 'pi_digits.txt'
#逐行读取
# with open(file_name) as file_object:
# for line in fil... |
#列表生成式
list1 = [i for i in range(1,10,2)]
print(list1) |
# coding: utf-8
# ## Using Beautiful Soup to web scrape MLB statistics ##
# I will be adapting the excellent tutorial at [Nylon Calculus](http://nyloncalculus.com/2015/09/07/nylon-calculus-101-data-scraping-with-python/) to scrape stats from [baseball-reference.com](http://www.baseball-reference.com/leagues/MLB/bat.s... |
def my_list_sort(my_list):
x_list = []
r_list = []
for i in range(len(my_list)):
if my_list[i][0] == 'x':
x_list.append(my_list[i])
else:
r_list.append(my_list[i])
r_list.sort()
x_list.sort()
return x_list + r_list
print(my_list_sort([... |
# New Patterns by Kalyn Beach
import turtle;
# Create a blue pen and determine the window's width and height:def init():
def init():
pen = turtle.Pen();
pen.color(0, 0, 1); # blue
width = pen.window_width();
height = pen.window_height();
return pen, width, height;
# Given a number, design a p... |
# Seconds Calculations by Kalyn Beach
# Convert hours, minutes, and seconds to seconds using a pretest loop:
def secondsPretest():
ans = raw_input('Ready to convert? [Yes/No]: ');
while (ans == 'Yes' or ans == 'yes' or ans == 'Y' or ans == 'y'):
while (True):
hours = input("Enter hours (... |
# Dean's List Evaluator by Kalyn Beach
# Given a grade, calculate the student's GPA and determine if the student made
# the Dean's list:
def list():
gradeA = input("Enter number of A's: ");
gradeB = input("Enter number of B's: ");
gradeC = input("Enter number of C's: ");
gradeD = input("Enter number o... |
# Sum Evaluator by Kalyn Beach
def sumTotal(a, b):
theSum = 0;
while (a <= b):
theSum = theSum + a;
a = a + 1;
return theSum;
def repeat():
print "This program sums up sequences of numbers."
while (True):
bottom = input("Enter sequence bottom: ");
top = input("Enter... |
list = [1,2,3,4,5,6]
for num in list:
if num > 4:
print(num, 'число > 4')
else:
print(num)
list.append(input('введите число'))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Task 6: Classifier. (bonus)
# Take a dict with values of different type, return a dict of type:
# {value_type: number_of_elements_of_that_type}.
# {'a': 1, 3: [1,5], 'e': 'abc', '6': []} >> {'str': 1, 'list': 2, 'int': 1}
def classificator(d):
counts = dict()
fo... |
# -*- coding: utf-8 -*-
import csv
import os
from hw5_solution import Person
def modifier(fname):
"""Add fullname and age columns to a CSV file."""
fhand = open(fname, 'r')
dictreader = csv.DictReader(fhand)
fout = open('temp', 'w')
fields = dictreader.fieldnames[:]
fields.insert(3, 'fulln... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Task 4: Odd-even.
# Take a list of any numbers and filter it:
# - remove odd numbers if the number of elements in the list is even;
# - remove even numbers if the number of elements in the list is odd.
# [3, 7, 12] >> [3, 7]
# [3, 7, 12, 7] >> [12]
def odd_even(t):
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 19:44:40 2019
@author: Pale
"""
dict1={0:'Zero',1:'One',2:'Two',3:'Three',4:'four',\
5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
n=input("Enter number= ")
for i in n:
print( dict1[ord(i)-48],end=" ")
print() |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 08:20:26 2019
@author: Pale
"""
s1="***a barking dog\doesn\'t bite a man***"
print(s1)
s1.split()
s1.replace('dog','cat')
s1.find('barking')
s1.find('Barking')
s1.strip('*')
s1.rstrip('*')
"*".join("123")
"hello".center(30)
"hello how are you".title() |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 19:37:26 2019
@author: Pale
"""
def Stars(rows):
n=0
for i in range(1,rows+1):
for j in range(1,(rows-i)+1):
print(end=" ")
while n!=(2*i-1):
print("*", end="")
n=n+1
n=0
print... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 20:17:38 2019
@author: Pale
"""
income=float(input("Enter Income:"))
familysize=int(input("Enter family size:"))
if (income>=500000):
tax=income*0.3
print("Tax =",tax)
if (income<500000) and (income>=100000):
if(familysize>3):
tax=inc... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 23:25:42 2019
@author: Pale
"""
name=input("Type your name: ")
print('Hi, I have seen you before:'+name.upper()+'!\n')
len_name=len(name)
print("The length of your name is:"+str((len_name))+'\n')
name_f3=name[0:3]
print('The first 3 letters of your nam... |
#!/usr/bin/python3
if __name__ == "__main__":
import sys
argv = sys.argv[1:]
argv_count = len(argv)
index = 1
if argv_count == 0:
print("{} arguments.".format(argv_count))
elif argv_count == 1:
print("{} argument:".format(argv_count))
print("{}: {}".format(index, sys.argv... |
# coding:utf-8
from functools import partial
from itertools import groupby
import itertools
import re
ss = '111221'
def countAndSay(self, n):
s = '1'
for _ in range(n - 1):
s = ''.join(str(len(list(group))) + digit
for digit, group in itertools.groupby(s))
return s
for digit... |
import abc
__author__ = 'Jubril'
class Room(object):
__metaclass__ = abc.ABCMeta
max_occupants = 4
def __init__(self, name):
self.name = name
self.occupants = []
def get_member_details(self):
"""
Get the details of the occupants in a room
:r... |
student_list = []
str = "a b c d e f g h i j k l m n o p q r s t".split(" ")
for index in range(len(str)):
student_list.append(str[index])
print(student_list)
for names in student_list:
if names == 'b':
print(f"found {names}")
break
print(f"currently testing :: {names}")
for names in stude... |
print('Hello world')
bonus = (0.10 or 0.15)
if sales > 1000:
bonus = 1000 * 0.10
elif sales < 1000:
bonus = 1000 * 0.15
print(sales)
while sales >= 1000:
bonus = 1000 * 0.10 or 1000 * 0.15
print(sales)
|
import time
while True:
inp = input('Give your input or END: ')
t=time.time()%10
if inp=='END':
exit()
if t>=0 and t<3:
print('rock')
elif t>=3 and t<7:
print('paper')
else:
print('scissor') |
def add_time(start, duration, day_name=None):
day_count = 0
name_in_week = {
1: 'Saturday',
2: 'Sunday',
3: 'Monday',
4: 'Tuesday',
5: 'Wednesday',
6: 'Thursday',
7: 'Friday'
}
start_time_list = start.split()
hour = int(start_time_list[0].split... |
import math
import random
import sys
from asteroid import Asteroid
from screen import Screen
from ship import Ship
from torpedo import Torpedo
DEFAULT_ASTEROIDS_NUM = 5
ROTATION = 7
ASTEROID_SIZE = 3
AST_SPEED = [-4, -3, -2, -1, 1, 2, 3, 4]
DEFAULT_LIFE = 3
TORPEDO_LIFETIME = 200
SCORE_MARKERS = {
1: 100, # smal... |
#############################################################
# LOGIN : volberstan
# ID NUMBER : 206136749
# WRITER : elchanan volbersten
# I discussed the exercise with : chaim goldblat
# Internet pages I looked for : wikipedia
##############################################################
import math
def golde... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.