blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
f9ecd20bb04f7db53e4c0d3f4065851a4b11dd59 | GGOBOND/leetcode | /19_ Remove Nth Node From End of List.py | 1,345 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# dummy = ListNode(0)
# dummy.next = head
# p1 = p2 = dummy
# for i i... |
bbf0b56baf0c7d2ce9f24462cb7751661287b7b3 | J-Igor/Estruturas_Condicionais | /meusprojetos/15Notas_for.py | 260 | 3.75 | 4 | s = 0
for c in range(0, 15):
n = int(input('Digite suas médias: '))
s = s + n
print('A média entre todos os valores é igual a {:.1f}'.format(s/15))
if (n >= 7):
print('Parabéns, você foi aprovado!')
elif(n < 7):
print('Reprovado')
|
c2d783a45b11103a97ad3e7fdc33cfa668421a2f | avico83/learning | /ex4_var_print.py | 624 | 3.640625 | 4 | your_name = 'Zed A.Shaw'
your_age = 35 # no bulshit
your_height = 180 # centimeters
your_weight = 80 # kg
your_eyes = 'Blue'
your_teeth = 'white'
your_hair = 'brown'
print "Let's talk about %s." % your_name
print "He's %d inches tall." % your_height
print "He's %d kg heavy." % your_weight
print "Actually he's not too ... |
6b61831fe016a7ffce1f989e57328ede775085d5 | computingForSocialScience/cfss-homework-janeylee | /final_project/collectData.py | 2,254 | 3.515625 | 4 | import requests
import csv
def fetchTableInfo(tableID):
"""Downloads information about a particular table"""
url = "http://api.censusreporter.org/1.0/table/%s" % (tableID)
req = requests.get(url)
if not req.ok:
print "error in request"
data = req.json()
column_list = []
for key,v... |
42bfb35d408fc5f3660367882d4259c671b73157 | Daletxt/xiaojiayu | /game1.2 limit time.py | 1,058 | 3.984375 | 4 | print("Hello world")
temp = input("猜一下小甲鱼现在心里\
想的是哪个数字:\n""(你有5次机会)\n")
guess = int(temp)
if guess == 8:
print("卧槽,你是小甲鱼心里蛔虫吗?!")
print("哼,猜中了也没有奖励!")
else:
i = 0
while guess != 8:
i += 1
if guess != 8:
if guess > 8:
print("哥,大了大了~~\n你还有",(5-i),"次机会。\n")
else:
print("嘿,小了小了~~\n你还有",(5-i),"次机会。\n")... |
157b9be4565465ba4bfc855b0ee92f8660ebd12a | Daletxt/xiaojiayu | /xunhuan.py | 1,758 | 3.875 | 4 |
score = int(input('请输入一个分数:'))
if 100 >= score >= 90:
print('A')
if 90 > score >= 80:
print('B')
if 80 > score >= 60:
print('C')
if 60 > score >= 0:
print('D')
if score < 0 or score > 100:
print('输入错误!')
score = int(input('请输入一个分数:'))
if 100 >= score >= 90:
print('A')
else:
if 90 > score >= 80:
print('B')... |
5d8c8842d81a3a584e42c5497f61f12370f2d725 | Daletxt/xiaojiayu | /input.py | 304 | 3.6875 | 4 | name=input("请输入您的姓名:\n")
print("你好,"+name+"!")
calc=input("请输入1-100之间的数字:\n")
num=int(calc)
if 100>=num>=1:
print("你好漂亮^_^")
else:
print('你大爷好丑T_T')
|
0f7f700f829d375e1d8c232fc87175f47f5d3751 | Daletxt/xiaojiayu | /30os os.path.py | 2,567 | 3.609375 | 4 | print('hello,world')
import os
os.getcwd()#获取当前路径
os.chdir('D:/Python')#改变路径
os.listdir()#列出当前路径下的所有文件名
os.mkdir('D:\\Python/S')#创建单层目录,如该目录已存在抛出异常
#os.remove('D:/Python/remove.txt')
os.makedirs('D:/Python/S/A/B')
#os.removedirs('D:/Python/S')#非空,抛出异常
#os.removedirs('D:/Python/S/A')#非空,抛出异常
os.removedirs('D:/Python/S/... |
aadcbc2aca1d9f10503bcac93c3e4468b0f39d7c | Daletxt/xiaojiayu | /40classBIF.issubclass.isinstance.hasattr.setattr.getattr.delattr.property.py | 2,804 | 4.3125 | 4 | print('hello,world')
#类和对象一些相关的BIF
#issubclass(class,classinfo)检查class是否是classinfo的子类,非严格性,
#1.一个类被认为是其自身的子类
#2.classinfo可以是类对象组成的元组,只要class是其中任何一个候选类的子类,则返回True
class A:
pass
class B(A):
pass
print("B是A的子类吗",issubclass(B,A))
print("B是B的子类吗",issubclass(B,B))
print("A是B的子类吗",issubclass(A,B))
print("A是元组(A,B)的子类吗",is... |
98a3a6eb20da780ed73b60a6e317b422b8c9e4c5 | shrek-7/python-yify | /gui/YifySubs.py | 650 | 3.59375 | 4 | from tkinter import *
from subs import search_subtitles
window = Tk()
window.wm_title(string="Yify Subtitles")
def get_subs():
search_subtitles(e1_value.get())
l1 = Label(window, text="Movie Name : ")
l1.grid(row=1, column=0, padx=10, pady=10)
l2 = Label(window, text="Find your file in F:\subtitle.zip ")
l2.... |
1d668571715b7e57212c655864114fc6d033451c | ZhongQiangDev/O_NJU_JK | /能否成环/能否成环.py | 601 | 3.609375 | 4 | import collections
def solve(nodes):
N = len(nodes)
follow = collections.defaultdict(list)
for node in nodes:
for f in nodes:
if node[-1] == f[0]:
follow[node].append(f)
def dfs(path):
if len(path) == N:
return path[-1][-1] == path[0][0]
... |
4c5b1232479b58325db6bf20c50f0c443a897408 | shiqing881215/Python | /basic/file.py | 855 | 3.9375 | 4 | fhandle = open('sampleFile.txt', 'r') # default mode is read, so you can also omit it
print fhandle
print type(fhandle)
count = 0
for line in fhandle :
print line
count = count + 1
print 'Line Count : ', count
# Read the whole file into a string
# Attention, we nee to open the file again - I guess either las... |
43ebbeacae18cb60f4de3c986033597e2d815dda | shiqing881215/Python | /object&database/inheritence.py | 817 | 4.28125 | 4 | class PartyAnimal :
x = 0
name = ""
# This is the constructor
def __init__(self, name) :
self.name = name
print "I'm constructing", self.name
# method, each python class at least has one variable called self
def party(self):
self.x = self.x+1
print self.name, " says ", self.x
# This is the destructor
... |
4fbb26d010002e088acd3a0297ac9b446961cb30 | Manendar/branch-new-data | /trial.py | 253 | 4.125 | 4 | # this function counts vowels in a given string
def vowels(s):
count=0
vowel = "aeiouAEIOU"
for i in s:
if i in vowel:
count +=1
return count
if __name__ == '__main__':
print(vowels("aeiou"))
print(__name__)
|
55533ed84d4bc0624e093b3f5428659d53822746 | Ajay998/Hotel-booking | /Hotelcal.py | 2,554 | 3.8125 | 4 | class Hotelcal:
def __init__(self):
self.data = {}
self.addHotel()
def addHotel(self):
name = input("Enter Hotel name: ")
if self.data.get(name, True):
self.data[name] = {}
self.addRoom(name)
def addRoom(self, name):
roomno = in... |
26d29d2cf85515321b29910184c60d1ab4d405dd | CrisOrtega/demeter | /CreateDDBB.py | 1,755 | 3.734375 | 4 | import sqlite3
conn = sqlite3.connect('demeter.sqlite')
cursor = conn.cursor()
print("Opened database successfully")
# https://medium.com/analytics-vidhya/programming-with-databases-in-python-using-sqlite-4cecbef51ab9
try:
cursor.execute('''drop TABLE if exists customers;''')
except sqlite3.Error as e:
print(... |
ad348fb03c54408fbde5723bc242ccefa2db7b1e | kowrink/Build-a-search-engine-using-python | /assign3.py | 9,103 | 3.59375 | 4 | from collections import Counter
import re
import math
import operator
import timeit
# from prettytable import PrettyTable
##The word.txt use "###" to seperate meterials in different files
pattern = re.compile('^###.')
def inv(corpus_dict,docs):
"""
list<list> Returns a list that contain all... |
1762ec6a2b9a905bd7569d47ef8ad75bfca0fce3 | zhxiaozhi/untitled9 | /day03/12-赋值运算符的特殊场景.py | 700 | 4.1875 | 4 | # 等号连接的变量可以传递赋值
a = b = c = d = 'hello'
print(a, b, c, d)
# x = 'yes' = y = z 错误,赋值运算时从右到左。y不能赋值‘yes’
m, n = 3, 5 # 拆包,(3,5)是一个元组
print(m, n)
x = 'hello', 'good', 'yes'
print(x) # ('hello', 'good', 'yes')
# 拆包时,变量的个数和值的个数不一致,会报错
# y,z = 1, 2, 3, 4, 5
# print(y,z)
# o, p, q = 4, 2
# print(o, p, q)
# *表示可变长度... |
003df186dd9b8ca16c5302fc4ae53917938c6509 | zhxiaozhi/untitled9 | /day02/02-查看数据类型.py | 584 | 3.921875 | 4 | a = 34
b = 'hello'
c = True
d = ['hello','qytang','cisco']
# 使用type内置类可以查看一个变量对应的数据类型
print(type(a)) # <class 'int'> 整数型
print(type(b)) # <class 'str'> 字符串类型
print(type(c)) # <class 'bool'> 布尔型
print(type(d)) # <class 'list'> 列表类型
print(type(3.14)) # <class 'float'> 浮点数类型
# 在Python里,变量是没有数据类型的
# 我们所说的变量的数据类型,其... |
21d633e77954027f3b4a5f1e549d4585d742bb8d | zhxiaozhi/untitled9 | /day03/09-算术运算符.py | 499 | 3.890625 | 4 | # Python里支持很多算术运算符
# +加 -减 *乘 /除 **乘方 //整除 %取余
print(1 + 1) # 2
print(4 - 2) # 2
print(3 * 2) # 6
# 在Python3中,两个整数相除,得到的结果会是一个float浮点数
print(6 / 2) # 3.0
print(9 / 2) # 4.5
print(3 ** 3) # 27
print(81 ** 1 / 2) # 40.5 , 81/2
print(81 ** (1 / 2)) # 9.0
print(10 / 3) # 3.333333333333333
print(10 ... |
a22fc05d9c29a340c06d3b43814182f1ca3b8544 | zhxiaozhi/untitled9 | /day03/14-逻辑运算符.py | 611 | 3.953125 | 4 | # 逻辑运算符 逻辑与and 逻辑或or 逻辑非not
# 逻辑与and规则:只要有一个运算数是False,结果就是False;只有所有的运算数都是True,结果才是True
print(2 > 1 and 5 > 3) # True
print(2 > 1 and 5 > 3 and 10 > 2) # True
print(3 > 2 and 5 < 4 and 6 > 1) # False
# 逻辑或or规则:只要有一个运算数是True,结果就是True;只有所有的运算树都是False,结果才是False
print(3 > 9 or 4 < 7 or 10 < 3) # True
print(3 >... |
9dc95fe1fcdaf8c6e2304f9e1aa495042bf3a368 | gowthamgoli/Cracking-the-Coding-Interview | /Chapter2/Palindrome.py | 698 | 3.984375 | 4 | from LinkedList import LinkedList
def isPalindrome(ll):
slow = ll.head
fast = ll.head
stack = []
counter = 0
while fast and fast.next:
#print fast.value
counter += 1
stack.append(slow.value)
slow = slow.next
fast = fast.next.next
print stack
if counter%2==0:
slow = slow.next
while slow:
if sl... |
447ffb2c9d2dece83cb7e3dea552251d52501145 | SmerlinFernandez/PiedraPapelOTijeras | /main.py | 1,255 | 3.90625 | 4 | #Esta una recreación del juego piedra, papel o tijeras en Python
import random
import sys
aleatorio = random.randrange(1,4)
eleccion_m = ''
while True:
print("Elige Piedra(p), Papel(a) o Tijera(t) [Presiona s para salir]")
eleccion = input().lower()
if eleccion == 'p' or eleccion == 'a' or eleccion == 't... |
63503c4a9ad0d919ddb7b8aaf5e36b67156d890f | 0002amos/labbar-python | /leaderboard2.py | 3,047 | 3.671875 | 4 | """File to add leaderboard funktions to Mastermind"""
import json
from operator import itemgetter
import graphics as g
def create_window():
"""Create leaderboard window"""
lb_window = g.GraphWin("score", 200, 400)
return lb_window
def clear(win):
"""Cleans the leaderboard window"""
for item in ... |
438559e6533c9a35b81ffa517b9d6a361b6f4f0a | Wisam80/project-cashflow-management | /cashflow-manager.py | 3,491 | 4.4375 | 4 | # Management System APP
# user_name=(input("What is your name? "))
# 1. Income:
income = {}
name_of_income = []
amount_of_income = []
total_income = 0
# 2. Expenditures:
expenditures = {}
name_of_expenditures = []
amount_of_expenditures = []
total_expenditures = 0
# balance
remaining_balance = 0
man... |
d5bf6b4f2a8ed643a3b64ebf3057259ed19f8623 | ArtesiaWater/pastas | /pastas/stats.py | 24,479 | 3.5 | 4 | """Statistics for time series models.
Statistics can be calculated for the following time series:
- Observation series
- Simulated series
- Residual series
- Innovation series
Each of these series can be obtained through their individual (private) get
method for a specific time frame.
two different types of statistics ... |
f23e9b415175dffbbe1fb1cae40438cc6612d496 | priyam009/Python-Codecademy | /Text Manipulation Examples/x_length_words.py | 521 | 4.125 | 4 | #Create a function called x_length_words that takes a string named sentence and an integer named x as parameters. This function should return True if every word in sentence has a length greater than or equal to x.
def x_length_words(sentence, x):
sentence = sentence.split()
count = 0
for word in sentence:
fo... |
27b08fd75ad185244ddb9a44453d83326fe8d88a | priyam009/Python-Codecademy | /Loops Examples/exponents.py | 347 | 4.375 | 4 | #Create a function named exponents that takes two lists as parameters named bases and powers. Return a new list containing every number in bases raised to every number in powers.
def exponents(base, powers):
new_lst= []
for i in base:
for j in powers:
new_lst.append(i ** j)
return new_lst
print(expon... |
9275738c76e060d910ef17a4644f8c21b89ce90f | priyam009/Python-Codecademy | /Loops Examples/max_num.py | 276 | 4.1875 | 4 | #Create a function named max_num that takes a list of numbers named nums as a parameter. The function should return the largest number in nums
def max_num(nums):
max = nums[0]
for i in nums:
if i >max:
max = i
return max
print(max_num([50, -10, 0, 75, 20])) |
7436c22da3003ca6285a36b03b29438eb30cab3f | zach96guan/Stupid_LeetCoder | /Linkedlist/708.Insert_into_a_Sorted_Circular_Linked_List/Insert_into_a_Sorted_Circular_Linked_List.py | 843 | 3.859375 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
# one-pass, O(N)
dummy = Node(insertVal, head)
# corner case
if... |
e2ef1aa8bc1eb116b2134f27c2ba4b856f7c156f | zach96guan/Stupid_LeetCoder | /Recursion/110.Balanced_Binary_Tree/Balanced_Binary_Tree.py | 683 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
# O(N), bottom-up
return self.helper(root)[0]
def helper(self... |
5a353a9157b92f92984abaff42e92b339b0fd0c1 | zach96guan/Stupid_LeetCoder | /Linkedlist/24.Swap_Nodes_in_Pairs/Swap_Nodes_in_Pairs.py | 664 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# from pre -> a -> b -> b.next to pre -> b -> a -> b... |
d86429ce89d62edb51add82c5e078ca43e7625f8 | zach96guan/Stupid_LeetCoder | /Design/146.LRU_Cache/LRU_Cache.py | 1,484 | 3.78125 | 4 | # dictionary + doubly-linked list
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.dic = {}
self.head... |
3757f503b2f5acc6de0baee3c3d9eb1f7259f57c | zach96guan/Stupid_LeetCoder | /Trie/1032.Stream_of_Characters/Stream_of_Characters.py | 1,143 | 3.59375 | 4 | class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.flag = False # is end
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
cur = self.root
for ch in word:
cur = cur.children[ch]
... |
d8b778f31c6f16aa5b66587f12d4f827d15fabe2 | zach96guan/Stupid_LeetCoder | /Recursion/1123.Lowest_Common_Ancestor_of_Deepest_Leaves/Lowest_Common_Ancestor_of_Deepest_Leaves.py | 763 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
# O(N), recursion
self.lca = None
self.deepest = 0
... |
c082f269846bcfc63b956899f9bf7f85610bc03a | zach96guan/Stupid_LeetCoder | /Recursion/119.Pascal's_Triangle_II/Pascal's_Triangle_II.py | 537 | 3.5 | 4 | class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
# recursion
rows = []
def helper(i, j):
if j == 0 or i == j:
return 1
return rows[i - 1][j] + rows[i - 1][j - 1]
... |
9f433654a624fc8a6ed23efd2660afad5e4463d4 | zach96guan/Stupid_LeetCoder | /Others/229.Majority_Element_II/Majority_Element_II.py | 700 | 3.515625 | 4 | class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# O(n), O(1)
# Voting Algorithm
cnt1 = cnt2 = 0
cand1 = cand2 = None
for num in nums:
if num == cand1:
cnt1 +=... |
9ca451db33de0d33baef3d3b1d8eeee0be5a6658 | emilybarre/list_practice | /database.py | 1,295 | 3.75 | 4 | def create_database_entry(name,ID_no,age):
new_patient = [name, ID_no, age, list()];
return new_patient
def print_directory(db):
other_data = ["Room 2", "Room 3", "Room 4", "Room 5"]
for i, patient in enumerate(db):
print("Name: {}, ID: {}, age: {}, location: {}".format(patient[0],patient[1]... |
81452be56123ee27e4fbd3a1aa371fe39652a9b4 | Debashish-hub/Python | /MyCaptain1.py | 561 | 4.40625 | 4 | # Displaying fibonacci series upto n terms
n = int(input("Enter the number of terms? "))
# Initialisation of 2 terms
n1, n2 = 0, 1
count = 0
# Checking for validation and printing the fibonacci series
if n <= 0:
print("Please enter a positive integer!")
elif n == 1:
print("Fibonacci series upto ", ... |
b406c770a706b6d97acdf85908890c050941a1fe | violehtone/aoc_2020 | /exercises/day8.py | 933 | 3.703125 | 4 | #!usr/bin/env python3
import sys
def go_through_instructions(instr_args):
"""instr_args is a list of tuples containing
instructions and arguments, i.e. ("jmp", 5)"""
i_values = []
i = 0
accumulator = 0
while i < len(instr_args):
# Check if executing for second time
if(i in i_values):
... |
6714ac53c140054ffac601a874b63f54a495a12f | tyermercado/python-hacker-rank | /longest_descending_substring.py | 555 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 15 11:21:59 2019
@author: bijayamanandhar
"""
def longest_descending_substring(s):
print('s')
descending_substring = ''
temp = ''
i = 0
while i < len(s) - 1:
temp = s[i]
print(temp)
while ord(s[i + 1]) < ... |
4f906ffbb833dbbfa4a806c8f458fde74e98e3f3 | tyermercado/python-hacker-rank | /divisible_sum_pair.py | 1,857 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 22:32:30 2019
@author: bijayamanandhar
"""
#Github repo:
#https://www.hackerrank.com/challenges/divisible-sum-pairs/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign
"""
You are given an array of integ... |
8e8707939a5990e1ec015df2f3be9723d6aa2ba9 | ein0920/python_cookbook | /ch2_字符串和文本/b_book.py | 12,668 | 3.65625 | 4 |
# 1、split
if __name__ == '__main__':
import re
line = 'asdf fjdk; afed, fjek,asdf, foo'
# (a) Splitting on space, comma, and semicolon
parts = re.split(r'[;,\s]\s*', line)
print(parts)
# (b) Splitting with a capture group
fields = re.split(r'(;|,|\s)\s*', line)
print(fields)
... |
4b6f787bbb56dca3779b2facc2cb544e4fd48ade | Worcester-Preparatory-School-Comp-Sci/turtle-graphics-3-max-spencer-kat-verrie-gud-teem | /ksm.py | 2,872 | 3.78125 | 4 | #Kat,Spencer,Max
#cityscape
import turtle
import math
#These variables make it easier to goto each corner
leftSide = turtle.window_width() / 2 * -1
topSide = turtle.window_height() / 2
rightSide = turtle.window_width() / 2
bottomSide = turtle.window_height() / 2 * -1
t... |
c4b693d3e61f81411a66c1071f19775d85d2b482 | nteno555/py | /warmup/Game_Python.py | 1,048 | 4 | 4 | hum = int(input("How many cars are in the parking lot?"))
if hum > 15:
print("Oh no! Too many!")
elif hum < 1:
print("The parking lot is empty!")
else:
print("Ok then.")
heythee = int(input("How many teeth did you lose?"))
if heythee > 25:
print("Impossible!")
elif heythee < 1:
print("You will prob... |
e92361ebc85b6d6484672bbbc23d7767c288163a | KickItAndCode/Algorithms | /ArraysListSets/MissingNumber.py | 1,037 | 3.890625 | 4 | # 268. Missing Number
# Given an array containing n distinct numbers
# taken from 0, 1, 2, ..., n, find the one that is
# missing from the array.
# Example 1:
# Input: [3,0,1]
# Output: 2
# Example 2:
# Input: [9,6,4,2,3,5,7,0,1]
# Output: 8
# Note:
# Your algorithm should run in linear runtime complexity.
# Coul... |
b93cf24ee0c5698067fa3e76a0e806f0e2816a93 | KickItAndCode/Algorithms | /LeetCode/CountPrimes.py | 806 | 4.09375 | 4 | # 204. Count Primes
# Count the number of prime numbers less than a non-negative number, n.
# Example:
# Input: 10
# Output: 4
# Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
def countPrimes(n):
if n <= 2:
return 0
is_prime = [True] * n
is_prime[0] = is_prime[1] = Fa... |
2caf9c7f8e1e8537fc29a0cd78c968ef64d59475 | KickItAndCode/Algorithms | /Heaps/KSmallestPairs.py | 5,249 | 3.875 | 4 | # 373. Find K Pairs with Smallest Sums
# You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
# Define a pair(u, v) which consists of one element from the first array and one element from the second array.
# Find the k pairs(u1, v1), (u2, v2) ...(uk, vk) with the smallest sums... |
8bd8635e4ac776c73e92bfd91c4c95e8a85e1b03 | KickItAndCode/Algorithms | /LeetCode/TinyUrlEncoding.py | 1,624 | 4 | 4 | # 535. Encode and Decode TinyURL
# Note: This is a companion problem to the System Design problem: Design TinyURL.
# TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
# Design the encode and decod... |
5f3a3ddeb5c90db54752b601fcf2adbe4f34afbf | KickItAndCode/Algorithms | /LeetCode/LargestRange.py | 3,683 | 4.15625 | 4 | import unittest
#Write a function that takes in an array of integers and returns an array of length 2
# representing the largest range of numbers contained in that array. The first number
# in the output array should be the first number in the range while the second number
# should be the last number in the range.... |
e012b598dcac653174c9af79000f28a8aefe6897 | KickItAndCode/Algorithms | /DynamicProgramming/CoinChange.py | 2,647 | 3.90625 | 4 | """
Given a target amount n and a list (array) of distinct coin values, what's the fewest coins needed to make the change amount.
For example:
If n = 10 and coins = [1,5,10]. Then there are 4 possible ways to make change:
1+1+1+1+1+1+1+1+1+1
5 + 1+1+1+1+1
5+5
10
With 1 coin being the minimum amount.
"""
from ... |
e1b49bd922347042eb7372216b9e9bf5aecbff9f | KickItAndCode/Algorithms | /Trees/PathSumII.py | 998 | 3.78125 | 4 | # 113. Path Sum II
# Given a binary tree and a sum, find all root-to-leaf paths where
# each path's sum equals the given sum.
# Note: A leaf is a node with no children.
# Example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ / \
# 7 2 5 1... |
4756ca7726b92adcfa5fe19ce2d0d49ddee01b27 | KickItAndCode/Algorithms | /Trees/SortedArrayToBST.py | 390 | 3.578125 | 4 | def sortedArrayToBST(self, nums):
# check if array is empty
# Get the mid point
mid = len(nums) // 2
# and create that nood as root
root = TreeNode(nums[mid])
# recursively slice from mid to the left and mid
# to the right for the tree
root.left = self.sortedArrayToBST(nums[: mid])
... |
4536c31db8d8840fb87e598646a7a90ad1c8589f | KickItAndCode/Algorithms | /Graphs, BFS, DFS/BFS/WordLadder.py | 6,460 | 3.84375 | 4 | # 127. Word Ladder
# Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
# Only one letter can be changed at a time.
# Each transformed word must exist in the word list. Note that beginWord is not a transformed... |
a43edd3f97e3c2229fbf824591fc5a5e0a1894b8 | KickItAndCode/Algorithms | /DynamicProgramming/UniquePaths.py | 1,320 | 4.34375 | 4 | # 62. Unique Paths
# robot is located at the top-left corner of a m x n grid(marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid(marked 'Finish' in the diagram below).
# How many possible unique pat... |
cc7a6ed4d1d79a5cda406012a0c0e268a64eed06 | KickItAndCode/Algorithms | /BinarySearch/SquareRoot.py | 245 | 3.609375 | 4 | def squareRoot(k):
l, r = 0, k
while l <= r:
mid = l + (r-l) // 2
midSquared = mid * mid
if midSquared <= k:
l = mid + 1
else:
r = mid - 1
return l - 1
print(squareRoot(4))
|
6fbbed2ff14ea75481d00df62e5366ecdb4aa535 | KickItAndCode/Algorithms | /LeetCode/MonotonicArray.py | 1,261 | 4.09375 | 4 | # 896. Monotonic Array
# An array is monotonic if it is either monotone increasing or monotone decreasing.
# An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
# Return true if and only if the given array A is monotonic.
# Example 1... |
86fd55a2d7264324ad169204d4c28024698d59f8 | KickItAndCode/Algorithms | /Graphs, BFS, DFS/2D Board BFS/SurroundedRegions.py | 2,413 | 4.125 | 4 | # 130. Surrounded Regions
# Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
# Example:
# X X X X
# X O O X
# X X O X
# X O X X
# After running your function, the board should be:
# X X X X... |
39df7799ff2716caae33a3d546b4b069b7d77a20 | KickItAndCode/Algorithms | /LeetCode/FlipGame.py | 1,069 | 3.796875 | 4 | # 293. Flip Game
# You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.
... |
7dcc944b11294347140856b1de6480bb7bcbdc70 | KickItAndCode/Algorithms | /TwoPointer/SubArrayProductLessThanK.py | 2,132 | 3.921875 | 4 | # 713. Subarray Product Less Than K
# Your are given an array of positive integers nums.
# Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
# Example 1:
# Input: nums = [10, 5, 2, 6], k = 100
# Output: 8
# Explanation: The 8 subarrays that hav... |
eaa492907c1968e818cfe8f4757e53dbfe8ba597 | KickItAndCode/Algorithms | /Intervals/MinimumNumberOfArrowsToBurstBalloons.py | 1,693 | 3.6875 | 4 |
# 452. Minimum Number of Arrows to Burst Balloons
# There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of ... |
33a53ba0f09a7d16e9c928e2590592bb4626fb44 | KickItAndCode/Algorithms | /Trees/SizeOfBST.py | 373 | 3.703125 | 4 | class Node:
def __init__(self, val=None):
self.left = None
self.right = None
self.val = val
def Size(root):
if root is None:
return 0
left = Size(root.left)
right = Size(root.right)
return left + right + 1
root = Node(2)
root.left = Node(1)
root.right = ... |
cee1000a372f57cf303353188606df73f3ea923b | KickItAndCode/Algorithms | /ArraysListSets/MoveZeroes.py | 1,572 | 3.796875 | 4 | from nose.tools import assert_equal
# 283. Move Zeroes
# Given an array nums, write a function to move all 0's to the
# end of it while maintaining the relative order of the non-zero
# elements.
# Example:
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
# Note:
# You must do this in-place without making a copy of the... |
07a17f7ee314b90ec057279a78af34345cbd7911 | KickItAndCode/Algorithms | /LeetCode/MaximumSumSubarrayLessThanOrEqualToSum.py | 1,452 | 4.0625 | 4 | # Maximum sum subarray having sum less than or equal to given sum
# Given an array of integers and a sum. We have to find sum of subarray having maximum sum less than or equal to given sum in array.
# Examples:
# Input : arr[] = { 1, 2, 3, 4, 5 }
# sum = 11
# Output : 10
# Subarray having maximum sum is { 1, ... |
d5067b51281765198e4d3021c7c4e0943a0c2b1b | KickItAndCode/Algorithms | /BinarySearch/CapacityToShipPackagesWithinDDays.py | 3,619 | 4.1875 | 4 | # 1011. Capacity To Ship Packages Within D Days
# A conveyor belt has packages that must be shipped from one port to another within D days.
# The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load... |
ba680cd215c489a45e172fab33a1e73236099464 | KickItAndCode/Algorithms | /ArraysListSets/ProductOfArrayExceptSelf.py | 1,729 | 3.796875 | 4 | # 238. Product of Array Except Self
# Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
# Example:
# Input: [1, 2, 3, 4]
# Output: [24, 12, 8, 6]
# Note: Please solve it without division and in O(n).
# Follow... |
6919df3beda2e02e01a77b28c43171c5a70b8db3 | KickItAndCode/Algorithms | /LeetCode/RepeatedDNASubsequences.py | 1,186 | 3.75 | 4 | # 187. Repeated DNA Sequences
# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
# Write a function to find all the 10-letter-long sequences (substrings) that occur more than... |
70ee7a473dfef293a283af568731e5f637a04d21 | KickItAndCode/Algorithms | /Recursion/TowerOfHanoi.py | 1,906 | 4.15625 | 4 | # Program for Tower of Hanoi
# Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
# 1) Only one disk can be moved at a time.
# 2) Each move consists of taking the upper disk from one of... |
4233d6a91fe0b4d2a088cc13bf11a5cc1a0cccee | KickItAndCode/Algorithms | /ArraysListSets/GenerateParentheses.py | 2,883 | 4.125 | 4 | # 22. Generate Parentheses
# Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
# For example, given n = 3, a solution set is:
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
# Approach 2 (Directed Backtracking)
# The 3 Keys To Backt... |
20b2f905ede51a09a845da6c4101d38e53311b2e | KickItAndCode/Algorithms | /Heaps/TopKFrequentElements.py | 1,059 | 3.984375 | 4 | # 347. Top K Frequent Elements
# Given a non-empty array of integers, return the k most
# frequent elements.
# Example 1:
# Input: nums = [1,1,1,2,2,3], k = 2
# Output: [1,2]
# Example 2:
# Input: nums = [1], k = 1
# Output: [1]
# Note:
# You may assume k is always valid, 1 ≤ k ≤ number of
# unique elements.
# Yo... |
2e2566b2ca88aab8ec1ced1125e746f114f10937 | KickItAndCode/Algorithms | /ArraysListSets/SpiralMatrixII.py | 1,156 | 3.96875 | 4 | # 59. Spiral Matrix II
# Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
# Example:
# Input: 3
# Output:
# [
# [ 1, 2, 3 ],
# [ 8, 9, 4 ],
# [ 7, 6, 5 ]
# ]
def generateMatrix2(n):
if not n:
return []
res = [[0 for _ in range(n)] for _ in ra... |
d2bf19530d4b37cad334ccb7082aae764a04d367 | KickItAndCode/Algorithms | /Trees/MaxPathSumTree.py | 2,958 | 4 | 4 | # 123 Max Path Sum In Binary Tree
# Write a function that takes in a Binary Tree and returns its max path sum. A path is a collection of connected nodes where no node is connected to more than two other nodes
# a path sum is the sum of the values of the nodes in a particular path. Each Binary Tree node has a value st... |
e45a425269e94af9c8ca8ff856c23a3685faf484 | KickItAndCode/Algorithms | /LeetCode/IntersectionOfTwoArrays.py | 1,139 | 3.84375 | 4 | # 349. Intersection of Two Arrays
# Given two arrays, write a function to compute their intersection.
# Example 1:
# Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]
# Output: [2]
# Example 2:
# Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]
# Output: [9, 4]
# Note:
# Each element in the result must be unique.
# The ... |
931397f5da720ee16b13b569402fe590d669c144 | KickItAndCode/Algorithms | /ArraysListSets/SpiralMatrix.py | 1,552 | 3.875 | 4 | # 54. Spiral Matrix
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
# Example 1:
# Input:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# Output: [1,2,3,6,9,8,7,4,5]
# Example 2:
# Input:
# [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9,10,11,12]
# ]... |
876c9089c9a427abcfef690fd69eb2398828e65b | Soumyadeep07/Competitive-Codes | /HackerRank/The Time in Words | 1,383 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the timeInWords function below.
def timeInWords(h, m):
# !!!!! START OF MY CODE !!!!! #
time = ['one minute','two minutes','three minutes','four minutes','five minutes','six minutes','seven ... |
795c36c05471c4fb6ed14b1c0e7dba461f48c52d | caovicto/ScheduleBuilder | /Design/Program.py | 996 | 3.5625 | 4 | import re
from Design.Requirement import *
class Program:
def __init__(self, number, name, reqString):
self.number = number
self.name = name
self.credits = 0
self.requirements = []
parsedWords = re.findall(r"\nRequired Credits: \d*", reqString)
self.credits = int(p... |
501b1350c55cb6c5967a31200ab476579ad35e7a | daiki1998/python_library | /math/matrix_product.py | 817 | 3.703125 | 4 |
"""
A×Bの行列積
計算量
O(N^3)
"""
def mul(A, B, mod):
C = [[0 for _ in range(len(A))] for _ in range(len(A[0]))]
for i in range(len(A)):
for j in range(len(A[0])):
for k in range(len(A)):
C[i][k] += A[i][j]*B[j][k]
C[i][k] %= mod
return C
"""
AのT乗を求める
計算量
O(A^3... |
301f60274a170ac85522582ca077c5d997a58462 | murilossilva/CalcPy | /calc.py | 3,684 | 3.96875 | 4 | import math as m
print('1 - Adição\n2 - Subtração\n3 - Multiplicação\n4 - Divisão')
print('5 - Potenciação\n6 - Raiz quadrada\n7 - Raiz Cúbica\n8 - Logaritmo')
print('9 - Equação de 2º Grau\n0 - Sair\n')
menu = int(input("Digite a operação desejada: "))
print('')
#Função para realizar novamente o uso da calculadora#
... |
38df1467a16af2618662010110144c15777dd7a4 | W7297911/test | /python/firstPython/类方法_自定义.py | 401 | 3.6875 | 4 | class Tool(object):
# 使用赋值语句定义类属性,记录所有工具对象的数量
count = 0
@classmethod
def show_tool_count(cls):
print("工具数量的对象: {}".format(cls.count))
def __init__(self, name):
self.name = name
# 让类属性的值 +1
Tool.count += 1
# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
# 调用类方法
Tool.show_tool_count() |
fe24cc5afafeadbdaa5a48686404497b14b18dd2 | W7297911/test | /python/wangyi/02_函数.py | 198 | 3.875 | 4 | def addnum(num1,num2):
#print((num1+num2*2)/2)
return (num1+num2*2)/2
a =int(input("请输入第一个数字:"))
b =int(input("请输入第一个数字:"))
result=addnum(a,b)
print(result)
|
0b11b3ee73f22ad71e1ea1b530390302b240b600 | W7297911/test | /python/wangyi/白富美.py | 378 | 3.5 | 4 | #1.询问是否皮肤是白的
a = input("媒婆,她皮肤怎么样(1:红润光泽,2:一般):")
#2.询问是否够富有
b = input("媒婆,她家产是否上千万(1:是,2:不是):")
#3.询问是否漂亮
c = input("媒婆,她漂亮吗(1:是,2:不是):")
#4.判断是否是白富美
if a=="1" and b=="1" and c=="1":
print("白富美")
|
794b1ee2ec61b152c771f804e98ab40ad2c5ba7d | W7297911/test | /python/test/4.1.py | 940 | 3.890625 | 4 | #coding: utf-8
#一个简单的数据库
#字典使用人名作为键。每个人用另一个字典来表示,其键'phone'和'addr'分别表示他们的电话号码和地址
people = {
'Alice':{
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth':{
'phone': '9102',
'addr': 'Bar street 42'
},
'Cecil':{
'phone': '3158',
'addr': 'Baz avenue 90'
... |
40ae569d511f6575ddd9660b9444602d0e755d38 | W7297911/test | /python/wangyi/while嵌套2.py | 184 | 3.90625 | 4 | i=1
while i<=5:
# print("* "*i, end="")
j=1
while j<=i:
print("* ", end="")
j+=1
print("")
i+=1
h=4
while h>0:
g=1
while g<=h:
print("* ", end="")
g+=1
print("")
h-=1
|
ed54191aceeb68a1daac35a64caccb66f07cb1cc | W7297911/test | /python/firstPython/私有属性和方法.py | 404 | 3.59375 | 4 | class Women:
def __init__(self, name):
self.name = name
self.__age = 18
def __secret(self):
# 在对象的方法内部,是可以访问对象的私有属性的
print('{} 的年龄是 {}'.format(self.name, self.__age))
xiaofang = Women('小芳')
# 私有属性,在外界不能够被直接访问
print(xiaofang.__age)
# 私有方法,同样不允许在外界直接访问
xiaofang.__secret() |
61991f5e64dc79803acfa49828ffaec2a9070741 | svirepovden/tg_support_bot | /database/schema.py | 2,193 | 3.578125 | 4 | import sqlite3
SQL_SCHEMA_MESSAGES = '''CREATE TABLE "messages" (
"message_id" INTEGER NOT NULL,
"chat_id" INTEGER NOT NULL,
"content" TEXT NOT NULL,
"date" INTEGER NOT NULL,
"status" TEXT NOT NULL DEFAULT 'open',
FOREIGN KEY("chat_id") REFERENCES "chats"("chat_id"),
PRIMARY KEY("message_id")
);'''
SQL_SCHEMA_... |
c531a0a2748d0aeaceb773c56dcd73fc1e0514e8 | gamerwalt/PythonTutorials | /main.py | 441 | 4.0625 | 4 |
#day 1
#test = input("What is your name?")
#print(f"Length of your name is {len(test)}")
#day1 - 1st Challenge
#a = input("a:")
#b = input("b:")
#temp = a
#a = b
#b = temp
#print("a = " + a)
#print("b = " + b)
#day1 - 2nd Challenge
print("Welcome to the Band Name Generator.")
city = input("What's the name of the c... |
af54ad04354086f9bc47f5fe60f54ce7ff3abce4 | PaiKai-Lee/week2 | /python_1.py | 1,697 | 3.859375 | 4 | #在函式中 使用迴圈 計算最小值到最大值之間,所有整數的總和。
def calculate(min,max):
sum=0
for i in range(min,max+1) :
sum+=i
print(sum)
print("要求一:")
calculate(1, 3)
calculate(4, 8)
def avg(data):
sum=0
num=len(data["employees"])
for i in data["employees"]:
sum+=i["salary"]
print(sum/num)
print("\n要求二... |
3b4f9ea9c6d1257928b6ee539904746f5e7fa6b5 | marc-haddad/cs50-psets | /pset6/credit/credit.py | 2,388 | 4.125 | 4 | # Marc Omar Haddad
# CS50 - pset6: 'Credit'
# September 4, 2019
from cs50 import get_string
# This program uses Luhn's algorithm to check the validity and type of credit cards
def main():
num = get_string("Number: ")
# Repeatedly prompts user for valid numeric input
while (num.isdigit() != True):
... |
ceef18623bcc8901305c624db540308606e05d5c | RaViS888/010123131 | /expression tree/list_truth.py | 4,624 | 3.59375 | 4 | #6101012620130
import itertools
class Stack: # ref form https://runestone.academy/runestone/books/published/pythonds/BasicDS/ImplementingaStackinPython.html
stack_list = [] # เก็บoperator symbol
def __str__(self):
self.stack_list
def is_empty(self): # ทำให้stackว่าง
return self.stack_li... |
55dc9691651c39f92c9a3f37b5c67fc80688c9ed | nate-hunter/python-cc | /ch05-if-statements/ordinal_numbers.py | 337 | 3.84375 | 4 | # 5.11: 11/15/21
numbers = list(range(1,10))
# numbers = list(range(1,40))
if numbers:
for n in numbers:
right_num = int(str(n)[-1])
if right_num == 1:
print(f'{n}st')
elif right_num == 2:
print(f'{n}nd')
elif right_num == 3:
print(f'{n}rd')
else:
print(f'{n}th')
else:
print('There are numb... |
eba970f91a25c886fa95fd5f25f7bc42f214e0a7 | dconn20/Random | /Random.py | 243 | 4.21875 | 4 | # program that prints out a random number
# between 1 and 10
import random
x = int (input("Enter number here: "))
y = int (input("Enter number here: "))
number = random.randint (x,y)
print ("Here is a random number {}" .format (number))
|
dd83a56158305d026e4ade04f5978370ace79ee2 | sun2011yao/Think-Python | /Ch12/most_frequent.py | 565 | 3.875 | 4 |
def readFile(filename):
fd = open(filename)
return fd.read()
def makeHistogram(s):
res = {}
for letter in s:
res[letter] = res.get(letter, 0) + 1
return res
def mostFrequent(s):
hist = makeHistogram(s)
t = []
for letter, fre in hist.items():
t.append((fre, letter))
... |
14f03f53b53fee9132afebbc12ed6b72d75315e6 | aaronjrenfroe/Algorithms | /fibonacci_memoize.py | 465 | 4.125 | 4 | # Returns the nth number in the fibonacci sequence
def fib_memo(n, memo):
if n == 0:
return 0
elif memo[n] != None:
return memo[n]
elif n == 1 or n == 2:
memo[n] = 1
else:
memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo)
return memo[n]
# memo initialiseation cen be done differntly
# but ... |
6900883d6429c006c72ef5bea597203a7144944e | jo-m/data-mining-exercises | /ex1/1.1-mapper.py | 387 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import sys
import re
import string
alnum = re.compile(r'[\W_]+', re.UNICODE)
atoz = re.compile(r'[^a-z]+')
for line in sys.stdin:
line = alnum.sub(' ', line.strip())
words = line.split()
for word in words:
word = word.lower()
if len(atoz.su... |
acd4d4f445b1fc268bd9133b47193b2567a7d0a9 | Alan-Flynn/Python-Labs | /table.py | 290 | 3.671875 | 4 | # Name: Your Name
# Student ID: 012345678
# File: digram.py
############################################################################
##
## Your code goes here
##
TC = -20
while TC <= 50:
TF = (TC * 1.8) + 32
print("Temperature:",TC,"C,",TF,"F.")
TC = TC + 5
|
cd3f7d51e980f06227df722a3a92a93dc6e98217 | ivannpe/CSSI2017 | /CSSI/Python/spaceship.py | 805 | 3.84375 | 4 | class Spaceship:
def __init__(self, name, color, destination, origin, launched):
self.name = name
self.color = color
self.destination = destination
self.origin = origin
self.launched = launched
def description(self):
return "The {0} is {1} and is going to {2} from... |
5b675b3a6e56e66952961223fdb46c0ffbde94aa | ivannpe/CSSI2017 | /CSSI/Python/practice.py | 118 | 3.578125 | 4 | my_string = [10,9,8,7,6,5,4,3,2,1,0]
for number in my_string:
print str(number) + ' bottles of milk on the wall'
|
2439686fe8009eb5c38dccabe893366b525151dd | Frijke1978/LinuxAcademy | /Python 3 Scripting for System Administrators/Handling Errors.py | 2,042 | 4.0625 | 4 | Handling Errors with try/except/else/finally
In our reverse-file script, what happens if the filename doesn’t exist? Let’s give it a shot:
$ reverse-file fake.txt
Traceback (most recent call last):
File "/home/user/bin/reverse-file", line 11, in
with open(args.filename) as f:
FileNotFoundError: [Errno 2] N... |
c54d475ea800479f4cdf5b2a1f95e3e5efde9452 | Frijke1978/LinuxAcademy | /Python 3 Scripting for System Administrators/The while Loop.py | 2,207 | 4.6875 | 5 | The while Loop
The most basic type of loop that we have at our disposal is the while loop. This type of loop repeats itself based on a condition that we pass to it. Here’s the general structure of a while loop:
while CONDITION:
pass
The CONDITION in this statement works the same way that it does for an if state... |
601a99925da4f5facb83904bbb3d32df389e34f3 | Frijke1978/LinuxAcademy | /Python a consise introduction/Module 3/ProblemSet3_2.py | 191 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 21:58:06 2018
@author: Frijke
"""
def problem3_2(collection):
for i in range(0, len(collection)):
print(collection[i]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.