blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
53bc1949d4d989f076e481341e6c52fffb549da4
mayakota/KOTA_MAYA
/Semester_1/Lesson_05/5.01_ex_02.py
655
4.15625
4
height = float(input("What is your height?")) weight = float(input("What is your weight?")) BMI = 0 condition = "undetermined" def calcBMI(height,weight): global BMI,condition BMI = (weight/height) * 703 if BMI < 18.5 : condition = "condition is Underweight" elif BMI < 24.9 : condition...
true
9bfca2db61d14c15064ed7c42e3bdeb6714de64c
mayakota/KOTA_MAYA
/Semester_1/Lesson_05/5.02_ex06.py
559
4.25
4
def recursion(): username = input("Please enter your username: ") password = input("Please enter your password: ") if username == "username" and password == "password": print("correct.") else: if password == "password": print("Username is incorrect.") recursio...
true
bf23188fb3c90c34da9d2b64ba6aeed16d623fd1
shashankgargnyu/algorithms
/Python/GreedyAlgorithms/greedy_algorithms.py
1,920
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file contains Python implementations of greedy algorithms from Intro to Algorithms (Cormen et al.). The aim here is not efficient Python implementations but to duplicate the pseudo-code in the book as closely as possible. Also, since the goal is to help students ...
true
8f2a974d5aa0eb91db1b2978ced812678e34f69f
LYoung-Hub/Algorithm-Data-Structure
/wordDictionary.py
2,039
4.125
4
class TrieNode(object): def __init__(self): self.cnt = 0 self.children = [None] * 26 self.end = False class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word): ...
true
cf90416b58d12338fb6c626109ef0ecf11c0807f
sravanneeli/Data-structures-Algorithms
/stack/parenthesis_matching.py
888
4.125
4
""" Parenthesis Matching: whether braces are matching in a string """ from stack.stack_class import Stack bracket_dict = {')': '(', ']': '[', '}': '{'} def is_balanced(exp): """ Check whether all the parenthesis are balanced are not :param exp: expression in string format :return: True or False ...
true
7c811aba960dd8ebeb03863e298ba55f43a5ed3c
sravanneeli/Data-structures-Algorithms
/Sorting_Algorithms/merge_sort.py
1,321
4.15625
4
def merge(arr, start, mid, end): temp = [0] * (end - start + 1) i, j, k = start, mid + 1, 0 while i <= mid and j <= end: if arr[i] < arr[j]: temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 while...
false
46fe2a640740d758681f4cff963a0f8dc2bf87ff
lajospajtek/thought-tracker.projecteuler
/p302.py
2,977
4.15625
4
#!/usr/bin/python # -*- coding: Latin1 -*- # Problem 302 # 18 September 2010 # # A positive integer n is powerful if p^(2) is a divisor of n for every prime # factor p in n. # # A positive integer n is a perfect power if n can be expressed as a power of # another positive integer. # # A positive integer n is an Achi...
false
db069f0bdb81b54b5ca7ab589fd8db33bff0368b
lajospajtek/thought-tracker.projecteuler
/p057.py
1,097
4.15625
4
#!/usr/bin/python # -*- coding: Latin1 -*- # Problem 057 # # It is possible to show that the square root of two can be expressed as an infinite continued fraction. # # √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... # # By expanding this for the first four iterations, we get: # # 1 + 1/2 = 3/2 = 1.5 # 1 + 1/(2 + ...
true
4e612bc6b0425b59d37e9341cd4bc8783a2f2bad
sauravgsh16/DataStructures_Algorithms
/g4g/ALGO/Searching/Coding_Problems/12_max_element_in_array_which_is_increasing_and_then_decreasing.py
1,725
4.15625
4
''' Find the maximum element in an array which is first increasing and then decreasing ''' ''' Eg: arr = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1] Output: 500 Linear Search: We can search for the maximum element and once we come across an element less than max, we break and return max ''' ''' Bi...
true
536926dbe1374a5bfac6d3fd62074cde4a1cab12
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Arrays/Sorting/14_union_and_intersection.py
1,174
4.125
4
''' Union and Intersection of two sorted arrays Input : arr1[] = {1, 3, 4, 5, 7} arr2[] = {2, 5, 6} Output : Union : {1, 2, 3, 4, 5, 6, 7} Intersection : {3, 5} ''' def union(arr1, arr2): m = len(arr1) n = len(arr2) i = k = 0 result = [] while i < m and k < n: ...
false
b820d08879eecae30d95bcaa221be073f71a22ad
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/RN_7_check_each_internal_node_has_exactly_1_child.py
1,372
4.15625
4
''' Check if each internal node has only one child ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None # In Preorder traversal, descendants (or Preorder successors) of every node # appear after the node. In the above example, 20 is the first n...
true
1507e2ab37a5f36e5ba8a20fd41acff2815e9fa8
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/24_symmetric_tree_iterative.py
1,250
4.28125
4
''' Check if the tree is a symmetric tree - Iterative ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def check_symmetric(root): if not root: return True if not root.left and not root.right: return True ...
true
06354d4f46de16ca4d0162548992da2fe6061973
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/26_find_middle_of_perfect_binary_tree.py
900
4.15625
4
''' Find middle of a perfect binary tree without finding height ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None ''' Use two pointer slow and fast, like linked list Move fast by 2 leaf nodes, and slow by one. Once fast reaches leaf...
true
748bccf48ef30c79bb9312e2d3be2c37c66cf459
HarperHao/python
/mypython/第七章文件实验报告/001.py
1,235
4.28125
4
"""统计指定文件夹大小以及文件和子文件夹数量""" import os.path totalSize = 0 fileNum = 0 dirNum = 0 def visitDir(path): global totalSize global fileNum global dirNum for lists in os.listdir(path): sub_path = os.path.join(path, lists) if os.path.isfile(sub_path): fileNum = fileNum + 1 ...
true
6fecf6d2c96d29409c240b76a7a0844668b17594
kalyanitech2021/codingpractice
/string/easy/prgm4.py
701
4.25
4
# Given a String S, reverse the string without reversing its individual words. Words are separated by dots. # Example: # Input: # S = i.like.this.program.very.much # Output: much.very.program.this.like.i # Explanation: After reversing the whole # string(not individual words), the input # string becomes # much...
true
83b5224314c1eba5d985c0413b69960dc9c26c3a
pavel-malin/new_practices
/new_practice/decorators_practice/abc_decorators_meta.py
654
4.1875
4
''' Using a subclass to extend the signature of its parent's abstract method import abc class BasePizza(object, metaclass=abc.ABCMeta): @abc.abstractmethod def get_ingredients(self): """Returns the ingredient list.""" class Calzone(BasePizza): def get_ingredients(self, with_egg=False): e...
true
9216d686ad0deb206998db55005c4e4889c6332f
courtneyng/Intro-To-Python
/If-exercises/If-exercises.py
681
4.125
4
# Program ID: If-exercises # Author: Courtney Ng, Jasmine Li # Period 7 # Program Description: Using if statements months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November'] # months.append('December') ans = input("Enter the name of a month: ") i...
true
2d1e08e74910d00f238f27b705b7196a35dacdf9
courtneyng/Intro-To-Python
/Tuples_and_Lists/A_List_Of_Numbers.py
1,727
4.28125
4
# Program ID: A_List_Of_Numbers # Author: Courtney Ng # Period: 7 # Program Description: List extensions in Python # numList = [1, 1, 2, 3, 5, 8, 11, 19, 30, 49] # product = 30*8*11*19*30*49 num1 = int(input("Enter the first number.")) numList = [100, 101, 102] numList.append(num1) numList.remove(100) numLi...
true
b4a981c76af3be316f3b22b2c0d979bd7386e73c
courtneyng/Intro-To-Python
/Tuples_and_Lists/list_extensions.py
797
4.34375
4
# Program ID: lists_extensions # Author: Courtney Ng # Period: 7 # Program Description: List extensions in Python # Given list fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] # The new list extensions test fruits.count('apple') print(fruits.count('apple')) # Added a print stateme...
true
bcef00fbacb443c75b8a69a97c56d78924ce4d7d
pouya-mhb/University-Excersises-and-Projects
/Compiler Class/prefix suffix substring proper prefix subsequence/substring of a string.py
454
4.53125
5
#substring of a string stringValue = input("Enter string : ") def substring(stringValue): print("The original string is : " + str(stringValue)) # Get all substrings of string # Using list comprehension + string slicing res = [stringValue[i: j] for i in range(len(stringValue)) for j in range(...
true
d6cf7a9f246b4e57cc1f748eccfd1d24dc64575a
shiblon/pytour
/3/tutorials/recursion.py
1,988
4.78125
5
# vim:tw=50 """Recursion With an understanding of how to write and call functions, we can now combine the two concepts in a really nifty way called **recursion**. For seasoned programmers, this concept will not be at all new - please feel free to move on. Everyone else: strap in. Python functions, like those in many...
true
d7771130f1ee54dc2d3924e8266c91c559bf4063
shiblon/pytour
/3/tutorials/hello.py
1,596
4.71875
5
# vim:tw=50 """Hello, Python 3! Welcome to Python version 3, a very fun language to use and learn! Here we have a simple "Hello World!" program. All you have to do is print, and you have output. Try running it now, either by clicking *Run*, or pressing *Shift-Enter*. What happened? This tutorial contains a *Python ...
true
60b0ff336ec48cb60786c47528fa31777ffc8693
shiblon/pytour
/tutorials/urls.py
1,583
4.125
4
# vim:tw=50 """Opening URLs The web is like a huge collection of files, all jamming up the pipes as they fall off the truck. Let's quickly turn our attention there, and learn a little more about file objects while we're at it. Let's use |urllib| (http://docs.python.org/2/library/urllib.html) to open the Google Priva...
true
503f1aa74c5d3c2dbd5f5b4e6f97cdbc67aeaa23
abhisek08/Basic-Python-Programs
/problem22.py
1,247
4.4375
4
''' You, the user, will have in your head a number between 0 and 100. The program will guess a number, and you, the user, will say whether it is too high, too low, or your number. At the end of this exchange, your program should print out how many guesses it took to get your number. As the writer of this program, y...
true
6affb302816e8fcf5015596806c5082fa2d3d30d
abhisek08/Basic-Python-Programs
/problem5.py
1,248
4.25
4
''' Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of diff...
true
107a32642f0def5ce58017a4d6156bebf1287a1c
abhisek08/Basic-Python-Programs
/problem16.py
1,008
4.34375
4
''' Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wr...
true
cc0fe65d97a1914cc986b3dd480ff97bd8a53320
wilsouza/RbGomoku
/src/core/utils.py
1,504
4.28125
4
import numpy as np def get_diagonal(table, offset): """ Get diagonal from table Get a list elements referencing the diagonal by offset from main diagonal :param table: matrix to get diagonal :param offset: Offset of the diagonal from the main diagonal. Can ...
true
7653c8e4c2176b8672a531988ef26c1331540b5d
bsundahl/IACS-Computes-2016
/Instruction/Libraries/bryansSecondLibrary.py
245
4.4375
4
def factorial(n): ''' This function takes an integer input and then prints out the factorial of that number. This function is recursive. ''' if n == 1 or n == 0: return 1 else: return n * factorial(n-1)
true
7b5e3de71b6bdd958b6debafe5d0882503f87f20
rahul-pande/ds501
/hw1/problem1.py
1,445
4.3125
4
#------------------------------------------------------------------------- ''' Problem 1: getting familiar with python and unit tests. In this problem, please install python verion 3 and the following package: * nose (for unit tests) To install python packages, you can use any python package mana...
true
7de333d37e0af493325591c525cef536290f13be
GameroM/Lists_Practice
/14_Lists_Even_Extract.py
360
4.21875
4
## Write a Python program to print the numbers of a specified list after removing ## even numbers from it x = [1,2,3,4,5,6,7,8,15,20,25,42] newli = [] def evenish(): for elem in x: if elem % 2 != 0: newli.append(elem) return newli print('The original list is:', x) print('The li...
true
0632f5713b13eb0b83c1866566125a069d4f997d
GameroM/Lists_Practice
/8_Lists_Empty_Check.py
445
4.375
4
## Write a Python program to check if a list is empty or not x = [] def creation(): while True: userin=input('Enter values,type exit to stop:') if userin == 'exit': break else: x.append(userin) return x print('The list created from user input...
true
8a8ccbf32880b637bba81516a69e23b3cabd2229
blackseabass/Python-Projects
/Homework/week5_exercise2.py
1,483
4.3125
4
#!/usr/bin/env python """ File Name: week5_exercise2.py Developer: Eduardo Garcia Date Last Modified: 10/4/2014 Description: User plays Rock, Paper, Sciissors with the computer Email Address: garciaeduardo1223@gmail.com """ import random def main(): print("Rock. Paper. Scissors." "\n" "Enter 1 for ...
true
c8639d6ef1d7044f1a840f7446fc7cfb624a1209
amitravikumar/Guvi-Assignments
/Program14.py
283
4.3125
4
#WAP to find the area of an equilateral triangle import math side = float(input("Enter the side: ")) def find_area_of_triangle(a): return(round(((1/4) * math.sqrt(3) * (a**2)), 2)) result = find_area_of_triangle(side) print("Area of equilateral triangle is ", result)
true
5e5803c836e3d83613e880061b29d6862774836b
amitravikumar/Guvi-Assignments
/Program4.py
309
4.3125
4
#WAP to enter length and breadth of a rectangle and find its perimeter length, breadth = map(float,input("Enter length and breadth with spaces").split()) def perimeter_of_rectangle(a,b): return 2*(a+b) perimeter = perimeter_of_rectangle(length,breadth) print("Perimeter of rectangle is", perimeter)
true
1971a9a13cc857df612840450c1fb3f455d8a034
gitfolder/cct
/Python/calculator.py
1,680
4.21875
4
# take user input and validate, keep asking until number given, or quit on CTRL+C or CTR+D def number_input(text): while True: try: return float(input(text)) except ValueError: print("Not a number") except (KeyboardInterrupt, EOFError): raise SystemExit def print_menu(): print("\n1. A...
true
45b822d5189e7e8317f7deb26deed12e7562d29e
jebarajganesh1/Ds-assignment-
/Practical 5.py
1,415
4.1875
4
#Write a program to search an element from a list. Give user the option to perform #Linear or Binary search. def LinearSearch(array, element_l):     for i in range (len(array)):         if array[i] == element_l:             return i     return -1 def BinarySearch(array, element_l):     first = 0     array.sort()     ...
true
cfa2dee09f7d4b7dec7c328f8cef5f085e17dd95
Amirreza5/Class
/example_comparison02.py
218
4.125
4
num = int(input('How many numbers do you want to compare: ')) list_num = list() for i in range(0, num): inp_num = int(input('Please enter a number: ')) list_num.append(inp_num) list_num.sort() print(list_num)
true
5436a11b86faa2784d2a3aab6b9449bbca9df2fd
mynameismon/12thPracticals
/question_6#alt/question_6.py
1,755
4.125
4
<<<<<<< HEAD # Create random numbers between any two values and add them to a list of fixed size (say 5) import random #generate list of random numbers def random_list(size, min, max): lst = [] for i in range(size): lst.append(random.randint(min, max)) return lst x = random_list(5, 1, 100) # the lis...
true
2b7b16fe2ba676de0de95fd695afa8ab9af61544
RicaBenhossi/Alura-Learning
/Python/01-DataStructure_Python/route_linked_list.py
2,136
4.15625
4
from data_structure.linked_list import LinkedList class Store: def __init__(self, name, address) -> None: self.name = name self.address = address def __repr__(self) -> str: return '{}\n {}'.format(self.name, self.address) def show_result(lnk_list: LinkedList) -> None: print() ...
false
18ab5a5323df219b155c0681ce69e45a3b8dd2fc
Baltiyski/HackBulgaria
/Programming0-1/week01/02-If-Elif-Else-Simple-Problems/calculator.py
485
4.21875
4
a = input("Enter a: "); a = int(a); b = input("Enter b: "); b = int(b); oper = input("Enter operation : "); result = 0; if(oper == "+"): result = a + b; print("Result is: ") print(result) elif(oper == "-"): result = a - b; print("Result is: ") print(result) elif(oper == "*"): result = a *...
false
542c400ed5a8bfb88006ce3b2c7f881088720131
YANYANYEAH/jianzhi-offor-python
/16_数值的整数次方.py
1,609
4.40625
4
# -*- coding:utf-8 -*- # // 面试题16:数值的整数次方 # // 题目:实现函数double Power(double base, int exponent),求base的exponent # // 次方。不得使用库函数,同时不需要考虑大数问题。 # tips: 考虑特殊条件,比如 exponent 为负数, 此时结果需要取倒数 # 当结果去倒数的时候,需要考虑分母为0的情况,0^n = 0或者1,n^0 = 1 # 此处需要考虑 简单的方法,比如a^n = a^(n/2) * a^(n/2) 此时需要考虑n为奇数还是偶数 # def get_result(...
false
f58cd8b8c7c7f9f8175fb0816e0ae8073d6101d1
magdeevd/gb-python
/homework_5/third.py
1,052
4.15625
4
def main(): """ 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов (не менее 10 строк). Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. """ sala...
false
38ac39d0e0b2827c8bc495ffd72b551ac1bda54e
JulhaMouraR/BiotecGirls
/Hackathon.py
878
4.1875
4
import sqlite3 conn = sqlite3.connect('estudantes.db') cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS students( UserID VARCHAR(20) NOT NULL, username VARCHAR(60) NOT NULL, firstname VARCHAR(60) NOT NULL, email VARCHAR(60) NOT NULL, password VARCHAR(80) NOT NULL); ''') #gravando no bd conn.commit...
false
6a3ca57e16621b671baeb4343ed1a82c6da2f4c9
jonathanjaimes/python
/5.7_perimetro.py
1,564
4.15625
4
#En esta primera función se ingresan los datos necesarios. def tomaDatos(): punto1 = input("Ingrese el nombre del primer punto: ") x1 = float(input(f"Ingrese la primera coordenada del punto {punto1}: ")) y1 = float(input(f"Ingres la segunda coordenada del punto {punto1}: ")) punto2 = input("Ingrese el nomb...
false
2300e2a3c3ccb603907e2bcbd895f25cbbca504d
Enfioz/enpands-problems
/weekdays.py
535
4.34375
4
# Patrick Corcoran # A program that outputs whether or not # today is a weekday or is the weekend. import datetime now = datetime.datetime.now() current_day = now.weekday weekend = (5,7) if current_day == weekend: print("It is the weekend, yay!") else: print("Yes, unfortunately today is a weekd...
true
6c511888f1cfcb208e0aa3a03d5c2cbfe2e7b015
Aninda05/Java-only
/lambda.py
308
4.1875
4
print("*****THE SUM OF SQUARES USING LAMBDA*****\n") x=int(input("Enter the first number:")) y=int(input("Enter the second number:")) z=int(input("Enter the third number:")) def fuc(x,y,z): a=lambda x:x*x b=lambda x,y:x+y*y c=lambda y,z:y+z*z return(c(b(a(x),y),z)) print"The result is: ",fuc(x,y,z)
false
617d4aa7fd56d6511a28954c6bfd384c8b9251d1
andreeaanbrus/Python-School-Assignments
/Assignment 1/8_setB.py
893
4.25
4
''' Determine the twin prime numbers p1 and p2 immediately larger than the given non-null natural number n. Two prime numbers p and q are called twin if q-p = 2. ''' def read(): x = int(input("Give the number: ")) return x def isPrime(x): if(x < 2): return False if(x > 2 and x % 2 ==...
true
cc608e03490880b23f1cb4e53a781670cb898d01
vlad-bezden/py.checkio
/oreilly/reverse_every_ascending.py
1,364
4.40625
4
"""Reverse Every Ascending https://py.checkio.org/en/mission/reverse-every-ascending/ Create and return a new iterable that contains the same elements as the argument iterable items, but with the reversed order of the elements inside every maximal strictly ascending sublist. This function should n...
true
d0ef4d781f2518afb1210abedf14239e6b06c0e2
vlad-bezden/py.checkio
/oreilly/remove_all_after.py
1,247
4.65625
5
"""Remove All After. https://py.checkio.org/en/mission/remove-all-after/ Not all of the elements are important. What you need to do here is to remove all of the elements after the given one from list. For illustration, we have an list [1, 2, 3, 4, 5] and we need to remove all the elements tha...
true
56e4820a3eb210789a5b4d86cf4386d4028edb91
vlad-bezden/py.checkio
/oreilly/how_deep.py
1,704
4.5625
5
"""How Deep. https://py.checkio.org/en/mission/how-deep/ You are given a tuple that consists of integers and other tuples, which in turn can also contain tuples. Your task is to find out how deep this structure is or how deep the nesting of these tuples is. For example, in the (1, 2, 3) tuple...
true
4ea6cc426ebeeaf6f594465a48a6bfb836555467
vlad-bezden/py.checkio
/mine/perls_in_the_box.py
2,354
4.65625
5
"""Pearls in the Box https://py.checkio.org/en/mission/box-probability/ To start the game they put several black and white pearls in one of the boxes. Each robot has N moves, after which the initial set is being restored for the next game. Each turn, the robot takes a pearl out of the box and put...
true
7956966c7aa9ffed8da7d23e75d98ae1867c376a
vlad-bezden/py.checkio
/electronic_station/similar_triangles.py
2,498
4.28125
4
"""Similar Triangles https://py.checkio.org/en/mission/similar-triangles/ This is a mission to check the similarity of two triangles. You are given two lists as coordinates of vertices of each triangle. You have to return a bool. (The triangles are similar or not) Example: similar_triangles...
true
d880c75abc5b1980a6e0bd5b2435c647963a08d1
vlad-bezden/py.checkio
/oreilly/median_of_three.py
1,986
4.125
4
"""Median of Three https://py.checkio.org/en/mission/median-of-three/ Given an List of ints, create and return a new List whose first two elements are the same as in items, after which each element equals the median of the three elements in the original list ending in that position. Input: Li...
true
d8803c10cf12c5afb6898dd2c5cce4e7be0adeed
vlad-bezden/py.checkio
/oreilly/chunk.py
1,083
4.4375
4
"""Chunk. https://py.checkio.org/en/mission/chunk/ You have a lot of work to do, so you might want to split it into smaller pieces. This way you'll know which piece you'll do on Monday, which will be for Tuesday and so on. Split a list into smaller lists of the same size (chunks). The last ch...
true
a1241876f32a8cbcfa522b6393ae8ba20837549b
vlad-bezden/py.checkio
/elementary/split_list.py
885
4.375
4
"""Split List https://py.checkio.org/en/mission/split-list/ You have to split a given array into two arrays. If it has an odd amount of elements, then the first array should have more elements. If it has no elements, then two empty arrays should be returned. example Input: Array. Ou...
true
93b69fd2a07e076c8d968d862e19bb1831aa6aab
vlad-bezden/py.checkio
/mine/skew-symmetric_matrix.py
2,305
4.1875
4
"""Skew-symmetric Matrix https://py.checkio.org/en/mission/skew-symmetric-matrix/ In mathematics, particularly in linear algebra, a skew-symmetric matrix (also known as an antisymmetric or antimetric) is a square matrix A which is transposed and negative. This means that it satisfies the equation ...
true
b1dee53024fb0e1420d3d3443eb26f6f2c949bf1
linkel/MITx-6.00.1x-2018
/Week 1 and 2/alphacount2.py
1,218
4.125
4
s = 'kpreasymrrs' longest = s[0] longestholder = s[0] #go through the numbers of the range from the second letter to the end for i in (range(1, len(s))): #if this letter is bigger or equal to the last letter in longest variable then add it on (meaning alphabetical order) if s[i] >= longest[-1]: longest ...
true
fc17ad2770c01b01220527948074999663a5cb0e
amir-mersad/ICS3U-Unit5-01-Python
/function.py
885
4.46875
4
#!/usr/bin/env python3 # Created by: Amir Mersad # Created on: November 2019 # This program converts temperature in degrees Celsius # to temperature degrees Fahrenheit def celsius_to_fahrenheit(): # This program converts temperature in degrees Celsius # to temperature degrees Fahrenheit # Input ce...
true
3fe8ff6ea8a307276a311b01f494c3e92175868d
corridda/Studies
/Articles/Python/pythonetc/year_2018/september/operator_and_slices.py
2,069
4.5
4
"""Оператор [] и срезы""" """В Python можно переопределить оператор [], определив магический метод __getitem__. Так, например, можно создать объект, который виртуально содержит бесконечное количество повторяющихся элементов:""" class Cycle: def __init__(self, lst): self._lst = lst def __getitem__(se...
false
b779876874fbc28d28cdf052cd11ff1e6f8c314c
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/e-g/float__test.py
618
4.15625
4
"""class float([x])""" # https://www.programiz.com/python-programming/methods/built-in/float """Return a floating point number constructed from a number or string x.""" print(f"float(): {float()}") print(f"float(10.5): {float(10.5)}") s = ' -2.5\n' print(f"float(' -2.5'): {float(s)}") print(f"float('NaN'): {flo...
false
22806e83c0bf42cbab9b17e32580e80e3d0ad87a
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/c-d/dict__test.py
673
4.1875
4
"""class dict""" # https://www.programiz.com/python-programming/methods/built-in/dict """ class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Create a new dictionary. The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class. ...
false
a642a315921776c3d5920bd3e9f649a888462773
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/list_test.py
2,003
4.46875
4
"""class list([iterable])""" # https://www.programiz.com/python-programming/methods/built-in/list """Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range. The list() constructor creates a list in Python. Python list() constructor takes ...
true
3ec93bc3e2bbb8ec2f59a612ac2ad112aa1f4930
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.8. Generator expressions/example.py
230
4.25
4
# A generator expression is a compact generator notation in parentheses. # A generator expression yields a new generator object. a = (x**2 for x in range(6)) print(f"a: {a}") print(f"type(a): {type(a)}") for i in a: print(i)
true
c46fa1c8b803ed58abbfeb86d53d0b47f76c0c7d
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/h-i/hasattr_test.py
597
4.21875
4
"""hasattr(object, name)""" # https://www.programiz.com/python-programming/methods/built-in/hasattr print(f"'int' has 'real': {hasattr(int, 'real')}\n") class A: def __init__(self, a, b): self.a = a self.b = b obj_1 = A(1, 2) obj_2 = 15 print(f"hasattr(obj_1, 'a'): {hasattr(obj_1, 'a')}") prin...
false
d866a29053b2e57c7dacf0d44ebaa0078138305a
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/a-b/all__test.py
1,808
4.25
4
"""all(iterable)""" # https://www.programiz.com/python-programming/methods/built-in/all """Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:""" def all_func(iterable): for element in iterable: if not element: return False return True def m...
true
5315e68a06067a3ab9a99178ab86ce613dc163fb
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/c-d/divmod__test.py
816
4.21875
4
"""divmod(a, b)""" # https://www.programiz.com/python-programming/methods/built-in/divmod """Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For in...
true
f312b493d986a88f5f05e4ef2c0db055aa8a8c8d
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/l-n/min_test.py
2,432
4.25
4
"""min(iterable, *[, key, default]) min(arg1, arg2, *args[, key])""" # https://www.programiz.com/python-programming/methods/built-in/min """Return the smallest item in an iterable or the smallest of two or more arguments. If one positional argument is provided, it should be an iterable. The smallest item in the it...
true
bf573e2b7eafe79adde1e52d40e21d5d393b043e
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Language_Reference/6. Expressions/6.2. Atoms/6.2.4. Displays for lists, sets and dictionaries/example.py
218
4.125
4
# The comprehension consists of a single expression followed by at least one for clause # and zero or more for or if clauses. a = [x**2 for x in range(11) if x % 2 == 0] print(f"a: {a}") print(f"type(a): {type(a)}")
true
e5de070bfe40a82008d8d9e6ed6986c618dc7043
corridda/Studies
/Articles/Python/pythonetc/year_2018/october/python_etc_oct_23.py
1,278
4.1875
4
"""https://t.me/pythonetc/230""" """You can modify the code behavior during unit tests not only by using mocks and other advanced techniques but also with straightforward object modification:""" import random import unittest from unittest import TestCase # class Foo: # def is_positive(self): # return sel...
true
beb99591beb990888eb58b3d949b3b44a21bcb2f
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Standard_Library/Built-in Functions/s-z/tuple_test.py
724
4.40625
4
""" tuple([iterable]) class type(object) class type(name, bases, dict)""" # https://www.programiz.com/python-programming/methods/built-in/tuple """Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range. If an iterable is pass...
true
8341587ff2d172282ab6b00a82ea56380f062e4f
corridda/Studies
/CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 5. Data Structures/5.6. Looping Techniques/Looping Techniques.py
1,713
4.15625
4
import math # looping through dictionaries -> items() knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k,v in knights.items(): print(k, ':', v) # looping through a sequence -> # the position index and corresponding value can be retrieved at the same time using the enumerate() function. for i, v in enu...
true
b099a789095e0219156d5cc73d690a738c42ed79
corridda/Studies
/Articles/Python/pythonetc/year_2018/september/autovivification.py
1,204
4.15625
4
from collections import defaultdict """collections.defaultdict позволяет создать словарь, который возвращает значение по умолчанию, если запрошенный ключ отсутствует (вместо выбрасывания KeyError). Для создания defaultdictвам нужно предоставить не просто дефолтное значение, а фабрику таких значений. Так вы можете созд...
false
846c4d29e4c35d7bcfef67418034cd9647ef2e2c
swyatik/Python-core-07-Vovk
/Task 6/Home Work 2/6.2.7.py
1,227
4.28125
4
"""Змінити послідовність стовпців матриці так, щоб елементи її першого рядка були відсортовані за зростанням. """ from random import randint # function of prints a matrix def printMatrix(matrix): for item in matrix: for jtem in item: print("%4d " % j, end="") print() colum...
false
6b3f8316bc32ae76e7975953ae2839bc47a0d317
swyatik/Python-core-07-Vovk
/Task 4/2_number_string.py
293
4.15625
4
number = 1234 strNumber = str(number) product = int(strNumber[0]) * int(strNumber[1]) * int(strNumber[2]) * int(strNumber[3]) reversNumber = int(strNumber[::-1]) print('Product of number %d is %15d' % (number, product)) print('Inverse number to number %d is %8d' % (number, reversNumber))
true
56403e728de4d373716f254eeda78713f902edf3
swyatik/Python-core-07-Vovk
/Task 8/8.2.5.py
1,683
4.125
4
"""Задано два символьних рядка із малих і великих латинських літер та цифр. Розробити програму, яка будує і друкує в алфавітному порядку множину літер, які є в обох масивах, і множини літер окремо першого і другого масивів. """ def printSetSort(userSet): usrSetSort = sorted(userSet) for i in range...
false
fe02d0c885670f821eae1389a3b1f62f3921801a
swyatik/Python-core-07-Vovk
/Task 1/11_total_points.py
1,650
4.15625
4
# Функція, що перевіряє чи рядок число int or float. # Повертає tuple (true or false, тип даних в рядку) def check_int_float(string): if string == '': return (True, 'int') if string[0] == '-': return (False, '') if string.isdigit(): return (True, 'int') else: ...
false
e4f868c12aec7eb4028611d46bf578e5e7619556
bakunobu/exercise
/python_programming /Chapter_1.3/stats.py
1,067
4.5625
5
""" Обобщая упражнение о равномерных случайных числах, составьте программу stats.ру, получающую в аргумен­те командной строки целое число n и использующую функцию random.random ( ) для вывода n равномерно случайных чисел от О до 1, а затем вы­водящую их среднее, минимальное и максимальное значения """ import random ...
false
03b684e80451215ec5a507b100db38088ec81c19
bakunobu/exercise
/1400_basic_tasks/chap_3/3.45.py
1,405
4.46875
4
""" Меня вынесла формулировка. На самом деле задание сводится к тому, что имеется последовательность длиной 180 символов, в которой индекс есть у каждой пары чисел, например номер элемента|->|индекс 1 -> 0 2 -> 0 3 -> 1 4 -> 1 5 -> 2 6 -> 2 и т.д. """ import doctest # k = int(input()) # a def find_index(k: int) -> i...
false
01479006da67767f219e8d241f421c50d12df092
bakunobu/exercise
/python_programming /Chapter_1.1_and_1.2/dragon_curve.py
1,795
4.5
4
""" Составьте программу, выводящую инструкции по рисованию кривых дракона в по­рядке от О до 5. """ def inverse_replacer(my_str:str, a:str, b:str) -> str: """ Replaces a wit b and b with a in my_str Args: ===== my_str: str the sequence of symbols a: str if my_str[i] == a: my_...
false
e5ac3cabe485c1b6b7ced5c4bbb77415d9a67b7a
bakunobu/exercise
/python_programming /Chapter_1.1_and_1.2/box_muler.py
1,211
4.28125
4
""" Один способ создания случайного числа в со­ответствии с распределением Гаусса подразумевает использование фор­мулы Бокса-Мюллера. Составьте программу, выводящую значение согласно стандарт­ному Гауссову распределению. """ import math import random import random def box_muller_trans(v:float, u: float) -> float:...
false
a7681c1f46b63a681c59f7d052e11850177112a1
bakunobu/exercise
/python_programming /Chapter_1.1_and_1.2/day_of_a_week.py
1,311
4.34375
4
""" Составьте программу, получающую дату и выводящую день недели, выпадающий на эту дату. Программа должна получать три аргу­мента командной строки: m (месяц), d (день) и у (год). Значение 1 перемен­ной m соответствует январю, 2 -февралю и т.д. В вы воде О соответствует воскресенью, 1 -понедельнику, 2 -вторнику и т.д....
false
307fa5db59cf3b748e45f8cf80cb9ac4688e4133
mervealgi/python-tutorials
/day2.py
1,239
4.375
4
#INTRODUCTION TO PYTHON DAY2 ###LOGICAL OPERATIONS a, b = True , False print(type(a)) print(a or b) #will be True print(a and b) #will be False print(not a) #will be False print (a != b) #will be True,bcs re not equal print(a == b) #will be False, bcs re not equal ###SLICING array1 = "PYTHON" print(array1[0]...
false
7b3534f75029b8193313f08afaec998f015a71ec
TNEWS01/projets
/Formation_Python/Listes.py
2,064
4.28125
4
# ------------------- # Les listes # ------------------- # Créer une liste et lui assigner le nom de variable ma_liste ma_liste = [1,2,3] print(ma_liste) # ------------------- ma_liste = ['Une chaine',23,100.232,'o'] print(ma_liste) # ------------------- # Nombre d'éléments dans la liste ma_liste = ['un','deux','troi...
false
b6e3692dd74e0baea8f85aec440d2c1831d360a4
Bobby981229/Python-Learning
/Day 02 - Language Element/String_Type.py
533
4.40625
4
""" 字符串运算符 判断是否为小写字母: 'a' <= char <= 'z' 判断是否为大写字母: 'A' <= char <= 'Z' 判断是否为字母: 'a' <= char <= 'z' or 'A' <= char <= 'Z' 判断是否为中文: '\u4e00' <= char <= '\u9fa5' 判断是否为数字: '0' <= char <= '9' """ # 统计字符串中小写字母的个数 str1 = "Hello, World !" count = 0 # 遍历循环查找字符串中的小写字母 for char in str1: if 'a' <= char <= 'z': coun...
false
0c3a027118d292cce1b372a295e646165e4a2459
Bobby981229/Python-Learning
/Day 07 - Data Structures_List/Operator.py
2,372
4.25
4
""" 运算符 """ s1 = 'hello ' * 3 print(s1) # hello hello hello s2 = 'world' s1 += s2 # 拼接字符串 s1 = s1 + s2 print(s1) # hello hello hello world print('ll' in s1) # True, ll在hello中 print('good' in s1) # False, good在hello中 str2 = 'abc123456' # 从字符串中取出指定位置的字符(下标运算) print(str2[2]) # c, 从零开始 # 字符串切片(从指定的开始索引到指定的结束索引) p...
false
974397c2a0980ada4e92b3e13b38483b803dbee9
Bobby981229/Python-Learning
/Day 11 - Introduction to OOP/Print_Obj.py
767
4.21875
4
""" 打印对象 在类中放置__repr__魔术方法 该方法返回的字符串就是用print函数打印对象的时候会显示的内容 """ class Student: """学生""" def __init__(self, name, age): """初始化方法""" self.name = name self.age = age def study(self, course_name): """学习""" print(f'{self.name}正在学习{course_name}.') def play(self): ...
false
5c3e9eca8a134aa837b3a06ac22fb4acc2c8973f
Bobby981229/Python-Learning
/Day 10 - Data Structures_Dictionary/Dictionary_Calculation.py
1,030
4.15625
4
""" 字典的运算 """ person = {'name': '刘尚远', 'age': 21, 'weight': 68, 'home': '西影路46号'} # 检查name和tel两个键在不在person字典中 print('name & tel in person:', 'name' in person, 'tel' in person) # True False print() # 通过age修将person字典中对应的值修改为22 if 'age' in person: # 如果age存在person中, 则修改age的值 person['age'] = 22 print('修改后的age:...
false
8aa5fbf8d58db8094e0dab793af65cab51b378e8
aakinlalu/Mini-Python-Projects
/dow_csv/dow_csv_solution.py
1,713
4.125
4
""" Dow CSV ------- The table in the file 'dow2008.csv' has records holding the daily performance of the Dow Jones Industrial Average from the beginning of 2008. The table has the following columns (separated by commas). DATE OPEN HIGH LOW CLOSE VOLUME ADJ_CLOSE 2008-01-02 13261.82 ...
true
99728de2ec99c6e60ff42a3a7811f5268028031d
jhoover4/algorithms
/cracking_the_coding/chapter_1-Arrays/7_rotate_matrix.py
2,120
4.40625
4
import unittest from typing import List def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Problem: Rotate an M x N matrix 90 degrees. Answer: Time complexity: O(MxN) """ if not matrix or not matrix[0]: raise ValueError("Must supply valid M x N matrix.") col_len...
true
a0909167df71ff56d79b4f59e3fa22a9aea8d5b4
jifrivly/Python
/calculator.py
775
4.125
4
num1 = float(input("Enter a number : ")) num2 = float(input("Enter a number : ")) def add(x, y): return x+y def sub(x, y): return x-y def mul(x, y): return x*y def div(x, y): if y == 0: return "0 division not accepted" else: return x/y print("Choose an option : \n1 : Additi...
false
31b15085fa9411fb18e684b4de113a5336d12fe9
lofajob/PyLes
/lessons/Podoba/ls4/3or4.py
343
4.3125
4
i = 10 while i > 0: print i if i>5: print "Bigger than 5!" elif i%2 !=0: print "this is ODD number" print "and i <= 5" else: print "i <= 5" print "this is EVEN nember, not ODD" print "special number! :)" i=i-1 print "we are after 'while' l...
false
3708eda29bf47b6a2ab23eb56e8f95b9f88e4a5e
ChaitDevOps/Scripts
/PythonScripts/ad-lists.py
1,018
4.5
4
#!/usr/bin/python # ad-lists.py # Diving a little deeper into Lists. #.append() Appends an element to the 'END' of the exisitng list. from __future__ import print_function l = [1,2,3] l.append([4]) print(l) #.extend() extends list by appending elements from the iterable l = [4,5,6] l.extend([7,8,9]) print(l) # .in...
true
85769cf60c277a432a21b44b95e3814d23511666
ChaitDevOps/Scripts
/PythonScripts/lambda.py
556
4.15625
4
#!/usr/bin/python # Lambda Expressions # lambda.py # Chaitanya Bingu # Lamba expressions is basically a one line condensed version of a function. # Writing a Square Function, we will break it down into a Lambda Expression. def square(num): result = num**2 print result square(2) def square(num): print num...
true
9f44f5d1b42a232efb349cd9a484b1eb0d68372f
ChaitDevOps/Scripts
/PythonScripts/advanced_strings.py
2,053
4.4375
4
#!/usr/bin/python # Chait # Advanced Strings in Python. # advanced_strings.py from __future__ import print_function # .capitalize() # Converts First Letter of String to Upper Case s = "hello world" print(s.capitalize()) # .upper() and .lower() print(s.upper()) print(s.lower()) # .count() and .find() # .count() -- W...
true
fde8e0f55ea61fbb7fecd6c0cd4cc61e0e18ea84
ggerod/Code
/PY/recurseexponent.py
294
4.1875
4
#!/usr/bin/python3 def exponent(num,expo): if (expo==0): return(1) if (expo%2 == 0): y=exponent(num,expo/2) return(y*y) else: y=exponent(num,expo-1) return(num * y) NUM=12 EXPO=25 answer=exponent(NUM,EXPO) print(NUM,"**",EXPO,"=",answer)
false
bcc7ae5bdfe6d3a4f2b0433ca78c7c931a629519
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Array Sequences/Array Sequences Interview Questions/Array Sequence Interview Questions/Sentence-Reversal.py
1,431
4.21875
4
#!/usr/bin/env python3 """ Solution """ def rev_word1(s): return ' '.join(s.split()[::-1]) """ Practise """ def rev_word2(s): return ' '.join(reversed(s.split())) def rev_word3(s): """ Manually doing the splits on the spaces. """ words = [] length = len(s) spaces = [' '] # Index Tracker i = 0 # While ind...
true
19a3cc106f1dadaf621ef20dd79d62861ab01ac7
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Sorting and Searching/01_Binary_Search.py
754
4.25
4
#!/usr/bin/env python3 def binary_search(arr, element): # First & last index value first = 0 last = len(arr) - 1 found = False while first <= last and not found: mid = (first + last) // 2 # // required for Python3 to get the floor # Match found if arr[mid] == element: found = True # set new midp...
true
78993e5a2442e7947655a263788fbf83a9c50c0d
kartik-mewara/pyhton-programs
/Python/25_sets_methods.py
672
4.4375
4
s={1,2,3,4,5,6} print(s) print(type(s)) s1={} print(type(s1)) #this will result in type of dict so for making empty set we follow given method s1=set() print(type(s1)) s1.add(10) s1.add(20) print(s1) s1.add((1,2,3)) # s1.add([1,2,3]) this will throws an erros as we can only add types which are hashable of unmutable as ...
true
51fe08037ca0d96b83b0dadded63411c1791aecd
kartik-mewara/pyhton-programs
/Python/05_typecasting.py
593
4.125
4
# a="1234" # a+=5 # print(a) this will not work as a is a string but we expect ans 1239so for that we will type cast a which is string into int a="1234" print(type(a)) a=int(a) a+=5 print(type(a)) print(a) # now it will work fine # similerly we can type cast string to int to string int to float float to in etc b=2.3...
true
332bb7e70a8168e8194a995f6eca4b1983997400
kartik-mewara/pyhton-programs
/Python/13_string_template.py
255
4.34375
4
letter='''Dear <|name|> you are selected on the date Date: <|date|> ''' name=input("Enter name of person\n") date=input("Enter date of joining\n") # print(letter) letter=letter.replace("<|name|>",name) letter=letter.replace("<|date|>",date) print(letter)
true