blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c8b643d16c3e97b66dc304ba2ab4323134de3430 | leoniepnzr/MyExercises | /ex18.py | 1,246 | 4.8125 | 5 | #functions: name pieces of code, take arguments, lets you do mini-scripts
#created with def
#* tells Python to take all arguments and collect them in list, like argv for functions
def print_two(*args):#make a function with "def", giving function a name, *args in parantheses to work, just like argv, start with :
ar... | true |
d566fd621c31a770484e719e9096930421f30c49 | leoniepnzr/MyExercises | /ex33.py | 399 | 4.25 | 4 | #while loops for running until Boolean expression is False
#to follow loop jumping, write print everywhere in code (top, middle, bottom) -> trying to understand
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the... | true |
976be5017743a3f36e2587676b76b4ae6bc7be8c | JuliusBoateng/data_structs_and_algs | /fundamentals/selection_sort.py | 780 | 4.125 | 4 | #!/usr/bin/env python3
import random
def find_index_of_min(arr, start):
min_element = arr[start]
min_index = start
for index in range(start + 1, len(arr)):
if arr[index] < min_element:
min_element = arr[index]
min_index = index
return min_index
def swap(arr, first, se... | true |
8d8fc57bb1d3617fb301628ffdecbd633446ce33 | luoyi94/Python | /02-循环判断/案例:九九乘法表.py | 367 | 4.21875 | 4 | # 第 1 步:用嵌套打印小星星
# i = 1
# while i <= 5:
# print("*" * i)
# i += 1
# print("end")
# 用列row来控制总数 有多少列就有多少行col 只有 列 +1,对应 行 才 +1
row = 1
while row <= 9:
col = 1
while row >= col:
print("%d X %d = %d" % (row, col, row * col),end="\t")
col += 1
print()
row += 1
| false |
c1cc167c298d81f5eea15a63cbf1e0b5a0251769 | dathanwong/Dojo_Assignments | /Python/python/ForLoopBasicII.py | 2,346 | 4.15625 | 4 | #1. Biggie Size
#Given a list write a function that hanges all positive numbers to big
def biggie(list):
for x in range(len(list)):
if list[x] > 0:
list[x]="big"
return list
print(biggie([-2,3,5,-5]))
#2. Count Positives
# given a list of numbers replace the last value wiht the number of po... | true |
82818bf299d970c9bd47036bb268cc2c88330c41 | abhishekk40/Test1 | /test1.py | 423 | 4.15625 | 4 | a=6
y=0
for i in range(1,6): # Always keep the first loop for the Count of Number of lines
for j in range(1,y+1): # This loop is for Printing Space
print(" ",end=" ")
y=y+1 #This is for increasing the number of spaces everytime
for k in range(1,a): #This loop is for Printing "1"
print("1",en... | true |
18231c614f5ae04068e1b33132e31f3e16317f00 | jonvaljean/flask-course | /decorators.py | 1,102 | 4.59375 | 5 | #a decorator is a function that gets called before another function
#SAVE THESE TEMPLATES for decorators with and without parameters
import functools
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func():
print("in the decorator!")
func() #always call the func... | true |
58ec57242e5f775f110328bf2a8af557c9329c18 | HYPERTONE/EPI-Python | /Primitive Types/4.3 - Reverse Bits.py | 789 | 4.375 | 4 |
# Write a program that takes a 64-bit unsigned integer and returns the 64-bit unsigned integer consisting
# of the bits of the input in reverse order.
def reverseBit(num):
result = 0
while num:
result = (result << 1) + (num & 1)
num >>= 1
return result
# The goal here is to AND our num b... | true |
cbfc948f149cb6c96efa71a300146b902bf60b6f | HYPERTONE/EPI-Python | /Binary Trees/9.1 - Test If A Binary Tree Is Height-Balanced.py | 1,597 | 4.375 | 4 |
# A binary tree is said to be height balanced if for each node in the tree, the difference in height of its left and right subtrees
# is at most one. A perfect binary tree is height-balanced, as is a complete binary tree. A height-balanced binary tree does not have to
# be perfect or complete.
# Write a program that... | true |
5f5693cd376ba31a0f25d7882a7d34c71b255646 | HYPERTONE/EPI-Python | /Binary Trees/9.2 - Test If A Binary Tree Is Symmetric.py | 1,135 | 4.4375 | 4 |
# A binary tree is symmetric if you can draw a vertical line through the root and then the left subtree is a mirror image of the
# right subtree.
# Write a prgoram that checks whether a binary tree is symmetric.
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
... | true |
d63590eb2be1bc0891198db6fc5c4f19666a95d4 | chengjun0917/DailyQuestion | /shuaidi/question02.py | 1,650 | 4.15625 | 4 | from random import randint
from sys import exit
min_of_target = 0
max_of_target = 100
target = randint(min_of_target,max_of_target)
chances = 7
print("Welcome to guess number game!")
print(f"You have {chances} chances to guess the number, which is range from {min_of_target} to {max_of_target}.")
print("Each time you ... | true |
554532a2f891decc28fcbb9b448c4156825b1b41 | k1211/30daysHackerRank | /Day12/day12.py | 2,088 | 4.21875 | 4 | # You are given two classes, Person and Student, where Person is the base class and Student is the derived class.
# Completed code for Person and a declaration for Student are provided for you in the editor.
# Observe that Student inherits all the properties of Person.
#
# Complete the Student class by writing the foll... | true |
1e07fbc119e4d4714a20308b7d6c6a66d5f6250a | k1211/30daysHackerRank | /Day13/day13.py | 1,099 | 4.28125 | 4 | # Given a Book class and a Solution class, write a MyBook class that does the following:
#
# - Inherits from Book
# - Has a parameterized constructor taking these 3 parameters:
# - string title
# - string author
# - int price
# Implements the Book class' abstract display() method so it prints these 3 lines:... | true |
66a7797612d2d64534d42cb1a99951d8ca3ddd58 | k1211/30daysHackerRank | /Day3/day3.py | 569 | 4.5625 | 5 | # Given an integer, n , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5 , print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Complete the stub code provided in you... | true |
99d5cd5b49cf6dc7eefc30daae1d06d755c8364e | kiranraju03/PractiseCode | /HackerEarth/e-maze-in.py | 698 | 4.3125 | 4 | """
Maze display
A person is stuck in a maze at a starting position of (0,0), a route map is given as an input, find the end position
after he has traversed the route map
Route Map directions, L,R,U,D : left, right, up and down
Hint : Numberical Scale concept
Complexity:
Time : O(N) : N is the length of the route ma... | true |
f009eded0a83e3a3555f3512b41a5130cbf5965c | kiranraju03/PractiseCode | /HackerRank/CountingValley.py | 640 | 4.375 | 4 | """
Counting Valley
Check for number of valleys crossed in a hike with uphills(U) and downhills(D)
When the hiker comes to a valley after U/D count the valley
Sample Input : UDDDUDUU
Visual : _ is the valley
_/\ _
\ /
\/\/
"""
def valleyCounter(path):
sea_level = 0 # represents surface/valley
... | false |
e26ac036f6b8a05e4fde1e2d6e42e8dbe212272e | kiranraju03/PractiseCode | /Strings/CaesarCipher.py | 1,595 | 4.15625 | 4 | """
Caesar Cipher
Create an encrypted string using the key as the number of shifts to be made
"""
# Solution 1 : 26 characters Approach
# Time : O(1) : as we are dealing with only 26 characters, O(26), i.e., O(1) constant operation
# Space : O(n) : n is the length of the string that needs to be encrypted
def caesar_c... | true |
78cda78517737e238cdb18e820cee96de227f072 | kiranraju03/PractiseCode | /HackerRank/SockMerchant.py | 1,343 | 4.125 | 4 | """Find the number of pairs of socks from the set of socks
Input : number of socks (n) and array of socks ([])
Output : number of socks pairs available in the array
"""
from collections import Counter
def sockPairChecker(socks):
socks_count = Counter(socks)
for eachcount in socks_count:
sock_color = e... | true |
e6ab2e9ed88ef22e88e56ca8ca68640bd3d1ac88 | kiranraju03/PractiseCode | /Searching/ThreeLargeNumbers.py | 1,159 | 4.53125 | 5 | """
Find the 3 largest numbers in a array
Complexity :
Time : O(N) : N is the length of the array
Space : O(1) : Only shifting of values is involved
"""
# Helper method : Used to assign values to the three number array
# if the index is 2, then the values have to be left shifted once and so for others
def shift_updat... | true |
f9bd700a14a2def73cf25ffd208443c9f958fcd6 | a-soliman/py-hello_you | /hello.py | 605 | 4.15625 | 4 | '''
1. Ask user for name.
2. Ask user for age.
3. Ask user for city.
4. Ask user what they enjoy
5. Create output text.
6. Print output to screen
'''
from person_class import *
from sanitize import *
name = input('What is your name?: ')
name = trim(name)
name = make_lower(name)
name = make_title(name)
age ... | true |
0a1fe2c9621a03a5529fef3b866b2fcb10e251e4 | PassionateLooker/competetive-programming-python | /27convertCm_to_inchMeterAndKm.py | 826 | 4.15625 | 4 | # print(46.52/2.54) #cm to inch
# print(3491/100) #cm to meter
# print(3491/1000) #cm to km
cent=float(input("Enter centemeter"))
cent_to_inch=cent/2.54
cent_to_meter=cent/100
cent_to_km=cent/1000
print(cent,"centemeter in inches is",cent_to_inch)
print(cent,"centemeter in meter is",cent_to_mete... | false |
ce8d3d9bc08854ea430b7b9b50d248d81772cf13 | hmangukia/Hack2020 | /Python/SumOfSquares.py | 581 | 4.25 | 4 | '''
This program finds the sum of square
of first n natural numbers.
Input is obtained from the user.
'''
def SumOfSquares(n):
sum = 0
for i in range(1, n+1):
sum = sum + i * i
return sum
def SquaresOfSum(n):
sum = 0
for i in range(1, n+1):
sum = sum + i
return (sum * sum)
n =... | true |
8709f9c81dbf0cff43a7b72b1bafc58dacc22669 | MoRahmanWork/Py4Fin | /LearningHowToCode/Programmiz/Functions.py | 1,374 | 4.40625 | 4 | def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Paul')
def greet(name, msg="Good morning!"):
"""
This function greets to
the person with the
provided message.
If the message is not prov... | true |
3e362c72c37808bb83f742e336e7a354db4d1ee3 | carwyyn/Jumblejumble | /get_words.py | 742 | 4.375 | 4 | import pickle
#a function to retrieve the words from the text file, save them to a list of lists, and store it in pickle
def get_word(file_name, l_name):
#open the text file at the address of file_name
with open(file_name, "r+") as l_name:
#read the text file
whole = l_name.read()
#cre... | true |
d95a59cedaa3724c86391d90ef72bfe66d6586f8 | merinjo90/PHYTHON_MINI_PROJECT | /Bank_Application/bank_application.py | 2,197 | 4.34375 | 4 |
"""
#create a bank application.
# : "Account"-parent class, with a "BankName: ABC bank,IFSCcode : 45154,Balance" as
# class variables. inital balace "10000"common to all customer.
# :"AccountHolder"-child class, with instance variables "name,AccNo" and functions
# "Deposit,widrow,Bala... | true |
61b9117744cbaca25ef9ec0144b0bb5fc276cc78 | mrseidel-classes/archives | /ICS3U/ICS3U-2019-2020F/Code/notes/20 - formal_documentation/formalDocumentation_ex3.py | 1,175 | 4.46875 | 4 | #-----------------------------------------------------------------------------
# Name: Formal Documentation i.e. docstrings (formalDocumentation_ex3.py)
# Purpose: Provides an example of how to create docstrings in Python using
# formal documentation standards.
#
# Author: Mr. Seidel
# Created: ... | true |
bf39ffd74d9b82192bffa74b189dd30b71788dc3 | mrseidel-classes/archives | /ICS3U/ICS3U-2019-2020F/Code/notes/30 - dictionaries/dictionaries_ex1.py | 827 | 4.5 | 4 | #-----------------------------------------------------------------------------
# Name: Dictionaries (dictionaries_ex1.py)
# Purpose: To provide examples of how to use dictionaries
# Accessing keys, values, and adding in information
#
# Author: Mr. Seidel
# Created: 18-Nov-2018
# Updated... | true |
1f20f0afd76db21f0a9b952d072892e981a47d1d | mrseidel-classes/archives | /ICS3U/ICS3U-2019-2020S/Code/notes/21 - logging/logging_ex1.py | 2,170 | 4.15625 | 4 | #-----------------------------------------------------------------------------
# Name: Logging (logging_ex1.py)
# Purpose: To provide examples of how to debug and log information in
# Python programs.
#
# Author: Mr. Seidel
# Created: 11-Nov-2018
# Updated: 02-May-2020 (updated Non... | true |
57b208265cf027b9cfd74921fbb1b16cb2ebf371 | mrseidel-classes/archives | /ICS4U/ICS4U-2021-2022S/Code/examples/recursion/Python/recursive_drawing.py | 976 | 4.28125 | 4 | '''
Recursive example using Turtle graphics to draw
Modified from this work
https://p5js.org/examples/simulate-recursive-tree.html
'''
def branch(height, theta): # recursive function
'''
Draws a single branch of a tree.
Parameters
----------
height : int
The length of the branch in the tre... | true |
6c4ca067f7d85cb9b3c999fca62a3b332fe18604 | mrseidel-classes/archives | /ICS3U/ICS3U-2018-2019-Code/notes/08b - logging/logging_ex5.py | 2,992 | 4.40625 | 4 | #-----------------------------------------------------------------------------
# Name: Logging (logging_ex5.py)
# Purpose: To provide examples of how to debug and log information in
# Python programs.
# Important:
# This version implicitly creates a CRITICAL error
# ... | true |
4c577daf3b94303327af0cfbf8ca06b63cdf98f2 | mrseidel-classes/archives | /ICS3U/ICS3U-2018-2019S/Code/notes/02 - conditionalStatements (if)/conditionalStatements.py | 883 | 4.21875 | 4 | #-----------------------------------------------------------------------------
# Name: Conditional Statements (conditionalStatements.py)
# Purpose: To provide information about how conditional statements (if)
# work in Python
#
# Author: Mr. Seidel
# Created: 15-Aug-2018
# Updated: 15-Aug-2... | true |
1825a895b2ece800dfb949c115529043607cd498 | theIncredibleMarek/algorithms_in_python | /insertion_sort.py | 2,537 | 4.1875 | 4 | #!/usr/bin/env python3
# TODO - start from the 2nd element - index is 1
# if ascending - check if smaller than the one immediately preceding
# if descending - check if bigger than the one immediately preceding
# finish when you reach the end of the list
def sort(input, ascending=True):
print("Original: {}".forma... | true |
59a3a226dfc7ce191d25ff070d356adb970d984a | hugofolloni/50-days-of-code-challenge | /019/fibonacci-sequence.py | 432 | 4.125 | 4 | print("-----------\n FIBONACCI\n-----------")
parameters = int(input("Tell me the length of your wanted Fibonacci sequence?\n "))
fibArray = [0, 1]
def fibonacciCalculator():
penultimo = fibArray[-2]
ultimo = fibArray[-1]
newNumber = penultimo + ultimo
fibArray.append(newNumber)
for i in range(0, ... | false |
963fdbbf6fe77bcbd86e55c03d7ec1938de8d6f7 | Prot0type1/IS-51-FINAL | /FINAL.py | 1,378 | 4.125 | 4 | """
start
this program will output the grades of students on the final by:
-number of grades
-average of grades
-percentage of grades above the average percentage
the average grade is 83.25.
the total number of grades is 24.
the percentage of grades above average is 54.17
the list will be introduced from... | true |
79bf452c4f9f4e5d78565fd0efdfa77f5302e891 | shearocke/IT_SQL1 | /MyDatabase.py | 1,074 | 4.4375 | 4 | import sqlite3
# create a name for the database
database = 'Company.db'
# create a connection to the database
conn = sqlite3.connect(database)
# conn.execute('DROP TABLE IF EXISTS Customers')
#
# create table with fields and data types
# conn.execute('''CREATE TABLE Customers
# (id INT NOT NULL,
# ... | true |
2c340beb71b8bce58cc3c5b1b2e1683a1b82c820 | Luciano0000/Pyhon- | /object/魔术方法/QianFeng023object3.py | 1,064 | 4.3125 | 4 | # 魔术方法续:
# __str__
'''
触发时机:使用print(对象名)或者str(对象名)的时候触发去调用__str__里面的内容
参数:一个self接收对象
返回值:必须要在__str__中有返回值且是字符串类型
作用:print(对象时)进行操作,得到字符串,通常用于快捷操作
注意:无
'''
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'name是:'+self.name+',age是:'+... | false |
97c2b618a64f9ee80aa0317ea2e204f52495dd39 | Luciano0000/Pyhon- | /List/QianFeng008list02.py | 1,047 | 4.15625 | 4 | # 列表的切片
#['abc','kkokok','dasd','geeww',99,80.8]
list1 = ['abc','kkokok','杨幂','胡一菲',666,68.8]
#列表里允许任意类型
print(list1)
print(list1[2:4]) #杨幂 胡一菲 脚标:2 3 同样包前不包后 [2:4]
#截取的结果再次保存在一个列表中 ['','']
print(list1[::2]) #支持步长
print(list1[-1::-2]) #支持逆序
# list 列表的添加:
# 临时的小数据库: list
# list的添加函数 :1.append()追加 2.extend()列表的合并... | false |
68647861144f8807638df84e08185d03264c8d02 | Carla08/cracking-the-interview | /data_structures/linked_lists/node_lists_problems.py | 2,890 | 4.125 | 4 | from typing import List
from data_structures.linked_lists.linked_list import LinkedList
def reverse_linked_list(lst):
n = lst.head
_next = None
_prev = lst.head
while n:
_next = n.nxt
n.nxt = _prev
_prev = n
n = _next
lst.head.nxt = None
lst.head = _prev
ret... | true |
c25ab8635033d6aa75ba95f82cdd6b7d2f8d3301 | MichaelKirkaldyV/Algos_ | /findmiddle.py | 1,330 | 4.125 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, head=None):
self.size = 0
self.head = head
def insertNode(self, value):
node = Node(value)
print(node)
if self.head == None:
... | true |
b128d95e3c348686674f2162d958e4705d72bf45 | 123akhil/datascience | /6.00.1x_Introduction_to_Computer_Science_and_Programming_Using_Python/edx_old/Resources/6.00.1x/PROBLEMS/Finger Excercises/test.py | 210 | 4.3125 | 4 | # -*- coding: cp1252 -*-
a = int(raw_input('Mete tu nmero: '))
if a>3:
print(' ')
print ('Tu nmero es mayor que 3')
else:
print('Tu numero es menor o igual que 3')
print ('Hemos terminado')
| false |
ec6bae2cb2305d4d9f86090204a7025481a130ea | ganesspandian2/programming-in-python | /vowcha.py | 269 | 4.125 | 4 | def isvowel(s):
for i in s:
if i=="a" or i=="e" or i=="i" or i=="o" or i=="u":
return True
return False
s=input()
if isvowel(s):
print("The given character is Vowel")
else:
print("The given character is Consonant")
| false |
f71dc34a7f9a7010f8c6cf830149d3a649a996b1 | daviidluna/PythonLists | /lists.py | 1,195 | 4.1875 | 4 | mine = ['a promised', 'land', 'hehe']
print(mine)
yes = ['cabbage', 'eggplant', 'watermelon']
if 'watermelon' in yes:
print('yes, watermelon is present in the list \'yes\'')
wait_list = ['amanda', 'fiber', 'oliver']
if 'oliver' in wait_list:
print('yes he is on the wait list')
# Accessing list items
one = ['... | true |
859566908e2be6b188a8c660df0e7d766d1624b5 | ahdeshpande/PythonPrograms | /html_unordered_list.py | 1,454 | 4.21875 | 4 | def string_list_to_html_ul(string_list):
"""
Function that converts a string list to an HTML unordered list
"""
# Create a html unordered list from the user input list.
# Add the start tag of ul
html_string = "<ul>\n"
# Iterate through input list
for user_input in string_list:
... | true |
708f717b8ed7b06eb15998d711fa97cf70e1da14 | renatamoon/python_classes_poo | /python_98_classes_pessoa.py | 2,603 | 4.25 | 4 | from datetime import datetime
class Pessoa: #quando uma funcao esta dentro de uma classe
#ela é um metodo
ano_atual = int(datetime.strftime(datetime.now(), '%Y')) #var da classe
#todos os objetos terão essa variavel
def __init__(self, nome, idade, comendo=False, falando=False):
self.nome... | false |
276ea714e674774dd1ab9f1256be7068c7629d27 | renatamoon/python_classes_poo | /python_110_heranca.py | 1,333 | 4.59375 | 5 | #APRENDEREMOS HERANÇA - ONDE UM OBJETO É OUTRO OBJETO
#a herança funciona de cima para baixo. A pessoa é quem decidiu os metodos principais para as
#outras classes. O CLIENTE E ALUNO é uma melhoria da classe Pessoa, é mais especializado.
#enquanto a Pessoa pode ser usada por qualquer classe, as outras subclasses (Cl... | false |
65025e1d13901d95f63f6d2783100aa1608c46c0 | KKAiser97/trantrungkien-fundamentals-c4e26 | /exses2/BMI.py | 295 | 4.15625 | 4 | cm=float(input("Enter your height(cm): "))
h=cm/100
w=float(input("Enter your weight(kg): "))
bmi=w/(h*h)
print(bmi)
if bmi<16:
print("Severely underweight")
elif bmi<18.5:
print("Underweight")
elif bmi<25:
print("Normal")
elif bmi<30:
print("Overweigh")
else:
print("Obese") | false |
19e233a3acb218beb3108334b725d5bce97020e2 | 7134g/m_troops | /py/common/design_patterns/Duty.py | 967 | 4.15625 | 4 | """
责任链模式
这条链条是一个对象包含对另一个对象的引用而形成链条,每个节点有对请求的条件,当不满足条件将传递给下一个节点处理。
"""
class Bases:
def __init__(self, obj=None):
self.obj = obj
def screen(self, number):
pass
class Top(Bases):
def screen(self, number):
if 200 > number > 100:
print("{} 划入A集合".format(number))
... | false |
a05cc0a95deaa4eeb51a108105ec6d11dfa77df6 | unclexo/data-structures-and-algorithms | /3.Maps/python/Map.py | 2,894 | 4.125 | 4 | """
The implementation of Map ADT
But using Python list ADT
"""
class Map:
""" Creates empty map instance """
def __init__(self):
self._items = list()
""" Returns the number of entries in the map """
def __len__(self):
return len(self._items)
""" Determines if the map co... | true |
a702ddc653080253f5b99f72af3a6bfc7577c212 | jaychovatiya4995/B6-python-Es-LU | /day4Assignment1.py | 573 | 4.5625 | 5 | # Find all occurrence of substring in given string
import re
test_str = "what we think we become; we are python programmer"
# get substring
test_sub = input("Enter a substring : ")
# printing original string
print("The original string is : " + test_str)
# printing substring
print("The substrin... | true |
120e946f16c877c7fc5f2e3ebf3f32dabd8c7290 | MrYangShenZhen/pythonstudy | /类的学习/迭代器.py | 1,228 | 4.21875 | 4 | ########通过iter()内置函数取得可迭代对象的迭代器。
# list = [1,2,3,4,5] # list是可迭代对象
# lterator = iter(list) # 通过iter()方法取得list的迭代器
# print(lterator)
# ####next()函数是通过迭代器获取下一个位置的值。
# print(next(lterator)) # 1
# print(next(lterator)) # 2
# print(next(lterator)) # 3
# print(next(lterator)) # 4
# print(next(lterator)) # 5
# print(n... | false |
fe4612af0b77bc0b63393dd4866dd40b57a15b67 | MrYangShenZhen/pythonstudy | /类的学习/私有类(封装).py | 872 | 4.15625 | 4 | #####双下划线代表该属性是类的私有属性。只能内部调用
######## 私有属性/方法可以在类本身中使用,但不能在类/对象外、子类/子类对象中使用python中的封装操作,
######## 不是通过权限限制而是通过改名实现的可以通过“类名.__dict__”查看属性(包括私有属性)和值,在类的内部使用
######## 私有属性,python内部会自动改名成“_类名__属性名”形式
class People(object):
def __init__(self,name,age,gender, money):
self.name = name
self.age = age
... | false |
c7c07302b753e1441634b08603f7eae31f878865 | michaelpotgieter/em-ai-cee | /02_guess_number_game/program.py | 1,472 | 4.125 | 4 | import random
print('----------------------------------')
print('| GUESS THE NUMBER |')
print('----------------------------------')
print()
# initialise numbers and ask for name
unumber_a = 0
unumber_b = 0
user_name = input('What is your name ')
print("I'll guess a number between two which ... | false |
27a74709b50496ca2af27051d2862558db520143 | Lopez-John/lambdata-Lopez-John | /module4/anothersqlite3_example.py | 1,080 | 4.375 | 4 | """creating and inserting data with sqlite"""
import sqlite3
def create_table(conn):
curs = conn.cursor()
create_table = '''
CREATE TABLE students(
id INTEGER PRIMARY KEY AUTOINCREMENT
name CHAR(20)
favorite_number INTEGER
leaste_favorite_number INTEGER... | false |
ffd8f674640427e61c5bc5ac96ab3f7f04548177 | joseEnrique/Algoritmos | /Recursividad-con-python/potencyRecursionNotFinalWithoutMemory.py | 718 | 4.21875 | 4 | # Jose Enrique Ruiz Navarro
# email- joseenriqueruiznavarro@gmail.com
#http://www.systerminal.com
# -*- encoding: utf-8 -*-
def potenciaNoFinal(base,exponente):
# base case
if(exponente==0):
result=1
elif(exponente<0):
result=1/potenciaNoFinal(base,-exponente)
else:
result = bas... | false |
0cf9b382e746712ad7fcf946a17f029b137c3ace | hari197/Tasks | /Task3.py | 603 | 4.40625 | 4 | # Program to find the sum of the series 1 + 3^2/3^3 + 5^2/5^3... upto n terms
#Taking input from user for the number of terms
n=int(input("Please enter the number of terms: "))
sum=0 #initialize sum
i=1 #initialize increment variable for loop
counter=0 #initialize counter
#If the input from the user is 0, print ... | true |
a634936bcf212b5bc9d5c44e52c89098241992e8 | ninaderi/Data-Sceince-ML-projects | /copy_loops.py | 1,939 | 4.125 | 4 | # import copy
#
# # initializing list 1
# li1 = [1, 2, [3,5], 4]
#
# # using deepcopy to deep copy
# li2 = copy.deepcopy(li1)
#
# # original elements of list
# print ("The original elements before deep copying")
# for i in range(0,len(li1)):
# print (li1[i],end=" ")
#
# print("\r")
#
# # adding and element to new l... | false |
4597c560c59325945747cf07858f5acc54e57435 | jswindlehurst/SumofPrimes2 | /main.py | 1,066 | 4.1875 | 4 | import math
def is_prime(number):
if number > 1:
if number == 2:
return True
if number % 2 == 0:
return False
for current in range(3, int(math.sqrt(number) + 1), 2):
if number % current == 0:
return False
return True
return Fa... | true |
48fd6448e063ada5e4cfa3d0ff9583de375f413c | intouchkey/GIT_TASK1 | /question3.py | 2,134 | 4.375 | 4 | import abc
class Transportation(metaclass = abc.ABCMeta):
"""Abstract base class"""
def __init__( self, start, end, distance ):
if self.__class__ == Transportation:
raise NotImplementedError
self.start = start
self.end = end
self.distance = distance
def get_start(self):
... | false |
157b9433760356c688e53921e2669343b3855881 | levashovn/test_task_sos | /task_5.py | 971 | 4.1875 | 4 | import random
def create_txt_file():
ask = True
f = open('random_numbers.txt', 'w')
while ask:
try:
rows_count = int(input('Please enter a number of rows to write: '))
ask = False
for row in range(rows_count):
for i in range(25):
num = random.randint(1, 100)
f.write(str(num))
f.write('... | true |
659a31b1550d3e59f969b1d33d1dbf0be88b6baf | DanielBMeeker/module4 | /main/basic_if.py | 1,919 | 4.21875 | 4 | """
Program: basic_if.py
Author: Daniel Meeker
Date: 06/09/2020
This program accepts user input for desired membership
level then calculates and returns the cost of the level.
"""
# function definitions:
def get_membership(): # Get user input
membership = input("Welcome to the Programmer's Toolkit Monthly Su... | true |
3b376c2319a691ae7e89e5408050c6ae552da1fb | jongfranco/python-workshop-2 | /day-1/if-else.py | 662 | 4.1875 | 4 | """
Structure of if else
if predicate:
code
code
code
elif predicate2: (not cumpolsory)
code
code
elif predicate3: (not cumpolsory)
code
code
elif predicate4: (not cumpolsory)
code
code
else: (not compulsory)
code
code
elif --> else if
"""
# if 1 > 2:
# print('i am in ... | false |
ce0923065367583a597ca521b774fa28ff50b04f | jekhokie/scriptbox | /python--learnings/list_comprehension.py | 1,098 | 4.25 | 4 | #!/usr/bin/env python
#
# Topics: List Comprehension
#
# Background: List comprehension examples and functionality.
#
# Sources:
# - https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/
import unittest
# test functionality
class TestMethods(unittest.TestCase):
def test_loop(self):
... | true |
c57fbb2147a8edefafd100334fba3a43167ba878 | jekhokie/scriptbox | /python--learnings/coding-practice/weird_or_not.py | 382 | 4.34375 | 4 | #!/usr/bin/env python
#
# If n is:
# odd, print Weird
# even and 2 <= n <= 5, print Not Weird
# even and 6 <= n <= 20, print Weird
# even and > 20, print Not Weird
#
N = int(input())
if N % 2 != 0:
print("Weird")
else:
if N >= 2 and N <= 5:
print("Not Weird")
elif N >= 6 and N <= 20:
... | false |
ae9f23d7211586056bcc0419a76fd8cb2cf756fd | Saurabh-001/Small-Python-Projects | /Guess the Number/Input Range.py | 1,450 | 4.25 | 4 | import random
import math
name = input("Enter your name: ")
lower_bound = int(input("Enter the lower bound: "))
upper_bound = int(input("Enter the upper bound: "))
maximum_chance = int(math.log2(upper_bound-lower_bound+1)) + 1
wins = 0
row_wins = 0
option = 'Y'
option_list = ['Y','N','y','n']
while option=='Y' or... | true |
86c7acab30712b8770f6b413e8d34854c5715622 | deadbok/eal_programming | /Assignment 2A/prog1.py | 1,037 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: Program 1
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (13/1... | true |
bf5f81da98a32189b8c4d147b522e9ddaf30db0b | deadbok/eal_programming | /Assignment 2A/prog2.py | 1,948 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: Program 2
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (13/1... | true |
7d9f56f41b590c03af0be8e72ba22b92a933cbf0 | deadbok/eal_programming | /Assignment B1/prog7.py | 1,140 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
'''
Name: Program 7
Author: Martin Bo Kristensen Grønholdt.
Version: 1.0 (6/11... | true |
ca11d5f806eb1105b7d11d2ed52890f049b33407 | deadbok/eal_programming | /Assignment 5/prog6.py | 2,424 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# The above lines tell the shell to use python as interpreter when the
# script is called directly, and that this file uses utf-8 encoding,
# because of the country specific letter in my surname.
"""
Name: Program 6 "Test Average and Grade"
Author: Martin Bo Kristensen Grø... | true |
5b5ace9639d6044ebca12fd640dbf83fc0aa053b | guto-alves/datastructures-and-algorithms | /daily-coding-problem/88-ContextLogic-Division/division.py | 750 | 4.21875 | 4 | """
Implement division of two positive integers without using the division,
multiplication, or modulus operators. Return the quotient as an integer,
ignoring the remainder.
"""
def divide(dividend, divisor):
if divisor == 0:
return None
sign = -1 if dividend < 0 or divisor < 0 else 1
di... | true |
6564708f15277b9bd4f0ef5adcdbaf97d52dfae8 | lawun330/Python_Basics | /Regular Expression/regular expressions.py | 2,013 | 4.625 | 5 | #regular expressions work with strings
import re
string=r"@" #a raw string called "@" desired to be matched
#raw strings don't escape anything which makes regular expression easier
if re.match(string,"wun333@gmail.com"):
#re.match() matches one string with another starting from the beginning of both strings... | true |
4b6e5276714dd23c45a39e1fe9bd7adccee3cf36 | quizque/ICS4U | /Labs/Lab 1/Calculators.py | 924 | 4.3125 | 4 | import math
# Calculate area of a cone
# INPUTS
# - Radius (float)
# - Height (float)
# OUTPUT
# - Area (print)
print("~~~~~ CALCULATE AREA OF CONE ~~~~~")
print("Area of the cone: ", (1/3)*(3.14159*math.pow(float(input("Enter radius of cone: ")),2)*float(input("Enter height of cone: "))))
# Calculate fahrenhei... | true |
efb714d84deea785f55a6057e7889eac10d7c26d | quizque/ICS4U | /Labs/Lab 9/Part2.py | 730 | 4.28125 | 4 | #********************************************************************************
#** Nick Coombe 2020/03/14 ***
#** Lab 9 Part 2 ***
#** ***
#** Part 2 of Lab 9 ***
#** Create a function that prints a box ***
#** ***
#********************************************************************************
# Prints a box of g... | true |
db8923680b9e9f72b78ece2c179dccb9bf1e8a83 | carlabeltran/data_analytics_visualization | /3.1_introduction_to_python_I/in_class/07-Ins_Conditionals/conditionals.py | 376 | 4.1875 | 4 | x = 1
y = 10
if x > y:
print("x is greater than y!")
if x == 1:
print("x equals one")
if y != 1:
print("y is not one")
if (x == 1 and y == 10):
print("both conditionals are true")
if (x > 10):
print("x is greater than 10")
elif (x < 5):
print("x is less than 5")
else:
print("x is between 5 and 10")
... | true |
34f5adc2c7c2150186b7f45496db28f1258b03d4 | adrianlebaron/python_notes | /work/week_three.py | 1,265 | 4.125 | 4 | # make variable word
# def word_reverser(string):
# print(f"I'm sorry, you need to be at least 25 years old")
# usernames = [
# 'jon',
# 'tyrion',
# 'theon',
# 'cersei',
# 'sansa',
# ]
# for username in usernames:
# if username == 'cersei':
# print(f'Sorry, {username}, you are not allowed')
# ... | true |
a2bc458851e87a37aab20734fb93c3754024d0c8 | adrianlebaron/python_notes | /dictionaries/complicated/comprehension.py | 659 | 4.40625 | 4 | # Exercise 21: Solution in small_course.py
Section 1, Lecture 47
Exercise for reference:
Filter the dictionary by removing all items with a value of greater than 1.
d = {"a": 1, "b": 2, "c": 3}
# Answer:
d = {"a": 1, "b": 2, "c": 3}
d = dict((key, value) for key, value in d.items() if value <= 1)
print(d)
Explana... | true |
04b064ff66f0758e9c3d79da65b372ddaca16e32 | wesenu/python-algorithms | /insertion_sort.py | 970 | 4.46875 | 4 | # From Lecture 3, Insertion Sort & Merge Sort
class InsertionSortArray:
''' Maintains a sorted one-dimensional array of comparable elements using insertion sort.
The one-dimensional array is represented as a list.
Interface with the array using insert, remove, and display. '''
def __init__(self, array... | true |
9cd7fe204067cdff5641d3603a032e3604d44f93 | Anirban2404/MachineLearning_Coursera | /Assignments_Python/Week2/computeCost.py | 771 | 4.15625 | 4 | # COMPUTECOST Compute cost for linear regression J = COMPUTECOST(X, y, theta)
# computes the cost of using theta as the parameter for linear regression to fit
# the data points in X and y
import numpy as np
def computeCost(X, y, theta):
# Initialize some useful values
m = y.size # number of training examples
... | true |
ddcb7e96cc70e2df680acd96fc321d9561d8761e | sraj-s/Data-case-handling | /grid.py | 266 | 4.28125 | 4 | from tkinter import *
root = Tk()
#creating a label widget
myLabel1 = Label(root, text="Hello world")
myLabel2 = Label(root, text="My name is sambeg")
#shoving it into the screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=5)
root.mainloop()
| true |
242f6e74796f62432d702fe1b422965a55a0292f | rajputrajat/teaching_basic_programming | /day_22/functions_exercise.py | 788 | 4.15625 | 4 | # take - how many numbers in a list
# take individual number, and create a list
# print that list
# find out maximum and minimum number in that list
def make_list():
count = int(input('how many numbers: '))
numbers = []
for n in range(count):
num = int(input('enter number: '))
numbers.appen... | true |
2f0e624f57747767f9eb20638ef85e95b52eda2d | rajputrajat/teaching_basic_programming | /day_11/fruits_shopping.py | 415 | 4.15625 | 4 | num_fruits = int(input('how many fruits did you buy today: '))
print()
cost = 0.0
while num_fruits >= 1:
num_fruits = num_fruits - 1
name = input('name of fruit: ')
weight_input = 'how much ' + name + ' did you buy: '
weight = float(input(weight_input))
rate = float(input('cost of ' + name + ' rs/... | false |
61664092edac9d06f2e97ee28e2e36368a0f294f | nataly247/Python-Core | /Loops/task7-list-add-element.py | 523 | 4.125 | 4 | #7. Змінити попередню програму так, щоб в кінці кожної букви елементів
# при виводі додавався певний символ, наприклад “#”.
# (Підказка: цикл for може бути вкладений в інший цикл,
# а також треба використати функцію print(“ ”, end=”%”)).
list = ["cat", "dog", "boy", "girl"];
for i in list:
for j in i:
... | false |
fd24661a2c11233d39c60fbb3780b8265d79764e | yedkk/python-datastructure-algorithm | /python basic/basic 5.py | 568 | 4.1875 | 4 | # This is the programs that convert Celsius to Fahrenheit
# I get the number of Celsius and print the list of convert
# Author Kangong Yuan
# Get the input from users
celsius = int(input("Enter the number of celsius temperatures to display: "))
# Print the title of list
print('Celsius\tFahrenheit')
# Set the variab... | true |
c4d1cb84dbd8b6b343baa94fed074c62ebc7c18b | yedkk/python-datastructure-algorithm | /python basic/basic 2.py | 875 | 4.375 | 4 | #This progroms want to get user's weight and height and calculate their then tell then the situation of their bmi
#First get the wieght and height of the user
#Second calculate the bemi throgh formula
#Third decide the situation of their bmi
# Author Kangdong Yuan
#Get the input of the height and the weight
height=fl... | true |
63024e12ceabc427d785a055513a66c73b586ed9 | yedkk/python-datastructure-algorithm | /python basic/basic_GUI.py | 1,161 | 4.5625 | 5 | # This program ask user to give sides and return graph to users
# Author Kangdong Yuan
# import random and turtle
import random
import turtle
t = turtle.Turtle()
# set the function
def makePolygon (sides,length,width,fillColor,angle,borderColor):
# fill the color
t.color(borderColor,fillColor)
t.begin_fill()... | true |
8ebc214fdf3e1c68d73df01640a3ed0422ae78e0 | MohammadRafik/algos_and_datastructures | /leetcode_30day_challenge/week2/min_stack.py | 1,066 | 4.125 | 4 | class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.min_index = []
self.list = []
def push(self, x: int) -> None:
self.list.append(x)
if self.min_index == []:
self.min_index.append(0)
elif self.list[-... | false |
48efb4754266b43608892f0aca35ca015648994b | serapred/algorithms | /sorting/insertion_sort.py | 846 | 4.28125 | 4 | def insertion_sort(collection):
"""
Pure pyton implementation of the insertion sort algorithm
@collection: some mutable collection of unordered items
@returns: same collection in ascending order
time complexity:
- lower bound omega(n)
- average theta(n^2)
- upper bou... | true |
9dfb65fedcc93b40b842ff3e4d304dd470d3732c | pedh/CLRS-Solutions | /codes/heapsort.py | 1,139 | 4.15625 | 4 | """
Heapsort.
"""
import random
def max_heapify(heap, index, heap_size):
"""Max-heapify."""
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and heap[left_index] > heap[index]:
largest = left_index
else:
largest = index
if right_index < heap_siz... | false |
d1e5bc78200728b2cb01a5c05aa0d87540d87375 | rewaaf/Convert-List | /convertList.py | 638 | 4.3125 | 4 | # with user input:
def convert(list_item):
list_item[-1] = 'and '+str(list_item[-1])
new_str = ''
new_str = ', '.join(str(item) for item in list_item)
return new_str
user_list = input('Hello dear, enter your list to convert it to string: ').split() #convert user input to list
print('your list is: ')
p... | false |
df431bbc0c4604391c1cbbbed7b37b6518d1a757 | pedr0diniz/cevpython | /Python_Aulas/aula2.13a - Laços de Repetição 1 - for.py | 1,451 | 4.15625 | 4 | #laço com variável de controle
#laço c no intervalo (1,10):
#dê um passo
#pega
#traduzindo:
#for c in range(1,10):
#passo()
#pega() #mesmo com o pega fora do laço, ele só será executado depois do laço
#laço c no intervalo (0,3):
#passo
#pula #evitando determinados números
#passo
#pega
#traduzi... | false |
228ae00c8cfeaae3ef3950bdc2b24cbd1293f4bd | pedr0diniz/cevpython | /PythonExercícios/ex022 - Analisador de Textos.py | 1,379 | 4.34375 | 4 | # DESAFIO 022 - Crie um programa que leia o nome completo de uma pessoa e mostre:
#O nome com todas as letras maiúsculas;
#O nome com todas as letras minúsculas;
#Quantas letras ao todo (sem considerar espaços);
#Quantas letras tem o primeiro nome.
nome = str(input('Digite seu nome completo: '))
M = nome.upper()
m = ... | false |
6ecb7851ed7b8756044306077f552efef5b8c411 | pedr0diniz/cevpython | /PythonExercícios/ex099 - Função que descobre o maior.py | 803 | 4.15625 | 4 | # DESAFIO 099 - Faça um programa que tenha uma função maior(), que receba vários PARÂMETROS com valores inteiros.
# Seu programa tem que analisar todos os valores e dizer qual deles é o MAIOR e dizer quantos valores foram informados.
def maior(*num):
for nu in num:
numeros.append(nu)
if printa is True... | false |
3815e63031e53111c4056fa198e832d4a6e82776 | pedr0diniz/cevpython | /PythonExercícios/ex104 - Validando entrada de dados em Python.py | 706 | 4.15625 | 4 | # DESAFIO 104 - Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante à função input() do
#Python, só que fazendo a validação para aceitar apenas um valor numérico.
#Ex: n = leiaInt('Digite um n')
def leiaInt(frase):
ok = False #precisei criar esse boolean. seria ideal poder usar "i... | false |
6b3d221210ac17f6514b0e627b25a76a54a2d5d3 | pedr0diniz/cevpython | /PythonExercícios/ex014 - Conversor de Temperaturas.py | 307 | 4.15625 | 4 | # DESAFIO 014 - Escreva um programa que coonverta uma temperatura digitada em ºC para ºF.
c = float(input('Digite a temperatura em ºC: '))
f = ((9*c)/5)+32
print('A temperatura de {}ºC corresponde a {}ºF.'.format(c,f))
#ou
print('A temperatura de {}ºC corresponde a {}ºF.'.format(c,((9*c)/5)+32)) | false |
95e19c84d5a8838e3d9fe33f9a47253118acd256 | raysales/treehouse-festival-level-up-your-code | /map.py | 690 | 4.46875 | 4 | # What does it do?
# map() applies a function to an iterable
flowers = ['sunflower', 'daisy', 'rose', 'peony']
# regular loop
plural = []
for flower in flowers:
if flower[-1] == 'y':
plural.append(flower[:(len(flower) -1)] + 'ies')
else:
plural.append(flower + 's')
print(plural)
# map()
def ... | true |
d60913c8c04026085d1b8b30c9a5e1d1025de5dc | nafis195/Codepath-Intermediate-Software-Engineering | /Week1/1. S2 - UMPIRE_Practice.py | 222 | 4.3125 | 4 | # Bismillahir Rahmanir Rahim
# Session 2 - UMPIRE Practice
# Write a function that reverses a string.
# Example:
# Input: "hello"
# Output: "olleh"
userInput = input("Please enter a string: ")
userInput = userInput[::-1]
print(userInput) | false |
0847e5ba72fca9d6cb7dc07d5e92aa93222cd9aa | mtlam/ASTP-720_F2020 | /HW5/particle.py | 2,678 | 4.125 | 4 | '''
Michael Lam
ASTP-720, Fall 2020
Class to represent a point-mass particle
Also performs the integration
'''
import numpy as np
from coordinate import Coordinate
class Particle:
"""
Class that contains the coordinates and
mass of a point particle
In order to do the integration, it will
also kee... | true |
31c2a5b3138eb55415adefcee51d7ac8ab982c6d | ArahamLag/pyfeb20repo | /script.py | 584 | 4.125 | 4 | import math
def get_number(number):
if isinstance(number, int):
print(" a number was passed to the function")
if number % 2 == 0:
print(' the number is even')
else:
print(' the number is odd')
if number < 0:
print("""the number i... | true |
ec6fa5468bc9a7e951606c74afd906077b3ad7e4 | changsquare/first | /practice8.py | 1,258 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 17:12:45 2019
@author: chang2
"""
'''
lambda expression
They are syntactically restricted to a single expression.
Semantically, they are just syntactic sugar for a normal function definition.
Like nested function definitions, lambda functions ... | true |
1ebb051f83721b594e644dfb8ba540d1f10c4f67 | HariAc/python-calculator | /calc.py | 663 | 4.28125 | 4 | operation = input('''
welcome to python calculator
+ for addition
- for subtraction
* for multiplication
/ for division
enter the operation= ''')
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
if operation == '+':
print('{} + {} = '.format(num1, num2))
print(num... | true |
b1d98614995b6117e1029e008c801d64f54668ca | eldss-classwork/CSC110 | /Creating Modules/oldLady.py | 1,537 | 4.375 | 4 | # Evan Douglass
# HW 8: Children's song, the reprise
# Grade at challenge
'''This module defines several variables and methods used to print the
children's song "There was an Old Lady"'''
# Animals used in the song
ANIMALS = ('fly.', 'spider,', 'bird.', 'cat.',
'dog.', 'goat.', 'cow.', 'horse.')
# A list of the s... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.