blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
88044fba92673eae63292c65aa63c804fc4fb041 | ridersw/Karumanchi---Algorithms | /selectionSort.py | 448 | 4.125 | 4 | def selectionSort(arr):
size = len(elements)
for swi in range(len(elements)-1):
minIndex = swi
for swj in range(minIndex+1, size):
if elements[swj] < elements[minIndex]:
minIndex = swj
if swi != minIndex:
elements[swi], elements[minIndex] = elements[minIndex], elements[swi]
if __... | true |
cd5b89dda0ce27d88438439d7e58b3c89128384d | ianhom/Python-Noob | /Note_1/list.py | 566 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [ 'abcd', 123, 1.23, 'Ian' ]
smalllist = [ 123, 'Jane' ]
print list # print all elements
print list[0] # print the first element
print list[1:3] # print the second one to the third one
print list[2:] # print the third and followi... | false |
c00a4cbed2ed5edb26bbcb8741d12f2e6bc3bf1b | ianhom/Python-Noob | /Note_2/class1.py | 981 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class dog:
'This is a dog class' #函数提示
dogcnt = 1;
def __init__(self, name, age): #构造函数
self.name = name
self.age = age
dog.dogcnt += 1
def ShowCnt(self):
print "The count of dog is %d" % dog.dogcnt
de... | false |
4d4f0c00d086198d3899bce833ed3463c30a5599 | sam-79/Assignment_Submission | /Day1_Assignment.py | 370 | 4.1875 | 4 |
#List sorting in descending order
int_list = [74,4,2,7,55,76,47478,4,21,124,42,4,4,36,6,8,0,95,6]
int_list.sort(reverse=True)
print(int_list)
alpha_list=['t','o','i','q','z','m','v','p','r']
alpha_list.sort(reverse=True)
print(alpha_list)
#User input list sorting
input_list= input("Enter list elements: ").split(... | false |
b68e7cd455c23630cae9c80094108316a5f3683d | agmontserrat/Ejercicios_Python_UNSAM | /Clase07/documentacion.py | 1,155 | 4.125 | 4 | #Para cada una de las siguientes funciones:
#Pensá cuál es el contrato de la función.
#Agregale la documentación adecuada.
#Comentá el código si te parece que aporta.
#Detectá si hay invariantes de ciclo y comentalo al final de la función
def valor_absoluto(num):
'''Devuelve el valor absoluto de un número... | false |
e60d1d29e10422a69b0b867be7f849f4030e51fa | baishuai/leetcode | /algorithms/p151/151.py | 300 | 4.125 | 4 | # Given an input string, reverse the string word by word.
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(reversed(s.split()))
| true |
17fd1c22103dd367ed6e6488eff4330f2928d0e7 | xieguoyong/shiyanlou | /cases/python_captcha/sort_test.py | 772 | 4.3125 | 4 | dic = {'a': 31, 'bc': 5, 'c': 3, 'asd': 4, 'aa': 74, 'd': 0}
print("打印出字典的键和值的列表:", dic.items())
# sorted 方法中 key指定按什么排序
# 这里的 lambda x: x[1] 即指定以列表的x[1] 即value来排序,x[0]则是以key排序
print("指定以value来排序:", sorted(dic.items(), key=lambda x: x[1]))
# sorted 默认从小到大排序,加上reverse=True 参数则翻转为从大到小排序
print("指定从大到小排序:", sorted(dic.i... | false |
181f19fec56913372b5aa480dfea3e5d3c4c91b8 | senseiakhanye/pythontraining | /section5/ifelseif.py | 246 | 4.21875 | 4 | isFound = True
if (isFound):
print("Is found")
else:
print("Is not found")
#else if for python is different
num = 2
if (num == 1):
print("Number is one")
elif (num == 2):
print("Number if two")
else:
print("Number is three") | true |
baca925b539e5fcc04be482c5fc8b27a6ff355eb | johnstinson99/introduction_to_python | /course materials/b05_matplotlib/d_sankey/sankey_example_1_defaults.py | 1,070 | 4.34375 | 4 | """Demonstrate the Sankey class by producing three basic diagrams.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
# Example 1 -- Mostly defaults
# This demonstrates how to create a simple diagram by implicitly calling the
# Sankey.add() method and by appending finish() to ... | true |
1fc9ba256d1201e878b76e6d9419d162d0e9cd59 | anuragpatilc/anu | /TAsk9_Rouletle_wheel_colors.py | 992 | 4.375 | 4 | # Program to decides the colour of the roulette wheel colour
# Ask the user to select the packet between 0 to 36
packet = int(input('Enter the packet to tell the colour of that packet: '))
if packet < 0 or packet > 36:
print('Please enter the number between 0 to 36')
else:
if packet == 0:
print('... | true |
83ccf65950e90bd1cf095c29e5b1c61b1d7a75d9 | zeus911/sre | /leetcode/Search-for-a-Range.py | 1,062 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'liuhui'
'''
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
... | true |
1dfd1b6ceeaaa4e18804ebdf96697fff2e494a25 | mimichen226/GirlsWhoCode_SIP2018 | /Python/Libraries/DONE_rock_paper_scissors.py | 562 | 4.1875 | 4 | ########### Code for Rock Paper Scissors ############
import random
gestures = ["scissors", "rock", "paper"]
computer = random.choice(gestures)
human = input("Rock, paper, scissors, SHOOT: ")
human = human.lower().lstrip().rstrip()
print("Computer chooses {}".format(computer.upper()))
if computer == human:
prin... | true |
bff09661d3f94c924370978ec58eba596f184bcc | penelopy/interview_prep | /Basic_Algorithms/reverse_string.py | 389 | 4.3125 | 4 | """ Reverse a string"""
def reverse_string(stringy):
reversed_list = [] #strings are immutable, must convert to list and reverse
reversed_list.extend(stringy)
for i in range(len(reversed_list)/2):
reversed_list[i], reversed_list[-1 - i] = reversed_list[-1 -i], reversed_list[i]
print "".join(... | true |
6507cb3071727a87c6c7309f92e7530b74fcc5a2 | penelopy/interview_prep | /Trees_and_Graphs/tree_practice_file.py | 1,262 | 4.25 | 4 | """NOTES AND PRACTICE FILE
Ex. Binary Tree
1
/ \
2 3
Ex. Binary Search Tree
2
/ \
1 3
A binary search is performed on sorted data. With binary trees you use them to quickly look up numbers and compare them. They have quick insertion and lookup.
"""
class BinarySearchTree:
def __init__... | true |
a6cfcadcba5fb1aba6dc49e653b2ac9625f18de2 | chieinviolet/oop_project2 | /user_name.py | 929 | 4.15625 | 4 | """
※雰囲気コード
データ型宣言: UserName <<python ではクラス型と呼ばれる。
属性:
実際のユーザー名
ルール:
・ユーザー名は4文字以上20文字以下である
できること
・ユーザー名を大文字に変換する
"""
class UserName:
def __init__(self, name):
if not (4 <= len(name) <= 20):
raise ValueError(f'{name}は文字数違反やで!')
self.name = name
def s... | false |
29b81abb43d6167f5ead8d625e705a9675831b8d | bavipanda/Bavithra | /check the given is alphabets or digits.py | 207 | 4.25 | 4 | ch = input()
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print("is an Alphabet")
elif(ch >= '0' and ch <= '9'):
print("is a Digit")
else:
print("is Not an Alphabet or a Digit")
| false |
2bec8e896b556bc8077e14e4ee64cec5957a6ef8 | ak14249/Python | /dictionary.py | 578 | 4.25 | 4 | myDict={"Class" : "Engineer", "Name" : "Ayush", "Age" : "25"}
print(myDict)
print(myDict["Class"])
print(myDict.get("Name"))
print(myDict.values())
for val in myDict:
print(myDict[val])
for x,y in myDict.items():
print(x,y)
myDict["Name"]="Prateek"
print(myDict)
myDict["Designation"]="Linux Admin"
print(myDict)
... | false |
2ee39e37dec9a9c5df1f70683a5a01d2a6935f09 | ak14249/Python | /map_function.py | 2,336 | 4.40625 | 4 | print("Que: Write a map function that adds plus 5 to each item in the list.\n")
lst1=[10, 20, 30, 40, 50, 60]
lst2=list(map(lambda x:x+5,lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Write a map function that returns the squares of the items in the list.\n")
l... | true |
6098028a07d94854e273ca763d3ff1f566ea6c4d | karthikrk1/python_utils | /primeSieve.py | 1,330 | 4.34375 | 4 | #!/bin/python3
'''
This is an implementation of the sieve of eratosthenes. It is created for n=10^6 (Default Value).
To use this in the program, please import this program as import primeSieve and call the default buildSieve method
Author: Karthik Ramakrishnan
'''
def buildSieve(N=1000000):
'''
This function... | true |
af8e0ab5c3cabbda9b75721c81492e285345c9d3 | brianhoang7/6a | /find_median.py | 940 | 4.28125 | 4 | # Author: Brian Hoang
# Date: 11/06/2019
# Description: function that takes list as parameter and finds the median of that list
#function takes list as parameter
def find_median(my_list):
#sorts list from least to greatest
my_list.sort()
#distinguishes even number of items in list
if len(my_list) % 2 ... | true |
bbacdc29ca3d75eeaee34e1d9800e57b390bd83c | pastcyber/Tuplesweek4 | /main.py | 917 | 4.1875 | 4 | value = (5, 4, 2000, 2.51, 8, 9, 151)
def menu():
global value
option = ''
while(option != 6):
print('*** Tuple example ***')
print('1. Print Tuple ***')
print('2. Loop over tuple')
print('3. Copy Tuple')
print('4. Convert to list')
print('5. Sort Tuple')
print('6. Exit ***')
op... | true |
70f84fb61188d4a12f42bc5ab4e90f190dde764b | YOOY/leetcode_notes | /problem/check_if_number_is_a_sum_of_powers_of_three.py | 292 | 4.15625 | 4 | # check if n can be formed by 3**0 + 3**1 + ... + 3**n
# if any r equals to 2 it means we need 2 * (3 ** n) which should be false
def checkPowersOfThree(n):
while n > 1:
n, r = divmod(n, 3)
if r == 2:
return False
return True
print(checkPowersOfThree(21)) | true |
07815b759c627172f59ac80c7bc403f6b9b48a90 | Aditi-Billore/leetcode_may_challenge | /Week2/trie.py | 2,258 | 4.1875 | 4 | # Implementation of trie, prefix tree that stores string keys in tree. It is used for information retrieval.
#
class TrieNode:
def __init__(self):
self.children = [None] *26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
... | true |
7b9424dc3a0cf43e35df9557d8739d48587ad0a1 | jcarlosbatista/pacote-desafios-pythonicos | /07_front_back.py | 2,802 | 4.125 | 4 | """
07. front_back
Considere dividir uma string em duas metades.
Caso o comprimento seja par, a metade da frente e de trás tem o mesmo tamanho.
Caso o comprimento seja impar, o caracter extra fica na metade da frente.
Exemplo: 'abcde', a metade da frente é 'abc' e a de trás é 'de'.
Finalmente, dadas duas strings a e... | false |
b591729dcfbbb565158ad7a7541b8bfaa0378cda | Tu7ex/Python_Programming | /Clase1.py | 2,565 | 4.21875 | 4 | '''Comentario'''
#adsasd
var = 1
print(type(var)) #Muestra el tipo de variable que es.
print("")
# Cadena de caracteres
cadena1="Clase n° 1"
cadena2='Curzo de Python'
print(type(cadena1))
# Boolean (True -> V, False -> F)
encendido= True
print(type(encendido))
print("")
# Operadores aritméticos
# Suma
x=20
y=5
res = x... | false |
239d29e78ee6f68d72bcda0a08f25d62ee223b7d | ellezv/data_structures | /src/trie_tree.py | 2,588 | 4.1875 | 4 | """Implementation of a Trie tree."""
class TrieTree(object):
"""."""
def __init__(self):
"""Instantiate a Trie tree."""
self._root = {}
self._size = 0
def insert(self, iter):
"""Insert a string in the trie tree."""
if type(iter) is str:
if not self.con... | true |
64f36d53d21666be487100bd9d919afd18ece35c | ginchando/SimplePython | /CheckLeapYear/check.py | 731 | 4.1875 | 4 | year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
isLeapYear = False
if year % 400 == 0:
isLeapYear = True
elif year % 4 == 0 and year % 100 != 0:
isLeapYear = True
result = "is" if isLeapYear else "is not"
print(f"{year} {result} a leap year")
month_name = {
1: "January",
2: "F... | false |
20e60f62e4865b7a1beb1cdd67330159ebbba35c | LesterZ819/PythonProTips | /PythonBasics/Lists/CreatingLists.py | 534 | 4.15625 | 4 | #You can create a list of values by putting them in [brackets] and assigning them a variable.
#For example:
varialble = [item1, item2, item3, item4]
#lists can contain any time of value, or multiple value types
#Example list containing floats or real numbers.
float = [1.25, 15.99, 21.33]
#Example of a list con... | true |
9f13a8c2f6f5d0f9095da83f175c15a51108096c | LukeBecker15/learn-arcade-work | /Lab 06 - Text Adventure/lab_06.py | 2,656 | 4.15625 | 4 | class Room:
def __init__(self, description, north, south, east, west):
self.description = description
self.north = north
self.south = south
self.east = east
self.west = west
def main():
room_list = []
room = Room("You are in the entrance to the Clue house.\nThe p... | true |
183d3360519f1935140cefd8830662d0f168e6ae | DhirajAmbure/MachineLearningProjects | /PythonPracticePrograms/factorialOfNumber.py | 1,225 | 4.28125 | 4 | import math as m
def findfact(number):
if number == 1:
return number
elif number != 0:
return number * findfact(number - 1)
number = int(input("Enter number to find Factorial: "))
if number < 0:
print("factorial can not be found for negative numbers")
elif number ==0:
... | true |
4318daad6d05bf2528b5025bab4974939267bf07 | Ladydiana/LearnPython | /CompoundDataStructures.py | 1,229 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
COMPOUND DATA STRUCTURES
"""
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}}
h... | false |
18a845aa39833a9b137bd19759c543a8a77054b6 | Ladydiana/LearnPython | /ListComprehensions.py | 959 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
LIST COMPREHENSIONS
"""
#capitalized_cities = [city.title() for city in cities]
squares = [x**2 for x in range(9) if x % 2 == 0]
print(squares)
#If you would like to add else, you have to move the conditionals to the beginning of the listcomp
squares = [x**2 if x % 2 == 0 else x ... | true |
1a4584feb95da66abab5d2b0cb40664f2eab59dc | Ladydiana/LearnPython | /LambdaExpressions.py | 872 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
LAMBDA EXPRESSIONS
---You can use lambda expressions to create anonymous functions.
"""
multiply = lambda x, y: x * y
print(multiply(4, 7))
"""
QuUIZ - Lambda with Map
"""
numbers = [
[34, 63, 88, 71, 29],
[90, 78, 51, 27, 45],
[63,... | false |
e5f63dd75eadec1499cb15037c3b4623ace06b76 | abhi472/Pluralsight | /Chapter5/classes.py | 1,035 | 4.1875 | 4 | students = []
class Student:
school_name = "Sumermal Jain Public School" # this is similar to a static variable but unlike java we do not need to have a static class for static variables we
# can have a class instance just like school_name for static call of it
... | true |
62eadc4c3eb829a71a0a2fd24282da4a2c8f3232 | abhi472/Pluralsight | /Chapter3/rangeLoop.py | 444 | 4.375 | 4 | x = 0
for index in range(10): # here range creates a list of size 10(argument that has been passed)
x += 10
print("The value of X is {0}".format(x))
for index in range(5, 10): # two args mean list start from 5 and goes till 9
x += 10
print("The value of X is {0}".format(x))
for index in range(5, 10,... | true |
c5f3a449b0a84d29787adc5ecbd2438fe616aed2 | lampubolep/HackerRank30days | /day3.py | 458 | 4.3125 | 4 | # receiving input integer
n = int(input())
# if n is odd, print Weird
if (n % 2) != 0:
print("Weird")
# if n is even and in the inclusive range of 2 to 5, print Not Weird
elif (n%2 == 0 and n>=2 and n<=5):
print("Not Weird")
#if n is even and in the inclusive range of 6 to 20 print Weird
elif (n%2 == 0 and n>=6 an... | false |
80b8be8ba4fabddfcffaf7d8a69039c83679938f | JubindraKc/python_assignment_dec15 | /#4_firstname_lastname_split.py | 503 | 4.28125 | 4 | def full_name():
print("your first name is ", first_name)
print("your last name is ", last_name)
choice = input("will you include your middle name? y/n\n")
name = input("please enter your full name separated with whitespace\n")
if choice == 'y':
first_name, last_name, middle_name = name.split(" ... | true |
48d8c9acfbbe437a075f8850b40559cc5a7d52d7 | simonechen/PythonStartUp | /ex1.py | 407 | 4.1875 | 4 | # print("Hello World!")
# print("Hello Again")
# print("I like typing this.")
# print("This is fun.")
# print("Yay! Pringting.")
# print("I'd much rather you 'not'.")
print('I "said" do not touch this.') # ' "" '
print("I'm back.") # Terminate
print("-how to make my script print only one of the lines?")
print("-one way... | true |
48bcb4c1c7e29d4185555c559d565c949e9c4617 | queeniekwan/mis3640 | /session05/mypolygon.py | 1,526 | 4.28125 | 4 | import turtle
import math
# print(andrew)
# draw a square
# for i in range(4):
# andrew.fd(100)
# andrew.lt(90)
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
def polyline(t, n, length, angle):
"""
Draws n line segments with given length and angle (in degrees) be... | false |
57629ce5b3adbfeb89b532c2b2af3b4977815c26 | queeniekwan/mis3640 | /session13/set_demo.py | 540 | 4.3125 | 4 | def unique_letters(word):
unique_letters = []
for letter in word:
if letter not in unique_letters:
unique_letters.append(letter)
return unique_letters
print(unique_letters('bookkeeper'))
# set is a function and type that returns unique elements in an item
word = 'bookkeeper'
s = set(w... | true |
ce7990693175eab9465ba280d06b8ec38e7c22a0 | queeniekwan/mis3640 | /session05/ex_05.py | 1,732 | 4.125 | 4 | import turtle
import math
from turtle_shape import circle, arc, polygon, move
def circle_flower (t, r):
"""
Draws a circle flower, t is a turtle, r is the radius of the circle
"""
for _ in range(6):
arc(t,r,60)
t.lt(60)
arc(t,r,120)
t.lt(60)
def yinyang (t):
"""
... | false |
4babb313798da7167ba3ffbf63c6ce25ee2528c5 | sayaliupasani1/Learning_Python | /basic_codes/list1.py | 899 | 4.15625 | 4 | fruits = ["Mango", "Apple", "Banana", "Chickoo", "Custard Apple", "Strawberry"]
vegetables = ["Carrots", "Spinach", "Onion", "Kale", "Potato", "Capsicum", "Lettuce"]
print (type(fruits))
print(fruits)
#fruits.extend(vegetables)
#print(fruits)
#fruits.extend(vegetables[1])
print (fruits)
fruits.extend(vegetables[1:3])
... | true |
acf185f967bab8d3111bc6960294ea116d48cb1a | elkin5/curso-python-azulschool | /src/examples/ejericiosE2cadenas.py | 656 | 4.21875 | 4 | '''1.- Dada la cadena “El veloz murciélago hindú comía feliz cardillo y kiwi”, imprimir su variante justificada a la derecha rellenando con ‘>’, a la izquierda rellenando con ‘<‘ y centrada en 60 caracteres con asteriscos utilizando métodos de cadenas.'''
string = "El veloz murciélago hindú comía feliz cardillo y kiwi... | false |
7693ec8848f94f4375fa79e2d216744c71d4f56f | michaelpeng/anagramsgalore | /anagramlist.py | 1,251 | 4.3125 | 4 | """
Given a list of strings, tell which items are anagrams in the list, which ones are not
["scare", "sharp", "acres", "cares", "ho", "bob", "shoes", "harps", "oh"]
return list of lists, each list grouping anagrams together
"""
"""
Function to check two strings are anagrams of each other
'scare'
'acres'
True
"""
de... | true |
097e582da15e74f03d068917779f50f5560b845e | JoaoGabrielDamasceno/Estudo_Python | /Iteradores e Geradores/iterator_iterable.py | 358 | 4.375 | 4 | """
Iterator -> Objeto que dá para ser iterável e retorna um dado.
-> Se consegue usar a função next()
Iterable -> Função que retorna um iterável
-> Retornará um objeto quando a função iter() for chamada
lista = [1,2,3]
- O pyhton pega essa lista e faz iter(lista) num laço de repetição
- A cada pass... | false |
9d6eaa66b5e3e24818e50cadbbbba75e76a5ca73 | ramlingamahesh/python_programs | /conditionsandloops/Sumof_NaturalNumbers.py | 615 | 4.21875 | 4 | num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while (num > 0):
sum += num
num -= 1
print("The sum is", sum)
# 2 Python Program - Find Sum of Natural Numbers
print("Enter '0' for exi... | true |
24a599fb4fa7dcf2a5fe305b6a0905429dc2d195 | ramlingamahesh/python_programs | /conditionsandloops/GCDorHCF.py | 779 | 4.125 | 4 | '''n1 = 48
n2 = 36
# find smaller
if (n1 > n2):
smaller = n2
else:
smaller = n1
# getting hcf
i = 1
while (i <= smaller):
if (n1 % i == 0 and n2 % i == 0):
hcf = i
i = i + 1
print("hcf = ", hcf)'''
# Method 2: Using Recursion
'''
def find_hcf(n1, n2):
if (n2 == 0):
return n1
... | false |
ec5b56efd27c6d6c232e3c21f80bdccba626b68b | ramlingamahesh/python_programs | /conditionsandloops/FindNumbers_Divisible by Number.py | 646 | 4.15625 | 4 | # Python Program - Find Numbers divisible by another number
print("Enter 'x' for exit.");
print("Enter any five numbers: ");
num1 = input();
if num1 == 'x':
exit();
else:
num2 = input();
num3 = input();
num4 = input();
num5 = input();
number1 = int(num1);
number2 = int(num2);
number3 = ... | true |
5209c52949500091bda483d0b6b7fba199098637 | shohanurhossainsourav/python-learn | /program28.py | 341 | 4.375 | 4 | matrix = [
[1, 2, 3],
[4, 5, 6],
]
print(matrix[0][2])
# print matrix value using nested loop
matrix = [
[1, 2, 3],
[4, 5, 6],
]
for row in matrix:
for col in row:
print(col)
matrix1 = [
[1, 2, 3],
[4, 5, 6],
]
# 0 row 2nd coloumn/3rd index value changed to 10
matrix1[0][2] = 10
... | true |
ff6a9327111545c69ad4f59c5b5f2878def92431 | ikki2530/holbertonschool-machine_learning | /math/0x02-calculus/10-matisse.py | 740 | 4.53125 | 5 | #!/usr/bin/env python3
"""Derivative of a polynomial"""
def poly_derivative(poly):
"""
-Description: calculates the derivative of a polynomial.
the index of the list represents the power of x that the
coefficient belongs to.
-poly: is a list of coefficients representing a polynomial
- Returns:... | true |
d82167ca61a739e2d8c6919137e144a987ee22a3 | ikki2530/holbertonschool-machine_learning | /math/0x00-linear_algebra/8-ridin_bareback.py | 1,123 | 4.3125 | 4 | #!/usr/bin/env python3
"""multiply 2 matrices"""
def matrix_shape(matrix):
"""
matrix: matrix to calcuted the shape
Return: A list with the matrix shape [n, m],
n is the number of rows and m number of columns
"""
lista = []
if type(matrix) == list:
dm = len(matrix)
lista.ap... | true |
181117260d2bcdc404dcd55a6f51966afa880e83 | ikki2530/holbertonschool-machine_learning | /supervised_learning/0x07-cnn/0-conv_forward.py | 2,649 | 4.53125 | 5 | #!/usr/bin/env python3
"""
performs forward propagation over a convolutional layer of a neural network
"""
import numpy as np
def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)):
"""
- Performs forward propagation over a convolutional layer of a
neural network.
- A_prev is a nump... | true |
d5435c2f2cca0098f13f5d2ca37100b58eed8515 | David-Papworth/qa-assessment-example-2 | /assessment-examples.py | 2,639 | 4.1875 | 4 | # <QUESTION 1>
# Given a word and a string of characters, return the word with all of the given characters
# replaced with underscores
# This should be case sensitive
# <EXAMPLES>
# one("hello world", "aeiou") → "h_ll_ w_rld"
# one("didgeridoo", "do") → "_i_geri___"
# one("punctation... | true |
0875700b5375f46ffcb44da81fff916e10808e6d | siddarthjha/Python-Programs | /06_inheritance.py | 1,338 | 4.28125 | 4 | """
Concept of Inheritance.
"""
print('I am created to make understand the concept of inheritance ')
class Upes:
def __init__(self, i, n):
print('I am a constructor of Upes ')
self.i = i
self.n = n
print('Ok i am done bye....')
def fun(self):
print('I am ... | true |
b9f0b7f7699c8834a9c3a7b287f7f68b09b100ee | GabrielByte/Programming_logic | /Python_Exersice/ex018.py | 289 | 4.34375 | 4 | '''
Make a program that calculates sine, cosine and tangent
'''
from math import sin, cos, tan, radians
angle = radians(float(input("Enter an angle: ")))
print(f"This is the result; Sine: {sin(angle):.2f}")
print(f"Cosine: {cos(angle):.2f}")
print(f"and Tangent: {tan(angle):.2f}")
| true |
45e8158ac5e78c5deea43e77bebb2773c3aee215 | GabrielByte/Programming_logic | /Python_Exersice/ex017.py | 230 | 4.1875 | 4 | '''
Make a program that calculates Hypotenouse
'''
from math import pow,sqrt
x = float(input("Enter a number: "))
y = float(input("Enter another one: "))
h = sqrt(pow(x,2) + (pow(y,2)))
print(f"This is the result {h:.2}")
| true |
38b524a20fa88a549e0926230a63571a113c6249 | tabssum/Python-Basic-Programming | /rename_files.py | 997 | 4.21875 | 4 | #!/usr/bin/python
import os
import argparse
def rename_files():
parser=argparse.ArgumentParser()
parser.add_argument('-fp','--folderpath',help="Specify path of folder to rename files")
args=parser.parse_args()
#Check for valid folderpath
if args.folderpath :
#Get files in particular folder
... | true |
dbccaa5b83a7764eb172b0e1653f7f086dd7b95e | smakireddy/python-playground | /ArraysAndStrings/PrisonCellAfterNDays.py | 2,265 | 4.21875 | 4 | """"
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
(Note... | true |
7d543273ad847de56beaae7761f9280640cfe012 | smakireddy/python-playground | /ArraysAndStrings/hackerrank_binary.py | 1,396 | 4.15625 | 4 | """
Objective
Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given a base- integer, , convert it to binary (base-). Then find and print the base- integer denoting the maximum number of consecutive 's in 's binary representation. When working... | true |
29bf475491bbb765a9e739822fe09e7e383a1fef | aototo/python_learn | /week2/week2 bisection.py | 878 | 4.15625 | 4 | print("Please think of a number between 0 and 100!")
high = 100
low = 0
nowCorrect = int(( high + low ) / 2)
print('Is your secret number '+ str(nowCorrect) + '?')
while True:
input_value = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed... | true |
7bbe2bf4078108379bff6f1b4edcf1d61dad66fd | Jeremiah-David/codingchallenges | /python-cc.py | 1,363 | 4.15625 | 4 | # Write a function called repeatStr which repeats the given string
# string exactly n times.
# My Solution:
def repeat_str(repeat, string):
result = ""
for line in range(repeat):
result = result + string
return (result)
# Sample tests:
# import codewars_test as test
... | true |
55e74e7fa646c954cefac68cd885b63a639191a3 | attaullahshafiq10/My-Python-Programs | /Conditions and loops/4-To Check Prime Number.py | 646 | 4.1875 | 4 | # A prime number is a natural number greater than 1 and having no positive divisor other than 1 and itself.
# For example: 3, 7, 11 etc are prime numbers
# Other natural numbers that are not prime numbers are called composite numbers.
# For example: 4, 6, 9 etc. are composite numbers
# Code
num = int(input("... | true |
bb69af4b9a1f55be425c9dbd16d19768cef3345d | winkitee/coding-interview-problems | /11-20/15_find_pythagorean_triplets.py | 911 | 4.28125 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Given a list of numbers, find if there exists a pythagorean triplet in that list.
A pythagorean triplet is 3 variables a, b, c where a2 + b2 = c2
Example:
Input: [3, 5, 12, 5, 13]
Output: True
Here, 5^2 + 12^2 = 13^2.
"""
def findPythagorea... | true |
5c1c1b11dc666990e8344bf2cd5cc8e2a663d46f | winkitee/coding-interview-problems | /71-80/80_make_the_largest_number.py | 586 | 4.15625 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Given a number of integers, combine them so it would create the largest number.
Example:
Input: [17, 7, 2, 45, 72]
Output: 77245217
def largestNum(nums):
# Fill this in.
print(largestNum([17, 7, 2, 45, 72]))
# 77245217
"""
class larges... | true |
dd07fe905d62c6de15dd052c2b54ff82de8ced23 | winkitee/coding-interview-problems | /31-40/34_contiguous_subarray_with_maximum_sum.py | 876 | 4.21875 | 4 | """
Hi, here's your problem today. This problem was recently asked by Twitter:
You are given an array of integers. Find the maximum sum of all possible
contiguous subarrays of the array.
Example:
[34, -50, 42, 14, -5, 86]
Given this input array, the output should be 137. The contiguous subarray with
the largest sum... | true |
3a65bf1e00e3897174298a3dc7162b4c75c90742 | GabuTheGreat/GabuTheGreat.github.io | /challange/recursion_1.py | 467 | 4.1875 | 4 | n= int(input("Enter number the first number: "))
def isPrime(num):
"""Returns True if num is prime."""
if (num == 1) or (num % 2 == 0) or (num % 3 == 0) :
return False
if (num == 2) or (num == 3) :
return True
check_var= 5
set_var = 2
while check_var * check_var <= num:
... | true |
7ddb79a6c8b6d3cd0778e7e12eeb27af72598c35 | Poyx15/Tutorials | /Codecademy Practice/VisualizeData/DataFrame/ColumnOperation.py | 287 | 4.1875 | 4 | # import codecademylib
# from string import lower
import pandas as pd
df = pd.DataFrame([
['JOHN SMITH', 'john.smith@gmail.com'],
['Jane Doe', 'jdoe@yahoo.com'],
['joe schmo', 'joeschmo@hotmail.com']
],
columns=['Name', 'Email']
)
# Add columns here
df['Lowercase Name'] = df['Name'].str.lower()
... | false |
0f036e9d59a6b7e4d12401f3e453dd2f8cb6fcdb | toufiq007/Python-Tutorial-For-Beginners | /chapter nine/list_comprehension.py | 1,044 | 4.25 | 4 |
# list comprehension
# print a list to square number of 1-10
# traditional way
num = list(range(1,11))
num_list = [i for i in range(1,11)]
print(num)
# def square_number(x):
# square_list = []
# for i in x:
# square_list.append(i**2)
# return square_list
# print(square_number(num))
square_l... | false |
fbb50bc38f14354555cef3e2bf8cd66e2a3f9270 | toufiq007/Python-Tutorial-For-Beginners | /chapter three/while_loop.py | 412 | 4.21875 | 4 |
#loop
#while loop
# steps
# first declare a variable
# second write the while loop block
# in while loop block you must declare a condition
# find the odd and even number by using while number between 0-100
i = 0;
while i<=100:
print(f'odd number {i}')
i+=2
# find the even and even number by using whi... | true |
74bee5049a2462c78824fdee03bc35c9bcd6759e | toufiq007/Python-Tutorial-For-Beginners | /chapter twelve/lambda_expresion_intro.py | 512 | 4.25 | 4 |
# lambda expression --> anonymous function
# it means when a function has no name then we called it anonymous function
# syntex
# 1: first write lambda keyword
# 2: second give the parameters
# 3: then give : and give the operator tha'ts it
def add(x,y):
return x+y
print(add(10,5))
add = lambda a,b : a+b
p... | true |
4024a43132422ded8732257256bfb91b98cf3582 | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/iterator_iterable.py | 515 | 4.21875 | 4 |
# iterator vs iterables
numbers = [1,2,3,4,5] # , tuple and string alls are iterables
# new_number = iter(numbers)
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
square_numbers = map(lambda x:x**2,numbers)
# map , filter this al... | true |
e7557d739edf11756cbec9759a5e7afaefa7955e | toufiq007/Python-Tutorial-For-Beginners | /chapter two/exercise3.py | 975 | 4.125 | 4 |
# user_name,user_char = input('enter your name and a single characte ==>').split(',')
name,character = input('please enter a name and character ').split(',')
#another times
# print(f'the lenght of your name is = {len(name)}')
# print(f'character is = {(name.lower()).count((character.lower()))}')
# (name.lower()).c... | true |
bd809f3954aded9bef550a88b32eb1a958b7b1b5 | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/zip_part2.py | 978 | 4.1875 | 4 |
l1= [1,2,3,4,5,6]
l2 = [10,20,30,40,50,60]
# find the max number of those list coupe item and store them into a new list
def find_max(l1,l2):
new_array = []
for pair in zip(l1,l2):
new_array.append(max(pair))
return new_array
print(find_max(l1,l2))
# find the smallest numbers and stored... | true |
41097f82056b1013fefd43169ac216060394710e | toufiq007/Python-Tutorial-For-Beginners | /chapter seven/add_delete_data.py | 1,547 | 4.28125 | 4 |
# add and delete data form dictionaries
user_info = {
'name' : 'Mostafiz',
'age' : 20,
'favourite_movie' : ['coco','terminator','matrix'],
'favourite_songs' : ['forgive me','ei obelay'],
'nickname' : ('lebu','manik','baba')
}
user_info['others'] = ['textile engnieering student at ptec']
# pri... | false |
60b9af30be744aec3de24fd4f422c688570644f3 | toufiq007/Python-Tutorial-For-Beginners | /chapter eleven/args_as_arguement.py | 452 | 4.28125 | 4 |
# Args as arguements
def multiply_nums(*args):
print(args)
print(type(args)) # [1,2,3,4,5]
mutiply = 1
for i in args:
mutiply *= i
return mutiply
# when you pass a list or tuple by arguemnts in your function then you must give * argument after give your list or tuple name
number = [1,... | true |
21647313d550a72c49db44ddb740922b2199c2e1 | toufiq007/Python-Tutorial-For-Beginners | /chapter eight/set_intro.py | 984 | 4.375 | 4 | # set data type
# unordered collection of unique items
# i a set data type you can't store one data in multipying times it should be use in onetime
# set removes which data are in mulple times
# the main use of set is to make a unique collection of data it means every data should be onetimes in a set
# s = {1,2,3,4... | true |
0bb687e8e8af5de27e6a4d7fb3c64d32e902fe42 | toufiq007/Python-Tutorial-For-Beginners | /chapter seven/exercise1.py | 1,024 | 4.1875 | 4 |
# def cube_func(x):
# cube_dic = dict()
# for i in x:
# num = i**3
# number_dic = {
# i : num
# }
# cube_dic.update(number_dic)
# return cube_dic
# number = list(range(1,10))
# print(cube_func(number))
# make a function that function take a single... | false |
e624a05600178ddc779ed8f0c552380ad76b6d7e | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/enumerate_func.py | 584 | 4.34375 | 4 |
# we use emumerate function with for loop to tract the position of our item
# item in iterable
# how we can use without enumerate function
# names = ['limon','toufiq','mostafiz','salman','tamim']
# pos = 0
# for i in names:
# # print(f' {pos} --> {i} ')
# pos += 1
# show the output on below
# 0-->... | false |
4dc27bfcc459e5a66e85c8cd84027676b72d82cf | toufiq007/Python-Tutorial-For-Beginners | /chapter five/exercise3.py | 733 | 4.21875 | 4 |
names = ['abc','def','ghi']
# make the reverse in every list item
def reverse_list(x):
reverse_item = []
for i in range(len(names)):
pop_items = names.pop()
reverse_item.append(pop_items)
return reverse_item
print(reverse_list(names))
words = ['abc','def','ghi']
def reverse... | false |
080bf5bb5c575a0dfc6b1d805c252097b2fe6389 | joannarivero215/i3--Lesson-2 | /Lesson3.py | 1,577 | 4.15625 | 4 | #to comment
#when naming file, do not add spaces
#age_of_dog = 3, meaningful variable name instead of using x
names = ["corey", "philip", "rose","daniel"] #assigning variables values to varibale name in a list(need braket)
print names #without quotation to print value
print names[1] #says second name
print '\n'
for ... | true |
095615f1bac4635998d783a8c1e6aad0f17c1930 | hmedina24/Python2021 | /Practice/basic_python_practice/practice04.py | 431 | 4.3125 | 4 | #Create a program that asks the user for a number and then prints out a list of all the divisors that number.
#(If you don't know what a divisor is, it is a number that divides evely into another number.) For example, 13 is a divisor of 26 /13 has no remainder.)
def main():
num = int(input("Enter a number"))
d... | true |
077dd6078669f3ff73df753fa86ace4b7c38ccae | hmedina24/Python2021 | /Sort_Algorithms /insertionSort.py | 582 | 4.15625 | 4 | def insertionSort(arr):
#traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
#move elements of arr[0..i-1], that greater
#than key, to one position ahead
#of their current position
j = i-1
while(j >= 0 and key < arr[j]):
arr[j+1] ... | true |
a87d462cc9760c43b2e75cfffcada78a0d1f3a92 | NikitaTipule/PPL_Lab | /Assignment6/shapes.py | 1,286 | 4.21875 | 4 | import turtle
s = turtle.getscreen()
t = turtle.Turtle()
class shape:
def __init__(self, sides = 0, length = 0):
self.sides = sides
self.length = length
class polygon(shape):
def info(self):
print("In geometry , a polygon can be defined as a flat or plane , two dimentional with strai... | false |
4f39c91b7ed484576a00a3a0fca619e5d79c7a75 | mulyesmita15/Birthday-Remaining-Python | /birthday Remaining.py | 799 | 4.15625 | 4 | from datetime import datetime
import time
def get_user_birthday():
date_str = input("Enter your birth date in DD/MM/YYYY: ")
try:
birthday = datetime.strptime(date_str, "%d/%m/%Y")
except TypeError:
birthday = datetime.datetime(*(time.strptime(date_str, "%d/%m/%Y")[0:6]))
ret... | false |
280316ead847ed3f6aaf806b316926ab74102f92 | titotamaro/List_Spinner | /List_Spinner/List_Spinner.py | 1,198 | 4.1875 | 4 | list_awal = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] #akan diubah menjadi[3,6,9][2,5,8][1,4,7]
#[3,6,9] ==> setiap kolom selisih 3 angka
#[2,5,8]
#[1,4,7]
def counterClockwise (list_x): # fungsi counterClockwise untuk list_x
hasil = [] # storage untuk penghitungan
for i in range(1,len(list_x)+1): # jumlah bari... | false |
257f16e47cff4e8ac9c09a2c612c26514a144272 | eternalAbyss/Python_codes | /Data_Structures/zip.py | 585 | 4.34375 | 4 | # Returns an iterator that combines multiple iterables into one sequence of tuples. Each tuple contains the elements in
# that position from all the iterables.
items = ['bananas', 'mattresses', 'dog kennels', 'machine', 'cheeses']
weights = [15, 34, 42, 120, 5]
print(list(zip(items, weights)))
item_list = list(zip(it... | true |
5f5deaa62dde074fe526e3b079565fa5a25c51ab | konstantin2508/geekbrains_lessons | /Lesson2_Циклы_Рекурсия_Функции/les2_2_Рекурсия.py | 396 | 4.15625 | 4 | # Рекурсия
# Даны 2 числа: необходимо вывести все числа от A до B,
# в порядке возрастания (A<B) или убывания (A>B)
def func(a, b):
if a == b:
return f'{a}'
elif a > b:
return f'{a}, {func(a - 1, b)}'
elif a < b:
return f'{a}, {func(a + 1, b)}'
print(func(3, 25))
print(func(20, 2)) | false |
c24e68e1d77ba3e532987225382ae2f325424426 | muha-abdulaziz/langs-tests | /python-tests/sqrt.py | 419 | 4.3125 | 4 | """
This program finds the square root.
"""
x = int(input('Enter an integer: '))
def sqrt(x):
'''
This program finds the square root.
'''
x = x
ans = 0
while ans ** 2 < abs(x):
ans = ans + 1
if ans ** 2 != abs(x):
print(x, "is not a perfect square.")
else:
if x... | true |
4e77c72219eec3043169f21e5ea39683d274d768 | vssousa/hacker-rank-solutions | /data_structures/linked_lists/merge_two_sorted_linked_lists.py | 982 | 4.34375 | 4 | """
Merge two linked lists
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def MergeLists(headA, headB):
... | true |
866d69100bf11fa6508f0831af38d793fcbc1203 | CapstoneProject18/Twitter-sentiment-analysis | /s3.py | 711 | 4.34375 | 4 | #function to generate list of duplicate values in the list
def remove_Duplicate(list):
final_list = []
for letter in list: #empty final list to store duplicate values in list ... | true |
6a95042055f70c57d1b7f162d425999f4ea0b9ef | rhaeguard/algorithms-and-interview-questions-python | /string-questions/reverse_string_recursion.py | 368 | 4.28125 | 4 | """
Reverse the string using recursion
"""
def reverse_recurse(string, st, end):
if st > end:
return ''.join(string)
else:
tmp_char = string[st]
string[st] = string[end]
string[end] = tmp_char
return reverse_recurse(string, st+1, end-1)
def reverse(string):
return... | true |
29780713ccfde18c564112343872fc00415e994b | rhaeguard/algorithms-and-interview-questions-python | /problem_solving/triple_step.py | 449 | 4.4375 | 4 | """
Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3
steps at a time. Implement a method to count how many possible ways the child can run up the
stairs.
"""
def triple_steps(step_size):
if step_size == 1 or step_size == 0:
return 1
elif step_size ==... | true |
4a5ff8792e2f2106205376b2e4ac135045abf3d9 | akashgkrishnan/HackerRank_Solutions | /language_proficiency/symmetric_difference.py | 741 | 4.34375 | 4 | # Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
# Input Format
# The first line of input contains an integer, .
# The second line contains space-separated integers.
# The th... | true |
c4b02fa604cfbaeda727970e16450d9caceb3cd0 | namanm97/sl1 | /7a.py | 744 | 4.375 | 4 | # 7A
# Write a python program to define a student class that includes name,
# usn and marks of 3 subjects. Write functions calculate() - to calculate the
# sum of the marks print() to print the student details.
class student:
usn = " "
name = " "
marks1 = 0
marks2 = 0
marks3 = 0
def __init__(self,usn,name,ma... | true |
57970d0c4d360cb2efbee1272d167883a9af77e9 | pavanibalaram/python | /sampleprograms/maximumnumber.py | 204 | 4.1875 | 4 | def max():
if a<=b:
print(" {} is a maximum number" .format(b))
else:
print(" {} is a maximum number".format(a))
a=int(input("enter a number"))
b=int(input("enter a number"))
max() | false |
de429dafc1e0289e1db3f2959c3898bf108da63f | zbloss/PythonDS-MLBootcamp | /Python-Data-Science-and-Machine-Learning-Bootcamp/Machine Learning Sections/Principal-Component-Analysis/PCA.py | 1,536 | 4.125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# PCA is just a transformation of the data that seeks to explain what features really
# affect the data
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
cancer.keys()
cancer['... | true |
46ec9a084ae3e98e217ccd160257b870111b8c4e | coshbar/Trabalhos | /Phyton/Max_Subarray.py | 627 | 4.1875 | 4 | #Have the function MaxSubarray(arr) take the array of numbers stored in arr and determine the largest sum that can be formed by any contiguous subarray in the array.
#For example, if arr is [-2, 5, -1, 7, -3] then your program should return 11 because the sum is formed by the subarray [5, -1, 7].
#Adding any element b... | true |
507d763a8196d7f37aeacc592130234b38cf3fa4 | stevenjlance/videogame-python-oop-cli | /game.py | 2,753 | 4.40625 | 4 | import random
class Player:
# Class variables that are shared among ALL players
player_list = [] #Each time we create a player, we will push them into this list.
player_count = 0
def __init__(self, name):
## These instance variables should be unique to each user. Every user will HAVE a name, but each user... | true |
9a52340002ffd0ac3b93cb796958deee21219aef | eguaaby/Exercises | /ex06.py | 428 | 4.34375 | 4 | # Check whether the input string
# is a palindrome or not
def ex6():
user_input = raw_input("Please enter a word: ")
palindrome = True
wordLength = len(user_input)
for i in range(0, wordLength/2 + 1):
if user_input[i] != user_input[wordLength-1-i]:
palindrome = False
if palindro... | true |
4b5b369fafd5657f10492685af047a6604254d05 | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex5_1_2.py | 901 | 4.1875 | 4 | # Chapter 5
# Exercise 1 & 2: Write a program which repeatedly reads numbers until the user enters
# “done”. Once “done” is entered, print out the total, count, average of the
# numbers, maximum and minimum of the numbers. If the user enters anything other than a number, detect their mistake
# using try and except ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.