text
stringlengths
37
1.41M
import random from datetime import datetime # Get the current time and hope that the user set their clock correctly. # h is current hour and m is current minute. h = datetime.now().hour m = datetime.now().minute # n is the (sudo)random number being generated and used for decisions. n = random.randint(1,7) print('You...
# 404. Sum of Left Leaves # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int ""...
listdata = [9.96, 1.27, 5.07,6.45, 8.38, 9.29] maxval = max(listdata) minval = min(listdata) print(maxval);print(minval) print('----------------------') txt = 'Alotofthingsoccuerachday' maxval = max(txt) minval = min(txt) print(maxval);print(minval) print('----------------------') maxval = max(2+3, 2*3, 2**3, 3**2...
listdata=[1,2,3,4] ret1=5 in listdata ret2=2 in listdata print(ret1);print(ret2) strdata='abcde' ret3='c' in strdata ret4='j' in strdata print(ret3);print(ret4)
# 阿当姆斯法 def f(ex, ey): return -ey + ex + 1 N = 11 # 求解次数 h = 0.1 # 步长 y = 1 # y(0)的值为0 def init(y0): n = 0 x0 = 0 ret = [] while 3 > n: x1 = x0 + h k1 = f(x0, y0) k2 = f(x0 + h / 2, y0 + (h / 2) * k1) k3 = f(x0 + h / 2, y0 + (h / 2) * k2) k4...
# Created by RANVIR 04/06/16 #While confi Hardware keep -ve Terminal of Led pin is comman #And connect +ve termina to each pin Of GPIO #As arrange your led accoroding to that place gpio pin list in Pinlist variable import RPi.GPIO as GPIO # Importing RPi as Gpio import time #importing time for dealy contr...
from abc import ABC, abstractmethod class AbstractClass(ABC): @abstractmethod def do_something(self): print("Some implementation!") # class DoAdd42(AbstractClass): # def do_something(self): # return self.value + 42 # # # class DoMul42(AbstractClass): # def do_something(self): # ...
""" Employee class """ from classes.Qualification import Qualification class Employee: def __init__(self, employee_id, first_name, last_name, ssn, phone, address, city, state, postal_code, employed_by, position, salary, qualifications): self.employee_id: int = employee_i...
__author__="najib" """from chatterbot import ChatBot from chatterbot.trainers import ListTrainer #create a new chat bot Chatnajib = ChatBot("Bot") #training my chatbot bot starts with knowledge from chatterbot.trainers import ListTrainer conversation = ["hello", "hi there!", "how ar...
import pandas as pd from sklearn import linear_model dataset = pd.read_csv('salary.csv') print("Rows:",dataset.shape[0],"Columns:",dataset.shape[1]) #separating out independent variable X=dataset.iloc[:,:-1].values Y=dataset.iloc[:,1].values #print(X,"\n\n",Y) #splitting dataset into training and test set from sklea...
#!/usr/bin/python3 def uniq_add(my_list=[]): history = [] sum = 0 for i in range(len(my_list)): if i == 0: history.append(my_list[i]) sum += my_list[i] if history.count(my_list[i]) == 0: sum += my_list[i] history.append(my_list[i]) return s...
# Introduction to Programming Project 1 # Author: Reisha Puranik # Date: October 11, 2019 def process(eq, op): if op == '/': print("here",eq) index = eq.index('/') op1 = float(eq[index - 1]) op2 = float(eq[index + 1]) result = op1 / op2 del(eq[index - 1:index + 2]) ...
# Python3 implementation to check if # both halves of the string have # at least one different character MAX = 26 # Function which break string into two # halves Increments frequency of characters # for first half Decrements frequency of # characters for second half true if any # index has non-zero value def function...
def odd_even(val): a=val if a%2=0: return("even") else: return("odd") value= int(input("enter any integer:")) read=odd_even(value) print(read)
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 20:22:18 2018 @author: jwright.06 """ a = 0 b = 0 for x in range(1,101): a += x**2 b += x c = b**2 - a print(c)
""" 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? """ def gcd(a,b): r = a % b while r != 0: a = b b = r r = a % b ...
""" File: titanic_survived.py Name: Chia-Lin Ko ---------------------------------- This file contains 3 of the most important steps in machine learning: 1) Data pre-processing 2) Training 3) Predicting """ import math TRAIN_DATA_PATH = 'titanic_data/train.csv' NUM_EPOCHS = 1000 ALPHA = 0.01 def sigmoid(k): """ ...
""" File: guess_my_number.py Name: ----------------------------- This program plays a Console game "Guess My Number" which asks user to input a number until he/she gets it """ # This number controls when to stop the game import numpy as np SECRET = int(np.random.random_sample()*100) #SECRET = 0 def main(): print...
""" File: how_many_lines.py Name: Jerry Liao 2020/09 --------------------------- This file shows how to calculate the number of lines in romeojuliet.txt by Python code """ # This constant shows the file path to romeojuliet.txt FILE = 'text/romeojuliet.txt' def main(): """ This program prints the number of lines i...
""" File: find_max.py Name: -------------------------- This program finds the maximum among all the user inputs. Students can refer to this file when they are doing Problem 2 in Assignment 2 """ # This constant controls when to stop EXIT = -1 def main(): """ This program finds the maximum among user inpu...
""" File: caesar.py Name: Chia-Lin Ko ------------------------------ This program demonstrates the idea of caesar cipher. Users will be asked to input a number to produce shifted ALPHABET as the cipher table. After that, any strings typed in will be encrypted. """ # This constant shows the original order of alphabeti...
""" File: flip_horizontally.py Name: ------------------------------------ This program shows how to create an empty SimpleImage as well as making a mirrored image of poppy.png by inserting old pixels into the blank new canvas """ from simpleimage import SimpleImage def main(): img = SimpleImage("images/poppy.p...
""" File: bouncing_ball.py Name: Chia-Lin Ko ------------------------- This program simulates a bouncing ball at (START_X, START_Y) that has VX as x velocity and 0 as y velocity. Each bounce reduces y velocity to REDUCE of itself. """ from campy.graphics.gobjects import GOval from campy.graphics.gwindow impo...
""" File: my_power_function.py Name: Chia-Lin Ko ------------------------------- This program shows students how to make their own functions by defining def my_power(a, b) """ def main(): print('This program prints a to the power of b.') a = int(input('a: ')) b = int(input('b: ')) print(my_power(a, b)) def my_...
from karel.stanfordkarel import * """ File: CollectNewspaperKarel.py Name: Chia-Lin Ko -------------------------------- This program instructs Karel to walk to the door of its house, pick up the newspaper (represented by a beeper, of course), and then return to its initial position in the upper left corner of the h...
""" File: titanic_level1.py Name: ---------------------------------- This file builds a machine learning algorithm from scratch by Python codes. We'll be using 'with open' to read in dataset, store data into a Python dict, and finally train the model and test it on kaggle. This model is the most flexible one among a...
from cs50 import get_int def main(h): # Asks for input while h is smaller or equal to 0 or bigger then 8 while h <= 0 or h > 8: h = get_int("Height: ") # determine width w = h # create piramid for i in range(1, h+1): space = w - i print(" " * space, end="") p...
#coding: utf-8 #author:hx ''' ZeroDivisionError 除(或取模)零 (所有数据类型) AttributeError 对象没有这个属性 #open('str.txt','r') FileNotFoundError找不到文件 ImportError 导入模块/对象失败 IndexError 序列中没有此索引(index) KeyError映射中没有这个键( 元组) NameError 未声明/初始化对象 (没有属性) SyntaxError Python 语法错误 IndentationError 缩进错误 TypeError 对类型无效的操作 ValueError 传入无效的参数 ''' ...
class Washer: def __init__(self, water=15, scour=5): self.water = water self.scour = scour def set_water(self, water): self.water = water def set_scour(self, scour): self.scour = scour def add_water(self): print('Add water', self.water) def add_scour(self...
#coding: utf-8 #author: hexi #实例1 #break mystr="asdfghjkl" for i in mystr: if i=='h': break print(i) print("执行成功") #continue ''' mystr="asdfghjkl" for i in mystr: if i=='h': continue print(i) print("执行成功") ''' #实例2 list1=[1,3,5,7] list2=[2,4,6,8] new_list=list() for i in list1: for...
''' FIFO (First in First out) implementation of a queue using circular lists when we deque an element and want to advance the front index use the arithmetic f = (f + 1) % N where N is the size of the list ''' class ArrayQueue: '''Fifo queue implementatio using a Python list as underlying storage.''' DEFAUL...
import numpy as np from random import sample #Used for random initialization def choose_k_random_centroids(X, K): """ Function to return K random centroids from the training examples """ random_indices = sample(range(0,X.shape[0]),K) return np.array([X[i] for i in random_indices])
import pygame # ----------- Game Initialization ------------------- pygame.init() displayWidth, displayHeight = 700, 800 gameDisplay = pygame.display.set_mode((displayWidth, displayHeight)) pygame.display.set_caption('Basic Pygame Template') clock = pygame.time.Clock() # ----------- Constants --------------- FPS = 6...
class SimpleBudget: def __init__(self, category, balance): self.balance = balance self.category = category def __str__(self): return f"A {self.category} budget with N{self.balance}" #methods def deposit(self, amount): self.balance += amount print(f"Yo...
ix=1 while ix < 4: print(ix) if ix== 5: break ix +=1 else: print("Else part")
import unittest class Vertex(object): def __init__(self, name): self.neighbors = [] self.name = name def __str__(self): return self.name def bfs(adj): visited = [] for v in adj: to_visit = [v] while to_visit != []: v = to_visit.pop(0) if...
import unittest class Node(object): def __init__(self): self.data = None self.node1 = None self.node2 = None def transform(root): if root is None: return root begin, end = _transform(root) return begin def _transform(root): if root is None: return None, Non...
# Old class style class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state class Foo(Borg): def __init__(self,aaa): Borg.__init__(self) self.aaa = aaa # New class style class BorgNew(object): __shared_state = {} def __init__(self): sel...
# Write a Python program that reads in 3 numbers and displays the following: # a) the average of the three numbers # b) the maximum fo the three numbers print("Please enter three numbers of your choosing.") num1 = float(input("Enter your first number: ")) num2 = float(input("Enter your second number: ")) num3 = float...
x1 = int(input("Enter x1: ")) y1 = int(input("Enter y1: ")) x2 = int(input("Enter x2: ")) y2 = int(input("Enter y2: ")) x = int(input("Enter x: ")) y = int(input("Enter y: ")) if x1 <= x <= x2 and y1 <= y <= y2: print("True") else: print("False")
# Int functions only with integers (Whole number) ways to bypass this is by using Float # Example: Print(Int(8+3.3)) will print only 11 # However, print(float(8+3.3)) will print 11.3 # Text inside of single or double quotes makes the content inside it a string # If an apostrophe is needed in a strin...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # print(abs(10)) # print(abs(-10)) # print(abs(10.12)) # print(min(1,2)) # print(max(2,3)) # print(int(1.22)) # print(int(100)) # print(int('100')) # print(float('100.44')) # print(float(100.44)) # print(float('100')) # print(str(100)) # print(str(100.12)) # print(str...
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print(1,2,3,4,5) 1 2 3 4 5 >>> number=[1,2,3,4,5] >>> print(number) [1, 2, 3, 4, 5] >>> print(*number) 1 2 3 4 5 >>> print("abc") abc >>> print(*"ab...
# Multiple Linear Regression import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('50_Startups.csv') # Prepare data X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encode categorical data # Encode IV from sklearn.preprocessing import LabelEnc...
# Write a class to hold player information, e.g. what room they are in # currently. from item import Food, Egg class Player: def __init__(self, name, current_room): self.name = name self.current_room = current_room self.items = [] self.strength = 100 def travel(self, direction...
def check(s_1, s_2): s_1 += s_1 if (s_1.count(s_2) != 0): print("YES") # Now Rajat Become Happy. else: print("NO") for i in range(int(input())): s_1 = input() s_2 = input() if len(s_1) == len(s_2): check(s_1, s_2) else: print("NO")
for _ in range(int(input())): distanceNeedToBeCovered = int(input()) x = input() y = input() print("NO") if int(x, 2) & int(y, 2) else print("YES")
for _ in range(int(input())): str1=input() str2=input() new="" if len(str1)!=len(str2): # Check if sizes of two strings are same print("NO") else: new= str1 + str1 # Create a temporary string new by concatenating Str1 with itself if new.count(str2)>0: ...
for _ in range(int(input())): s1 = input() s2 = input() temp = '' if len(s1) != len(s2) : print('No') else: temp = s1+s1 if s2 in temp: print("YES") else: print('NO')
for _ in range(int(input())): N=int(input()) a=int(input(),2) # Converting input to integer from binary string b=int(input(),2) # Converting input to integer from binary string if (a & b)==0: # We used bitwise And Operator # 1 & 1 = 1 print("YES") ...
from Stream.stream import Stream import csv # # # class TextStream(Stream): # def __int__(self, path): # super().__init__(None) # self.path = path # # def get_path(self): # return self.path # # # textStream = TextStream('../data/taxi.csv') # # print(textStream.get_path()) # Use the P...
#A 3-layer neural network implementation. #Much credit to Tariq Rashid's Make Your Own Neural Network book import numpy import scipy.special import csv class neuralNet: def __init__(self, num_inputs, num_hiddens, num_outputs, learning_rate): self.inodes = num_inputs self.hnodes = num_hiddens ...
#Thomas Rowley # insert elements either appending or inserting # 2 delete an element either by value or by index # 3 find if something in the list # 4 Find the index where an element is in the list # 5 reverse th eorder of the array x=1 l1="**************************************" l2="* My game ...
answer= str(input()) #input is a function that returns a string while answer == "Peter": print(answer.lower()) # method of Strings (always refer it with a dot) answer= "Changed" answer = answer.lower() print (answer)
#Thomas Rowley #6/7/2021 #Learning how to work with strings # make 3 string variables print them individually #"print st1 + st2" #print st2 + st3 #print st1 + st2 + st3 phrase1 = "Lebron" phrase2 = "<" phrase3 = "Tacko" phrase4 = str(input()) print(phrase1, " ", phrase2, " ", phrase3) print(phrase1, " " + phrase...
import random print('This is a number guessing game. Guess a number between 1 and 20.') print('You have 6 chances') secret = random.randint(1,20) for i in range(1,7): print ('>> ') guess = int(input()) if guess > secret: print('Guess too high. Try guessing a smaller number') elif guess < secre...
import logging logging.basicConfig(filename = 'debug_log.txt', level = logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s') # by adding the filename argument, we can output all the debug messages to a file instead of printing to console. # this enables storage of debug messages as these are appended ...
# gui manipulation using pyautogui module import pyautogui # get screensize print(pyautogui.size()) # returns a tuple of width and height # move mouse cursor to a specific coordinate >> starts at (0,0) at top left and (width-1,height-1) at bottom right # x-coords incrase to the left. y-coords incrs down #pyaut...
print('Hello World') #expression print(2+2) #expression always evaluate to a single value #BODMAS rule followed by python #they evaluate using operators (mathematical) # data types # integer, ints = whole numbers e.g 2 # floating point numbers, floats = decimal values, 3.14 # strings = array of chars. # string...
# Regressão Linear Múltipla # Base de dados de preços das casas retiradas do Kaggle # "House Sales in King County, USA" # Importando as bibliotecas import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolut...
with open('guest_book.txt', 'a') as file: while True: ask = input("请输入你的姓名('q'键退出):") if ask == 'q': break ask += '\n' print("您好!" + ask) file.write(ask)
from math import pi, sin, cos Radius = 100.0 Steps = 72 NLongitudes = 10 NLatitudes = 4 def main(): color("green") makeLongitudes() color("yellow") makeLatitudes() def makeLongitudes(): for i in range(NLongitudes): first = None theta = i * (2 * pi / NLongitudes) sint = sin(theta) cost = cos(theta) for...
def swap(line, column): swapped_line = line first_variable = find_first_variable(line, column) second_variable = find_second_variable(line, column) swapped_line = swapped_line.replace(second_variable, first_variable) swapped_line = swapped_line.replace(first_variable, second_variable, 1) retu...
from pymongo import MongoClient DB_NAME = 'nba_db' PLAYERS_COL = 'players' # nba_db.players collection TEAMS_COL = 'teams' CURRENT_SEASON = "2015-16" # nba_db.2015-16 collection and current season class NBADatabase: """ Interface that describes the methods of an NBADatabase. """ def get_players(sel...
""" Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. """ # O(n) time complexity and O(1) space complexity from typing import List class Solution: def increasingTriplet(self, nums:...
from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ self.transpose(matrix) self.reflect(matrix) def transpose(self,matrix): n = len(matrix) for ...
""" Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Solution We can solve this question by using a set. We traverse the linked list and check if the next node’s value is inside the set. If it is, then we modify the curren...
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # You may assume the two numbers do not contain any leading zero, except the number 0 itself. # ...
""" Given an unsorted integer array nums, find the smallest missing positive integer. """ def firstMissingPositive(nums): nums.sort() if not nums or (nums[-1] < 1) : return 1 for i in range(1, nums[-1]+1): if i not in nums: return i return nums[-1]+1 """ Time/Space: O(n)/...
""" Write a function reverseArray(A) that takes in an array A and reverses it, without using another array or collection data structure; in-place. Example: A = [10, 5, 6, 9] reverseArray(A) A // [9, 6, 5, 10] """ A = [10, 5, 6, 9] def reverseArray(A): return [list for list in A[::-1]] print(reverseArr...
import json from difflib import get_close_matches data = json.load(open("data.json")) def meaning(word): global i word = word.lower() if word in data: return data[word] if word.title() in data: return data[word.tile()] if word.upper() in data: return data[word.upper()] ...
"""Write a program which accept number from user and return addition of digits in that number. Input : 5187934 Output : 37 """ def Sumdigit(num): sum=0 digit=0 while num!=0: digit=num%10 sum=sum+digit num=num//10 return sum def main(): value=int(input("Enter the number:")) add=Sumdigit(value...
"""Write a program which accept one number and display below pattern. Input : 5 Output : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5""" def Display(num): i=0 j=0 for i in range(num): for j in range(1,num+1,1): print(j,end=" ") print() def main(): value=int(input("Enter the numbe...
"""Write a program which contains filter(), map() and reduce() in it. Python application which contains one list of numbers. List contains the numbers which are accepted from user. Filter should filter out all such numbers which greater than or equal to 70 and less than or equal to 90. Map function will increase eac...
"""Write a program which accept N numbers from user and store it into List. Accept one another number from user and return frequency of that number from List. Input : Number of elements : 11 Input Elements : 13 5 45 7 4 56 5 34 2 5 65 Element to search : 5 Output : 3 """ def Frequency(brr,num1): freq=0 for ...
"""Write a program which accept N numbers from user and store it into List. Return addition of all elements from that List. Input : Number of elements : 6 Input Elements : 13 5 45 7 4 56 Output : 130 """ def Addition(brr): sum=0 for i in range(len(brr)): sum=sum+brr[i] return sum def main(): no=0 ...
from pyquery import PyQuery as pq import requests #输入保存到本地的文件名 filename = input("Please input the name you want to save: ") #提供小说的编号,https://www.biqukan.com/0_790/ 提供0_790就行,输入0_790 book_url = input("Please input url of this novel: ") #获取小说文本内容 def get_txt(url): #获取url的返回值 response = requests.get(url) ...
#!/usr/bin/env python # -*- coding:utf-8 -*- name = 'whole global name' ''' 注:此处全局的变量名,写成name,只是为了演示而用 实际上,好的编程风格,应该写成gName之类的名字, 以表示该变量是Global的变量 ''' class Person: name = 'class global name' def __init__(self, newPersonName): # self.name = newPersonName ''' 此处,没有使用self.name ...
# -*-coding: utf-8 -*- # @Time : 2021/1/1 15:03 # @Author : Cooper # @FileName: text2.py # @Software: PyCharm import threading import time class myThread(threading.Thread): def __init__(self,name,delay): threading.Thread.__init__(self) self.name=name self.delay=delay def run(...
""" 作者:Oliver 功能:用户输入密码比对账户信息 日期:20190120 版本:1.0 """ name_tup = ("a", "b", "c") password_tup = ("123", "234", "345") input_times = {"a": 0, "b": 0, "c": 0} name = input("请输入你的账户:") while input_times[name] < 3: password = input("请输入你的密码:") if name in name_tup: if password == password_tup[name_tup.index(n...
#Michelle Tan #10/27/2020 #Lab 6 def is_lower_101(string): #Takes a single character as input and returns True if the character is lowercase and False otherwise stringInt = ord(string) upperString=chr(stringInt-32) if string.upper() == upperString: return True else: return False def char_...
# Michelle Tan # Prof. Turner # Section 01 name = input('What is your name? ') print('Hello ' + name + '!')
#Michelle Tan #Instructor: Turner #Section: 01# #Lab 3 import unittest from logic import * class TestCases(unittest.TestCase): #Testing the is_even function using an even, odd, negative even, negative odd number def test_is_even_1(self): self.assertTrue(is_even(2)) def test_is_even_2(self): ...
def guessing_game(no_of_guess, target): ''' A function named guessing_game, it asks for the user guess and prints your guess is higher or lower. This is repeated by the no_of_guess.day2.py Parameters: no_of_guesses and target Returns: the positive difference between the final guess and the ...
def GPA_calculator(scores, units): ''' A function named GPA_calculator which computes the GPA of a student Parameter: scores - The score of the student units: The units of each course Returns: The GPA of the student. @author: Babatunde Koiki Created on 2020-03-24 ''' ...
def wrapper(para,n): """ This function takes in a paragraph as a string and aximum number of characters as an integer Returns the wrapped text as a string Created on Tue Apr 7 11:02:34 2020 @author: Babatunde Koiki """ new_text = para.split("\n") final=[] ...
def sparse_search(data, search_val): print("Data: " + str(data)) print("Search Value: " + str(search_val)) first = 0 last = len(data)-1 # runs as long as pointer do not intersect. E.G left crosses over right pointer while first <= last: # sets middle index of first to last array ...
# Filename : test.py # coding=utf-8 __author__ = 'wind' print ('hello world') #事实上Python 为了优化速度,使用了小整数对象池,避免为整数频繁申请和销毁内存空间。而Python 对小整数的定义是 [-5, 257), #只有数字在-5到256之间它们的id才会相等,超过了这个范围就不行了,同样的道理,字符串对象也有一个类似的缓冲池,超过区间范围内自然不会相等了 #如果你需要某个 # Python 函数或语句的快速信息帮助, # 那么你可以使用内建的 help 功能。 # 尤其在你使用带提示符的命令行的时候, # 它十分有用。比如,运行 help(...
#!/usr/bin/env python # Booleans are statements that take on either True or False as a value. # We can create booleans by comparing two values and seeing if they are equal # This will be False print("Andre the Giant" == "Short") # This is True print("Andre the Giant" == "Andre the Giant") # True and False are special...
#!/usr/bin/env python # Let's say we want to take the square root of a number. # Python's math module has a handy function that can do that. # But, we have to import the module before we can use it. import math # Now, we can access the functions in the module by using the module name, then a dot, then the function to ...
#!/usr/bin/env python # Let's assume that Superman is three times more interested in foods having a lot of protein than he is worried about them having too much fat. # We can "weight" the protein number by his criteria, or multiply it by three. # First we'll calculate the weighted value for protein. weighted_protein = ...
#!/usr/bin/env python # We can use the max() method to find the maximum value in a column. max_protein = food_info["Protein_(g)"].max() # And then we can divide the column by the scalar. normalized_protein = food_info["Protein_(g)"] / max_protein # See how all the values are between 0 and 1 now? print(normalized_prot...
#!/usr/bin/env python # Define a list of lists data = [["tiger", "lion"], ["duck", "goose"], ["cardinal", "bluebird"]] # Extract the first column from the list first_column = [row[0] for row in data] # Double all of the prices in apple_price, and assign the resulting list to apple_price_doubled. # Subtract 100 from ...
#!/usr/bin/env python # We can use for loops and if statements to find the smallest value in a list. the_list = [20,50,5,100] # Set smallest_item to a value that is bigger than anything in the_list. smallest_item = 1000 for item in the_list: # Check if each item is less than smallest_item. if item < smallest_i...
#!/usr/bin/env python # We can use the set() function to convert lists into sets. # A set is a data type, just like a list, but it only contains each value once. car_makers = ["Ford", "Volvo", "Audi", "Ford", "Volvo"] # Volvo and ford are duplicates print(car_makers) # Converting to a set unique_car_makers = set(car_...
#!/usr/bin/env python class Car(): # The special __init__ function is run whenever a class is instantiated. # The init function can take arguments, but self is always the first one. # Self is a reference to the instance of the class. def __init__(self, car): # Using self before car means that ca...
#!/usr/bin/env python #Read the "crime_rates.csv" file in, split it on the newline character (\n), and store the result into the rows variable # We can split a string into a list. a_string = "This\nis\na\nstring\n" split_string = a_string.split('\n') print(split_string) # Here's another example. string_two = "How much...
#!/usr/bin/env python max_val = None data = [-10, -20, -50, -100] for i in data: # If max_val equals None, or i is greater than max_val, then set max_val equal to i. # This ensures that no matter how small the values in data are, max_val will always get changed to a value in the list. # If you are checking ...
#!/usr/bin/env python # Let's practice with some list slicing. a = [4,5,6,7,8] # New list containing index 2 and 3. print(a[2:4]) # New list with no elements. print(a[2:2]) # New list containing only index 2. print(a[2:3]) # Assign a slice containing index 2 and 3 from slice_me to slice1. # Assign a slice containing...
#!/usr/bin/env python # We can make an empty list with square brackets a = [] # We can also initialize a list with values inside of it b = [1, "I'm a string in a list!", 5.1] c = [1,2,3] d = [5,7,3,2,1] e = ["hello", "world"] f = [10.6, 8.3]