text stringlengths 37 1.41M |
|---|
from tkinter import *
# create the root
root = Tk()
# create a label
myLabel1 = Label(root, text="Hello World!")
myLabel2 = Label(root, text="balogna sales: 1500 units")
myLabel3 = Label(root, text="balogna sales: 1500 units")
myLabel4 = Label(root, text="balogna sales: 1500 units")
myLabel5 = Label(root, text="balog... |
## Read files with pandas
import pandas as pd
# Load spreadsheet: xl
xl = pd.ExcelFile(file)
# Print sheet names
print(xl.sheet_names)
# Load a sheet into a DataFrame by name
df1 = xl.parse('2004')
# Load a sheet into a DataFrame by index
df2 = xl.parse(0)
# Additional parameters:
# skiprows = List of rows to skip
... |
'''This is a basic pipe module.
A pipe consists of a centerline, unlimited number of levels
on each side. The levels are first calculated in s-n coordinate
system, and then they will be converted into x-y coordinate
system.
'''
import numpy as np
from . import functions
from math import pi, sqrt, log, floor, ceil
... |
#dictionary of organs with function description
Organ1 = {'name': 'Heart', 'location': 'sternum', 'function': 'Blood pumpimg'}
Organ2 = {'name': 'Lungs', 'location': 'sternum', 'function': 'Ventilation'}
Organ3 = {'name': 'Kidneys', 'location': 'abdominal cavity', 'function': 'Metabolism'}
print(Organ3['location'])
pri... |
# vino
char='a','e','i','o','u'
if a in char:
print("vowel")
else:
print("consonent")
|
# Import modules
import os
import csv
# Create a variable for csv file
polling = "Resources/election_data.csv"
# Tell the program to open file, skip the header row, and create a list for listed variables
with open(polling) as csv_file:
reader = csv.reader(csv_file, delimiter=',')
header = next(reader)
can... |
class Book():
def __init__(self, name, author):
self.name = name
self.author = author
def getDetails(self):
return self.name + " by " + self.author
class ChildrensBook(Book):
def __init__(self, name, author, age):
Book.__init__(self,name, author)
self.age = age
... |
#!/home.westgrid/thea/programs/anaconda/bin/python
# get the longest n sequences from fasta file
# if multiple with same length, all will be returned
from Bio import SeqIO
import argparse
__author__ = 'theavanrossum'
parser = argparse.ArgumentParser(description='Get the sequence lengths from fasta file.')
parser.ad... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 1 13:48:37 2017
@author: MacKenzie Harnett
Tests fermat's theorem across multiple code.
"""
'Exercise 5.2'
'Problem 1'
def check_fermat(a, b, c, n):
if (n>2):
if(a**n + b**n == c**n):
return "Holy smokes, Fermat was wrong!"
els... |
#!/usr/bin/python
import time
import sys
import random
# Subroutine: merge
# Input: two arrays, the left and right halves of
# the array to be sorted
# Output: a single array that merges left and right,
# in sorted order
#
def merge( left, right ):
# Initialize return array, will contain the merged... |
def remove_at(pos, seq):
return seq[:pos] + seq[pos+1:]
def insert_in_middle(val, lst):
# inserts a value 'val' in middle of list 'lst'..works on lists only
middle = len(lst)/2
lst[middle:middle] = [val]
def insert_in_middle(val, tup):
# same as above, but works for tuples only
middl... |
def merge(left, right):
result = left + right
i = 0
j = 1
while j < len(result):
if result[i] > result[j]:
k = result[i]
result[i] = result[j]
result[j] = k
i = 0
j = 1
else:
i += 1
j += 1
return result
|
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
# that the 6th prime is 13. What is the 10001st prime number?
import math
def solution(n):
if n == 1:
return 2
i = 2
p = 3
while i <= n:
prime = True
for j in range(3, int(math.sqrt(p)) + 1, 2):
... |
# 2520 is the smallest number that can be divided by each of the numbers from 1
# to 10 without any remainder. What is the smallest positive number that is
# evenly divisible by all of the numbers from 1 to 20?
import math
def esieve(n):
isprime = [False, False] + [True] * (n - 1)
p = 2
while p * p <= n:... |
import main
class TestClass:
def test_1(self):
# main.input = lambda: 'some_input'
output = main.main()
assert output == 'Hello world'
def test_2(self):
# main.input = lambda: 'some_other_input'
output = main.main()
assert output == 'Hello world'
def test_... |
from collections import defaultdict
if __name__ == '__main__':
n, m = map(int, raw_input().split())
position = defaultdict(list)
for i in range(1, n + 1):
word = raw_input()
position[word].append(i)
for i in range(m):
word = raw_input()
if word in position:
p... |
#!/usr/bin/env python
# coding: utf-8
import os
import tweet
import search_tweet
from colorama import Fore, Back, Style
os.system('cls' if os.name == 'nt' else 'clear')
boucle = True
while boucle == True: #Infinit loop
print (60 * '-')
print ('\033[1m' +'La Cambuzz- Coworking')
print ('\033[4m'+"Blablabla")
p... |
#I'm trying to design a better solution (thanks to cucurbita for suggestions)
def split_minutes (mins):
digits = [];
while (mins):
digits.insert (0, (mins % 10) * ( 10 ** len (digits) ));
mins //= 10;
return (digits);
table_en = {
0: 'o\' clock',
1: 'one',
2: 'two',
3: 'three',
4: 'four... |
from math import sqrt, floor;
def encrypt (text):
lo, final = floor (sqrt (len (text))), '';
rows, cols = lo, lo if (lo ** 2) >= len (text) else lo + 1;
for j in range (1, cols + 1):
for i in range (j, len (text) + 1, cols):
final += text [i - 1];
final += ' ';
return (final);
print (encrypt (input()));
|
import requests
from datetime import datetime
api_key='3d2b0607dfa7de038532106616405471'
location=input("enter the city name:")
complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+location+"&appid"+api_key
api_link = requests.get(complete_api_link)
api_data = api_link.json()
temp_city = ((... |
"""Encrypts and decrypts strings using a Vigenère Cipher."""
# Author: Ian Orzel, iorzel2019@my.fit.edu
# Course: CSE 2050, Fall 2020
# Project: Vigenère Cipher
from sys import stdin, stdout
from string import ascii_lowercase
key = stdin.readline().strip()
stdout.write(f'{key}\n')
for line in stdin:
if line[0] =... |
from tkinter import *
window = Tk()
'''
change the window size
'''
window.geometry('1024x768')
'''
create a window title
'''
window.title('this is the window title')
'''
create a window icon
'''
window.iconbitmap('F:\\python projects\\images\\testicon1_jdZ_2.ico')
'''
add photo in the window
'... |
def even_odd(num_list):
even_sum = odd_sum = 0
for item in num_list:
if item % 2 == 0:
even_sum += 1
else:
odd_sum += 1
print("Sum of even numbers is %s" % even_sum)
print("Sum of odd numbers is %s" % odd_sum)
even_odd([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 18])
eve... |
# Multiple Linear Regression
# Importing the libraries
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
# Importing the dataset
dataset = pd.read_csv('50_Startups.cs... |
numbers_scores = [2, 12, 4, 6, 8, 40, 44, 80, 30, 24]
for numb in numbers_scores:
a = numb + 1
print(a)
#2
for read in "I am Victor":
print(read.upper())
#3
school = [{'school_class': '4a', 'scores': [3,4,4,5,2]},
{'school_class': '4b', 'scores': [2,5,4,3,2]},
{'school_class': "4c",... |
# def serch(alist, item):
# found = False
# for i in alist:
# if item == i:
# found = True
# return found
#
# alist = [1,4,35,60,90]
# print(serch(alist, 90))
# def orderedSequentialSearch(alist, item):
# pos = 0
# found = False
# stop = False
#
# while pos<len(alist) ... |
import random
import os
VIDA_INICIAL_PIKACHU = 100
VIDA_INICIAL_SQUIRTLE = 100
TAMAÑO_BARRA_VIDA = 20
vida_pikachu=VIDA_INICIAL_PIKACHU
vida_squirtle=VIDA_INICIAL_SQUIRTLE
while vida_pikachu>0 and vida_squirtle>0:
#Se devuelven los numeros
print("Turno de Pikachu")
ataque_pikachu = random.ra... |
# Implementation of the Map ADT using closed hashing and a probe with double hashing.
from arrays import Array
class HashMap:
# Defines constants to represent the status of each table entry
UNUSED = None
EMPTY = _MapEntry( None, None)
# Creates an empty map instance.
def __init__( self):
s... |
import wikipediaapi
def game_setup():
print("Welcome to a game of Tic-Tac-Toe!")
num_players = int(input("How many players are going to play?"))
rule_display = input("Would you like to see the rules? Y/N")
return num_players, rule_display
def fetch_ruleset_from_wiki():
wiki_wiki = wikipediaapi.... |
print "Please enter two lists"
listOne = input()
listTwo = input()
listNew = list()
for numberOne in listOne:
for numberTwo in listTwo:
if(numberOne == numberTwo):
listNew.append(number)
input()
|
print "What is your name?"
name = raw_input()
print "How old are you?"
age = int(raw_input())
print name, " will turn 100 in ", 100 - age, " years"
|
import json
import argparse
from estnltk.vabamorf import morf
def write_tokens_analysis(in_file, out_file):
"""Reads tokens from the in_file,
performs morphological analysis with disambiguation=False and
writes tokens with morphological analysis to the out_file.
Every line of the out_file has th... |
"""
CSC148 Lab 3: Nim (with no classes!)
NOTE: You do NOT have to do anything in this file.
Just run it and play the game!
=== CSC148 Winter 2021 ===
Department of Computer Science,
University of Toronto
=== Module Description ===
This module contains a simplified implementation of the number game, ... |
import pygame
import random
import time
def react(attacker, defender):
successful_decider = random.randint(0,100)
damage_a = 0
damage_d = 0
result = ""
choice = defender.defensive_mode
if choice == "block" and successful_decider <= 30:
damage_a = calculate_damage(attacker, defender) * defender.shield
r... |
# Write a program to convert days into months and days.
inputDays = int(input("Enter the no. of days"))
print(inputDays)
years = inputDays//365
month= inputDays//30
days=inputDays-(month*30)
#print("The number of years is ",years)
print("The number of months is ",month)
print("The number of days is ",days) |
import sys
lines = []
def is_safe(x, y):
return 0 <= x < len(lines[0]) and 0 <= y < len(lines) and lines[x][y] != ' '
def go_down(x, y):
return x + 1, y
def go_up(x, y):
return x - 1, y
def go_right(x, y):
return x, y + 1
def go_left(x, y):
return x, y - 1
def go_forward(x, y, direction... |
text = input('年齢は?')
# age = int( text )
if not text.isdigit() :
print( '数値を入力して' )
|
def on_button_pressed_a():
player.move(-1)
input.on_button_pressed(Button.A, on_button_pressed_a)
def on_button_pressed_b():
player.move(1)
input.on_button_pressed(Button.B, on_button_pressed_b)
mines: game.LedSprite = None
player: game.LedSprite = None
game.set_score(0)
player = game.create_sprite(2, 4)
roof... |
s='python for life'
#print(s)
size=len(s)
print(size)
print(s[0:6])
print(s[7:10])
print(s[11:15])
print(s[2:10])
print(s[8:13])
#print(s[0:11]+' '+ s[11:15].upper())
print(s[0:11]+ s[11:15].upper())
#print(s[0:6].upper()+' '+ s[7:10]+' '+ s[11:15].upper())
print(s[0:7].upper()+ s[7:10]+' '+ s[11:15].upper()) |
'''
Mooc 的请求模块:包含 get, post, head 常用的三大请求
'''
from time import sleep
from functools import wraps
from socket import timeout, setdefaulttimeout
from urllib import request, parse
from urllib.error import ContentTooShortError, URLError, HTTPError
from Mooc.Mooc_Config import *
__all__ = [
'RequestFailed', 'reque... |
#!/usr/bin/python3
from sys import argv
from time import time
def prime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, num, 2):
if num % i == 0:
return False
return True
def yieldprime... |
#!/usr/bin/python3
'''
a simple clock with a gui
@Author Gabriel Fernandes
'''
import sys
import tkinter
from time import strftime
def main(args):
tk = tkinter.Tk()
tk.title('Clock')
global window
window = tkinter.Label(tk)
window['font'] = 'Helvetica 80 bold'
window['text'] = strftime('%H:%M:%S')
window.pa... |
#!usr/bin/python3
from sys import argv
from time import time, sleep
def looping(secs):
start = time()
count = 0
while True:
if(time()-start > secs):
break
count += 1
print('%9d loops paste' %(count))
if __name__=='__main... |
try:
import tkinter as tk
except:
print('tkinter is preinstalled on the newest version of python on windows and Mac')
print('For other Operating Systems without tKinter preinstalled use pip install tkinter such as arch linux varients with the terminal command:')
print('sudo pacman -S tk')
print('For... |
# https://leetcode.com/problems/verifying-an-alien-dictionary/
class Solution:
def isAlienSorted(self, words: [str], order: str) -> bool:
if not words:
return True
cost = {letter: i for i, letter in enumerate(order)}
for i in range(len(words) - 1):
first = words[i]
... |
# https://leetcode.com/problems/degree-of-an-array/
from collections import defaultdict
class Solution(object):
def findShortestSubArray(self, nums):
first_pos = dict()
last_pos = dict()
count = defaultdict(int)
for i, num in enumerate(nums):
if num not in first_pos:
... |
# https://leetcode.com/problems/print-foobar-alternately/
from threading import Lock, Thread
class FooBar:
def __init__(self, n):
self.n = n
self.foo_lock = Lock()
self.bar_lock = Lock()
self.bar_lock.acquire()
def foo(self, printFoo) -> None:
for i in range(self.n):
... |
def computepay(a,b):
if h > 40:
hExtra = h - 40
rph4Extra = rph * 1.5
payExtra = hExtra * rph4Extra
payNormal = 40 * rph
pay = payExtra + payNormal
return pay
else:
pay = h * rph
return pay
hrs = input("Enter Hours:")
rph = input("Enter... |
cin=input('text = ')
posStart=cin.find(':')
strLen=len(cin)
#str2=cin[posStart+1:]
str2=cin[posStart+1:strLen]
cin2=str2.strip()
cin2=float(cin2)
print(cin2)
|
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
fhandle = open(name)
hour=list()
hour1=list()
dictionary=dict()
for line in fhandle:
line=line.rstrip()
if not line.startswith('From '):
continue
fromLine=line.split()
time=fromLine[5]
time=time.split(':')
... |
hrs = input("Enter Hours:")
rph = input("Enter Rate per Hour:")
try:
h = float(hrs)
rph = float(rph)
except:
print("error in input type!try again....")
quit()
if h>40:
hExtra=h-40
rph4Extra = rph * 1.5
payExtra = hExtra * rph4Extra
payNormal=40*rph
pay=payExtra+payNormal... |
class Node:
def __init__(self,left=None,right=None,val=None):
self.left = left
self.right = right
self.val = val
class BinaryTree:
def __init__(self):
self.root = None
self.cnt = 0
def InsertRoot(self, val):
rootNode = Node(None, None, val)
self.... |
"""
---Create Target Array in the Given Order---
Given two arrays of integers nums and index. Your task is to create
target array under the following rules:
Initially target array is empty.
From left to right read nums[i] and index[i], insert at index index[i]
the value nums[i] in target array.
Repeat the previous s... |
"""
---Reverse Words in a String III---
Given a string, you need to reverse the order of characters in each word within a sentence while still
preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated... |
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import csv
import glob
import os
#download the purchase data in csv form from Ricemill to the same file that contains this program
#you need to have selenium package to run the program.
"""
This program will automatically fill in the order... |
# author: Jonathan Few
# description: An AI to play 2048
from game import Board, Action
import numpy as np
import copy
SIMULATIONS = 100 # Number of simulations to run for each potential move
LOOK_AHEAD = 80 # Number of moves to look ahead
ACTIONS = {Action.UP: "Up", Action.RIGHT: "Right", Action.DOWN: "Down", Actio... |
'''
CS 6140 Machine Learning - Assignment 05
Problem 3 - K-means Clustering
@author: Rajesh Sakhamuru
@version: 8/5/2020
'''
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import sys
def distance(pnt1, pnt2):
return math.sqrt(((pnt1 - pnt2) ** 2).sum())
def chooseCentroids... |
#!/usr/bin/env python
test_count = input()
for t in range(test_count):
string = raw_input()
length = len(string)
if length <= 10:
print string
else:
print string[0] + str(length - 2) + string[length - 1]
|
import mymath
import unittest
class TestAdd(unittest.TestCase):
"""
Test the add function from mymath library
"""
def test_add_integers(self):
"""
Tests that the addition of two integers returns the correct total
"""
result = mymath.add(1, 2)
self.assertEqual(r... |
from PIL import Image, ImageOps
def add_border(input_image, output_image, border):
img = Image.open(input_image)
if isinstance(border, int) or isinstance(border, tuple):
bimg = ImageOps.expand(img, border=border)
else:
raise RuntimeError('Border is not an integer or tuple!')
bimg.save... |
# Student: Josué Ignacio Cabrera Díaz
# for loops with for exercise
'''
Crear un archivo llamado 06_for.py
Crear una lista con nombres de persona e incluir, como mínimo, 5 nombres (como mínimo, uno ha de tener la vocal "a")
Crear una lista llamada "selected"
Recorrer, mediante un for, la lista d... |
##mile/英寸in
##meter-m/kilometer-km 90.3ft
str=raw_input("INPUT a Length with unit ended")
if str[-1] in ['E','e']:
a=eval(str[0:-4])
b=1.609344*a
print "%f mile=%f km"%(a,b)
if str[-1] in ['N','n']:
a=eval(str[0:-2])
b=0.0254*a
print "%f in=%f m"%(a,b)
if str[-2] in ['K','k']:
a=e... |
def is_triangle(a,b,c):
if c > a + b or b > a + c or a > b + c:
print 'No'
else:
print 'Yes'
def triangle_prompt():
print 'This program checks 3 lengths to see if they can form a closed triangle.\n'
a = float(raw_input('Enter a length.\n'))
b = float(raw_input('Enter another length.\n'))
c = ... |
import turtle
turtle = turtle.Turtle()
turtle.speed(1)
for angle in range(360):
turtle.left(1)
turtle.forward(2)
dummy = input() |
a = int(input("x: "))
b = int(input("y: "))
if (a >= b):
print(a, "is greater")
else:
print(b, "is greater")
|
import numpy as np
def wrap_angle(angle):
wraped_angle = (angle + np.pi) % (2 * np.pi) - np.pi
return wraped_angle |
from ClassificationDataset import ClassificationDataset
class ImageDataset(ClassificationDataset):
# A dataset, consisting of multiple samples/images
# and corresponding class labels.
def __init__(self):
self.rows=32
self.cols=32
self.channels=3
super().__init__()
def sample(self, si... |
#!/usr/bin/env python
import sys
import numpy as np
from numpy import random
def shuffle(source):
with open(source, 'r') as f1:
content = f1.readlines()
content = [line.strip() for line in content]
npLines = np.array(content)
random.shuffle(npLines)
listLines = list(npLines)
return listLines
d... |
a = "4567"
b = "9876"
def mul(a,b):
if len(a)==1 and len(b)==1:
return int(a)*int(b)
else:
x = a[0:len(a)/2]
y = a[len(a)/2:]
z = b[0:len(a)/2]
zz = b[len(a)/2:]
first = mul(str(y),str(zz))
last = mul(str(x),str(z))*10**len(a)
middle = mul(str(x+y),str(z+zz))
return first+last+middle
mul(a,b)
... |
MAX_FLOOR_NUMBER = 100
CURRENT_FLOOR = 1
MAX_FROM, MAX_TO = 0, 0
UP, DOWN, IDLE = 0, 1, 2
DIRECTION = IDLE
REQUESTS = []
IN_ELEVATOR = []
def go_up():
global CURRENT_FLOOR
max_floor = max(MAX_FROM, MAX_TO)
if CURRENT_FLOOR >= max_floor:
return False
else:
CURRENT_FLOOR += 1
re... |
import numpy as np
import pandas as pd
# from https://stackoverflow.com/questions/37935920/quantile-normalization-on-pandas-dataframe/41078786#41078786
# Sometimes you have text based data in there as well. This lets you specify
# the columns cols of your numerical data and will run quantile normalization
# on thos... |
string = input()
countA = string.count('a')
countO = string.count('o')
countU = string.count('u')
countI = string.count('i')
countE = string.count('e')
countY = string.count('y')
print('a ' + str(countA) + ',', 'o ' + str(countO) + ',', 'u ' + str(countU) + ',', end=' ')
print('i ' + str(countI) + ',', 'e ' + str(count... |
# procedure, convert_seconds, which takes as input a non-negative
# number of seconds and returns a string of the form
# '<integer> hours, <integer> minutes, <number> seconds' but
# where if <integer> is 1 for the number of hours or minutes,
# then it should be hour/minute. Further, <number> may be an integer
# or d... |
# Write a program to read through the mbox-short.txt
# and figure out who has sent the greatest number of mail messages.
# The program looks for 'From ' lines
# and takes the second word of those lines as the person who sent the mail.
# The program creates a Python dictionary that maps the sender's mail address
# to a ... |
# Write a program that prompts for a file name,
# then opens that file and reads through the file,
# looking for lines of the form:
# X-DSPAM-Confidence: 0.8475
# Count these lines and extract the floating point values from each of the lines
# and compute the average of those values and produce an output as shown be... |
#The CNPJ Number has 14 figures and in the formated form has 2 '.'
# one '/' and one '-', so the size of the string can only be 14 or 18
#"00.000.000/0000-00"
def validateCNPJ(cnpj):
n = len(cnpj)
if n == 14 and cnpj.isdecimal():
print("This CNPJ is valide")
return True
elif n == 18:
... |
def add(a, b):
c = a + b
print c
number_1 = 20
number_2 = 35
add(5, 6)
add(number_1, number_2) |
# word_count.py
# ===================================================
# Implement a word counter that counts the number of
# occurrences of all the words in a file. The word
# counter will return the top X words, as indicated
# by the user.
# ===================================================
import re
from hash_map ... |
def print_result(effort_status):
if not effort_status:
print("Sorry. You can't make the perfect firework show.")
else:
print("Congrats! You made the perfect firework show!")
if q:
print(f"Firework Effects left: {', '.join(str(x) for x in q)}")
if power:
print(f"Explosive ... |
def read_matrix(row, col):
total_sum = 0
for r in range(row):
x = [int(el) for el in (input().split(", "))]
matrix.append(x)
return matrix
def sum_matrix(result):
total_sum = 0
for i in result:
for j in i:
total_sum += j
return total_sum
matrix = []
row, c... |
import os
# data = open("/Users/Vasil/Desktop/Tier.txt", 'r')
# for line in data:
# if "man" in line.lower():
# print(line, end='')
# data.close()
# with open("/Users/Vasil/Desktop/Tier.txt", 'r') as data:
# no need to close the file
# for line in data:
# if 'tier' in line.lower():
# ... |
def numbers_searching(*args):
""" finding the duplicates """
list_a = []
duplicates = []
for el in args:
if el not in list_a:
list_a.append(el)
else:
duplicates.append(el)
""" finding the missing numbers """
x = sorted(set(list_a))
y = set(range(x[0],... |
def is_new_position_valid(matrix, row, col):
if r not in range(len(matrix)) or c not in range(len(matrix)):
return False
return True
def find_player(matrix):
is_found = False
for row in range(len(matrix)):
for col in range(len(matrix)):
current_position = matrix[row][col]
... |
phonebook = {}
command = input()
while not command[0].isdigit():
name, number = command.split('-')
phonebook[name] = number
command = input()
command = int(command)
for i in range(command):
search_name = input()
if search_name not in phonebook:
print(f"Contact {search_name} does not exist.... |
def get_words(file_path):
with open(file_path, 'r') as file:
return file.read().split()
def get_words_counts(file_path, words):
words_counts = { word: 0 for word in words }
with open(file_path, 'r') as file:
for line in file:
words_in_line = line.lower().split()
for ... |
#!/usr/bin/env python3
""" Some for and while loops that print various numerical/list manipulations."""
__appname__ = 'Loops.py'
__author__ = "Elin Falla (ekf16@ic.ac.uk)"
__version__ = "0.0.1"
# FOR loops in python #
# Prints 0-4
for i in range(5):
print(i)
# Prints out list
my_list = [0, 2, "geronimo!", 3.0... |
#!usr/bin/env python3
"""Script that prints the output of 'birds' dataset by species, showing latin name, common name and body mass."""
__appname__ = 'Tuple.py'
__author__ = 'Elin Falla (ef16@ic.ac.uk)'
__version__ = '0.0.1'
# Data #
birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7),
('Delich... |
'''
Retrieve random list of articles from wiki
Loop through this list
print title of article
Ask reader if user wants to read it
If they say yes, open the link to the article in a browser
Wait..if user presses N, repeat question and Loop
give an option to exit
'''
'''
need requests to retrieve list
need json to interp... |
# tính tổng, tích các phần tử tỏng list
lst = [34,234,456,67,34,3]
sum_ = 0
product_ = 1
for item in lst:
sum_ += item
product_ *= item
print(f"tong : {sum_}, tich: {product_}")
|
from collections import OrderedDict
from collections import namedtuple
City = namedtuple("City", "name country population coordinates")
def test_city_tokyo():
# namedtuple basics
tokyo = City("Tokyo", "JP", 36.933, (35.689722, 139.691667))
assert tokyo[0] == tokyo.name == "Tokyo"
assert tokyo[1] == t... |
"""
open(Final.txt)
input = scores
iterator, accumulator = 0
loop through scores
accumulator = accumulator + scores
iterator = iterator + 1
output = accumulator / total score
print average
total number of scores = num(24)
average = accumulator / total number of scores
print percentage of grade... |
import random
# ---------------------------------------------------------
# question 2
my_list = [(value*2)-1 for value in range(1, 6)]
print("i have created : ")
print(my_list)
# A
print(sorted(my_list, reverse=True))
# B
for num in my_list:
print(num)
# C
new_list = my_list[:]
i = 0
for num in new_l... |
# Class
# class definition
# must be executed before they have any effect
# can be placed in a branch of an if statement, or inside a function
# a new namespace created and used as the local scope when the definition enters
# a class object created when the definition is left normally
#
#... |
"""
The scraper module holds functions that actually scrape the e-commerce websites
"""
import requests
import formatter
from bs4 import BeautifulSoup
def httpsGet(URL):
"""
The httpsGet funciton makes HTTP called to the requested URL with custom headers
"""
headers = {"User-Agent": "Mozilla/5.0 (Wind... |
import math
# Fibonacci number
def fib(n):
if n <= 1:
return 1
return fib(n-1) + fib(n-2)
# Factorial
def factorial(n):
if n<= 1:
return 1
return factorial(n-1) * n
# Is Prime
def is_prime(n):
return (prime(n,int(math.sqrt(n))))
def prime(n,count):
if count == 0 or n == 1:
... |
import random
cont = True
money = int(input("How much money do you have?"))
while(cont):
game = input("What game do you want to play? Slots or Acey Duecy?")
bet = int(input("How much do you want to bet?"))
if (game == "Slots" or game == "slots"):
type = input("What type of slot? 50%, 25%,... |
'''
Created on Dec 23, 2009
@author: mdharwadkar
'''
#Simple Critter
#Demonstration of a basic class and object
class Critter(object):
"""A virtual pet"""
def __init__(self, name):
print "A new pet has been born..."
self.name = name
def __str__(self):
rep = "Critter object... |
import random
#Generating a random number from 1 - 100
number = random.randrange(100) + 1
#print(number)
#Welcome to....GUESS MY NUMBER!
print("Greetings. My name is Invincible, Vince for short")
ask_name = input("What is your name?:")
print("Hello %s" % ask_name)
print("You really think you can beat me? Never!")
... |
# Program to convert a hexadecimal number to decimal
MULTIPLIER = 16
hex_letters = {"a":10, "b":11, "c":12, "d":13, "e":14, "f":15}
def get_keys(dict):
return list(dict.keys())
def get_number():
number = input("Please enter a hexadecimal number: ")
return number
#def get_length(n):
# length = len(str... |
class Car:
"""
Car model with tires, engine, paint color
"""
def __init__(self, engine, tires, color):
self.engine = engine
self.tires = tires
self.color = color
def description(self):
print(f"A car with an {self.engine} engine, {self.tires} tires and {self.color} ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.