blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
00404a17c4abb680cc7424d8e968d4b5bce4de82 | bsakers/Introduction_to_Python | /classes_three.py | 1,976 | 4.3125 | 4 | class Computer(object):
condition = "new"
def __init__(self, model, color, ram, storage):
self.model = model
self.color = color
self.ram = ram
self.storage = storage
def display_computer(self):
return "This is a %s %s with %s gb of RAM and %s gb SSD." %(self.color, se... | true |
c4f1a54798667c53eb6952afc1d0fe923c052803 | bsakers/Introduction_to_Python | /classes.py | 1,977 | 4.34375 | 4 | #general sytax for a class:
class NewClassName(object):
# code
pass
#in the above, we simply state the keyword 'class' and whatever we want to name it
#then we state what the class will inherit from (here we inherit from python's object)
#the 'pass' keyword doesnt do anything, but can act as a placeholder to n... | true |
027342a1e6c8fa72fc03ea820f4770209fa04f77 | bsakers/Introduction_to_Python | /enumerate.py | 463 | 4.6875 | 5 | #enumerate supplies a corresponding index as we loop
options = ["pizza", "sushi", "gyro"]
#normal for loop:
for option in options:
print option
#enumerator (note that "index" could be replaced by anything; it's just a placeholder)
for index, option in enumerate(options):
print index, option
#we can ev... | true |
325ab3f4d26130fd386bbdb3473ae5c7dbe9ca63 | bsakers/Introduction_to_Python | /pig_latin_translator.py | 376 | 4.125 | 4 | print 'Welcome to the Pig Latin Translator!'
original_word = raw_input("Enter a word you would like translated: ").lower()
ending = "ay"
if len(original_word) > 0 and original_word.isalpha():
translated_word = original_word[1:len(original_word)] + original_word[0] + ending
print translated_word
else:
prin... | true |
3aae270f26e6a22bf805081abfee3ed682002282 | ayecoo-103/Python_Code_Drills | /03_Inst_ATM_Application_Logic/Unsolved/atm.py | 656 | 4.15625 | 4 | """This is a basic ATM Application.
This is a command line application that mimics the actions of an ATM.
Example:
$ python app.py
"""
accounts = [
{
"pin": 123456,
"balance" : 1436.19},
{
"pin" : 246802,
"balance": 3571.87},
{
"pin": 135791,
"balance" : 543.79},
{
"pi... | true |
ba4c6bb212ce1374b4bf1779ae7b2fc415d6017b | ignis05/informatyka-python | /!KLASA_4/2.3.py | 949 | 4.3125 | 4 | # Napisz program, który sprawdzi położenie punktu względem odcinka.
# Użytkownik podaje współrzędne początkowe i końcowe odcinka oraz współrzędne punktu.
# Program należy zabezpieczyć przed podaniem współrzędnych określających długość odcinka równą 0.
import math
def distance(a,b):
return math.sqrt((a.x - b.x)**2 ... | false |
ac51a04b6213e9a8b96e8b1b5d8e4310b56a945a | sarahdepalo/python-classes | /pokemon.py | 2,834 | 4.125 | 4 | #Below is the beginnings of a very basic pokemon game. Still needs a main menu built in. Someday I'd like to add the ability to maybe find new pokemon and battle random ones!
class Pokemon:
def __init__(self, name, health, attack, defense):
self.name = name
self.health = health
self.attack ... | true |
7c744188e7d75ac5ecf083c29b5449c43928e11d | pasanchamikara/ec-pythontraining-s03 | /numpy-tutorial/basics.py | 1,205 | 4.46875 | 4 | import numpy as np
# Basics
# a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # Create a rank 1 array
# print(type(a)) # Prints "<class 'numpy.ndarray'>"
# print(a.shape) # Prints "(3,)"
# print(a)
# | 1 2 3 4 |
# | 5 6 7 8 |
# print(a[0], a[1], a[2]) # Prints "1 2 3"
# a[0] = 5 ... | false |
b2478988fed601e0c3b2bbcba70605d0940622b4 | seshu141/20-Projects | /19th Program.py | 715 | 4.125 | 4 | # 19th program Find second biggest number of a list
print(" enter the range of no. and stop")
def Range(list1):
largest = list1[0]
largest2 = None
for item in list1[1:]:
if item > largest:
largest2 = largest
largest = item
elif largest2 == None or largest2 < ... | true |
40f42faa9ff184914e9725e845f69113d73634a2 | stevenckwong/learnpython | /ex06.py | 590 | 4.3125 | 4 | #String formatting
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print (joke_evaluation.format(hilarious))
a = "Adam"
b = "Bob"
c = "Cathryn"
friends = "There were once 3 friends named {}, {} and {}"
print (friends.format(a,b,c))
# positioning of the variables corresponds to the location of th... | true |
9b67263e7c33c532840bd950c7fc055053e70cd7 | stevenckwong/learnpython | /ex32.py | 676 | 4.53125 | 5 | #Loops and Lists
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
#the first kind of for loop that goes through a list
for number in the_count:
print(f"This is count {number}")
for fruit in fruits:
print(f"A fruit of type: {fruit}")
# not... | true |
66fa6d629d9ddfe80b4255e1ba72f95bff31ad4a | kwikl3arn/python-tutorial | /Python-Palindrome-Number.py | 290 | 4.25 | 4 | # Python Program for Palindrome Number
num = int(input("Enter a number: "))
temp = num
rev = 0
while num>0:
remain = num % 10
rev = (rev * 10) + remain
num = num // 10
if temp == rev:
print("Number is palindrome")
else:
print("Number is not palindrome")
| true |
4a369bff7a8797951f2ab3c7af2fef2b4ae75ba3 | CraGL/Hyperspectral-Inverse-Skinning | /PerVertex/util.py | 2,478 | 4.21875 | 4 | import re
import numpy as np
def veclen(vectors):
""" return L2 norm (vector length) along the last axis, for example to compute the length of an array of vectors """
return np.sqrt(np.sum(vectors**2, axis=-1))
def normalized(vectors):
""" normalize array of vectors along the last axis """
return vec... | true |
3667fe3935484f27411ba2d9522f282b98cd9d26 | adsr652/Python | /fact2.py | 534 | 4.1875 | 4 | def recu_fact(num):
if num==1:
return num
else:
return num * recu_fact(num-1)
num= int(input("Enter any no. : "))
if num < 0:
print("Factorial cannot be found for negative integer")
print("Reenter the value again ")
num= int(input("Enter any no. : "))
if num==0:
... | true |
6c8cb118721a066d8d31a7df10d030c5371a36f4 | Phyopyosan/Exercises | /If_Else_Statements.py | 2,063 | 4.15625 | 4 | #Boolean Expression
print(20 > 10)
print(20 == 10)
print(20 < 10)
print(bool("Hello World"))
print(bool(20))
Python Condition
Equals -> x == y
Not Equals -> x != y
Less Than -> x < y
Less Than or Equals to -> x <= y
Greater than -> x > y
Grater than or equal to -> x >= y
Boolean O... | false |
ef7bf55fa66a02245c45f2d263a69ee811ffbb7f | PatrickWMoore88/htx-immersive-08-2019 | /02-week/1-tuesday/labs/patrick-moore/patrickwmoore88-phonebook.py | 2,509 | 4.3125 | 4 | #Phone Book App
#Phonebook
phonebook = {
'A':{'Alex': '123-456-7890', 'Amy': '234-567-8901'},
'B':{'Brian': '345-678-9012', 'Bobby': '456-789-0123'},
'C':{'Chelsea': '567-890-1234', 'Candy': '678-901-2345'},
'D':{'Derrick': '789-012-3456', 'Donnie': '890-123-4567'},
'E':{'Erik': '901-234-5678', 'Er... | false |
7bf3ded502ca212e55ebdb24b40b27cdf9c020df | shillwil/cs-module-project-iterative-sorting | /src/searching/searching.py | 908 | 4.125 | 4 | def linear_search(arr, target):
# Your code here
if len(arr) is not 0:
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
return -1
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
# Your code here
if l... | true |
3feb8418eda00072433c911fc79984ff78cb77ba | 799898961/python-learn-note | /python学习笔记/第6章-循环控制/6.1遍历循环.py | 1,029 | 4.21875 | 4 | # 6.1遍历循环.py
# 字符串遍历:
for c in "python123":
print(c, end=",")
print()
# 列表遍历:
for item in [123, "python", 456]:
print(item, end=",")
print()
# 遍历某个结构形成的循环运行方式
# for <循环变量> in <遍历结构>:
# <语句块>
# 每次循环,能从遍历结构中逐一提取元素,放在循环变量里
# 并执行一次语句块
# 计数循环n次
# for i in range(n):
# <语句块>
# 遍... | false |
ec747b85a18d2962577e2e24547981b3d70be38b | kemar1997/TSTP_Programs | /Chapter13_TheFourPillarsOfObjectOrientedProgramming/Inheritance.py | 2,766 | 4.90625 | 5 | """
Inheritance in programming is similar to genetic inheritance. In genetic inheritance, you inherit attributes like eye
color from your parents. Similarly, when you create a class, it can inherit methods and variables from another class.
The class that is inherited from is the parent class, and the class that inherit... | true |
ced65aca9c260388d36e6d84939b29e3d60660c2 | kemar1997/TSTP_Programs | /Loops/range.py | 750 | 4.90625 | 5 | """
You can use the built-in range function to create a sequence of integers, and use a for-loop to iterate through them.
The range function takes two parameters: a number where the sequence starts and a number where the sequence stops. The
sequence of integers returned by the range function includes the first paramete... | true |
52c6816d339f1140d7da3fd7c97c9df468084f7f | kemar1997/TSTP_Programs | /String_Manipulation/Concatenation.py | 321 | 4.25 | 4 | """
You can add two (or more) strings together using the addition operator. HTe result is a string made up of the characters
from the first string, followed by the characters from the next string(s). Adding strings together is called
concatenation:
"""
print("cat" + "in" + "hat")
print("cat" + " in" + " the" + " hat"... | true |
56329c35e37e044922969f696523bd39b76281fb | kemar1997/TSTP_Programs | /Challenges/Ch12_Challenges/Triangle.py | 565 | 4.1875 | 4 | # Create a Triangle class with a method called area that calculates and returns
# its area. Then create a Triangle object, call area on it, and print the result.
# a,b,c are the sides of the triangle
class Triangle():
def __init__(self, a, b, c):
self.s1 = a
self.s2 = b
self.s3 = c
def... | true |
17601476e7b674a9900d695a47a4cecc327ae2cf | kemar1997/TSTP_Programs | /Challenges/Ch13_Challenges/Challenge4.py | 415 | 4.34375 | 4 | """
Create a class called Horse and a class called Rider. Use composition to model a horse that has a rider
"""
class Horse:
def __init__(self,
name,
owner):
self.name = name
self.owner = owner
class Rider:
def __init__(self, name):
self.name = name
... | true |
25da8767ef0a8ec27bfc216ca40c4cdf9967adf9 | kemar1997/TSTP_Programs | /Challenges/Ch4_Challenges/ch4_challenge1.py | 236 | 4.25 | 4 | """
1. Writing a function that takes a number as an input and returns that number squared.
"""
def square_a_number():
num = input("Enter a number: ")
num = int(num)
return num*num
result = square_a_number()
print(result) | true |
9b7c6e30ca621c5796db893acbb3eab3a7b7d1f5 | paskwal/python-hackerrank | /Basic_Data_Types/04_finding_the_percentage.py | 1,169 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#
# (c) @paskwal, 2019
# Problem
# You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry.
# The marks can be floating values. The user enters some integer N followed by the names and marks for N students.
# You are re... | true |
3c530015d9a9088feb6ce024b49fc3cd51717ba9 | shobha-bhagwat/Python | /games/RockPaperScissors.py | 1,554 | 4.15625 | 4 | import random
rock = 1
paper = 2
scissors = 3
names = {rock: "Rock", paper: "Paper", scissors: "Scissors"}
rules = {rock: scissors, paper: rock, scissors: paper}
player_score = 0
computer_score = 0
def start():
print("Lets play Rock, Paper, Scissors!!")
while game():
pass
scores()
def game()... | true |
3eed1469ae90561bb9a21487579d822b21d09f8b | shobha-bhagwat/Python | /algorithms/binarySearch.py | 440 | 4.125 | 4 | def binarySearch(arr, start, end, x):
while start <= end:
mid = (start + end)//2
if arr[mid] == x:
return mid
elif arr[mid] < x:
start = mid + 1
else:
end = mid -1
return -1
arr = [-5, 3.0, 10, 20, 50, 80]
x = 3
result = binarySearch(arr... | true |
5d321e674e79ec3037a4831fa1be766fe26a8aab | celusta/Python | /mookwl_P2Q4.py | 312 | 4.125 | 4 | # Filename: mookwl_P2Q4.py
# Name: Marcus Mook Wei Lun
# Description: Determine whether the input year is a leap year
# Prompt user for year
year = int(input("Enter year:"))
# Display result
if year%4 == 0 and year%100 != 0 or year%400 == 0 :
print(year, "is a leap year.")
else :
print(year, "is not a leap yea... | false |
1a257fddb2c63d53423544a9737d3dca62e85968 | xperrylinn/whiteboard | /algo/easy/branch_sums.py | 1,328 | 4.1875 | 4 | # Write a function that takes in a Binary tree and retuns a list of
# its branch sums ordered from leftmost branch to rightmost branch
#
# A branch is the sum of all values in a Binary Tree branch. A
# binary tree branch is a path of nodes in a tree that starts at the
# root and ends at any leaf
# This is the class ... | true |
9ae2ccf4e88e93d0c47565cd6b0b9d18825faa2f | supercp3/code_leetcode | /basedatestructure/stack_run_class.py | 822 | 4.15625 | 4 | class Node:
def __init__(self,value):
self.value=value
self.next=None
class Stack:
def __init__(self):
self.top=None
def push(self,value):
node=Node(value)
node.next=self.top
self.top=node
def pop(self):
node=self.top
if node is None:
raise Exception("this is an empty stack")
self.top=node.n... | true |
877ee9220c82d773f6b8e7e83b281e1be3b455dc | vedashri15/new1 | /Basic1.6.py | 717 | 4.84375 | 5 | #Write a Python program to accept a filename from the user and print the extension of that.
filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + f_extns[-1])
#The function returns a list of the words of a given string using a separator as the delimiter ... | true |
85c53dbee3db530435a9f69c43fac32606b6b476 | tonylattke/python_helpers | /5_functions_methods.py | 1,154 | 4.34375 | 4 | ######################## Example 1 - Create a function and using ########################
# Even or not
# @number : Number to decide
# @return : True if the number is even, otherwise Flase
def even(number):
return number % 2 == 0
# Testing Function
for aux in xrange(0,10):
if even(aux):
print "%d - Even" % aux
e... | true |
8f6f34a49a9920138306f43dca03aaf9d4952df3 | MilanaShhanukova/programming-2021-19fpl | /shapes/circle.py | 803 | 4.125 | 4 | """
Programming for linguists
Implementation of the class Circle
"""
from math import pi
from shapes.shape import Shape
class Circle(Shape):
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
super().__init__(uid)
self.radius = radius
def get_area(self):
... | true |
1c14f80470bc5c858587261c932b8fe958f1b1c3 | yvonneonu/Test8 | /test8.py | 774 | 4.34375 | 4 | # A Simple Python 3 program to compute
# sum of digits in numbers from 1 to n
#Returns sum of all digits in numbers from 1 to n
def countNumberWith3(n) :
result = 0 # initialize result
# One by one compute sum of digits
# in every number from 1 to n
for x in range(1, n + 1):
if(has3(x) == True... | true |
0efc63ac7d07f35ae5d978169adb8849f175bad4 | eawww/BI_HW | /HW1/seqid.py | 2,201 | 4.125 | 4 | #Bridget Mohn and Eric Wilson
#CS 466R
#Homework 1
#Reads an input filename from command line, opens the file, reads each character
#in the file to see whether the file contains a DNA, RNA, or Protein sequence
import sys
#Input filename is taken from the command line which is the second argument
InputFile... | true |
43af2548dc114926d4484a64679589929aa3f22a | cifpfbmoll/practica-5-python-joseluissaiz | /P5E10.py | 768 | 4.21875 | 4 | #Practica 5
# Ejercicio 10
# Escribe un programa que pida la altura de un triángulo y lo
# dibuje de la siguiente manera:
#
#--------Variables
numeroLinea = 1
#
#---------Imports
import sys
#---------Inputs
altura = input("Introduce la altura del triangulo : ")
try:
altura = int(altura)
... | false |
504b89011418c1661929552c52e3fe9842f7ad52 | cifpfbmoll/practica-5-python-joseluissaiz | /P5E3.py | 1,277 | 4.34375 | 4 | # Practica 5
# Ejercicio 3
# Escribe un programa que pida dos números y escriba la suma de enteros
# desde el primero hasta el último.
#
#
#------------------------imports
import sys
#
#------------------------variables
numeroCuenta = 0
numeroCuentaMostrar = ""
#
#------------------------inputs
#numUno
... | false |
3267bcaa907a1eda60abe8c60ff69b7cc7cff0a9 | Ryan-Lawton-Prog/IST | /IST Assessment Program/I1.py | 2,768 | 4.28125 | 4 | def a():
while = True:
print """
\tGuide Contents:
\t* raw_input() = Gives the user the option to input data to the user,
anything inbetween the '()' will be displayed before
the users input.
"""
raw_input()
break
test = True
while te... | true |
9bc1edb29c6feb34e3384611c3353014579821d0 | Ryan-Lawton-Prog/IST | /IST Assessment Program/Run.py | 1,632 | 4.15625 | 4 | import Beginner
# Program Varriable is now True
Program = True
# 'while' Program is true run and loop this
while Program:
# select your difficulty text
print "Please select your Stream"
print "Beginner:"
print "Intermediate:"
print "Advanced:"
# difficulty input
Difficulty = raw_inpu... | true |
5cbe7b44640c6d2c81d1d791e9c5f057b59c03fc | huytranvan2010/Python-Tutotial | /OOP/inheritance.py | 1,497 | 4.21875 | 4 | class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
""" Tạo c... | false |
40917733d3f5c754297756d8e440bdb2c96d5607 | calvinwalterheintzelman/Computer-Security-Algorithms | /Finding Primes/Fields.py | 1,307 | 4.125 | 4 | # Calvin Walter Heintzelman
# ECE 404
# Homework 3
# Python 3.7.2
import os
import sys
print("Please enter a small digit: ")
number = input()
while(number.isdigit() is False or int(number) < 1):
print("Error! Please only input a single small positive integer!")
number = input()
if(int(number)... | true |
42efd486938984bf55bb1699472c9abca16e3106 | Pratik180198/Every-Python-Code-Ever | /factorial.py | 480 | 4.375 | 4 | num1=input("Enter number: ")
try:
num=int(num1)
fact=1
for i in range(1,num+1): #Using For Loop
fact=fact*i
print("Factorial of {} is {}".format(num,fact)) #For Loop Answer
def factorial(num): #Using Recursive Method
if num == 0 or num ==1:
return 1
else:
... | true |
e37e9102d0cf0c191ee4b78bee54a22920f510c4 | z21mwKYq/Python | /Lesson1/les1_task5.py | 376 | 4.1875 | 4 | # Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
num = int(input("Ввдеите порядковый номер буквы"))
if (num > 26 or num < 1):
print("Нет буквы с таким порядковым номером")
exit(0)
print(f"Эта буква - {chr(num+96)}")
| false |
1af7bd227c2e2a919baeda39d55c27d631b93908 | maimumatsumoto/prac04 | /list_exercises.py | 2,474 | 4.28125 | 4 | #//1. Basic list operations//#
numbers=[]
for i in range(5):
value= int(input("Number: "))
numbers.append(value)
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The largest number is {}".format... | true |
32aa4728228b484ee7688709d0afccabcda6b64e | Andrest07/26th-27th_Nov_2019 | /Practice_Assorted_Problem/Num_14.py | 1,026 | 4.15625 | 4 | def makeForming(verb):
if verb.endswith("ie"):
verb = verb[0:len(verb)-2] + "ying"
elif verb.endswith("e") and not verb == "be" and not verb == "see" and not verb == "flee" and not verb == "knee":
verb = verb[0:len(verb)-1] + "ing"
elif (verb.endswith("a") or verb.endswith("o") or verb.... | false |
d7a241d07e554b6b0b56913e51aa3a853ee5c6b9 | gagnongr/Gregory-Gagnon | /Exercises/sum up odd ints.py | 718 | 4.40625 | 4 | # Sum up a series of even numbers
# Make sure user input is only even numbers
# Variable names without types are integers
print("Allow the user to enter a series of even integers. Sum them.")
print("Ignore non-even input. End input with a '.'")
# Initialize input number and the sum
number_str = input("Number: ")
the_... | true |
9fc52b2e6a2a43c2aa277e491f72319e29ba6a68 | CodecoolBP20161/python-pair-programming-exercises-2nd-tw-toti_aron | /listoverlap/listoverlap_module.py | 469 | 4.1875 | 4 | def listoverlap(list1, list2):
common_elements = []
for i in list1:
for j in list2:
if i == j and j not in common_elements:
common_elements.append(j)
return common_elements
def main():
list1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
list2 = [1, 2, 3, 4, 5, 6, 7,... | false |
f55ae7e36f0430c48633e5b032f0adf57c57c9b0 | cserajeevdas/Python-Coding | /decorator.py | 701 | 4.5625 | 5 | #assigned a method to a variable and called the method
# def f1():
# print("in f1")
# x = f1
# x()
#calling f2 from the rturn value of f1
# def f1():
# def f2():
# print("in f2")
# return f2
# x = f1()
# x()
#calling the nested method through passed method
# def f1(f):
# def f... | true |
fcdd687866bc08111a796b3f9650b6317c665049 | LucasEvo/Estudos-Python | /ex022.py | 690 | 4.3125 | 4 | # Crie um programa que leia o nome completo de uma pessoa e mostre:
# 1- O nome com todas a letras minúsculas
# 2- O nome com todas a letras maiúsculas
# 3- Quantas letras ao todo (sem considerar espaços).
# 4- Quantas letras tem o primeiro nome.
nome = str(input('Qual seu nome completo? R: ')).strip()
print('S... | false |
1089725bb18a94128e2bf06a80ac8bd7ee1074db | BaiMoHan/LearningPython_ING_202002 | /Part4/gobang.py | 1,495 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/13 14:45
# @Author : Baimohan/PH
# @Site : https://github.com/BaiMoHan
# @File : gobang.py
# @Software: PyCharm
# def Count(radium):
# from math import pi as p
# C = 2 * p * radium
# A = p * radium ** 2
# return C, A
#
#
# if __na... | false |
ce110be374e105cbea1b7ae6befb50d7b034e457 | walebash/Practice | /nameGenerator.py | 1,392 | 4.21875 | 4 | import random
import string
def name_generator(letters):
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 'y', 'v', 'w', 'x', 'y', 'z']
v = []
c = []
names = []
for letter in letters:
if l... | false |
2119fa5f8557ace83d4b4b1c8efddf7f050fff86 | lz023231/CX.PY | /控制窗体、内存、异常、语音/异常处理.py | 1,799 | 4.15625 | 4 |
'''
'''
#当程序遇到问题是不让程序结束,而略过错误继续向下执行
'''
try……except……else
格式:
try:
语句t
except 错误码 as e:
语句1
except 错误码 as e:
语句1
……
except 错误码 as e:
语句n
else:
语句e
注意:else可有可无
作用:用来检测try语句块中的错误,从而让except补货错误信息并处理
逻辑:当程序执行到try~expect~else语句时
1、如果当try“语句t”出现错误,会匹配第一个错误码,如果匹配上就执行对应的语句
2、如果当try“语句t”出现错误,没有匹配的异常,... | false |
5c36b47de38425bf90e47c7348b525a35c173305 | annewoosam/shopping-list | /shoppinglist.py | 628 | 4.21875 | 4 | print("create a quick, no duplicate, alphabetical shopping list by entering items then hitting enter when done.")
shopping_list=[]
while True:
add_item=input("add item>")
if add_item.lower()!="":
shopping_list.append(add_item.lower())
shopping_list=set(shopping_list)
print( "\no... | true |
987650133ed8611b645aef9a6c2ef0fef97dc2be | tasnia18/Python-assignment-certified-course-in-Coursera- | /Python Data Structure/7_2.py | 954 | 4.125 | 4 | """ 7.2 Write a program that prompts for a file name, then opens that file and reads through the file,
looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values
and produce an output as shown ... | true |
33791e76660c95af96ae04c7b45fd8b1bcfb5646 | snowd25/pyPract | /stringPermutation.py | 611 | 4.25 | 4 | #Python Program to Print All Permutations of a String in Lexicographic Order using Recursion
#without using permutations builtin
def permuteStr(lst,l,r):
if l == r:
print("".join(lst))
else:
for i in range(l,r+1):
lst[l],lst[i] =lst[i],lst[l]
permuteStr(lst,l+1,r)
lst[l],lst[i] =lst[i],lst[l]
# permuta... | true |
b299c50e3fa26dbf0c1f7dab579813670ec6dea1 | moonlimb/tree_problems | /isBST.py | 383 | 4.1875 | 4 | from Node import Node
def is_BST(node):
"""returns True if a given node is a root node of a binary search tree"""
if node.is_leaf():
return True
else:
# Node class contains comparison methods
if (node.left and node.left >= node) or (node.right and node >= node.right):
re... | true |
8db19628f571ab9cb2e0babcb961974c8baaf99d | imsreyas7/DAA-lab | /Recursion/expo3.py | 263 | 4.21875 | 4 | def expo3(x,n):
if n=0:
return 1
else:
if n%2 ==0:
return expo3(x,n/2)*expo(x,n/2)
else:
return x*expo(x,n-1)
x=int(input("Enter a number whose power has to be found "))
n=int(input("Enter the power "))
print("The result is ",expo3(x,n)) | true |
ad02d70583ed30bea2710fbc61df4a00680dfdc0 | Aksharikc12/python-ws | /M_2/Q_2.py | 1,407 | 4.53125 | 5 | '''2. Write a program to accept a two-dimensional array containing integers as the parameter and determine the following from the elements of the array:
a. element with minimum value in the entire array
b. element with maximum value in the entire array
c. the elements with minimum and maximum values in each column
d. t... | true |
211f7d8c6027e43fa5933eb581ecee3a8daf0edb | Aksharikc12/python-ws | /M_1/Q_1.py | 413 | 4.25 | 4 | '''1. Write a program to accept a number and determine whether it is a prime number or not.'''
import math
num=int(input("enter the number"))
is_prime=True
if num<2:
is_prime=False
else:
for i in range(2,int(math.sqrt(num)) + 1):
if num % i == 0:
is_prime=False
break
if is_pr... | true |
50959738f8045b5b3d0beea7c9992cbbe820dc82 | murphy1/python_problems | /chapter6_string.py | 1,577 | 4.1875 | 4 | # file for Chapter 6 of slither into python
import re
# Question 1, user input will state how many decimal places 'e' should be formatted to.
"""
e = 2.7182818284590452353602874713527
format_num = input("Enter Format Number:")
form = "{:."+format_num+"f}"
print(form.format(e))
"""
# Question 2, User will input 2 ... | true |
83b2663bf20b961eb4ac3273e59dbadcb852b9d5 | tommy-stone/Intro_CompSci_Python_Code | /Week_1/Problem Set 2.py | 258 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 13:28:18 2017
@author: tstone
"""
s = 'bobobooooobbbooobobbo'
count = 0
for vowel in s:
if vowel in 'bob':
count += 1
print("Number of times bob occurs is: " + str(count)) | false |
da1190857891ba038938c4e7bba4cd26dbcc21ac | zabdulmanea/movie_trailer_website | /media.py | 555 | 4.125 | 4 | class Movie():
"""
This class provides the structure to store movie information
Attributes:
title (str): The movie title
trailer_youtube_url (str): A link to the movie trailer on youtube
poster_image_url (str): A link to the movie poster
"""
# constructor of Movie class, ca... | true |
b73b09b2466c362a584cada47b9ed0ba2c249d9e | Nitin-Diwakar/100-days-of-code | /day25/main.py | 1,431 | 4.53125 | 5 | # Write a Python GUI program
# using tkinter module
# to input Miles in Entry widget
# that is in text box and convert
# to Kilometers Km on button click.
import tkinter as tk
def main():
window= tk.Tk()
window.title("Miles to Kilometers Converter")
window.geometry("375x200")
# cr... | true |
3d6cab692c8588bf46a2f4f4b96c441141472660 | Endie990/pythonweek-assigments | /Assignment_Guessing_game.py | 534 | 4.125 | 4 | #ass 2- guessing game
import random
guessnum=random.randint(1,9)
num= int(input('Guess a number between 1 and 9: '))
while guessnum!='num':
if num<guessnum:
print('Guess is too low,Try again')
num= int(input('Guess a number between 1 and 9: '))
elif ... | true |
5de52fcb51cf062e250533875d749f7fcd0c5a1e | AdityaJsr/Bl_week2 | /week 2/dictP/createDict.py | 587 | 4.125 | 4 | """
Title - Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string : 'w3resource'
Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
Access individual element through indexes.
Author... | true |
423df06c344e381a8d09156226b10ef17f37bebd | thatguysilver/pswaads | /listing.py | 966 | 4.21875 | 4 | '''
Trying to learn about the different list concatenation methods in py
and examine their efficiency.
'''
import time
def iterate_concat():
start = time.time()
new_list = []
for i in range(1000):
new_list += [i]
end = time.time()
return f'Regular iteration took {end - start} seconds.'
d... | true |
304769d3a15878e844f87a8fa360e8a7ee5a5c97 | dan480/caesars-cipher | /main.py | 1,364 | 4.3125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import argparse
from src.select_alphabet import select_alphabet
from src.decoding import decoding_func
from src.encoding import encoding_func
"""
The main file that runs the program logic.
The function of creating a command line parser is implemented here.
In the main () func... | true |
c9a18125f74caacb4b470d986bf7e09fe119b180 | Tchomasek/Codewars | /Codewars/6 kyu/Sort the odd.py | 663 | 4.3125 | 4 | def sort_array(source_array):
result = list(source_array)
even = {}
for index,num in enumerate(source_array):
if num % 2 == 0:
even[index] = num
result.remove(num)
result.sort()
for index,num in even.items():
result.insert(index, num)
return result
print(... | true |
0adb0d78954c719dadafd33dde275e43387b70bc | Machin-Learning/Exercises | /Section-1/Data Types/set.py | 1,475 | 4.40625 | 4 | # #Set
# 1. Set in python is immuttable/non changeable and does not show duplicate
# 2. Set are collection of element seprated by comma inside {,}
# 3. Set can't be indexed or... | true |
f6b584f4a4315fc01bba5463bca09b968f9f2d76 | Machin-Learning/Exercises | /Section-1/Data Types/variables.py | 1,191 | 4.125 | 4 | # Variables in python
# var = 5
# print(var)
# var = "Muzmmil pathan"
# print(var)
# Data Types
# 1. int()
# 2. str()
# 3. float()
# 4. list()
# 5. tuple()
# 6. set()
# 7. dict()
num = 4 #integers are a number "without point / non fractional / Decimal from 1-9 only"
print(type(num)... | true |
94f03f87bc88a62fcdcb3e215b6d3157a5d77149 | Machin-Learning/Exercises | /Section-3/Fuction and Method/User Input/user_input.py | 251 | 4.28125 | 4 | # User Input
# To get input from user we use input() method
name = input("Enter your name: ") # Remember input() take input in string format
age = input("Enter your age: ")
print(f"Welcom {name}")
print(f"Your life Expectancy {100 - int(age)} Years") | false |
d9e48b09f2c3a902b3009279f89263b5eee7087e | yashbagla321/Mad | /computeDistancePointToSegment.py | 1,014 | 4.15625 | 4 | print 'Enter x and y coordinates of the point'
x0 = float(input())
y0 = float(input())
print 'Enter x and y coordinates of point1 then point2 of the line'
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
import math
def computeDistancePointToSegment(x1,y1, x2,y2, x3,y... | true |
e898d4e4b96bf10bdba01c473cfa8de608ff158d | mxu007/leetcode | /414_Third_Maximum_Number.py | 1,890 | 4.1875 | 4 | # Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
# Example 1:
# Input: [3, 2, 1]
# Output: 1
# Explanation: The third maximum is 1.
# Example 2:
# Input: [1, 2]
# Output: 2
# Explanation: The ... | true |
00a7856bbfb3690bf77899cfa4ce5e1c59b43191 | saifeemustafaq/Magic-Maths-in-Python | /test.py | 892 | 4.25 | 4 | print ""
print " Please press enter after each step!"
print ""
print ' Think of a number below 10...'
a=raw_input( )
print ' Double the number you have thought.'
b=raw_input()
c= int(input(" Add something from 1-10 with the getting result and type it here (type only within 1-10... | true |
85f11d93c2b76f8a0f8def3f861002cb73056ef9 | Hariharan-K/python | /remove_all_occurrences.py | 1,086 | 4.34375 | 4 | # Remove all occurrences of a number x from a list of N elements
# Example: Remove 3 from a list of size 5 containing elements 1 3 2 3 3
# Input: 3 5 1 3 2 3 3
# Output: 1 2
# Input: 4 7 1 4 4 2 4 7 9
########################
import sys
def remove_all_occurrences(mylist,n):
# loop to traverse each element in list... | true |
b68c2c507980032894a5f75f3a3c619b28b559d1 | Hariharan-K/python | /max_sum_of_non_empty_array.py | 1,411 | 4.28125 | 4 | """
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maxim... | true |
de2318e0e48f591e07074c66b6fe9bd924fbd358 | xuzhanhao06/PythonBase | /20200602随机分配办公室.py | 553 | 4.125 | 4 | #将8人分配3教室
'''
1. 准备数据
2.分配
3.验证
'''
import random
#1.
teachers=['A','B','C','D','E','F','G','H']
offices=[[],[],[]]
#2.
for name in teachers:
#列表追加数据--append extend insert
num=random.randint(0,2)
offices[num].append(name)
print(offices)
#3.
#办公室+个编号
i=1
for office in offices:
#打印人... | false |
a859cf7b8c1e199bc6a6ed9c4e649f1b0ea344cb | xuzhanhao06/PythonBase | /20200602元组.py | 422 | 4.1875 | 4 | #如果想要存储多个数据,但是这些数据是 不能修改的数据 ,----元组
#元组特点:定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型。
t1=(10,20,30)
print(t1)#(10, 20, 30)
print(type(t1))#<class 'tuple'>
t2=(10,)
t3=(10)
print(type(t2))#'tuple'
print(type(t3))# 'int'
t4=('aaa')
print(type(t4))# 'str'
t5=('aaa',)
print(type(t5))#tuple
| false |
feb56976564ffc9050e2fbfc0538ac172fb9b10b | huangzhilv/PythonPro | /python_demo/error_debug_test/debug.py | 2,261 | 4.1875 | 4 | import logging
print('''---------------------调试---------------------
''')
# 需要一整套调试程序的手段来修复bug。
# 第一种 方法简单直接粗暴有效,就是用print()把可能有问题的变量打印出来看看:
# 用print()最大的坏处是将来还得删掉它,想想程序里到处都是print(),运行结果也会包含很多垃圾信息。所以,我们又有第二种方法。
def foo(s):
n = int(s)
print('>>> n = %d' % n)
return 10 / n
def main():
foo('0')
# ma... | false |
f398f63722bbc7361943d84f629334a9b880ed88 | huangzhilv/PythonPro | /python_demo/func_program/higher_order_func/__init__.py | 307 | 4.15625 | 4 | # 高阶函数
# 变量可以指向函数
print("abs(-10)=", abs(-10))
print("abs=", abs)
# 可见,abs(-10)是函数调用,而abs是函数本身。
f = abs
print("\nf(-10)=", f(-10))
# 传入函数
# 一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
print(add(-5, 6, abs))
| false |
7cb9735d6e8c25d21f8bae96ca9780332eab0d27 | kanglicheng/learn-python-2020 | /yinqi/week3.py | 2,359 | 4.21875 | 4 | # examples of dictionary
# Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
# print(Dict)
# del Dict ['Charlie']
# print(Dict)
# t = "Tim" in Dict
# print(t)
# res = {}
# print("x" in res)
"""""""""
problem 1
"""""""""
def get_rainfall(dat):
res = {}
for x in dat:
city = x[0]
amount... | false |
9fd8b191b77e79f0c6e335ddefc35817e5edddd6 | FengyiLi1102/Python-Learning | /check_fermat.py | 749 | 4.21875 | 4 | import math
def check_fermat(a, b, c, n):
if n <= 2 or type(a and b and c and n) is not int or a * b * c < 0:
raise ValueError
oo = 1
for b in range(1, b):
for a in range(1, a):
for n in range(2, n):
c = math.log((a**n + b**n), n)
if t... | false |
7bb3fd83c75400cf21e849e29494e117a57befa6 | EchoDemo/Python | /Python_elementary/unit5/class.py | 948 | 4.125 | 4 | #coding:utf-8
#1、创建dog类:
class Dog(object):
"""docstring for Dog"""
def __init__(self, name,age):
"""初始化属性name和age"""
self.name = name
self.age = age
self.master_numbers=0 #为属性指定默认值
def sit(self):
print(self.name.title()+" is now sitting.")
def roll_over(self):
print(self.name.title()+" rolled over."... | false |
e832abb0aa4eb61822c58068c5ff12dfc06851cd | EchoDemo/Python | /Python_elementary/unit2/list_sort.py | 540 | 4.25 | 4 | #coding:utf-8
#1、使用sort()对列表进行永久性排序;
cars=['bmw','audi','toyota','subaru']
cars.sort() #按字母顺序排列(永久性的)
print(cars)
cars.sort(reverse=True) #按字母逆序排列(永久性的)
print(cars)
#2、使用函数sorted()对列表进行临时排序;
cars=['bmw','audi','toyota','subaru']
print(cars)
print(sorted(cars)) #临时排序;
print(sorted(cars,reverse=True))
print(cars)
#3、... | false |
88f55010db0303121f3c6ba25cba54efe923589f | Colfu/codewars | /6th_kyu/autocomplete_yay.py | 2,620 | 4.21875 | 4 | # It's time to create an autocomplete function! Yay!
# The autocomplete function will take in an input string and a dictionary array
# and return the values from the dictionary that start with the input string. **Cr.1
# If there are more than 5 matches, restrict your output to the first 5 results. **Cr.2
# If there a... | true |
8c1e72d62ca4f9dcdc61a861d0dc8ed095d922ba | sankari-chelliah/Python | /int_binary.py | 414 | 4.34375 | 4 | #Program to convert integer to Binary number
num= int(input("Enter Number: "))
result=''
#Check the sign of the number
if num<0:
isneg=True
num = abs(num)
elif num==0:
result='0'
else:
isneg= False
# Does actual binary conversion
while num>0:
result=str(num%2)+result
num=num//2
#Display resu... | true |
3a40e7b025d83d81c9f59ee9b5774f4d68a5039b | ywkpl/DataStructuresAndAlgorithms | /Sort/MergeSort.py | 1,611 | 4.15625 | 4 | #归并排序,分而治之
import random,time
class MergeSort:
def __init__(self, capacity:int):
self._arr=[]
self._insert_values(capacity)
def _insert_values(self, capacity:int):
for x in range(capacity):
self._arr.append(random.randint(1,100000))
def print_all(self):
print(s... | false |
e00cd5b8f7123eb566e5bb8c84aaa479e2300877 | namand010/Project4091998 | /Learning_code/DaysinBtwDates.py | 1,661 | 4.1875 | 4 | def isleapyear(year):
if year % 4 == 0 or year % 400 == 0:
return True
else:
return False
def DaysInmonth(year,month):
if month == 1 or month == 3 or month == 5 or month == 7 \
or month == 8 or month == 10 or month == 12:
return 31
else:
if month == 2:
... | false |
932e7ff84d93da6509d9a8b44eb161d873ec72a4 | uestcljx/pythonBeginner | /prime.py | 1,415 | 4.15625 | 4 | #odd_iter 生成一个无穷奇数数列,作为初始数列(2以外的偶数都不是素数)
def odd_iter():
n = 1
while True:
n = n + 2
yield n
#not_divisible 输入参数n, 内部定义一个匿名函数,输入参数x, 判断x是否能被n整除
def not_divisible(n):
return lambda x: x % n > 0 # 注意这里定义了一个匿名函数,所以实际上not_divisible函数要接受两个参数
#生成无穷素数数列
def prime():
_iter = odd_iter() #初始数列
... | false |
ec094d809089a6cff9ded0f6cd4a10e98a698e60 | rstrozyk/codewars_projects1 | /#8 alternate_capitalization.py | 673 | 4.28125 | 4 | # Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index 0 will be considered even.
# For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples.
# The input will be a lowercase string with no spaces.
# Good luck!
d... | true |
1a84de296000421f725a38ef905ab5f590d085ac | SanghamitraDutta/dsp | /python/markov.py | 2,440 | 4.5625 | 5 | #!/usr/bin/env python
# Write a Markov text generator, [markov.py](python/markov.py). Your program should be called from the command line with two arguments: the name of a file containing *text to read*, and the *number of words to generate*. For example, if `chains.txt` contains the short story by Frigyes Karinthy, w... | true |
14f4b6abd789bffaf54ab8587be22f13dd87e572 | j721/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,128 | 4.4375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
middle = (start +end)//2
if len(arr) == 0:
return -1 #empty array
#if target is equal to the middle index in the array then return it
if arr[middle] == target:
... | true |
570b85577fcc8343c1d9fa11d8e0bd95eb3a4e3f | kulsuri/playground | /daily_coding_problem/solutions/problem_9.py | 611 | 4.1875 | 4 | # Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
# For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
def largest_sum(l):
inclusive = 0
exclusive = 0
... | true |
4ecf79677118a95f24d80fe0ead4272e8f61eeec | kulsuri/playground | /udemy-11-essential-coding-interview-questions/1.1_arrays_most_freq_no.py | 911 | 4.21875 | 4 | # return the most frequent element in an array in O(n) runtime
def most_frequent(given_array):
# insert all elements and corresponding count in a hash table
Hash = dict()
for c,v in enumerate(given_array):
if given_array[c] in Hash.keys():
Hash[given_array[c]] += 1
else:
... | true |
07d0eb183fcc1f3fd342e785a743043658114649 | kylebush1986/CS3080_Python_Programming | /Homework/Homework_3/hw3_kyle_bush_ex_3.py | 1,708 | 4.4375 | 4 | '''
Homework 3, Exercise 3
Kyle Bush
9/21/2020
This program stores a store inventory in a dictionary.
The user can add items, delete items, and print the inventory.
'''
def printInventory(inventory):
print()
print('Item'.ljust(20), 'Quantity'.ljust(8))
for item, number in inventory.items():
print(i... | true |
1270188cab6e1d289056abee5013a4f729bfb40d | justinDeu/path-viz | /algo.py | 1,273 | 4.40625 | 4 | from board import Board
class Algo():
"""Defines an algorithm to find a path from a start to an end point.
The algorithm will be run against a 2D array where different values
signify some state in the path. The values are as follows:
0 - a free cell
1 - a blocked cell (cannot ... | true |
5d3f9ba65e4c68e743ea21a0db8dbbb54c92bd6f | prahate/python-learn | /python_classes.py | 926 | 4.21875 | 4 | # self is defined as an instance of a class(similar to this in c++),and variables e.g. first, last and pay are called instance variables.
# instance variables are the ones that are unique for each instance e.g. first, last and pay. They are unique to each instance.
# __init__ is called as constructor(in languages like ... | true |
e9d4a5afa1859ec6b3ad87a3000bee910afef669 | prahate/python-learn | /python_sqlite.py | 698 | 4.5 | 4 | import sqlite3
# Creating a connection sqlite database, it will create .db file in file system
# other way to create is using memory, so database will be in memory (RAM)
# conn = sqlite3.connect(':memory:')
conn = sqlite3.connect('employees.db')
# To get cursor to the database
c = conn.cursor()
# Create table using... | true |
3175206b9d152bed4e484eff5dc8c229c9fa74af | ruthiler/Python_Exercicios | /Desafio077.py | 526 | 4.15625 | 4 | # Desafio 077: Crie um programa que tenha uma tupla
# com várias palavras (não usar acentos). Depois disso,
# você deve mostrar, para cada palavra, quais são as suas vogais.
palavras = ('aprender', 'programar', 'linguagem', 'python',
'curso', 'gratis', 'estudar', 'praticar',
'trabalhar', 'merca... | false |
6cd508557a1fe3d17d7e1eb8a051e0b5282b96cf | ruthiler/Python_Exercicios | /Desafio085.py | 630 | 4.21875 | 4 | # Desafio 085: Crie um programa onde o usuário possa digitar sete valores
# númericos e cadastre-os em uma lista única que mantenha separados os valores
# pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente
# encoding: utf-8
numeros = [[], []]
for n in range(1, 8):
num = int(input('0{}... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.