blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7f1c138d85fbee0ebe4f327ffb8d121124101765
wxl789/python
/day13/02-类属性.py
333
4.28125
4
class People(object): name = "tom"#公有的类属性 __age = 12#私有类属性 # def __init__(self,name): # self.name = name p = People() print(p.name) # print(p.__age) print(People.name) # print(People.__age) """ 注意: 不能在类的外面通过实例对象和类对象访问私有的类属性 """
false
5cfd2f5823ca835000b3e936f4072044a58570ce
wxl789/python
/Day08/2-代码/迭代器/2-生成器.py
1,130
4.28125
4
''' 生成器: generator生成器:使用yield关键字的函数被称为生成器函数。 使用yield的函数与普通函数的区别: 1、使用yield的函数返回一个生成器对象。 2、普通函数的返回值属于程序员自己设置。 yield:将一个函数拆分成多个模块,模块与模块之间为连续的。 yield可以间接控制进程或线程。 生成器可以认为是一个迭代器,使用方式与迭代器一致。 ''' # 普通函数的返回值默认为NoneType类型 def func1(): print(1) print(2) print(3) # print(type(func1)) # function # print(type(func1(...
false
16752c42c19fb346530892de7ff2966d8a66e245
wxl789/python
/Day10/2-代码/面向对象/4-通过对象调用类中的属性或函数.py
1,771
4.40625
4
# Wife的类 class Wife(): name = "" height = 1.5 weight = 50.0 # 创建普通的成员方法的方式与之前创建def的方式一致,只是第一个形参默认 # 为self。 # 初始值 返回值 多个形参 def goShopping(self): print("妻子能购物") def makeHousework(self): print("贤惠的做家务") def hideMoney(self, money): print("辛苦藏了%s的私房钱" % money) #...
false
615e85b944a61c73a1e1e0a2c99738750ebd112a
CHANDUVALI/Python_Assingment
/python27.py
274
4.21875
4
#Implement a progam to convert the input string to lower case ( without using standard library) Str1=input("Enter the string to be converted uppercase: ") for i in range (0,len(Str1)): x=ord(Str1[i]) if x>=65 and x<=90: x=x+32 y=chr(x) print(y,end="")
true
a105fe7cfd70b8b8eae640aae6983f5fddb64d09
CHANDUVALI/Python_Assingment
/cal.py
399
4.375
4
# Implement a python code for arithmetic calculator for operation *, / , + , - num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) choice = input("Enter choice(+,-,*,/):") if choice == '+': print(num1 + num2); elif choice == '-': print(num1 - num2); elif choice == '*': print(num1 * ...
false
6c299c77b83d1f18798aacebb941d947de7236d4
monajalal/Python_Playground
/binary_addition.py
510
4.1875
4
''' Implement a function that successfully adds two numbers together and returns their solution in binary. The conversion can be done before, or after the addition of the two. The binary number returned should be a string! Test.assert_equals(add_binary(51,12),"111111") ''' #the art of thinking simpler is POWER def ad...
true
cce21967d8f50cdc3ac1312886f909db26cae7cf
bjgrant/python-crash-course
/voting.py
1,033
4.3125
4
# if statement example age = 17 if age >= 18: print("You are old enough to vote!") print("Have you registered to vote yet?") # else stament example else: print("Sorry, you are too young to vote!") print("Please register to vote as soon as you turn 18!") # if-elif-else example age = 12 if age < 4: ...
true
0efc11ea4177989652d50c18eaeca9cf25988c18
bjgrant/python-crash-course
/cars.py
594
4.53125
5
# list of car makers cars = ["bmw", "audi", "toyota", "subaru"] # sorts the list alphabetically cars.sort() print(cars) # sorts the list in reverse alphabetic order cars = ["bmw", "audi", "toyota", "subaru"] cars.sort(reverse=True) print(cars) cars = ["bmw", "audi", "toyota", "subaru"] # Print the list contents sorted,...
true
5bfeeb9948c267f0d0a4029800ef0cd8157a3689
Japoncio3k/Hacktoberfest2021-5
/Python/sumOfDigits.py
225
4.1875
4
num = int(input("Enter a number: ")); if(num<0): print('The number must be positive') else: total = 0; while num!=0: total += num%10; num = num//10; print("The sum of the digits is: ", total);
true
1d52ec1e83e2f428223741dde50588025375dd26
derekhua/Advent-of-Code
/Day10/Solution.py
1,859
4.125
4
''' --- Day 10: Elves Look, Elves Say --- Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones", which becomes 1221 (1 2, 2 1s). Look-and-say sequence...
true
2ad7197fd85f713b16fece5d7253bb4a4bd8b606
JuanSaldana/100-days-of-code-challenges
/day-19/turtle_race.py
1,638
4.125
4
from turtle import Turtle, Screen, colormode from random import randint colormode(255) def set_random_color(turtle: Turtle): r, g, b = randint(0, 255), randint(0, 255), randint(0, 255) turtle.color((r, g, b)) def setup_race(n): turtles = [] screen_size = screen.screensize() step = screen_size[1...
true
8412be3158ced9cda22b82984ba0b2296c3da8a2
jsculsp/python_data_structure
/11/buildhist.py
1,361
4.25
4
# Prints a histogram for a distribution of the letter grades computed # from a collection of numeric grades extracted from a text file. from maphist import Histogram def main(): # Create a Histogram instance for computing the frequencies. gradeHist = Histogram('ABCDF') # Open the text file containing the grades....
true
4d79e76fceb858235da96274f62274bd8bc9fa7a
jsculsp/python_data_structure
/2/gameoflife.py
1,548
4.25
4
# Program for playing the game of Life. from life import LifeGrid from random import randrange # Define the initial configuration of live cells. INIT_CONFIG = [(randrange(10), randrange(10)) for i in range(50)] # Set the size of the grid. GRID_WIDTH = 10 GRID_HEIGHT = 10 # Indicate the number of generations. NUM_GEN...
true
7b37bb7acc6c035aaeb649d750983ec9af284bdc
jsculsp/python_data_structure
/8/priorityq.py
1,346
4.1875
4
# Implementation of the unbounded Priority Queue ADT using a Python list # with new items append to the end. class PriorityQueue(object): # Create an empty unbounded priority queue. def __init__(self): self._qList = list() # Return True if the queue is empty. def isEmpty(self): return len(self) == 0 # Re...
true
c83fe07fcf908618d2c1659fcecd53d7f65fa16e
daid3/PracticeOfPython
/201802/180219CalculateBMI.py
1,808
4.1875
4
#By 000 ####本程序计算BMI(Body Mass Index 身体质量指数) ##Python分支的应用:编写一个根据体重和身高计算并输出 BMI值的程序,要求同时输出国际和国内的BMI指标建议值。 # 分类 | 国际BMI值(kg/m^2) | 国内BMI值(kg/m^2) # 偏瘦 | < 18.5 | <18.5 # 正常 | 18.5~25 | 18.5~24 # 偏胖 | 25~30 | 24~28 # 肥胖 | >=30 | >=28 #emmmmm ...
false
740cb7bc4bd7ba52c7fc4e93458310faedb75a04
daid3/PracticeOfPython
/201803/180306OOExample.py
2,447
4.125
4
# !/usr/bin/env python # encoding: utf-8 __author__ = 'Administrator' #------------面向对象程序设计的例子 #铅球飞行轨迹计算 #铅球对象的属性:xpos,ypos,xvel,yvel #构建投射体类 Projectile #创建和更新对象的变量 from math import * #Projectile类: class Projectile: def __init__(self,angle,velcity,height): #根据给定的发射角度、初始速度和位置创建一个投射体对象 self.xpos=0.0 ...
false
ac0ca45de03da9e85d16cbd00e07595e92ceb8cc
Ethan2957/p02.1
/fizzbuzz.py
867
4.5
4
""" Problem: FizzBuzz is a counting game. Players take turns counting the next number in the sequence 1, 2, 3, 4 ... However, if the number is: * A multiple of 3 -> Say 'Fizz' instead * A multiple of 5 -> Say 'Buzz' instead * A multiple of 3 and 5 -> Say 'FizzBuzz' instead The function f...
true
7307669144fb61678697580311b3e82de4dc9784
sujoy98/scripts
/macChanger.py
2,495
4.34375
4
import subprocess import optparse # 'optparse' module allows us to get arguments from the user and parse them and use them in the code. # raw_input() -> python 2.7 & input() -> python3 # interface = raw_input("Enter a interface example -> eth0,wlan0 :-") ''' OptionParser is a class which holds all the user input ...
true
b3ccaee062de1a1701e4376c17af80b4f8450606
robot-tutorial/robotics_tutorial
/python/loop.py
542
4.15625
4
# range for i in range(10): print(i, end=' ') # 取消换行 for i in range(5, 10): print(i, end=' ') for i in range(5, 10, 2): print(i, end=' ') # loop over a list courses = ['Calculus', 'Linear Algebra', 'Mechanics'] # low-level for i in range(3): print(courses[i]) # advanced for course in courses: pri...
false
4da9e5bb9096d891064eb88bfa4ccfd5bcf95447
catechnix/greentree
/sorting_two_lists.py
502
4.15625
4
""" compared two sorted arrays and return one that combining the two arrays into one which is also sorted, can't use sort function """ array1=[0,3,2,1,6] array2=[1,2,4,5] print(array2) for i in array1: if i not in array2: array2.append(i) print(array2) array3=[] while array2: minimum = a...
true
32061facf23b68d0d1b6f7794366186dba758ead
catechnix/greentree
/print_object_attribute.py
442
4.375
4
""" Write a function called print_time that takes a Time object and prints it in the form hour:minute:second. """ class Time(): def __init__(self,hour,minute,second): self.hour=hour self.minute=minute self.second=second present_time=Time(12,5,34) def print_time(time): time_text="The pre...
true
fa3eb3ea8a585370c8f2aaebd508ed4927a93dd6
dreaminkv/gb_basic_python
/TolstovMikhail_dz_11/task_11_7.py
936
4.21875
4
# Реализовать проект «Операции с комплексными числами». Создать класс «Комплексное число». # Реализовать перегрузку методов сложения и умножения комплексных чисел. Проверить работу проекта. # Для этого создать экземпляры класса (комплексные числа), выполнить сложение и умножение созданных # экземпляров. Проверить корре...
false
8f6253e19d64eb0b4b7630e859f4e3a143fb0833
IBA07/Test_dome_challanges
/find_roots_second_ord_eq.py
751
4.1875
4
''' Implement the function find_roots to find the roots of the quadriatic equation: aX^2+bx+c. The function should return a tuple containing roots in any order. If the equation has only one solution, the function should return that solution as both elements of the tuple. The equation will always have at least one solut...
true
91bd2e803e12dae1fb6dad102e24e11db4dfdb03
ZainabFatima507/my
/check_if_+_-_0.py
210
4.1875
4
num = input ( "type a number:") if num >= "0": if num > "0": print ("the number is positive.") else: print("the number is zero.") else: print ("the number is negative.")
true
524b1d0fa45d90e7a326a37cc1f90cdabc1942e0
CTEC-121-Spring-2020/mod-5-programming-assignment-Rmballenger
/Prob-1/Prob-1.py
2,756
4.1875
4
# Module 4 # Programming Assignment 5 # Prob-1.py # Robert Ballenger # IPO # function definition def convertNumber(numberGiven): # Here a if/elif loop occurs where it checks if the numberGiven is equal to any of the numbers below, and if it does it prints the message. if numberGiven == 1: ...
true
beca7f8a9a8a4caea549852badd96324da92a245
sanchit0496/Python_Practice
/scratch_36.py
322
4.1875
4
#Dictionary D= {1:"Hello", 2: "World"} print(D) my_dict = dict(item1="Apple", item2="Orange") print(my_dict) my_dict={x:x*x for x in range(8)} print(my_dict) my_dict={y:y*y for y in range(8)} print(my_dict) my_dict={'name':'John',1:[2,4,5]} print(my_dict) my_dict={'name':'John',1:['Hello','World',5]} print(my_dic...
false
03f6b186c0858c30b3ec64a7954bc98d6c2b169f
StephenTanksley/cs-algorithms
/moving_zeroes/moving_zeroes.py
1,662
4.1875
4
''' Input: a List of integers Returns: a List of integers ''' """ U - Input is a list of integers. The list of integers will have some 0s included in it. The 0s need to be pushed to the tail end of the list. The rest of the list needs to remain in order. P1 (in-place swap plan) - 1) We need a way of...
true
fe2435cbaa4ebd9a2f7baca925e532e4fb5f6261
myllenamelo/Exerc-cio
/Q1_Tupla_Myllena_Melo.py
1,089
4.21875
4
''' seu carlos está abrindo uma lanchonete com apenas atendimento para delivery, levando em conta que não haverá loja fisica, o atendimento será online. Ajude seu Carlos a montar o cardápio da lanchonete. 1- Ultilizando tuplas monte todo o cardápio com comidas e bebidas por enquanto não precisa do preço 2- deve most...
false
4186c4b7ce7404bdb82854787a04983a3b1dd7c7
priyankitshukla/pythontut
/Logical Operator.py
594
4.25
4
is_Hot=False is_Cold=False if is_Hot: print(''' Its very hot day Drink Plenty of water ''') elif is_Cold: print('Its a cold day') else: print('Its a lovely day') print('Enjoy your day!') # Excersise with logical operator if is_Cold==False and is_Hot==False: prin...
true
dcfeb5f5a83c47e5123cf8e0c07c39a8ed246898
afahad0149/How-To-Think-Like-A-Computer-Scientist
/Chap 8 (STRINGS)/exercises/num5(percentage_of_a_letter).py
1,515
4.3125
4
import string def remove_punctuations(text): new_str = "" for ch in text: if ch not in string.punctuation: new_str += ch return new_str def word_frequency (text, letter): words = text.split() total_words = len(words) words_with_letter = 0 for word in words: if letter in word: words...
true
c4d70d36aac58acf24e9dc492266e1e32a36aa4e
magedu-python22/homework
/homework/10/P22048-fuzhou-xiaojie/homework10.py
1,583
4.15625
4
# 自定义 map, reduce, filter 接受两个参数(fn, iterable) # 检测iterable 是否为可迭代对象, 如果不是抛出异常 “Iterable not is Iterable” from collections import Iterable def add(x, y): return x + y def is_odd(x): return x % 2 == 1 class MyException(Exception): pass class Custom: def __init__(self, fn, iterable): ...
false
c5262a687592caede04cadc4f18ef5a66c8b9e0d
Chandu0992/youtube_pthon_practice
/core/array_example_one.py
1,044
4.15625
4
'''from array import * arr = array('i',[]) n = int(input("Please Enter size of the array : ")) for i in range(n): x = int(input("Enter next Value : ")) arr.append(x) #manual method print(arr) s = int(input("Enter a Value to search : ")) k = 0 for i in arr: if i == s: print(k) break k ...
true
5354b5ce25def354480fbd85463224f527e38e83
Ajat98/LeetCode-2020-Python
/good_to_know/reverse_32b_int.py
702
4.3125
4
''' Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpos...
true
00409eb918845cfc869eb7dec7c9e85292c98d25
sofyansetiawan/learn-python-bootcamp
/02-intermediate/condition.py
943
4.25
4
x = 3 y = 3 if(x == y): print("they are equals") else: print("the are not equals") print("program is working fine") # ------------------ a = 10 b = 10 c = 80 if(a == b): print("a is equals b") elif(b > a): print("b is greater than a") elif(a > b): print("a is greater than b") else: print("th...
false
412485e1024007908fc7ae3f65bc31897545985b
vaishnavi-gupta-au16/GeeksForGeeks
/Q_Merge Sort.py
1,565
4.125
4
""" Merge Sort Merge Sort is a Divide and Conquer algorithm. It repeatedly divides the array into two halves and combines them in sorted manner. Given an array arr[], its starting position l and its ending position r. Merge Sort is achieved using the following algorithm. MergeSort(arr[], l, r) If r > l ...
true
9cadb464d665ebddf21ddc73b136c0cf4026ba11
chaiwat2021/first_python
/list_add.py
390
4.34375
4
# append to the end of list thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) # insert with index thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) # extend list with values from another list thislist = ["apple", "banana", "cherry"] tropical = ["man...
true
f47e0a404ee9c531f82b657c0cc4ecc987e9279c
2flcastro/python-exercises
/solutions/2flcastro/intermediate/smallest_common_multiple.py
2,773
4.375
4
# ---------------------------------- # Smallest Commom Multiple # ---------------------------------- # Find the smallest common multiple of the provided parameters that can be # evenly divided by both, as well as by all sequential numbers in the range # between these parameters. # # The range will be a list of two numb...
true
c253c625f1d74938fc087d2206d75b75c974cd23
2flcastro/python-exercises
/beginner/longest_word.py
1,175
4.1875
4
# ---------------------------------- # Find the Longest Word in a String # ---------------------------------- # Return the length of the longest word in the provided sentence. # # Your response should be a number. # ---------------------------------- import unittest def find_longest_word(strg): return len(strg) ...
true
cb64405d60c43194cb2fd4455a68a4ec7f4441d0
2flcastro/python-exercises
/solutions/2flcastro/beginner/longest_word.py
2,172
4.28125
4
# ---------------------------------- # Find the Longest Word in a String # ---------------------------------- # Return the length of the longest word in the provided sentence. # # Your response should be a number. # ---------------------------------- import unittest # using list comprehension and max() built-in funct...
true
5a55b4a608a8512b528fe6ea53bccca2b13bafba
ads2100/100DaysOfPython
/Week#3/Day16.py
430
4.25
4
"""----------Day16----------""" Tuple1 = ( 'cat' , 5 , 1.9 , 'man' ) print(Tuple1)#print all value print(Tuple1[0])#print index 0 print(Tuple1[ 1 : 4 ])#print from index 1 to 3 Tuple2 = ( 'Dog' , ) #must use ( , ) if there one value print(Tuple2) Tuple3 = ( 'Dog' )#will print as a regular value not tuple print(Tuple3...
false
21461cf869ccdbf60483fa57465520315dc12450
fangfa3/test
/python/BasicAlgorithm/insert_sort.py
317
4.125
4
def insert_sort(array): length = len(array) for i in range(1, length): j = i while array[j] < array[j - 1] and j > 0: array[j], array[j-1] = array[j-1], array[j] j -= 1 if __name__ == '__main__': A = [2, 4, 5, 8, 1, 9, 7, 6, 3] insert_sort(A) print(A)
false
166f72638df619e350bc3763d1082890106a7303
smysnk/my-grow
/src/lib/redux/compose.py
820
4.1875
4
""" * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functi...
true
80c7a5e3c64f31e504c793b59951260636c65d17
mike-something/samples
/movies/movies_0.py
974
4.3125
4
# https://namingconvention.org/python/ # # define variables for the cost of tickets # # we try and use names for variables which are clear and memorable. Its # good to prefer longer names which are clearer - in a large program this # can really matter # adult_ticket_cost = 18 child_ticket_cost = 10 print('...
true
76db9c3360d671f7461297a63475063908e33df9
carlos-paezf/Snippets_MassCode
/python/factorial.py
472
4.5
4
#Calculates the factorial of a number. #Use recursion. If num is less than or equal to 1, return 1. #Otherwise, return the product of num and the factorial of num - 1. #Throws an exception if num is a negative or a floating point number. def factorial(num): if not ((num >= 0) & (num % 1 == 0)): raise Excep...
true
c8f0da7555edde737b7f5e8ad697305b1087079c
carlos-paezf/Snippets_MassCode
/python/keys_only.py
714
4.3125
4
#Function which accepts a dictionary of key value pairs and returns #a new flat list of only the keys. #Uses the .items() function with a for loop on the dictionary to #track both the key and value and returns a new list by appending #the keys to it. Best used on 1 level-deep key:value pair #dictionaries (a flat dictio...
true
56f8f9eb11022cce409c96cabf50ecb13273e7df
HaoyiZhao/Text-chat-bot
/word_count.py
1,116
4.34375
4
#!/usr/bin/python import sys import os.path # check if correct number of arguments if len(sys.argv)!=2: print "Invalid number of arguments, please only enter only one text file name as the command line argument" sys.exit() # check if file exists if os.path.isfile(sys.argv[1]): file=open(sys.argv[1], "r+") wordFreq...
true
c6c066383c6d2fc587e3c2bf5d26ee36c060e288
sarank21/SummerSchool-Assignment
/SaiShashankGP_EE20B040/Assignment1Q2.py
1,483
4.25
4
''' Author: Sai Shashank GP Date last modified: 07-07-2021 Purpose: To find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number. Sample input: 10 20 10 40 50 60 70 Sample ouput: {1: [0, 3], 2: [2, 3], 3: [3, 0], 4: [3, 2]} ''' # importing useful libraries impor...
true
11e4324bf7174179c032c239d3b19af379dd871a
Iaraseverino/my-first-repo
/Projects/exercise.py
397
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 22:05:34 2020 @author: Iari Severino """ def is_even(): number = input("type a number: ") if int(number) % 2 == 0: print('true') else: print('False') is_even() #%% def is_odd(): number = input("type a number: ") if int...
false
d5131ecef9b8ab0918033d2a66a4e21ff329dd39
NinjaOnRails/fillgaps
/fillGaps.py
916
4.15625
4
#! /usr/bin/env python3 # fillGaps - Finds all files with a given prefix in a folder, # locates any gaps in the numbering and renames them to close the gap. import shutil, os, re folder = input("Enter path to the folder containing your files: ") prefix = input("Enter prefix: ") def fillGaps(folder, prefix): reg...
true
23152386219203cd737c4dde47f9822c410ba181
enriqueee99/learning_python
/ejercicio_16.1.py
466
4.25
4
personas = {} for x in range(3): numero = int(input('Ingrese el numero de la persona: ')) nombre = input('Ingrese el nombre de la persona: ') personas[numero] = nombre print('Listado completo de las personas: ') for numero in personas: print(numero, personas[numero]) num_consulta = int(input('¿Qué num...
false
a7aff197a21019a5e75502ad3e7de79e08f80465
jesusbibieca/rock-paper-scissors
/piedra_papel_tijeras.py
2,820
4.4375
4
##Rock, paper o scissors## #Written by Jesus Bibieca on 6/21/2017... import random # I import the necessary library import time #This will import the module time to be able to wait #chose = "" #Initializing variables def computer(): #This function will get a rand value between 1-99 and depending on the num...
true
13c728affd7e5939a50aa5001c77f8bf25ee089c
FadilKarajic/fahrenheitToCelsius
/temp_converter.py
653
4.4375
4
#Program converts the temperature from Ferenheit to Celsius def getInput(): #get input tempInCAsString = input('Enter the temperature in Ferenheit: ') tempInF = int( tempInCAsString ) return tempInF def convertTemp(tempInF): #temperature conversion formula tempInC = (tempInF - 32) *...
true
273f798d759f25e69cfe21edcad3418d66ffd0aa
Victor094/edsaprojrecsort
/edsaprojrecsort/recursion.py
1,020
4.46875
4
def sum_array(array): '''Return sum of all items in array''' sum1 = 0 for item in array: sum1 = sum1 + item # adding every item to sum1 return sum1 # returning total sum1 def fibonacci(number): """ Calculate nth term in fibonacci sequence Args: n (int): nth term in fib...
true
c1ea1eede64d04257cd5ba8bde4aea1601044136
Rekid46/Python-Games
/Calculator/app.py
1,076
4.1875
4
from art import logo def add(a,b): return(a+b) def subtract(a,b): return(a-b) def multiply(a,b): return(a*b) def divide(a,b): return(a/b) operations = { "+": add, "-": subtract, "*": multiply, "/": divide } def calculator(): print(logo) n1=float(input("Enter first number: ")) n2=floa...
true
838775b7700e92d22745528eb8a0d03135d44f55
brandong1/python_textpro
/files.py
1,485
4.28125
4
myfile = open("fruits.txt") content = myfile.read() myfile.close() # Flush and close out the IO object print(content) ########## file = open("fruits.txt") content = file.read() file.close() print(content[:90]) ########## def foo(character, filepath="fruits.txt"): file = open(filepath) content = file.read()...
true
8e5033488a99f2c785a5d52e13745d4ab0910f61
tanglan2009/Python-exercise
/classCar.py
2,858
4.4375
4
# Imagine we run a car dealership. We sell all types of vehicles, # from motorcycles to trucks.We set ourselves apart from the competition # by our prices. Specifically, how we determine the price of a vehicle on # our lot: $5,000 x number of wheels a vehicle has. We love buying back our vehicles # as well. We offer ...
true
e8bab715fb8ff2303ff7d5eb444789393d298844
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex075.py
768
4.3125
4
'''Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares.''' tupla = (int(input('Digite um número: ')), int(input('Digite outro número: '))...
false
ca4270f470222f13e66ea1842074eb2cf0ba0806
cristianoandrad/ExerciciosPythonCursoEmVideo
/ex014.py
251
4.34375
4
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. cel = float(input('Informe a temperatura em celsius: ')) print('A temperatura equivalente em Fahrenheit é {}ºF'.format((cel * 1.8)+32))
false
c259a0fb4637d7d3c208a8e08657b7584501e424
Karlhsiao/py4kids
/homework/hw_30_pay_calc.py
1,262
4.21875
4
''' Calculate weekly payment by working hours and hourly rate ''' STANDARD_HOURS = 40 OVERTIME_FACTOR = 1.5 def process_user_input(working_hours, hourly_rate): hrs = float(working_hours) r = float(hourly_rate) return hrs, r def input_from_user(): #working hours in the week, ex. 40 working_h...
true
a094eace179eb7883904a900bb4ec3587c580d2c
KonstantinKlepikov/all-python-ml-learning
/python_learning/class_attention.py
1,427
4.15625
4
# example of traps of class construction """Chenging of class attributes can have side effect """ class X: a = 1 """Chenging of modified attributes can have side effect to """ class C: shared = [] def __init__(self): self.perobj = [] """Area of visibility in methods and classes """ def generate...
true
4d1f40485e149b3a99a3266349f33b59956e9e41
KonstantinKlepikov/all-python-ml-learning
/python_learning/super_example.py
993
4.4375
4
# example of super() usage """Traditional method of superclass calling """ class C: def act(self): print('spam') class D(C): def act(self): C.act(self) # explicit usage of superclass name to give it to self print('eggs') class DSuper(C): def act(self): super().act() ...
false
0704f17a81bb58ccfb55885b3f05ab85da62f5f6
himik-nainwal/PythonCodeFragments
/Search And Sort/BubbleSort Python.py
270
4.15625
4
def bubble_sort(array): for i in range(len(array)): for j in range(i,len(array)): if array[j] < array[i]: array[j], array[i] = array[i], array[j] return array print(bubble_sort([5,54,87,3,9,47,12,65,92,45,78,2]))
false
8dfac5602f8b55eb4b850bf8f3b7c15ea7c3363b
merryta/alx-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
550
4.34375
4
#!/usr/bin/python3 """ This is the "0-add_integer" module. add a and b and it can be int or floats """ def add_integer(a, b): ''' add two number Args: a : int or float b : int or float Rueturn an int ''' if not isinstance(a, int) and not isinstance(a, float): raise TypeError("...
true
3ad8001b48d6a98de48be16b061b2d64efd31315
bagustris/python-intro
/code/dictionary.py
245
4.125
4
#! /usr/bin/env python3 dictionary = {'book' : 'buku', 'table' :'meja', 'chair' : 'kursi' } for k in dictionary.keys(): print(k, "-->", dictionary[k]) for i in dictionary.items(): print(i) print(i[0]) print(i[1])
false
b6f03023ab52a12b262e46960de3ff0b3c1986d9
ras9841/practice
/sorting/sortMethods.py
2,150
4.25
4
def bubbleSort(lst): """ Time complexity: O(n^2) Space complexity: O(1) """ size = len(lst) for _ in range(size): swapping = True while swapping: for i in range(size-1): if lst[i] < lst[i+1]: lst[i], lst[i+1] = lst[i+1], lst[i]...
false
b8ba0f7e41dea4b26753cf931b2ad1fb67240a4f
Miguel-Caringal/CHCIProgrammingClub
/Challenge of the Week/week 1/easy/Miguel Caringal.py
277
4.21875
4
month= int(input()) day= int(input()) if month > 2: print ('After') else: if month == 2: if day == 18: print ('Special') elif day <18: print ('Before') else: print ('After') else: print ('Before')
false
a5a62e8a5f03096ad0ad03eb27d9da6e1864a6b5
JesusSePe/Python
/recursivity/Exercises3.py
1,503
4.28125
4
"""Exercise 1. Rus multiplication method.""" from math import trunc from random import randint def rus(num1, num2): if num1 == 1: print(num1, "\t\t", num2, "\t\t", num2) return num2 elif num1 % 2 == 0: print(num1, "\t\t", num2) return rus(trunc(num1 / 2), num2 * 2) else: ...
true
237d9f3039570ac80821bfde409e8acdf2344c47
lesenpai/project-euler
/task4.py
738
4.1875
4
""" Число-палиндром с обеих сторон (справа налево и слева направо) читается одинаково. Самое большое число-палиндром, полученное умножением двух двузначных чисел – 9009 = 91 × 99. Найдите самый большой палиндром, полученный умножением двух трехзначных чисел. """ def is_palindrome(n): s = str(n) return s == s...
false
502b41273a57a4d1ca29215e005d5763eb41e163
jeromeslash83/My-First-Projects
/random_stuff/BMI_Calculator.py
661
4.28125
4
#BMI CALCULATOR print("Welcome to Jerome's BMI Calculator!") while True: Name = input("What is your name? ") Weight = input("What is your weight (in kgs)? ") Height = input("What is your height(in m)?") BMI = float(Weight) / (float(Height) * float(Height)) print("Your BMI is", BMI) i...
false
01dfc11678b81a19780e0a47f2b962301c155df5
Markos9/Mi-primer-programa
/comer_helado.py
972
4.25
4
apetece_helado_input = input("Te apetece un helado? (SI/NO): ").upper() if apetece_helado_input == "SI": apetece_helado = True elif apetece_helado_input == "NO": apetece_helado = False print("Pues nada") else: print("Te he dicho que me digas si o no, no se que has dicho pero cuento como que no") a...
false
d02faf79c21f33ace38aabe121dcffc7a213e457
vivekmuralee/my_netops_repo
/learninglists.py
1,069
4.34375
4
my_list = [1,2,3] print (my_list) print (my_list[0]) print (my_list[1]) print (my_list[2]) ######################################################### print ('Appending to the lists') my_list.append("four") print(my_list) ###################################################### print ('Deleting List Elements') del my_...
true
92379a4874c8af8cc39ba72f79aeae7e0edb741c
RyanIsCoding2021/RyanIsCoding2021
/getting_started2.py
270
4.15625
4
if 3 + 3 == 6: print ("3 + 3 = 6") print("Hello!") name = input('what is your name?') print('Hello,', name) x = 10 y = x * 73 print(y) age = input("how old are you?") if age > 6: print("you can ride the rolercoaster!") else: print("you are too small!")
true
f9e1251d704a08dc1132f4d54fb5f46fb171766e
BjornChrisnach/Edx_IBM_Python_Basics_Data_Science
/objects_class_02.py
2,998
4.59375
5
#!/usr/bin/env python # Import the library import matplotlib.pyplot as plt # %matplotlib inline # Create a class Circle class Circle(object): # Constructor def __init__(self, radius=3, color='blue'): self.radius = radius self.color = color # Method def add_radius(self, r): ...
true
987a02de30705a5c911e4182c0e83a3e46baecb3
littleninja/udacity-playground
/machine_learning_preassessment/count_words.py
1,201
4.25
4
"""Count words.""" def count_words(s, n): """Return the n most frequently occuring words in s.""" # TODO: Count the number of occurences of each word in s word_dict = {} word_list = s.split(" ") max_count = 1 max_word_list = [] top_n = [] for word in word_list: if word...
true
857692c3bf179c775cb1416fc7d742dfbb254a39
NCCA/Renderman
/common/Vec4.py
1,551
4.125
4
import math ################################################################################ # Simple Vector class # x,y,z,w attributes for vector data ################################################################################ class Vec4: # ctor to assign values def __init__(self, x, y, z, w=1.0): ...
true
f6d6fce48a00f5af17044c4fafbcfef686ddd1f3
nikdom769/test_py111
/Tasks/a2_priority_queue.py
1,534
4.21875
4
""" Priority Queue Queue priorities are from 0 to 5 """ from typing import Any memory_prior_queue = {} def enqueue(elem: Any, priority: int = 0) -> None: """ Operation that add element to the end of the queue :param elem: element to be added :return: Nothing """ global memory_prior_queue ...
true
1e415caf237f77e59e13218ab583efdb567f0570
LordBars/python-tutorial
/python-tutorial/stringler-ve-methotları.py
753
4.125
4
## String'ler string = ' Merhaba, Dünya ' print("String'ler listedir. Elemanlara erişebilir ve değişterebilirsiniz") print(string) print("string[6]:", string[6]) print("len(string):", len(string)) print("Merhaba in string:", 'Merhaba' in string) print("Merhaba not in string:", 'Merhaba' not in string) print("string...
false
2be9e85741dc8553d4f6accc9f6bfd4f9ad545d1
jwex1000/Learning-Python
/learn_python_the_hard_way_ex/ex15_extra.py
865
4.4375
4
#!/usr/bin/env python # this imports the argv module from the sys libaray print "What is the name of the file you are looking for?" filename = raw_input("> ") #creates a variable txt and opens the variable passed into it from the argv module txt = open (filename) #Shows the user what the file name is print "Here's y...
true
45667bc90b655d757017bc8701ad16ce5060822c
codymlewis/Euler
/Nine.py
668
4.5625
5
''' A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' def find_triplet_product(): a = 1 b = 1 c = 1000 - (a + b) ...
false
3701a03acf60f25c3eb9037343f0fc99ccf82d0e
manaleee/python-foundations
/age_calculator.py
764
4.3125
4
from datetime import date def check_birthdate(year1,month1,day1): today = date.today() if today.year < year1: return False if today.year > year1: return True def calculate_age(year1,month1,day1): today = date.today() #age = today.year - birthdate.year - ((today.month, t...
false
66efbf4f5f6c20fe0a4a715e8f10bbf6d5690913
JMCCMJ/CSCI-220-Introduction-to-Programming
/HW 1/usury.py
1,750
4.34375
4
## ## Name: <Jan-Michael Carrington> ## <usury>.py ## ## Purpose: <This program calculates the priniple payments on a car or home ## purchase. It will tell exactly how much interest will be paid ## over the period of the loans. It also will tell the total payment.> ## ## ## Certification of Authenticity: ## ## I...
true
0d359a3c30b12076205a4b030b7723ecf65b7ba0
asiguqaCPT/Hangman_1
/hangman.py
1,137
4.1875
4
#TIP: use random.randint to get a random word from the list import random def read_file(file_name): """ TODO: Step 1 - open file and read lines as words """ words = open(file_name,'r') lines = words.readlines() return lines def select_random_word(words): """ TODO: Step 2 - select rand...
true
4d94f7809e935cfcebf874d37163f49abf581bf4
S-Oktay-Bicici/PYTHON-PROGRAMMING
/7-Metodlar-(Fonksiyonlar)/sqrt-karakök.py
1,333
4.5625
5
from math import sqrt # Kullanıcıdan değer alınıyor sayi = float(input("Sayı Giriniz: ")) # Karakök hesaplanarak kok değişkenine aktarılıyor kok = sqrt(sayi) # kok değişkenine sqrt fonksiyonunun sonucu aktarılmış print(sqrt(sayi)) # Sonuçlar yazdırılıyor print(sayi," sayısının karekökü" "=", kok) ########...
false
9b3f76d0f3659b1b5d9c4c1221213ea6fbbc2a5b
arloft/thinkpython-exercises
/python-thehardway-exercises/ex4.py
892
4.34375
4
my_name = "Aaron Arlof" my_age = 40 # sigh... my_height = 70 # inches my_weight = 152 # about my_eyes = 'blue' my_teeth = 'mostly white' my_hair = 'brown' print "Let's talk about %s." % my_name print "He's %d inches tall" % my_height print "He's %d pounds heavy" % my_weight print "Actually, that's not too heavy." prin...
true
c4d6ef81f598c2f0277bb734bfd90316be19043b
andrijana-kurtz/Udacity_Data_Structures_and_Algorithms
/project3/problem_5.py
2,914
4.21875
4
""" Building a Trie in Python Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search. Before w...
true
8ec108d9e7689393dce6d610019da91cd693dfd7
ottoman91/ds_algorithm
/merge_sort.py
1,124
4.375
4
def merge_sort(list_to_sort): #base case: lists with fewer than 2 elements are sorted if len(list_to_sort) < 2: return list_to_sort # step 1: divide the list in half # we use integer division so we'll never get a "half index" mid_index = len(list_to_sort) / 2 left = list_to_sort[:mid_index] right = l...
true
d7a97cdf17638e92d14fab42dfce81e4ff9636fa
IagoRodrigues/PythonProjects
/Python3_oo2/modelo.py
1,822
4.15625
4
class Filme: def __init__(self, nome, ano, duracao): # Atributos privados são marcados usando __ no inicio do nome self.__nome = nome.title() self.ano = ano self.duracao = duracao self.__likes = 0 # Posso criar getters usando uma função com o mesmo nome do atributo ...
false
b4505d0b7b4b1b9a2bbaebbd49ca261054ef935b
DIdaniel/coding-training
/3-countLetters/demo.py
275
4.125
4
# -*- coding: utf-8 -*- # 인풋 : string 넣는 input 만들기 # string function # 아웃풋 : STRING has STRING.LENGTH characters say = input('What is the input string? : ') def smthString(say) : print(say + ' has ' + str(len(say)) + ' characters' ) smthString(say)
false
03dc6d2c4223efe10b69acd3cc6b8bbda5732fc8
noltron000-coursework/data-structures
/source/recursion.py
1,182
4.40625
4
#!python def factorial(n): ''' factorial(n) returns the product of the integers 1 through n for n >= 0, otherwise raises ValueError for n < 0 or non-integer n ''' # check if n is negative or not an integer (invalid input) if not isinstance(n, int) or n < 0: raise ValueError(f'factorial is undefined for n = {n}...
true
1f6878f1a62be6110158401c6e04d0c8d46a5d8b
noltron000-coursework/data-structures
/source/palindromes.py
2,633
4.3125
4
#!python def is_palindrome(text): ''' A string of characters is a palindrome if it reads the same forwards and backwards, ignoring punctuation, whitespace, and letter casing. ''' # implement is_palindrome_iterative and is_palindrome_recursive below, then # change this to call your implementation to verify it p...
true
ac8e6616fe97a418e310efd5feced4ffde77a8cd
themeliskalomoiros/bilota
/stacks.py
1,696
4.46875
4
class Stack: """An abstract data type that stores items in the order in which they were added. Items are added to and removed from the 'top' of the stack. (LIFO)""" def __init__(self): self.items = [] def push(self, item): """Accepts an item as a parameter and appends it to the en...
true
994247baf36ffebae449b717429bd937ba770b60
paolithiago/Python-Paoli
/GraficoLinhaValores_Mes(Mod3Sigmoidal).py
607
4.3125
4
#2. REVISÃO MODULO 3 - VISUALIZAÇÃO DE DADOS import matplotlib.pyplot as plt # IMPORTA BIBLIOTECA MATPLOTLIB data = ['set','ago','jul'] # CRIA UMA LISTA COM OS MESES print(saldo_lista) # IMPRIME A LISTA COM OS TRES SALDOS(EX ANTERIOR) prin...
false
4022fb87a259c9fd1300fd4981eb3bd23dce7c1f
0ushany/learning
/python/python-crash-course/code/5_if/practice/7_fruit_like.py
406
4.15625
4
# 喜欢的水果 favorite_fruits = ['apple', 'banana', 'pear'] if 'apple' in favorite_fruits: print("You really like bananas!") if 'pineapple' in favorite_fruits: print("You really like pineapple") if 'banana' in favorite_fruits: print("You really like banana") if 'lemon' in favorite_fruits: print("You really l...
true
500d2e4daea05e14d3cedad52e0fae2d1ca4fe92
harjothkhara/computer-science
/Intro-Python-I/src/08_comprehensions.py
1,847
4.75
5
""" List comprehensions are one cool and unique feature of Python. They essentially act as a terse and concise way of initializing and populating a list given some expression that specifies how the list should be populated. Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions for m...
true
23d8562ec8a10caa237d4544bb07cfefbb6fcd7f
harjothkhara/computer-science
/Sprint-Challenge--Data-Structures-Python/names/binary_search_tree.py
2,610
4.1875
4
class BinarySearchTree: # a single node is a tree def __init__(self, value): # similar to LL/DLL self.value = value # root at each given node self.left = None # left side at each given node self.right = None # right side at each given node # Insert the given value into the tree ...
true
49e4c6e85a28647c59bd025e34ac9bae09b05fc8
rtorzilli/Methods-for-Neutral-Particle-Transport
/PreFlight Quizzes/PF3/ProductFunction.py
445
4.34375
4
''' Created on Oct 9, 2017 @author: Robert ''' #=============================================================================== # (5 points) Define a function that returns the product (i.e. ) of an unknown set of # numbers. #=============================================================================== def mathProd...
true
a8e5c4bc11d9a28b1ef139cbd0f3f6b7377e6780
itsmedachan/yuri-python-workspace
/YuriPythonProject2/YuriPy2-6.py
337
4.21875
4
str_temperature = input("What is the temperature today? (celsius) : ") temperature = int(str_temperature) if temperature >= 27: message = "It's hot today." elif temperature >= 20: message = "It's warm and pleasant today." elif temperature >= 14: message = "It's coolish today." else: message = "It's cold today....
true
423247af19d550fbf231b08b655c6d6287ff84e2
itsmedachan/yuri-python-workspace
/YuriPythonProject5/YuriPy5-3.py
590
4.125
4
import math class YuriPythonProject5no3: def circle_area(self): circumference_length = 2*math.pi*radius circle_area = math.pi*radius*radius return "円周は"+str(circumference_length)+"、面積は"+str(circle_area)+"です" print('円の円周と面積を求めます') radius = float(input('半径を入力してください: ')) circle = YuriPythonPro...
false
5079c30dbdb327661f2959b057a192e45fa20319
itsmedachan/yuri-python-workspace
/YuriPythonProject2/YuriPy2-1.py
242
4.15625
4
str_score = input("Input your score: ") score = int(str_score) if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print("Your grade is: ", grade)
true
0b5d8f76a5767a6c913dce4b8107f4399cfd77b2
louielolo/LeetCodeFMH
/BinTree/二叉树中结点和最大的二叉搜索树/largestBST.py
2,281
4.25
4
""" 给你一棵以 root 为根的 二叉树 ,请你返回 任意 二叉搜索子树的最大键值和。 二叉搜索树的定义如下: 任意节点的左子树中的键值都 小于 此节点的键值。 任意节点的右子树中的键值都 大于 此节点的键值。 任意节点的左子树和右子树都是二叉搜索树。   来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-sum-bst-in-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class TreeNode: def __init__(self,val=0,left=None,right=None...
false