text stringlengths 37 1.41M |
|---|
import heapq
def segemet(x,arr):
if x== len(arr):
return min(arr)
tmp = arr[:x]
heapq.heapify(tmp)
rtn_val = heapq.nsmallest(1, tmp)[0]
# print(rtn_val)
for i in range(x, len(arr)):
tmp.remove(arr[i-x])
tmp.append(arr[i])
small = heapq.nsmallest(1, tmp)[0]
... |
def isArmstrong( N):
digits = len(str(N))
rtn_num = 0
for each_dig in str(N):
rtn_num += pow(int(each_dig), digits)
if rtn_num == N:
return True
else:
return False
if __name__ == '__main__':
N = 153
print(isArmstrong(N)) |
def maxSlidingWindow( nums, k):
if k == 0:
return 0
max_val = nums[0]
max_arr = []
for i in range(0, k):
if nums[i] > max_val:
max_val = nums[i]
max_arr.append(max_val)
print(max_arr)
for i in range(k, len(nums)):
if nums[i-k] >= max_val:
max_v... |
def licenseKeyFormatting( S, K):
S = S.replace('-','')
str_len = len(S)
parts = int(str_len/K)
first = 0
if str_len%K !=0:
first =str_len%K
rtn_str = S[0:first].upper()
pivot = first
for j in range(parts):
rtn_str = rtn_str + '-' + S[pivot:pivot+K].upper()
pivot... |
class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
dict = {
5 : 0,
10 : 0
}
for each_ in bills:
if each_ == 5:
dict[5] +=1
elif each_ == 10:
... |
class Solution(object):
def balancedStringSplit(self, s):
"""
:type s: str
:rtype: int
"""
rtn = 0
cnt = 0
for each_ in s:
if each_ == 'L':
rtn +=1
else:
rtn -=1
if rtn ==0:
cn... |
from collections import deque
class PhoneDirectory(object):
def __init__(self, maxNumbers):
"""
Initialize your data structure here
@param maxNumbers - The maximum numbers that can be stored in the phone directory.
:type maxNumbers: int
"""
self.nums = deque()
... |
def maxProfit( prices):
cnt = 0
if len(prices) ==0:
return 0
for i in range(0,len(prices)-1):
if (prices[i+1]- prices[i]) > 0:
# print((prices[i+1], prices[i]))
cnt += (prices[i+1]- prices[i])
# print(cnt)
return cnt
if __name__ == '__main__':
... |
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
oper = '+'
dig = ''
for e in s:
if not e.isspace():
# print(e)
if e.isdigit():
dig+=e
... |
def isValid( s):
if len(s) % 2 != 0:
return False
rtn_list = []
for each_char in s:
if each_char in ['(', '[', '{']:
rtn_list.append(each_char)
elif each_char == ')':
if len(rtn_list) == 0 or '(' != rtn_list.pop():
return False
elif eac... |
def majorityElement( nums):
dump = {}
for each_num in nums:
if each_num in dump:
dump[each_num] +=1
else:
dump[each_num] = 1
for each_key in list(dump.keys()):
if dump[each_key] > int(len(nums)/2):
return each_key
if __name__ == '__main__':
nu... |
def totalFruitold1( tree):
max_ln = 2
temp_set = set()
temp_count = 0
index = 0
las_ele = tree[0]
las_index = 0
while index < len(tree):
# print(index)
if tree[index] in temp_set:
temp_count +=1
if las_ele != tree[index]:
las_ele = tree... |
def merge( intervals):
intervals.sort(key = lambda x: x[0])
# print(intervals)
rtn_list = []
while len(intervals) > 1:
# print(rtn_list, intervals)
if intervals[0][1] >= intervals[1][0]:
if intervals[0][1] >= intervals[1][1]:
new_ele = [intervals[0][0], inter... |
from collections import deque
class Solution(object):
def onBoundary(self, a, b):
if a == 0 or a == self.rows-1 or b ==0 or b == self.cols-1:
return True
return False
def solve(self, board):z`
"""
:type board: List[List[str]]
:rtype: None Do not return anyt... |
def uniquePaths( m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
numer = 1
demer = 1
k = n
if m < n:
k = m
for i in range(0, k - 1):
print(numer )
numer = numer * (m + n - 2 - i)
for i in range(1, k):
demer = demer * i
print(numer, de... |
class Solution(object):
def tictactoe(self, moves):
"""
:type moves: List[List[int]]
:rtype: str
"""
acount = 0
bcount = 0
ttt = [["" for _ in range(3)] for _ in range(3)]
isA = True
def check(char):
for i in range(3):
... |
class Solution(object):
def __init__(self):
self.rtn = set()
def palCheck(self, s, i, j):
while(i>=0 and j< len(s) and s[i] == s[j]):
self.rtn.add(str(i)+'#'+str(j))
i-=1
j+=1
def countSubstrings(self, s):
"""
:type s: str
:rtyp... |
#Ciara McMullin
# assignment 7
# section 2
# part 2
#part 2b
name = input("Name: ")
new_name = name.lower()
name_good = ""
for i in new_name:
if i.isalpha() == True:
name_good += i
print ("Your 'cleaned up' name is: ", name_good)
total = 0
length = len(name_good)
num = 0
for character in ... |
# Ciara McMullin
#intro to programming section 2
# assignment 6
# import functions and random
import myfunctions
import random
# PART 2G
# ask for problems
while True:
problems = int(input("How many problems would you like to attempt? "))
if problems <= 0:
print("Invalid number, try again")
e... |
# Ciara McMullin
# Assignment 8
# part 2
#product lists
product_names = ["salad", "chicken", "fruit"]
product_costs = [0.99, 1.29, 1.49]
product_amount = [10, 5, 20]
# create while loop for input
while True:
options = input("(s)earch, (l)ist, (a)dd, (r)emove, (u)pdate, r(e)port or (q)uit: ")
# option of search; u... |
import numpy as np #we use numpy for many things
def main():
i=0 #declare i equal to 0
n=10 #declare n equal to 10
x=119.0 #float x, these have a .
#we can use numpy to quickly make arrays
y = np.zeros(n,dtype=float) #declare 10 zeros
#we can use four loops to iterate through a variable
for i in range(n):... |
"""
Uzrakstiet programmu, kas ielasa vienu vārdu
un izvada uz ekrāna sveicienu sekojošā formātā:
"Labdien, vards, pimrdienā!"
Ja ievadīts nav jūsu vards, tiek izdrukāts teksts - Uzredzēšanos!
Pārbaudiet programmas darbību ar dažādiem ievaddatiem.
"""
vards=str(input("Ievadi savu vārdu: "))
print("Labdien, "... |
import pygame
import math
import random
from pygame.locals import*
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (10, 255, 10)
BLUE = (10, 10, 255)
RED = (255, 10, 10)
GREY = (100, 100, 100)
Prompt = input("Pick a color to draw with: \n a) Blue \n b) Green \n c) Red \n d) Confuse Me \n")
if Prompt == "a":
CO... |
testList = [1,2,3]
print(testList)
#append
testList.append(4)
print(testList)
#insert
testList.insert(1,1.5)
print(testList)
#delete
del testList[2]
print(testList)
#pop
popValue = testList.pop()
print(popValue)
print(testList) |
#!/usr/bin/python3
#-*-coding:utf-8 -*-
'''
题目:20、有效的括号 isValid
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
思路
利用栈
'... |
import json
from functools import wraps
def load_response(arg):
""" A magic wrapper for Dolead API functions. The return type of the wrapped
function has to be a response object from the requests module.
It can work in two ways :
>>> @load_response
>>> def my_api_call(*args):
>>> return ... |
# Author: CRS 9/30/21
magic_charge = int(input("Please input your magic charge value."))
shield_charge = int(input("Please input your shield charge value."))
if ((magic_charge >= 90 and shield_charge >= 75)):
print("You defeated the dragon! But the princess is in another castle.")
else:
print("The dragon burns ... |
import feature
import gameState
import room
import obj
import sys
from parser import Parse
playerIsAlive = True
gameWon = False
def printScreen(screen_file):
with open(screen_file) as input_file:
for line in input_file:
sys.stdout.write(line)
def getGametype():
while 1:
game_type = input("(N)ew game o... |
#cabeçalho #EXERCICIO 4
text = 'cadastrar produtos.py v1.0'
tam = len(text)
print('+','-' * tam,'+')
print('|',text,'|')
print('+','-' * tam,'+')
list = []
#funcao que adiciona os dicionarios na lista
def cad_prodt(cad: dict):
list.append(cad)
return
#coleta de dados e o chamado da funcao para adicionar os d... |
"""This program defines the Die class. We then define and implement the __init__, __str__, roll, and
get_value methods. We play a game of two rounds of dice rolls and we print the values of each round. """
import sys
import random
__author__ = "Alex Mansour"
__license__ = "GPL"
__version__ = "1.0.1"
__dat... |
# Phyllis Torres
# This program will read a text file of words and find words that have three consecutive double letters
# Define variables
tripleLetterWords = 0
noTripleConsec = 0
totalWords = 0
# Define input file
fin = open('words.txt')
print ('Words Containing Three Consecutive Double Letters\n')
... |
# Course: CS261 - Data Structures
# Student Name: Casey Levy
# Assignment: Assignment 2 - stack_da.py
# Description: Writing push, pop, and top methods for Stack class
# Last revised: 10/19/2020
from dynamic_array import *
class StackException(Exception):
"""
Custom exception to be used by Stack class
DO... |
import random
def genList(length, maximum):
a = []
for x in range(0,length):
b = random.randint(1,maximum)
a.append(b)
return a
arr = genList(10,15)
while True:
try:
limit = input('Clean out numbers above what point? ')
limit = int(limit)
except ValueError:
... |
"""
>>> sll1 = singly_linked_list([1])
>>> sll2 = singly_linked_list([2])
>>> print add_lists(sll1, sll2)
[3]
>>> sll1 = singly_linked_list([1, 2])
>>> sll2 = singly_linked_list([3, 4])
>>> print add_lists(sll1, sll2)
[4 -> 6]
>>> sll1 = singly_linked_list([6, 1, 7])
>>> sll2 = singly_linked_list([2, 9, 5])
>>> print a... |
"""
>>> are_permutations("abc", "cab")
True
>>> are_permutations("abc", "aab")
False
>>> are_permutations("abcd", "abc")
False
>>> are_permutations("", "")
True
>>> are_permutations("a", "a")
True
>>> are_permutations("aaa", "aaa")
True
>>> are_permutations("aaa", "aaaa")
False
>>> are_permutations("aab", "abb")
False
... |
"""
>>> find_additions([1,2,3], [2,3,4])
[4]
>>> find_additions([1,2,3], [3,4,5])
[4, 5]
>>> find_additions([1,2,3], [])
[]
>>> find_additions([], [1,2,3])
[1, 2, 3]
>>> find_additions([], [3,2,1])
[3, 2, 1]
"""
def find_additions(prev, cur):
prev_set = set(prev)
return filter(lambda item: item not in prev_set, cu... |
"""
>>> print is_palindrome(singly_linked_list([1]))
True
>>> print is_palindrome(singly_linked_list([1, 1]))
True
>>> print is_palindrome(singly_linked_list([1, 2]))
False
>>> print is_palindrome(singly_linked_list([1, 2, 1]))
True
>>> print is_palindrome(singly_linked_list([1, 2, 3]))
False
>>> print is_palindrome(si... |
"""
>>> pascal(0,0)
1
>>> pascal(1,1)
1
>>> pascal(1,2)
2
>>> pascal(1,3)
3
>>> pascal(2,3)
3
"""
def pascal(x, y):
if x == 0 or x == y:
return 1
return pascal(x, y - 1) + pascal(x - 1, y - 1)
if __name__ == '__main__':
import doctest
result = doctest.testmod()
if result.failed > 0:
print "Failed:",... |
def TambahAkhir (digits):
hasil = digits[-1]+1
if hasil >= 10:
hasil = list(map(int, str(hasil)))
digits.pop()
digits.extend(hasil)
return digits
else:
digits.pop()
digits.append(hasil)
return digits
def main():
digits = [9,9]
print(TambahAkhi... |
import random
# actions
def turn_on_ac(agent_state, world_state):
agent_state['room_temp'] -= 1
world_state['temperature'] += 0.1
return agent_state, world_state
def turn_off_ac(agent_state, world_state):
agent_state['room_temp'] += 1
world_state['temperature'] -= 0.1
return agent_state, world... |
#we import these two class because we need them in our code
from tkinter import *
import random, time
# All images were drawn by Dennis Phan
# Collaboration course project by Dennis Phan and Cheng-Hsi Li
# This is our code for the game, rock,paper,scissors
# our code is run & divided into different chunk ... |
import numpy
def normalise_modular_range(value, min, max):
"""Normalises values (e.g. angles) into the range {min, max}"""
return numpy.mod(value-min, max-min)+min
def find_optimal_angle_window(angles, jump=5):
"""Find the optimal search window for the angles using a window of `jump`"""
# The optimal ... |
# 홀수, 짝수 판단 프로그램(3항 연산자)
# 1.숫자 1개 입력
# 2.홀짝 판단하여 "홀수", "짝수" 출력하기
print('숫자 하나 입력 : ')
num = input()
result = (int(num)%2==0) and '짝수' or '홀수'
print(result)
inNum = int(input('정수 입력: '))
outStr = (inNum %2==0) and '짝수' or '홀수'
print(outStr)
##################################
# 동전교환기 프로그램
###############... |
#These classes and methods are used to solve the Australian Voting problem.
# will simulate a candidate and keep track of the candidate's name, number of votes
# it has and which ballots are currently choosing this candidate
class Candidate:
# constructor for the candidate class
def __init__ (self, name,... |
"""
This module demonstrates the representing of graphs in dictionarys.
"""
#!/usr/bin/env python
#representig directed graphs
EX_GRAPH0 = {0: set([1,2]), 1: set([]), 2: set([])}
EX_GRAPH1 = {0: set([1,4,5]), 1: set([2,6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
EX_GRAPH2 = {0: set([1,4,5]), 1:... |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
class City(object):
'''creating a polynomial object'''
def __doc__():
return '''This City class provides a way to represnt cities'''
def __init__(self, name):
self.name = name
self.edges = dict()
def __st... |
"""Kata for Arithmetic Operators."""
print("Hello Arithmetic Operators!")
a = 10
b = 20
x = a + b
print(x)
x = a - b
print(x)
x = a * b
print(x)
x = b / a
print(x)
x = b % a
print(x)
x = a ** b
print(x)
x = 9//2
print(x)
x = 9.0//2.0
print(x)
x = -11//-4
print(x)
x = -11.0//3
print(x)
|
"""Kata for Lists"""
print("Hello Lists!")
mylist = ['abcd', 786, 2.23, 'john', 70.2]
tinylist = [123, 'john']
print(mylist) # Prints complete list
print(mylist[0]) # Prints first element of the list
print(mylist[1:3]) # Prints elements starting from 2nd till 3rd
print(mylist[2:]) # Pr... |
'''
Created on 10/11/19
@author: Sanjana Madhu, collaborator: Michael Gajdosik
Pledge: I pledge my honor that I have abided by the Stevens Honor System
CS115 - Hw 5
'''
from cs115 import map, reduce
# Number of bits for data in the run-length encoding format.
# The assignment refers to this as k.
COMPRESSED_... |
'''
Created on 10/9/19
@author: Sanjana Madhu
Pledge: I pledge my honor that I have abided by the Stevens Honor System
CS115 - Lab 6
'''
def isOdd(n):
#42 in base 2 is 101010
'''Returns whether or not the integer argument is odd.'''
return n % 2 == 1
def numToBinary(n):
'''Preconditio... |
"""
We want to turn the given integer into a number that has only one non-zero digit using a tail rounding approach.
This means that at each step we take the last non 0 digit of the number and round it to 0 or to 10. If it's less than 5 we
round it to 0 if it's larger than or equal to 5 we round it to 10 (rounding to... |
"""
Find the number of ways to express n as sum of some (at least two) consecutive positive integers.
Example
For n = 9, the output should be
isSumOfConsecutive2(n) = 2.
There are two ways to represent n = 9: 2 + 3 + 4 = 9 and 4 + 5 = 9.
For n = 8, the output should be
isSumOfConsecutive2(n) = 0... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
2D - Randomwalk
used array
Created on Tue Jan 17 23:21:43 2017
@author: Wool(wool@wool.pe.kr)
"""
import random
import matplotlib
import matplotlib.pyplot as plt
x = []
y = []
count = 1000
width = 50
x.extend([0])
y.extend([0])
for i in range(1, count):
x.ex... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 9 22:53:14 2017
@author: woolseo
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
ax.set(xlim=[0, 10], ylim=[0, 5])
ax.set_aspect('equal', adjustable='box')
ax.grid(True... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Wool(wool@wool.pe.kr)
"""
from numpy import *
import matplotlib.pyplot as plt
#import numpy as np
N = 1000
t_max = 10**5
p = 0.3
cnt = 0
multi = 1
a = 1
k=1
store_t = []
store_xx = []
store_x = []
vari = []
def randwalk(t):
n = []
for i i... |
# -*- coding: utf-8 -*-
# 라이브러리 불러오기
import seaborn as sns
# titanic 데이터셋에서 age, fare 2개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age','fare']]
print(df.head())
print('\n')
# 사용자 함수 정의
def missing_value(series): # 시리즈를 인수로 전달
return series.isnull() # 불린 시리즈를 반환
# ... |
# -*- coding: utf-8 -*-
# 라이브러리 불러오기
import pandas as pd
import seaborn as sns
# titanic 데이터셋에서 age, fare 2개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age','fare']]
print(df.head()) #첫 5행만 표시
print('\n')
print(type(df))
print('\n')
# 데이터프레임에 숫자 10 더하기
addition = df + 10
print(a... |
# -*- coding: utf-8 -*-
# 라이브러리 불러오기
import pandas as pd
# read_csv() 함수로 df 생성
df = pd.read_csv('./auto-mpg.csv', header=None)
# 열 이름을 지정
df.columns = ['mpg','cylinders','displacement','horsepower','weight',
'acceleration','model year','origin','name']
print(df.head(3))
print('\n')
# mpg(mile pe... |
# -*- coding: utf-8 -*-
# 라이브러리 불러오기
import seaborn as sns
# titanic 데이터셋에서 age, fare 2개 열을 선택하여 데이터프레임 만들기
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age','fare']]
print(df.head())
print('\n')
# 사용자 함수 정의
def min_max(x): # 최대값 - 최소값
return x.max() - x.min()
# 데이터프레임의 각 열을 인수로 전달하면 시리즈를 ... |
__author__ = 'Meemaw'
def median(aList,l,r):
a = aList[l]
b = aList[r]
mid = ((l+r)//2)-1 if (l+r) % 2 == 0 else (l+r)//2
c = aList[mid]
temp = [a,b,c]
median = sorted([a,b,c])[1]
if median == temp[1]:
aList[l], aList[r] = aList[r], aList[l]
elif median == temp[2]:
aLis... |
# 높이 n개의 계단을 올라가는 방법을 리턴한다
def staircase(stairs, possible_steps):
stair_list = [1, 1]
for i in range(2, stairs + 1):
count = 0
for step in possible_steps:
if i >= step:
count += stair_list[i - step]
stair_list.append(count)
return stair_list[stairs]
pr... |
# Binary Search
# 정렬이 되어있는 리스트의 중간값과 찾고자 하는 값 비교 -> 탐색범위 절반으로 계속 줄여나감
def binary_search(element, some_list):
start_index = 0
end_index = len(some_list) - 1
while start_index <= end_index:
mid_index = (start_index + end_index) // 2
if some_list[mid_index] == element: # 중간값이 찾고자 하는 값... |
# 거듭제곱 알고리즘의 시간복잡도를 N이 아닌 lgN 으로 만들기
def power(x, y):
if y == 0:
return 1
half = power(x, y // 2) # dynamic programming 을 하지 않으면 두번 호출해야 하기 때문에 n번
if y % 2 == 0:
return half * half
else:
return x * half * half
"""
def power(x, y):
if y == 1:
return x
if ... |
for i in range(1,5):
for k in range(1,3):
print(i+k) |
import requests
import urllib.parse as parse
import json
'''
大致流程是:
1.利用data构造内容,然后urlopen打开
2.返回一个json格式的结果、s
3.结果就是girl的释义
'''
baseurl = 'https://fanyi.baidu.com/sug'
#存放模拟form的数据一定是dict格式
data = {
#girl 是翻译输入的英文内容,应该用户输入,此处使用硬编码。
'kw':'girl'
}
print(type(data))
# 构造一个请求头,请求头应该至少包含输入数据的长度
# request要求传入的请... |
class Solution(object):
def contains_duplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
value_store = {}
flag = False
for i in nums:
if i not in value_store:
value_store[i] = 1
else:
value... |
import math
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
a = math.log(x, 2)
y = a/2
while y < a:
val = pow(2, y)
out = int(val)*int(val)
if out <= x:
return int(val)
... |
class WordDistance(object):
def __init__(self, words):
"""
initialize your data structure here.
:type words: List[str]
"""
self.stack_store = []
self.len_store = 0
self.words = words
self.len_words = len(words)
def shortest(self, word1, word2):
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def print_list(self, node):
while node is not None:
print(node.val)
node = node.next
def swapPairs(self, head):
... |
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
pointer_m = 0
pointer_n = 0
... |
class NumArray(object):
nums = []
"""
Idea is to store all the calculations once and then just refer the stored values to calculate further
"""
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums = nums
... |
import Queue
# 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 deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: T... |
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
val_store = [0 for i in range(0, n+1)]
for k in range(0, n+1):
if k == 0 or k == 1:
val_store[k] = 1
else:
val_store[k] = val_sto... |
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
version_list = []
def isBadVersion(version):
global version_list
if not version_list[version-1]:
return True
else:
return False
class Solution(object):
def firstBadVersion(self, n):
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
'''
边界条件比较多,空输入返回真,只有一个子树的节点判断。
'''
if root == None:
... |
"""
Demonstrates concatenation and appending strings
"""
united = "United" #Declares a variables named united and assigns the string literal "United" to it
states = "States" #Declares a variables named states and assigns the string literal "States" to... |
"""
Demonstrates swapping the values of two variables
"""
number1 = 65 #Declares a variable named number1 and assigns it the value 65
number2 = 27 #Declares a variable named number2 and assigns it the value 27
temp_number = number1 #Copies the reference of n... |
"""
Create a program that finds the average of some number of test scores.
First, prompt the user to enter the number of test scores to average.
Validate that their input is greater than zero.
Then, based on how many test scores the user specified, prompt the user
to enter each test score.
Validate that each test sco... |
"""
Demonstrates string indexes
"""
example = "Community College of Philadelphia"
first_character = example[0] #Gets and prints the first character in the string
print("The first character is", first_character)
character_fifteen = example[15] #Gets and prin... |
#Imports the Bicycle object
from bicycle import Bicycle
"""
Demonstrates the use of the Bicycle object
"""
#Creates an instance of a Bicycle Object with three arguments
test_bike = Bicycle(9, 12, "orange")
#ACCESSORS
#Prints test_bike's gear, speed, and color using accessor functions
print("test_bike's gear =", test... |
"""
Automobile Object.
"""
#Class Header
class Automobile :
#Initializer
def __init__(self, make_in, model_in, year_in) :
self.make = make_in
self.model = model_in
self.year = year_in
#Retrieves the make
def getmake(self) :
return self.make
#Changes the make
def setmake(self, make_in) :
... |
"""
Demonstrates the arithmetic operators
"""
apples = 15 #Declares a variable named apples and assigns it the value 15
oranges = 13 #Declares a variable named oranges and assigns it the value 13
total = apples + oranges ... |
"""
Demonstrates reading a csv file.
!!! Run csv_writing.py to create the example.csv file first !!!
"""
#Opens the existing file
csv_file = open("example.csv", "r")
#Reads/discards the first line (containing the headers)
#The line must be read, but since we aren't using the headers in
#this program, the line of tex... |
"""
Demonstrates deleting elements from lists.
"""
numbers = [8, 10, 5, 7, 3, 1, 10] #A list named numbers containing the values 8, 5, 7, 3 and 1
print("numbers:", numbers) #Prints the numbers list (in list form)
del numbers[2] #Deletes the third element from th... |
"""
Demonstrates trimming strings.
"""
example = "John Smith , 123 Any Street , Philadelphia , PA , 19019 "
tokens = example.split(",")
#Untrimmed
print("Name :", tokens[0], ".", sep="")
print("Street :", tokens[1], ".", sep="")
print("City :", tokens[2], ".", sep="")
print("State :", tokens[3], ".", se... |
"""
Demonstrates reading a file sequentially
"""
file_to_read = open("friends.txt", "r") #Opens the friends.txt file in read-only mode
for line in file_to_read : #Uses a loop to iterate over the lines of text of the file and print each line.
print(line.rstrip("\n")) ... |
"""
Demonstrates the else clause
"""
water_temp = int(input("Enter the water temperature: ")) #Gets the temperature of the water
if water_temp <= 32 : #Prints if the water is frozen (temperature is less than or equal to 32) or not frozen
print("The water is frozen.")
else :
... |
"""
Josh Popp
CS 4775
Homework 2 #2b
Script for computing sequence alignments using Needleman-Wunsch with
linear gap penalties.
Arguments:
f - FASTA file with sequences in FASTA format.
s - JSON with the score matrix for alignment.
d - The gap penalty for the alignment.
Outputs:
Prints alignment t... |
#!/usr/bin/env python3
# usage: $ oj generate-input 'python3 generate.py'
import random
# generated by online-judge-template-generator v4.4.0 (https://github.com/kmyk/online-judge-template-generator)
def main():
# n = random.randint(1, 10) # TODO: edit here
n = 10
x = [None for _ in range(n)]
y = [Non... |
#!/usr/bin/env python
l = []
m = {}
n = 0
while n != -1:
n = input("Please enter a number (-1 to stop):")
if n not in l:
l.append(n)
if n != -1:
if n not in m:
m[n] = 0
if n in m:
m[n] += 1
print l[0:len(l)-1]
for key in m:
print key, "occurred", m[key], "times"
|
#!/usr/bin/env python
import sys
with open(sys.argv[1], "r") as f:
li = f.readlines()
last = raw_input("Please enter a surname:")
i = 0
first = []
while i < len(li):
name = li[i].split()
if last.lower() == name[1].lower():
first.append(name[0])
i = i + 1
if len(first) == 0:
print "No-one has that sur... |
import itertools
import math
class Grid:
grid = {}
last = None
def __init__(self) -> None:
super().__init__()
self.set(0, 0, 1)
self.last = 0
def set(self, x, y, value):
self.grid[(x, y)] = value
def calculatePosition(self, x, y):
if (x... |
# 1 part — пример обозначения ко
# # -*- coding: cp1251 =*=
# s = 'Hello, мир'
# print (s)
# 2 part
# s = 'Hello, мир'
#
# data = s.encode('cp1251')
# print(data)
# 3 part — узнать код у конкретного символа
# for c in range(ord('a'), ord('z')+1):
# print(chr(c))
# 4 part — чтение файла с другой кодировкой
# ... |
#!/usr/bin/env python3
from typing import List
"""6.1 Interconvert strings and integers.
Implement an integer to string conversion function, and a string to integer
conversion function.
"""
def int_to_str(i: int) -> str:
is_negative = False
if i < 0:
is_negative = True
i = -i
ret = [... |
"""
Class representing the board and its data
"""
from Cell import Cell
from Observable import Observable
import random
from Element import Element
class Board(Observable):
def __init__(self, rows, cols):
super(Board, self).__init__()
self.rows = rows
self.cols = cols
... |
import sys
def generate_column_names():
letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
names = []
for letter in letters:
names.append(letter)
for letter in letters:
for second in letters:
names.append(letter + second)
for letter in letters:
for second in letters:
for third in letters:
names.appen... |
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if test == '':
continue
words = test.strip().split(' ')
longest_word = max(words, key=len)
result = ''
for index, char in enumerate(longest_word):
result += index * '*' + c... |
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if test == '':
continue
unique_numbers = []
unique_numbers = [integer for integer in test.strip().split(',') if integer not in unique_numbers and not unique_numbers.append(integer)]
print(','.join(unique_numbers)) |
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if test == '':
continue
chars = list(test.strip())
non_repeated_characters = [char for char in chars if chars.count(char) == 1]
print(non_repeated_characters[0])
|
import collections
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if test == '':
continue
wines, pattern = test.strip().split(' | ')
wines = wines.split(' ')
result = []
for wine in wines:
n_pattern = list(pattern)
n_wine = list(wine.lower())
for char in n_wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.