text stringlengths 37 1.41M |
|---|
X = [1 , 1.05 , 1.10 , 1.15 , 1.20 , 1.25]
Y = [0.682689 , 0.706282 , 0.728668 , 0.749856 , 0.769861 , 0.788700]
n = len(Y)
h = X[1] - X[0]
#################################################################
# TWO POINT APPROXIMATION
print("\n\nTwo point approximation of derivative")
print("\nx0\tForward Difference f... |
import pandas as pd
(a , b , TOL , N) = (0 , 1 , 0.01 , 4)
def f(x):
return (x ** 3) + (4 * x * x) - 10
data = []
pd.options.display.float_format = "{:,.10f}".format
def bisection(a , b , N = 100 , TOL = 10 ** -5):
n = 1
while n <= N:
p = a + (b - a) / 2
data.append([n , a , b , p , f(p... |
'''2nd assignment
dijkstra's alg
class priorityqueue:
#constructor creates a heap
def enqueue(self, item):
def dequeue(self, item):
def isEmpty(self:
Height balanced AVL trees
Balance is maintained in each node
and is called balance. Subtrees are referenced as... |
"""
This File is for Mini Project in EED379 :Internet Of Things
Course : Internet Of Things EED379
Component : Mini Project
Topic: Home Automation using Google Assistant
Authors: Ojas Srivastava
Yatharth Jain
Code Component Description : This code is client side for the Raspberry Pi Node.
... |
# Diccionarios
countriesCapitals={"Alemania":"Berlin","Colombia":"Bogota","Francia":"Paris","España":"Madrid"}
#print (countriesCapitals["Alemania"])
# Agregar elementos
countriesCapitals["Italia"]="Lisboa"
# Modificar valores, se sobreescriben
countriesCapitals["Italia"]="Roma"
# Eliminar elementos
del countriesCapit... |
welcome=print("Bienvenido al programa, Inserte numeros cada vez mayores")
number=int(input("Inserte el primer numero entero: "))
while number>0:
number1=int(input("Inserte el siguiente numero: "))
print("Numero anterior ",str(number)," Siguiente numero ",str(number1))
number=number1
print(number)
print(number1)
... |
# Continue
name="Pildoras informaticas"
counter=0
print(len(name))
for letter in name:
if letter==" ":
continue
counter+=1
print(counter)
# Pass , Rompe un bucle, hace un clase nula,no se tiene en cuenta
# Else , Funciona cuando el bucle termina
email=input("introduce tu email: ")
arroba=False
for i in email:
... |
def encrypt_this(text):
print(text)
result = ""
for word in text.split(' '):
if len(word) == 1:
w = str(ord(word))
result += w + " "
if len(word) == 2:
w = str(ord(word[0])) + word[1]
result += w + " "
if len(word) == 3:
w =... |
from operator import itemgetter
def meeting(s):
names = []
result = ""
split = s.split(";")
for name in split:
name = name.split(":")
firstname = name[0].upper()
lastname = name[1].upper()
out = [firstname, lastname]
names.append(out)
# sort by last name,... |
def street_fighter_selection(fighters, initial_position, moves):
if len(moves) == 0:
return []
result = []
cur_pos = list(initial_position)
fighter_row = 0
for move in moves:
print("Current Pos {}".format(cur_pos))
if move == "left":
if cur_pos[0] > 0:
... |
import string
import re
def is_pangram(s):
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
sentence = []
for l in s:
l = l.lower()
if re.match("[a-z]",l):
if l not in sentence:
... |
# Write a program which accept number from user and print that number of $ & *
#on screen.
#Input : 5
#Output : $ * $ * $ * $ * $ *
#Input : 3
#Output : $ * $ * $ *
#Input : -3
#Output : $ * $ * $ *
def main():
no=int(input("Enter the number : "))
for i in range(no):
print("$"+"\t"+"*"+"\t",en... |
# Write a program which accept string from user and copy the
# contents of that string into another string. (Implement strncpy() function)
# Input : “Marvellous Multi OS”
# 10
# Output : “Marvellous
def StrNCpyX(strs,no):
list1=list(strs) # to convert string into array(list)
... |
# Accept N numbers from user and display summation of digits of each
# number.
# Input : N : 6
# Elements : 8225 665 3 76 953 858
# Output : 17 17 3 13 17 21
def DigitsSum(arr,no):
Sum=0
for x in range(0,no):
No=arr[x]
while No !=0:
Digit=No%10
Su... |
import pandas as pd
import sqlalchemy as sq
def get_database_connection():
"""
Used to retrive database configuration from file
"""
db = pd.read_csv('dbconfig.csv')
for line, row in db.iterrows():
username = row['username']
password = row['password']
server = row['server']
... |
# -*- coding: utf-8 -*-
"""
@author: Asish Yadav
"""
dicti = {1:'bed', 2:'bath' , 3:'bedbath' , 4:'and' , 5:'beyond'}
arr = []
string = "bedbathandbeyond"
p = 0
for i in range(len(string)):
for key in dicti:
if string[p:i+1] == dicti[key]:
arr.append(string[p:i+1])
p ... |
# - * - coding:utf8 - * - -
'''
@ Author : Tinkle G
'''
def checkdigits(s):
try:
float(s)
return True
except:
return False
def checkdigits_(s):
return any(char.isdigit() for char in s)
def jaccard_distance(tem,que):
cnt = 0
ret = []
for idx in range(len(que)):
... |
print('''pick one:
foarfece
hartie
piatra''')
print(" ")
print(" ")
while True:
game_dict = {"piatra" : 1, "foarfece" : 2, "hartie" : 3}
player1 = input("Player A: ")
player2 = input("Player B: ")
a = game_dict.get(player1)
b = game_dict.get(player2)
dif = a-... |
# handles horizontal rotation
def horizontal_move_checker(num, list, index):
if num > len(list[index[0]]) - 1:
num = 0
if num < 0:
num = len(list[index[0]]) - 1
return num
# prevents vertical movement off the board
def vertical_move_checker(num, list, index):
if num > len(list) - 1:... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 20:01:42 2020
@author: Julio
"""
''' Using numpy.zeros '''
from numpy import zeros
student_numb = int(input("Enter number of students: "))
gpa = zeros(student_numb,float)
i = 0
while i < student_numb:
gpa[i] = float(input("Enter the GPA of student: ")... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 18:16:38 2020
@author: Julio
"""
''' We are creating a 3D function '''
import numpy as np
import matplotlib.pyplot as plt
''' Creating a 2D function: sinusoidal 2D '''
# Like solutions of wave or Schr. equations.
# Rectangular boundary conditions
def fsin(x, y, m, ... |
#for the print of star
i=1
#spacing
j=2
while (i>=1):
a=" "*j+"*"*i+" "*j
print(a)
i+=2
j-=1
if i>5:
break;
j=1
i=3
while i>=1:
a=" "*j+"*"*i+" "*j
print(a)
j+=1
i-=2 |
# 定义一个列表
a = [1,2,3,4,5,6]
# 循环打印所有元素
for i in a:
print(i)
|
def isprime(n):
n *= 1.0
if n %2 == 0 and n != 2 or n % 3 == 0 and n != 3:
return False
for b in range(1, int((n ** 0.5 + 1) / 6.0 + 1)):
if n % (6 * b - 1) == 0:
return False
if n % (6 * b + 1) == 0:
return False
return True
def main():
f = open('pi.t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import os
import sys
class Replacer:
_BOTH_CASE_CHARS = """
а,a
е,e
о,o
р,p
с,c
х,x
"""
_UPPERCASE_CHARS = """
З,3
К,K
М,M
Н,H
Т,T
"""
_LOWERCAS... |
import random
import sys
import string
a=string.ascii_lowercase
b=string.ascii_uppercase
c=string.digits
d=string.punctuation
def gen():
print("Enter the password length")
e = int(input())# Enter password length
f = random.randint(1,e-3)
g = random.randint(1,e-f-2)
h = random.randint(1,e... |
import pprint
import random
import warnings
import numpy as np
from strategy import Game
pp = pprint.PrettyPrinter(indent=4)
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
def get_user_input():
pay_to_play = input(
"\nHow much would you like to bet? Input an amount with number... |
"""
A Python list is similar to an array in other languages. In Python, an empty
list can be created in the following ways
"""
my_list = []
my_list = list()
"""
As you can see, you can create the list using square brackets or by using the
Python built-in, list. A list contains a list of elements, such as st... |
# This subprogram calculate digit sum
import sys
import os
if __name__ == '__main__':
# Get process arguments
argv = sys.argv[1::]
result = 0
if len(argv) >= 2:
for i in argv:
result += int(i)
print('Result: ' + str(result)) |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import *
def qqplot(x_array, qpoints = 100):
## Standarlize the dataset
x_array_norm = (x_array - np.mean(x_array))/np.std(x_array)
## Here only consider 99 points. So that we will consider 1%, 2%,...,99%
x_leng = len(x_array)
... |
# coding:utf-8
import time
def fibrac(x):
if (x == 1 or x == 2):
return 1
return fibrac(x - 1) + fibrac(x - 2)
start = time.clock()
a = fibrac(45);
end = time.clock()
print("=======", a);
print("=======", (end-start)*1000);
|
#
# @lc app=leetcode.cn id=7 lang=python
#
# [7] 整数反转
#
# https://leetcode-cn.com/problems/reverse-integer/description/
#
# algorithms
# Easy (32.22%)
# Total Accepted: 111.9K
# Total Submissions: 347.4K
# Testcase Example: '123'
#
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
#
# 示例 1:
#
# 输入: 123
# 输出: 321
#
#
# 示例 ... |
#
# @lc app=leetcode.cn id=231 lang=python3
#
# [231] 2的幂
#
# https://leetcode-cn.com/problems/power-of-two/description/
#
# algorithms
# Easy (44.89%)
# Total Accepted: 16.1K
# Total Submissions: 35.9K
# Testcase Example: '1'
#
# 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
#
# 示例 1:
#
# 输入: 1
# 输出: true
# 解释: 2^0 = 1
#
# 示例 2... |
print("I will now count my chickens.")
print("Hens", 25.0 + 30.0 /6.0) # order of operation 30/6 = 5 plus 25 = 30
print ("Roosters", 100.0 - 25.0 * 3.0 % 4.0)
print("Now I will count the eggs")
print( 3.0 + 2.0 + 1.0 -5.0 + 4.0 % 2.0 -1.0 / 4.0 + 6.0)
print("Is it true that 3.0 + 2.0 < 5.0 - 7.0?")
print (3.0 + ... |
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def show(self):
print "Show Person Details"
def rev(self,name):
st=""
for i in range(len(name),0,-1):
st=st+name[i-1]
print("kkk: "+st)
def list_fr(self):
fr=["ap... |
"""
This file will contain the GameModel, used to...model the game model in the model/controller/view framework. Technically
this is an abstract class and/or informal interface, which will be implemented by specific game models for flexibility.
TODO should the controller ask the model for text, or should the model tel... |
"""
This file is for code relating to commands - they connect an expected input pattern to an in-game effect.
- Started 5/25/20, by Andrew Curry
- reworked 7/28/20, to put the text parsing logic in here, as well as minor refactoring and including how command data
is loaded
- tweaked text parsing to allow for m... |
number = float(input("실수입력 >>"))
print(number * 3)
|
#주석문..코드상의 결과에 영항을 미치지 않음
#그 코드의 설명을 적는다
def typecheck(val):
print(type(val))
p = 0 #p 정수변수
s = "i love you" #s는 문자열 변수
w = 2.5 #w는 실수 변수
d = True #d는 부울 변수(True, False)
print(p)
print(s)
print(w)
print(d)
result = type(p)
print(type(p), type(s), type(w), type(d))
typecheck(p)
typecheck(s)
typecheck(w)
typechec... |
#2020년 나이를 기반으로 학년계산
birth = int(input("태어난 년도를 입력하세요 >>"))
age = 2020 - int(birth) + 1
print(age,"세")
if age <= 26 and age >= 20:
print("대학생")
elif age < 20 and age >= 17:
print("고등학생")
elif age < 17 and age >= 14:
print("중학생")
elif age < 14 and age >= 8:
print("초등학생")
else:
print("학생이 아님") |
#두수를 입력 받아 대소관계 비교
num1 = int(input("첫번째 수를 입력하시오\n"))
num2 = int(input("두번째 수를 입력하시오\n"))
if num1 > num2:
print(num1, ">", num2)
elif num1 < num2:
print(num1, "<", num2)
else:
print(num1, "==", num2) |
# SCRIPT: replaceNeg.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: Input a list of integers containing both positive and negative numbers.
# You have to print a list in which all the negative integers of this list are re... |
#-----------------------------------------------------------------#
# SCRIPT: listGen.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: A Python program which accepts a sequence of comma-separated numbers from the user and generates a list... |
# SCRIPT: computePerf.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: Compute the performance of list comprehension vs. a for loop.
# Write two functions and use the Python time module to measure their execution time.
imp... |
# SCRIPT: cipherClient.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: A Python program that decodes hidden messages, specifically - Caesar Ciphers utilizing the standard English alphabet.
# Our Caesar Cipher will be based... |
from tkinter import *
import math
class Risanje:
def __init__(self,master):
# ustvarimo platno
self.platno=Canvas(master,width=500,height=500)
self.platno.pack() #z pack umestiš na platno
#piramida(self.platno,8,400,50,20)
#tarca(self.platno,8,150,200,10)
#trikotnik(s... |
"""
Nick Conway Wyss Institute 02-02-2010
Parses a basecall file
The basecall file is parsed as follows since it is a tab delimited text
file
FLOWCELL# LANE# IMAGE# BEAD# N Xtab FLAG
0 1 2 3 length-1
one basecall file per lane
... |
##This program is used to determine the most frequent k-mer (using k=3 as an example) in a given DNA sequence.
import itertools
def countkmers(sequence, k = 3):
bases = ["A","T","C","G"]
kms = [''.join(x) for x in itertools.product('ATGC', repeat=3)] ## create all possible conbinations of k-mers as a dictiona... |
import sys
sum = 0
n = 0
#sum input values
for number in open('data.txt'):
suma+=float(number)
new_change
n +=1
print suma/n
new_sth
#comment
## Hi! I'm just writting a comment!! Did not modify anything else!! :-)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
dummy = ListNode(0, head)
newbegin = dummy
... |
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def quickSort(nums, l, r):
if l >= r: return
flag = nums[r] # random better
s = l
for i in range(l, r):
if nums[i] < flag:
if i != s:
... |
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.d[key].append((value, timestamp))
def get(self, key: str, timestamp: int) -> str:
if... |
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
x = click[0]
y = click[1]
m = len(board)
n = len(board[0])
a = board[x][y]
if a == 'M':
board[x][y] = 'X'
elif a == 'E':
nu... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
fast = head
slow = head
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
lmin = self.minDepth(root.left)
rm... |
################################
# CPE 101
# Section: 15
# Lab 1, Problem Set 1
# Name: Tyler Lian
# Cal Poly ID: tklian
################################
if __name__ == "__main__":
#### Problem #1 ####
# initialize variables
original_number = 0
# obtains user input and makes the string an int
us... |
################################
# CPE 101
# Section: 15
# Lab 1, Problem Set 1
# Name: Tyler Lian
# Cal Poly ID: tklian
################################
if __name__ == "__main__":
# initializes variables
number = ""
subtract = 0
# gets input from user
number = input("Enter a number: ")
numbe... |
import functions
number_list = []
i = 0
while i !=3:
numstr = input("Enter a number: ")
numint = int(numstr)
if functions.input_ok(numint):
number_list.append(numint)
i += 1
else:
print("Input must be less than one hundred and greater than zero")
for j in number_list:
... |
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enque(self, item):
self.items.append(item)
def dequeue(self):
if len(self.items) < 1:
return None
return self.items.pop()
def print_stack(self):
... |
cardNumber = int(input("Enter your credit card number without spaces: "))
def isValid(number):
number = str(number)
cardIsValid = False
result = sumDoubleEvenLocation(number) + sumOddLocation(number)
prefix = isPrefix(number, "4") or isPrefix(number, "5") or isPrefix(number, "6") or isPrefix(number,... |
name = input("Enter your name: ")
print("Hello " + name + "!")
age = input("How old are you?: ")
print("Therefore, " + name + " is " + age + " years old!")
num1 = input("Type in a number: ")
num2 = input("Type in another number: ")
result = float(num1) + float(num2)
print(result) |
from abc import ABCMeta, abstractmethod
# Definition of mothods to build complex objects
class JourneyBuilder(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def transportType(transport):
"Transport type"
@staticmethod
@abstractmethod
def originLocation(origin):
"Origin loc... |
import os
import matplotlib.pyplot as plt
from Perceptron import perceptron
from LogisticRegression import logistic_regression
from DataReader import *
data_dir = "../data/"
train_filename = "train.txt"
test_filename = "test.txt"
img_index = 0
def visualize_features(X, y):
'''This function is used to plot a 2-D scat... |
number = int(input("Введите число: "))
result = int(number) + int(str(number) + str(number)) + int(str(number) + str(number) + str(number))
print(result)
|
def add(n):
n += 1
return n
def main():
n = 1
print(n)
n = add(n)
print(n)
if __name__ == '__main__':
main() |
import Mahjong
from Mahjong import Tile
class Player:
MAX_HAND_SIZE = 13
''' defines a new player'''
def __init__(self, name: str, turn: int):
self.name = id
''' player's tiles'''
''' open is a tuple (triplet as a list, position to be tilted)'''
self.open = []
... |
# 7-7. Infinity: Write a loop that never ends, and run it (To end the loop, press
# ctrl-C or close the window displaying the output )
count = 1
while count <= 5:
print(count) |
# 8-6. City Names: Write a function called city_country() that takes in the name
# of a city and its country The function should return a string formatted like this:
# "Santiago, Chile"
# Call your function with at least three city-country pairs, and print the value
# that’s returned
def describe_city(city... |
# Create a new list from a two list using the following condition
# Given a two list of numbers, write a program to create a new list such that the new list should contain odd numbers from the first list and even numbers from the second list.
# Given:
# list1 = [10, 20, 25, 30, 35]
# list2 = [40, 45, 60, 75, 90]
#... |
# 7-6. Three Exits: Write different versions of either Exercise 7-4 or Exercise 7-5
# that do each of the following at least once:
# • Use a conditional test in the while statement to stop the loop
# • Use an active variable to control how long the loop runs
# • Use a break statement to exit the loop when the us... |
# 7-5. Movie Tickets: A movie theater charges different ticket prices depending on
# a person’s age If a person is under the age of 3, the ticket is free; if they are
# between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is
# $15 Write a loop in which you ask users their age, and then tell t... |
# from requests.api import options
# import streamlit as st
# import pandas as pd
# import numpy as np
# import requests
# # Draw a title and some text to the app:
# '''
# # Data Product Manager - Decision Dashboard
# Below results are for .
# '''
# ticker_option = add_tickerbox = st.sidebar.selectbox(
# "... |
import time
import argparse
from OuriIA import *
from OuriBoard import *
#players
MINIMAX = "Minimax"
ALPHABETA = "Alphabeta"
PLAYER = "Player"
#levels of analysis and correspondent search depth
MINIMAX_5 = 7
MINIMAX_15 = 9
MINIMAX_30 = 10
ALPHABETA_5 = 11
ALPHABETA_15 = 13
ALPHABETA_30 = 15
def match_level(algorit... |
import numpy as np
from cs231n.layers import *
from cs231n.fast_layers import *
from cs231n.layer_utils import *
class ThreeLayerConvNet(object):
"""
A three-layer convolutional network with the following architecture:
conv - relu - 2x2 max pool - affine - relu - affine - softmax
The network operates o... |
#Sign your name: DannyH
'''
1. Make the following program work.
'''
print("This program takes three numbers and returns the sum.")
Total = 0
for i in range(3):
NumberBeingAdded = float(input("Enter a number: "))
Total += NumberBeingAdded
print("The total is:",Total)
'''
2. Write a Python progra... |
class Animal:
def __init__(self, species, age, name, gender, weight, life_expectancy):
self.species = species
self.age = age
self.name = name
self.gender = gender
self.weight = weight
self.is_alive = True
self.life_expectancy = life_expectancy
def grow(se... |
def collatz(z):
if z == 1:
print("Three cheers to Collatz!")
elif z%2 == 0:
print(int(z/2))
collatz(int(z/2))
else:
print(3*z+1)
collatz(3*z+1)
def colWhile(z):
i = 0
while z != 1:
if z%2 == 0:
z = int(z/2)
else:
z = 3*... |
# Linear and Polynomial Regression
#
# This file is made by Faris D Qadri at 03.03.21
# Property of PCINU Germany e. V. @winter project 2020
# Github: https://github.com/NUJerman
# Source code: https://towardsdatascience.com/random-forest-in-python-24d0893d51c0
#
# In this file I will explain you how to use linear and ... |
#!/usr/bin/python3
def weight_average(my_list=[]):
if len(my_list) == 0 or my_list is None:
return 0
dividendo = 0
divisor = 0
for i in range(len(my_list)):
dividendo += my_list[i][0] * my_list[i][1]
divisor += my_list[i][1]
return dividendo / divisor
|
class Shoe(object):
def __init__(self,brand,model,color,size):
self.brand = brand
self.model = model
self.color = color
self.size = size
self.tied = False
self.steps = 0
def tie(self):
self.tied = True
print "{} {}'s laces are now tied, ph... |
import random
class Coin:
def __init__(self):
self.__sideup = 'Heads'
def flip(self):
if random.randint(0,1) == 0:
self.__sideup = 'Heads'
else:
self.__sideup = 'Tails'
def get_sideup(self):
return self.__sideup
coin = Coin()
|
def apply_transformations(df, transformations):
"""
Apply transformations to pandas data frame
:param df: Pandas data frame on which to apply transformations
:type df: Pandas data frame
:param transformations: A dictionary of transformations.
Example: transformations={
"RENAME:Bi... |
print("整数値を3つ入力してください")
x = int(input("1つ目の値:"))
y = int(input("2つ目の値:"))
z = int(input("3つ目の値:"))
if x==y==z:
print("同じ値です")
else:
print("最大の値は{}です。".format(max([x,y,z]))) |
print("0~100 までの 得点(整数値) を2 つ入力してください")
x = int(input("1つ目の得点:"))
y = int(input("2つ目の得点:"))
if x>=60 and y >=60:
print("合格です")
else:
print("不合格です") |
print("文字を2つ入力してください。")
x = str(input("1つの文字"))
y = str(input("2つの文字"))
if x==y:
print("同じ文字です")
else:
print("異なる文字です") |
import math
# # Create a function called calc_dollars. In the function body, define a dictionary
# # and store it in a variable named piggyBank. The dictionary should have the
# # following keys defined. quarters,dimes, nickels, and pennies
# # For each coin type, give yourself as many as you like.
def calc_dollars... |
from urllib2 import urlopen
import json
import numpy as np#kind of array for fast manipulation
def crimeWeight(lati, longi, hr):#latitude longitude hour
#basically this function will return crime weight at the given latitude in 200 meter radius.
url = "https://data.phila.gov/resource/sspu-uyfa.json?$$app... |
"""
Draw a circle out of squares
"""
import turtle
frank = turtle.Turtle()
def square(t):
for i in range(4):
t.fd(100) # move forward 100 units
t.rt(90)
t.speed(10) # turn right 90 degrees
def draw_art():
# Instantiate a Screen object, window. Then customize window.
w... |
# Python 2.7
# 6
# More Passing Arguments
# The definition for a function can have several parameters,
# because of this, a function call may need several arguments.
# There are several ways to pass arguments to your functions...
# Positional Arguments
# need to be in the same order the parameters were w... |
"""
A simple interactive calculator program
Operators handled: addition (+), subtraction (-), multiplication (*), division (/)
"""
# initial user input/variables
number1 = raw_input("Give me a number: ")
number2 = raw_input("Give me another number: ")
# uncomment below to convert string input to integers (to make cal... |
# Python 2.7
# Directions:
# Make a dictionary called favorite_cities.
# Think of three names to use as keys (or ask three real people),
# and store at least one favorite city for each person.
# Finally, loop through the dictionary, then print each person's name
# and their favorite cities.
# To h... |
# Add the calculator with turtle
import turtle
frank = turtle.Turtle()
number1 = int(raw_input("Please give me a number "))
number2 = int(raw_input("Please give me a number "))
operation = raw_input("What operation would you like me to perform? ")
if operation == '+':
answer = number1 + number2
elif operatio... |
"""
A simple program checking height requirements for a rollercoaster.
Objective:
multi-way condition statement
"""
# Ask user for their name
# The value gets stored in the variable, name
name = raw_input("What is your name? ")
# Ask user for their height
# The value gets stored in the variable, height
# concate... |
import turtle
frank = turtle.Turtle()
def calc(number1, number2, operation, color):
if operation == "+":
answer = number1 + number2
elif operation == "-":
answer = number1 - number2
elif operation == "*":
answer = number1 * number2
elif ... |
"""
Example exercise on python lists:
how they're structured and what you can do with them.
"""
foods = ['apple']
foods.append('orange')
foods.extend(('yams','bannanas','tomatoes','TOES'))
#foods = [apples,orange,yams,bannanas,tomatoes]
print(foods[1])
if'apple' in foods:
print("TRUE")
for food in foods:
print food.... |
# Using a while loop with lists
# Python 2.7
# Objective: move items from one list to another
# Consider a list of newly registered but unverified users of a website. After we
# verify these users, we need to move them to seperate list of confirmed users.
# From what we just learned, we can use a while loop to pull u... |
# Choose your own adventure game
# WIZARD MOUNTAIN
# To be run in Python 2.7
# Change the functions, raw_input(), to input(), if you run in Python 3 or higher
# a text-based choose your own adventure game
# This adventure is like an upside down tree with branches
# this program is full of blocks of code, known as bra... |
"""
Calls methods from the Turtles class to
output a simple turtle race using Turtle Graphics
"""
import turtle
from racer_class import Turtles
# Calling methods from Turtles class
# methods:
# Defines All Turtles
red = Turtles(turtle) # __init__()
green = Turtles(turtle) ... |
"""
Draw a circle out of squares
"""
import turtle
def draw_square(frank):
for i in range(4):
frank.forward(100) # move forward 100 units
frank.right(90) # turn right 90 degrees
def draw_art():
# Instantiate a Screen object, window. Then customize window.
window = turtle.Screen... |
# Python 2.7
# Example from Python Crash Course by Eric Matthes
# Using break to Exit a loop
# So far, we've looked at stopping a while loop by using a flag variable
# You can also use a BREAK statement...
# To exit a while loop immediately without running any remaining code in the loop,
# regardless of the results o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.