blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f43f14fe47b99787333551c200df24d211f2f466 | digant0705/Algorithm | /LeetCode/Python/156 Binary Tree Upside Down.py | 823 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
Binary Tree Upside Down
=======================
Given a binary tree where all the right nodes are either leaf nodes with a
sibling (a left node that shares the same parent node) or empty, flip it upside
down and turn it into a tree where the original right nodes turned into left
leaf nodes... | true |
bb74d28eb5e2fae422a278a02c920d856bd11b5d | digant0705/Algorithm | /LeetCode/Python/059 Spiral Matrix II.py | 1,968 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Spiral Matrix II
================
Given an integer n, generate a square matrix filled with elements from 1 to n^2
in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
'''
class Solution(object):
'''算法思路:
... | true |
422aa7064b6f08b428a782685507ecd3d6b8b98a | digant0705/Algorithm | /LeetCode/Python/117 Populating Next Right Pointers in Each Node II.py | 1,611 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Populating Next Right Pointers in Each Node II
==============================================
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution
still work?
Note:
- You may only use constant ... | true |
49948daded2dd54ec0580b90f49602a9f109b623 | digant0705/Algorithm | /LeetCode/Python/114 Flatten Binary Tree to Linked List.py | 903 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Flatten Binary Tree to Linked List
==================================
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
... | true |
f70831de914e8e30bc7d5b585d604621b153d989 | digant0705/Algorithm | /LeetCode/Python/044 Wildcard Matching.py | 2,354 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
Wildcard Matching
=================
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function pr... | true |
676462bbeb65b4c86a49a3e15fda440170e117cb | digant0705/Algorithm | /LeetCode/Python/281 Zigzag Iterator.py | 1,770 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
Zigzag Iterator
===============
Given two 1d vectors, implement an iterator to return their elements
alternately.
For example, given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements
returned by next shoul... | true |
1b1ae8b841a23ef9411a169a2e41d7702ad2d7c3 | digant0705/Algorithm | /LeetCode/Python/048 Rotate Image.py | 1,873 | 4.15625 | 4 | # -*- coding: utf-8 -*-
'''
Rotate Image
============
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
'''
class Solution(object):
'''算法思路:
- o = (length - 1) / 2.0 旋转的中心为 (o, o)
- 可以根据 当前点 (row, col) 算出 将要翻转的点为... | false |
c7731d232c8a19ee8a5a62c6f095c7ef69f12e99 | digant0705/Algorithm | /LeetCode/Python/224 Basic Calculator.py | 2,347 | 4.21875 | 4 | # -*- coding: utf-8 -*-
'''
Basic Calculator
================
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus
+ or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is alwa... | false |
b1d4c792fa5bed9318d6b06ef5040f8033da7b92 | digant0705/Algorithm | /LeetCode/Python/371 Sum of Two Integers.py | 663 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Sum of Two Integers
===================
Calculate the sum of two integers a and b, but you are not allowed to use the
operator + and -.
Example:
Given a = 1 and b = 2, return 3.
"""
class Solution(object):
def add(self, a, b):
for _ in xrange(32):
a, b = a ^ b, ... | true |
35131f3bff52c30cf0ca3f99445ec08a53f020f6 | anatulea/codesignal_challenges | /Intro_CodeSignal/07_Through the Fog.py/31_depositProfit.py | 953 | 4.25 | 4 | '''
You have deposited a specific amount of money into your bank account. Each year your balance increases at the same growth rate. With the assumption that you don't make any additional deposits, find out how long it would take for your balance to pass a specific threshold.
Example
For deposit = 100, rate = 20, and ... | true |
40da9655f1ceb1450d203efa31a6bfc9a3748220 | anatulea/codesignal_challenges | /Intro_CodeSignal/01_The Jurney Begins/02_centuryFromYear.py | 1,220 | 4.1875 | 4 | '''
Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
Example
For year = 1905, the output should be
centuryFromYear(year) = 20;
For year = 1700, the output should be
centuryFromYear... | true |
67801342d06b60b610ee909bf60712796894cbad | anatulea/codesignal_challenges | /Python/11_Higher Order Thinking/73_tryFunctions.py | 1,391 | 4.40625 | 4 | '''
You've been working on a numerical analysis when something went horribly wrong: your solution returned completely unexpected results. It looks like you apply a wrong function at some point of calculation. This part of the program was implemented by your colleague who didn't follow the PEP standards, so it's extreme... | true |
7d95aafc8e3b783c05196c5ba11e448578bf5a9e | anatulea/codesignal_challenges | /Python/08_Itertools Kit/48_cyclicName.py | 1,147 | 4.71875 | 5 | '''
You've come up with a really cool name for your future startup company, and already have an idea about its logo. This logo will represent a circle, with the prefix of a cyclic string formed by the company name written around it.
The length n of the prefix you need to take depends on the size of the logo. You haven... | true |
ae12622ea7ab0959a7e0896b504f683487cac457 | anatulea/codesignal_challenges | /isIPv4Address.py | 1,229 | 4.125 | 4 | '''
An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address.
Given a string, find out ... | true |
79efe0f71e3216d25af3d67500a29423af62a35f | anatulea/codesignal_challenges | /Intro_CodeSignal/03_Smooth Sailing/13_reverseInParentheses.py | 1,577 | 4.21875 | 4 | '''
Write a function that reverses characters in (possibly nested) parentheses in the input string.
Input strings will always be well-formed with matching ()s.
Example
For inputString = "(bar)", the output should be
reverseInParentheses(inputString) = "rab";
For inputString = "foo(bar)baz", the output should be
reve... | true |
0f30ab84f246ce8c842d54dd760106bcb464304e | anatulea/codesignal_challenges | /Python/02_SlitheringinStrings/19_newStyleFormatting.py | 1,234 | 4.125 | 4 | '''
Implement a function that will turn the old-style string formating s into a new one so that the following two strings have the same meaning:
s % (*args)
s.format(*args)
Example
For s = "We expect the %f%% growth this week", the output should be
newStyleFormatting(s) = "We expect the {}% growth this week".
'''
d... | true |
5ef35cd82d9d5428fd4277db7190f95159b9c306 | tessadvries/DSF | /dsf-exercise12-snacknames-refactored.py | 344 | 4.28125 | 4 | friends = {
"Tessa" : " ",
"Manon" : " ",
"Stijn" : " ",
}
for key in friends:
length = len(key)
print(f'Hi {key}! Your name has {length} characters.')
friends[key] = input(f'{key}, what is your favorite snack? ')
value = friends[key]
print(friends)
for key, value in friends.items():
print(f'The favorite sna... | false |
d4d9a9ae96ebf4a33a9758802b9acdfeb555ccdc | ivn-svn/Python-Advanced-SoftUni | /Functions-Advanced/Exercises/12. recursion_palindrome.py | 401 | 4.25 | 4 | def palindrome(word, index=0, reversed_word=""):
if index == len(word):
if not reversed_word == word:
return f"{word} is not a palindrome"
return f"{word} is a palindrome"
else:
reversed_word += word[-(index + 1)]
return palindrome(word, index + 1, reversed_word)
... | true |
8c4dd6b4f43c3047bcdc057c3c8037f9ed4f71ef | guilhermeborges84/Programacao | /Curso JLCP/Exercícios/Exercicio2.py | 701 | 4.15625 | 4 | #Definino as variáveis
nome = str(input("Digite o seu nome: "))
cargo = str(input("Digite o seu cargo: "))
concatenado = 'Nome:' + nome + ' ,' + ' Cargo:' + cargo
#Concatenando manualmente
print(f'Valores concatenados manualmente: {nome} {cargo}')
print(f'Juntando string usando variáveis: {concatenado}')
inserir = in... | false |
f3946cde9b458f7e24e47188ce809f6bcead79bf | satish3366/PES-Assignnment-Set-2 | /37_dist_operations.py | 791 | 4.3125 | 4 | dict1={'Empid':12,'Ename':'Vijay','Band':'B1'}
dict2={'Rollno':11,'Name':'Arshiya','Class':7}
dict3={'Kname':'Ashu','Kage':8,'Bgroup':'B+'}
if dict1>dict2 and dict1>dict3:
print ("dict1 is th biggest",dict1)
elif dict2>dict1 and dict2>dict3:
print ("dict2 is the biggest",dict2)
else:
print ("dict3 is the ... | false |
3a7baad4cf891fe0d8bb6a7b5fa11ce938cbfda8 | om-100/assignment2 | /11.py | 519 | 4.6875 | 5 | """Create a variable, filename. Assuming that it has a three-letter
extension, and using slice operations, find the extension. For
README.txt, the extension should be txt. Write code using slice
operations that will give the name without the extension. Does your
code work on filenames of arbitrary length?"""
def filen... | true |
7d16b1a4caca082162ed41edb8d679beec2d3389 | LeonGuerreroM/Codigos-Python | /Binary_Power.py | 2,641 | 4.15625 | 4 | def binary_method(base, exponent, module):
'''Funcion que realiza la potenciación modular con el método binario
Entradas
base => base de la potencia
exponent => exponente de la potencia
module => módulo de la potenciación modular
Salidas
C => resultado de la potenciación modu... | false |
13d759a3accaba9725d3b70f6a261fe9d9eca1a9 | owaisali8/Python-Bootcamp-DSC-DSU | /week_1/2.py | 924 | 4.125 | 4 | def average(x):
return sum(x)/len(x)
user_records = int(input("How many student records do you want to save: "))
student_list = {}
student_marks = []
for i in range(user_records):
roll_number = input("Enter roll number:")
name = input("Enter name: ")
age = input("Enter age: ")
marks = int(input("E... | true |
f7ccdb31cc184e3603f2f465c1d68f5c694ef9d7 | Ollisteka/Chipher_Breaker | /logic/encryptor.py | 2,968 | 4.3125 | 4 | #!/usr/bin/env python3
# coding=utf-8
import json
import sys
import tempfile
from copy import copy
from random import shuffle
def read_json_file(filename, encoding):
"""
Read data, written in a json format from a file, and return it
:param encoding:
:param filename:
:return:
"""
with open(... | true |
909f28e3de50e5b1b096fe162e5aaba387c273f1 | sophialuo/CrackingTheCodingInterview_4thEdition | /chapter8/8.1.py | 379 | 4.1875 | 4 | #8.1
#Write a method to generate nth Fibonacci number
def fib_recursion(n):
if n <= 1:
return 1
return fib_recursion(n-1) + fib_recursion(n-2)
#a more space and time efficient way
def fib_efficient(n):
first = 0
second = 1
for i in range(n):
temp = second
s... | false |
d453fea7cdea71dc9ca2cf967350e9d9bfb836e3 | FlyingSparrow/Python3_Learning | /Python3.4_Project/com/base/section3/basic_datatype.py | 1,517 | 4.15625 | 4 | #!/usr/bin/python3
print("==============变量示例=================")
counter = 100
miles = 1000.0
name = "runoob"
print(counter)
print(miles)
print(name)
print("==============字符串示例=================")
str = 'Runoob'
print(str)
print(str[0:-1])
print(str[0])
print(str[2:5])
print(str[2:])
print(str*2)
print(str+"TEST")
p... | false |
15065a683fa733faa071b3f9e145100ca355951c | FlyingSparrow/Python3_Learning | /Python3.4_Project/com/base/section25/sample_23.py | 930 | 4.15625 | 4 | #!/usr/bin/python3
print("{0}简单计算器实现{1}".format('=' * 10, '=' * 10))
def add(x, y):
return x + y
def substract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
print('divisor can not be zero')
return
else:
return x / y
print('选择运算:'... | false |
f84cf15c04be752423408f06737cc5100c7f0cf4 | af94080/bitesofpy | /9/palindrome.py | 1,406 | 4.3125 | 4 | """A palindrome is a word, phrase, number, or other sequence of characters
which reads the same backward as forward"""
import os
import urllib.request
DICTIONARY = os.path.join('/tmp', 'dictionary_m_words.txt')
urllib.request.urlretrieve('http://bit.ly/2Cbj6zn', DICTIONARY)
def load_dictionary():
"""Lo... | true |
2a482264dc15fc4c17fc27e08d9247351e47815a | chinmaygiri007/Machine-Learning-Repository | /Part 2 - Regression/Section 6 - Polynomial Regression/Polynomial_Regression_Demo.py | 1,317 | 4.25 | 4 | #Creating the model using Polynomial Regression and fit the data and Visualize the data.
#Check out the difference between Linear and Polynomial Regression
#Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Reading the data
data = pd.read_csv("Position_Salaries.csv")
... | true |
96d90ae34f7e20c90adcc4637b04bdd885aa6865 | HimanshuKanojiya/Codewar-Challenges | /Disemvowel Trolls.py | 427 | 4.28125 | 4 | def disemvowel(string):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for items in vowels:
if items in string:
cur = string.replace(items,"") #it will replace the vowel with blank
string = cur #after completing the operation, it will update the current string
else... | true |
7d1547f6d3d93fc3253321c5edd6509165493910 | JCarter111/Python-kata-practice | /Square_digits.py | 2,368 | 4.46875 | 4 | # Kata practice from codewars
# https://www.codewars.com/kata/546e2562b03326a88e000020/train/python
# Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
# Note: The function accepts an integer a... | true |
5280f17272181f7eb09eef6b47e975e8bb8b7063 | katgzco/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 860 | 4.15625 | 4 | #!/usr/bin/python3
"""
Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
"""
max_integer return the max integer of a list
"""
class TestMaxInteger(unittest.TestCase):
def test_integer(self):
"Test numbers cases"
self.assertEqual(max... | false |
bd3af2c85a29e8f785fc9f53d8370ca5b95cb1ee | ckkhandare/mini_python_part2 | /City&tree.py | 1,767 | 4.21875 | 4 | dict1={}
while True:
print(''' 1. Add new city and trees commonly found in the city.\n
2. Display all cities and the list of trees for all cities.\n
3. Display list of trees of a particular city.\n
4. Display cities which have the given tree.\n
5. Delete city\n
6. Modify tree list\n
7. Exit\n''')
... | false |
2d4ae931777f45b7bb6a1b549d838bf6b37ab4eb | LuciRamos/python | /pep8.py | 928 | 4.15625 | 4 | """
PEP 8
São propostas de melhorias para a linguagem Python
A ideia da PEP8 é que possamos escrever códigos Python de forma Pythônica.
[1] - Utilize Camel Case para nomes de classes; - Iniciais maiusculas e sem
[2] - Utilize nomes em minusculo, separados por underline para funções ou variáveis
[3] - Utilize 4 e... | false |
fc22ede62dbfff1d6ad38bc27c353d41def148fe | Talw3g/pytoolbox | /src/pytoolbox_talw3g/confirm.py | 1,356 | 4.5 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
def confirm(question, default_choice='yes'):
"""
Adds available choices indicator at the end of 'question',
and returns True for 'yes' and False for 'no'.
If answer is empty, falls back to specified 'default_choice'.
PARAMETERS:
- question is man... | true |
e7d9e99375459e1031bf9dd0c2059421978ef31b | KartikeyParashar/Algorithm-Programs | /calendar.py | 1,434 | 4.28125 | 4 | # To the Util Class add dayOfWeek static function that takes a date as input and
# prints the day of the week that date falls on. Your program should take three
# commandline arguments: m (month), d (day), and y (year). For m use 1 for January,
# 2 for February, and so forth. For output print 0 for Sunday, 1 for Monda... | true |
b59b0b070037764fc71912183e64d047c53f9cf1 | aruntonic/algorithms | /dynamic_programming/tower_of_hanoi.py | 917 | 4.375 | 4 | def tower_of_hanoi(n, source, buffer, dest):
'''
In the classic problem of the wers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower.
The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one).You ha... | true |
f9f3819c0cacfd8d0aba22d64628ab343e94b5b7 | amulyadhupad/My-Python-practice | /square.py | 202 | 4.15625 | 4 | """ Code to print square of the given number"""
def square(num):
res =int(num) * int(num)
return res
num=input("Enter a number")
ans=square(num)
print("square of "+str(num)+" "+"is:"+str(ans)) | true |
e35bf120762ef57b77799846b2150a86de16c3de | robertyoung1993/Tester_home | /Basing/record_error.py | 766 | 4.21875 | 4 | """
记录错误
内置logging模块可以非常容易的记录错误信息
"""
import logging
# def foo(s):
# return 10 / int(s)
#
# def bar(s):
# return foo(s) * 2
#
# def main():
# try:
# bar('0')
# except Exception as e:
# logging.exception(e)
#
# main()
# print('END')
"""
抛出错误
"""
class FooError(ValueError):
pass
d... | false |
c93c2c8f1a4a7a0a2d8a69ad312ea8c06dc54446 | tuanvp10/eng88_python_oop | /animal.py | 555 | 4.25 | 4 | # Create animal class via animal file
class Animal:
def __init__(self): # self refers to this class
self.alive = True
self.spine = True
self.eyes = True
self.lungs = True
def breath(self):
return "Keep breathing to stay alive"
def eat(self):
return "Nom no... | true |
617b0b81f3c5ca52ec255b528b15d6862aa34f52 | maria-gabriely/Maria-Gabriely-POO-IFCE-INFO-P7 | /Presença/Atividade 02/Lista_Encadeada.py | 227 | 4.25 | 4 | # 3) Lista Encadeada (A retirada e a inserção de elementos se faz em qualquer posição da Lista).
Lista3 = [1,2,3,4,'a','c','d']
print(Lista3)
x = 'b'
Lista3.insert(5,x)
print(Lista3)
Lista3.pop(2)
print(Lista3)
| false |
a6a9ca58f31c8161792d2c6ce7a73f1318bc8589 | diegocolombo1989/Trabalho-Python | /Aula20/exercicios/Resolução/exercicio1.py | 2,183 | 4.28125 | 4 | # Aula 20 - 05-12-2019
# Lista com for e metodos
# Com esta lista:
lista = [
['codigo','produto','valor','quantidade'],
[1,'Cevada',15.00,10],
[2,'Lupulo',150.50,200],
[3,'Malte',57.80,5000],
[4,'Levedura 1',10.65,500],
[5,'Extrato de Levedura',15.00,60],
... | false |
0acbad19ec29c8ce0e13d9d44eff09759e921be0 | Patrick-J-Close/Introduction_to_Python_RiceU | /rpsls.py | 1,779 | 4.1875 | 4 | # Intro to Python course project 1: rock, paper, scissors, lizard, Spock
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# where each value beats the two prior values and beats the two following values
import random
def name_to_number(name):
# convert string input to integer value
if name == ... | true |
ee8ff8648e324b2ca1c66c4c030a68c816af1464 | Merrycheeza/CS3130 | /LabAss2/LabAss2.py | 1,331 | 4.34375 | 4 | ###################################
# #
# Class: CS3130 #
# Assignment: Lab Assignment 2 #
# Author: Samara Drewe #
# 4921860 #
# #
###################################
#!/usr/bin/env python3
import sys, re
running = True
# prints the menu
print("--")
print("Phone Number ")
print(" ")
while(r... | true |
30e22c55bb0fe9bd5221270053564adbe4d83932 | ine-rmotr-projects/INE-Fractal | /mandelbrot.py | 854 | 4.21875 | 4 | def mandelbrot(z0:complex, orbits:int=255) -> int:
"""Find the escape orbit of points under Mandelbrot iteration
# If z0 isn't coercible to complex, TypeError
>>> mandelbrot('X')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/davidmertz/git/INE/unittest/0... | true |
257f2d67b700463e128b2251d285e8ce53065b6f | bharath210/PythonLearning | /Assignments/FibonacciDemo.py | 388 | 4.15625 | 4 |
def fibb(n):
num1 = 0;
num2 = 1;
temp =0
if(n == 1):
print(num1)
else:
print(num1)
print(num2)
for i in range(2,n):
num3 = num2 + num1
# if n <= num3:
# break
print(num3)
temp = num3
num1 = num2... | false |
0d24827c20ed97cbdf445f2691554cac1b99f8c8 | naochaLuwang/Candy-Vending-Machine | /tuto.py | 1,288 | 4.25 | 4 | # program to mimic a candy vending machine
# suppose that there are five candies in the vending machine but the customer wants six
# display that the vending machine is short of 1 candy
# And if the customer wants the available candy, give it to the customer else ask for another number of candy.
av = 5
x = int(input("... | true |
789ac887653860972e9788eb9bc2d7c4e6064abc | Sajneen-Munmun720/Python-Exercises | /Calculating the number of upper case and lower case letter in a sentence.py | 432 | 4.1875 | 4 | def case_testing(string):
d={"Upper_case":0,"Lower_case":0}
for items in string:
if items.isupper():
d["Upper_case"]+=1
elif items.islower():
d["Lower_case"]+=1
else:
pass
print("Number of upper case is:",d["Upper_case"])
print("Numbe... | true |
edf7b53def0fffcecef3b00e4ea67464ba330d9c | Malcolm-Tompkins/ICS3U-Unit5-06-Python-Lists | /lists.py | 996 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on June 2, 2021
# Rounds off decimal numbers
def round_off_decimal(user_decimals, number_var):
final_digit = ((number_var[0] * (10 ** user_decimals)) + 0.5)
return final_digit
def main():
number_var = []
user_input1 = (input("Enter your... | true |
27b85920a9a7d8d9c2b42f5d3227ffb3f48acda8 | jorgegarba/CodiGo9 | /BackEnd/Semana4/Dia3/09-listas.py | 488 | 4.15625 | 4 | nombres = ["Juan","Jorge","Raul","Eusebio","Christian",100]
nombre = "Eusebio"
# para saber si el nombre esta en nuestro arreglo nombres
print(nombre in nombres)
# Buscar un nombre en esa lista
# for (let i = 0; i< nombres.lenght; i++){
# console.log(nombres[i])
# }
# Por cada nombrecito en nuestra lista nombres, ens... | false |
3e78ea8629c13cefe4fdcbf42f475eb4da525b2a | vladbochok/university-tasks | /c1s1/labwork-2.py | 1,792 | 4.21875 | 4 | """
This module is designed to calculate function S value with given
accuracy at given point.
Functions:
s - return value of function S
Global arguments:
a, b - set the domain of S
"""
from math import fabs
a = -1
b = 1
def s(x: float, eps: float) -> float:
"""Return value of S at given point x with gi... | true |
6f0bc83046ec214818b9b8cc6bc5962a5d819977 | thivatm/Hello-world | /Python/Counting the occurence of each word.py | 223 | 4.21875 | 4 | string=input("Enter string:").split(" ")
word=input("Enter word:")
from collections import Counter
word_count=Counter(string)
print(word_count)
final_count=word_count[word]
print("Count of the word is:")
print(final_count)
| true |
0cb00f6f4798c9bc5770f04b8a2a09cb0e3f0c43 | ssavann/Python-Data-Type | /MathOperation.py | 283 | 4.25 | 4 | #Mathematical operators
print(3 + 5) #addition
print(7 - 4) #substraction
print(3 * 2) #multiplication
print(6 / 3) #division will always be "Float" not integer
print(2**4) #power: 2 power of 4 = 16
print((3 * 3) + (3 / 3) - 3) #7.0
print(3 * (3 + 3) / 3 - 3) #3.0
| true |
c54d75b36108590ba19569ae24f6b72fd13b628b | Alankar-98/MWB_Python | /Functions.py | 239 | 4.15625 | 4 | # def basic_function():
# return "Hello World"
# print(basic_function())
def hour_to_mins(hour):
mins = hour * 60
return mins
print(hour_to_mins(float(input("Enter how many hour(s) you want to convert into mins: \n")))) | true |
ce788f6c65b9b8c4e3c47585b7024d2951b59d19 | GLARISHILDA/07-08-2021 | /cd_abstract_file_system.py | 928 | 4.15625 | 4 | # Write a function that provides a change directory (cd) function for an abstract file system.
class Path:
def __init__(self, path):
self.current_path = path # Current path
def cd(self, new_path): # cd function
parent = '..'
separator = '/'
# Absolute path
... | true |
a84755fd8627c33535f669980de25c072e0a3c83 | sandeshsonje/Machine_test | /First_Question.py | 555 | 4.21875 | 4 | '''1. Write a program which takes 2 digits, X,Y as input and generates a
2-dimensional array.
Example:
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Note: Values inside array can be any.(it's up to candida... | true |
f5e7a155de761f83f9ad7b8293bc5c81edda3f1f | Luciekimotho/datastructures-and-algorithms | /MSFT/stack.py | 821 | 4.1875 | 4 | #implementation using array
#class Stack:
# def __init__(self):
# self.items = []
# def push(self, item):
# self.items.append(item)
# def pop(self):
# return self.items.pop()
#implementation using lists
class Stack:
def __init__(self):
self.stack = list()
#inse... | true |
eab5e0186698af32d9301abf155e1d0af25e5f6f | jzamora5/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 647 | 4.1875 | 4 | #!/usr/bin/python3
""" Minimum Operations """
def minOperations(n):
"""
In a text file, there is a single character H. Your text editor can execute
only two operations in this file: Copy All and Paste. Given a number n,
write a method that calculates the fewest number of operations needed to
resu... | true |
746c24e8e59f8f85af4414d5832f0ec1bf9a4f7c | joeblackwaslike/codingbat | /recursion-1/powerN.py | 443 | 4.25 | 4 | """
powerN
Given base and n that are both 1 or more, compute recursively (no loops) the
value of base to the n power, so powerN(3, 2) is 9 (3 squared).
powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27
"""
def powerN(base, n):
if n == 1:
return base
else:
return base * powerN(base, n - 1)... | true |
2bf855bce42dcf61cee814e5f33825db0913a26b | LingChenBill/python_first_introduce | /head_first_python/ch01/05_07_1_list_solving.py | 1,589 | 4.1875 | 4 | fav_movies = ["The Holy Grail", "The life of Brian"]
print(fav_movies)
print(fav_movies[0])
print(fav_movies[1])
print("For 迭代列表:")
for each_flick in fav_movies:
print(each_flick)
# 列表处理代码被称为“组”
print("也可考虑用while循环迭代:")
count = 0
while count < len(fav_movies):
print(fav_movies[count])
count = count + 1
p... | false |
d6fb1774f0abf4a7dfacc3630206cc2e8fda883c | shenxiaoxu/leetcode | /questions/1807. Evaluate the Bracket Pairs of a String/evaluate.py | 1,448 | 4.125 | 4 | '''
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.
For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age".
You know the values of a wide range of keys. This is represented by a 2D string array knowled... | true |
7902a7ed39635064d0e3e93aa1a0a24e1ac4a625 | nikonst/Python | /OOP/oop1.py | 1,247 | 4.125 | 4 | # OOP Basic Concepts
class Person:
species = "Human" # Class field
def __init__(self, name, gender):
self.name = name
self.gender = gender
def introduceYourself(self):
print("Hi! My name is ", self.name)
def myFavouriteMovie(self):
print("Terminator I")
... | false |
bfe9ecfe1e7c5e04be74a9ad86e0deed0535063e | nikonst/Python | /Core/lists/big_diff.py | 691 | 4.125 | 4 | '''
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) - 7
big_diff([7, 2, 10, 9]) - 8
big_diff([2, 10, 7, 2]) - 8
'''
i... | true |
29dc483eabdfada41277bd0879d4d30db4c5e9e1 | nikonst/Python | /Core/lists/centered_average.py | 859 | 4.21875 | 4 | '''
Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value,
ignore just one copy, and likewise for the largest value. Use int division to produce the final a... | true |
e924c76da60630526344873dfd5523c3bf9bec7d | nikonst/Python | /Core/lists/max_end3.py | 792 | 4.40625 | 4 | '''
Given an array of ints length 3, figure out which is larger, the first or last element in the array,
and set all the other elements to be that value. Return the changed array.
max_end3([1, 2, 3]) - [3, 3, 3]
max_end3([11, 5, 9]) - [11, 11, 11]
max_end3([2, 11, 3]) - [3, 3, 3]
'''
def maxEnd3(nums):
... | true |
2dde45ecac9827dc9804a3d4277054bb07e5be02 | Vaishnavi-cyber-blip/LEarnPython | /Online library management system.py | 1,658 | 4.1875 | 4 | class Library:
def __init__(self, list_of_books, library_name):
self.library_name = library_name
self.list_of_books = list_of_books
def display_books(self):
print(f"Library name is {self.library_name}")
print(f"Here is the list of books we provide:{self.list_of_books}")
def... | true |
22685b80e601c73f188734b3d511d5de29f51708 | VesaKelani/python-exercises | /palindrome.py | 253 | 4.21875 | 4 |
wrd = input("Enter a word: ")
wrd = str(wrd)
rvs = wrd[::-1]
while rvs != wrd:
print("This word is not a palindrome")
wrd = input("Enter a word: ")
wrd = str(wrd)
rvs = wrd[::-1]
if rvs == wrd:
print("This word is a palindrome")
| false |
0d70416d7d6d50d3f69d38ab8bb6878b3e673667 | MarkVarga/python_to_do_list_app | /to_do_list_app.py | 1,819 | 4.21875 | 4 |
data = []
def show_menu():
print('Menu:')
print('1. Add an item')
print('2. Mark as done')
print('3. View items')
print('4. Exit')
def add_items():
item = input('What do you need to do? ')
data.append(item)
print('You have added: ', item)
add_more_items()
def add_more_items()... | true |
ff3ccbf45d3be6f6933f03ec3be4ec8c03c15be1 | j-hmd/daily-python | /Object-Oriented-Python/dataclasses_intro.py | 600 | 4.1875 | 4 | # Data classes make the class definition more concise since python 3.7
# it automates the creation of __init__ with the attributes passed to the
# creation of the object.
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int
price: float
b1 = Book("A Mao e a Luva",... | true |
975f43786306ca83189c8a7f310bec5b38c1ac84 | Pawan459/infytq-pf-day9 | /medium/Problem_40.py | 1,587 | 4.28125 | 4 | # University of Washington CSE140 Final 2015
# Given a list of lists of integers, write a python function, index_of_max_unique,
# which returns the index of the sub-list which has the most unique values.
# For example:
# index_of_max_unique([[1, 3, 3], [12, 4, 12, 7, 4, 4], [41, 2, 4, 7, 1, 12]])
# would return 2 si... | true |
9105402ce5b6bde25f2f0bc82d8ec5f523b63f17 | matckolck1/cosas | /anida.py | 316 | 4.125 | 4 | for i in range(3):
print ("a")
for j in range(3):
print ("b")
for i in range(2):
print("te quiero")
for m in range(3):
print("mucho")
for i in range(2):
print("te quiero")
for m in range(3):
print("mucho")
for t in range(1):
print("naranja")
| false |
fd86b2ae3b647afb8b1f7a0bcc081a8d7bf380e5 | buribae/is-additive-python | /is_additive.py | 1,143 | 4.15625 | 4 | import sys
import time
def secret(n):
return n+n
def primes_of(n):
"""Uses sieve of Eratosthenes to list prime numbers below input n
Args:
n: Maximum integer representing
Returns:
An array containing all prime numbers below n
Alternative:
Pyprimesieve https://github.com/jaredks/pyprimesieve
"""
if n < 2... | false |
fa2bb3897975551b93f517e134139139cf29d417 | Dervun/Python-at-Stepik | /2/6.10/6.10.py | 1,416 | 4.3125 | 4 | """
Напишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк,
заканчивающихся строкой, содержащей только строку "end" (без кавычек).
Программа должна вывести матрицу того же размера, у которой каждый элемент в позиции i, j
равен сумме элементов первой матрицы на позициях (i-1, ... | false |
ef4b1f9b167c368dbd47e7bd9c270db6326bc7af | Dervun/Python-at-Stepik | /1/11.5/11.5.py | 754 | 4.3125 | 4 | '''
Напишите программу, которая получает на вход три целых числа, по одному числу в строке,
и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число.
На ввод могут подаваться и повторяющиеся числа.
'''
arr = sorted([int(input()) for i in range(3)])
print(arr[2], arr[0], ar... | false |
ebb25b6998bf21815faa79944082816c04d95cb0 | sesantanav/python_basics | /poo.py | 1,415 | 4.25 | 4 | # Programación Orientada o Objetos con Python
# Clases
class NuevaClase:
pass
class Persona:
def __init__(self):
self._nombre = ""
self._edad = 0
# Metódods de la clase
# setters
def setNombre(self, nombre):
self._nombre = nombre
def setEdad(self, edad):
sel... | false |
1e7f67cd95ecd74857bcc0a2aeb4a45e6b13947d | harshonyou/SOFT1 | /week5/week5_practical4b_5.py | 440 | 4.125 | 4 | '''
Exercise 5:
Write a function to_upper_case(input_file, output_file) that takes two
string parameters containing the name of two text files. The function reads the content of the
input_file and saves it in upper case into the output_file.
'''
def to_upper_case(input_file, output_file):
with open(input_file) as x... | true |
dd0b87ac56156e3f3f7397395752cd9f57d33972 | harshonyou/SOFT1 | /week7/week7_practical6a_6.py | 1,075 | 4.375 | 4 | '''
Exercise 6:
In Programming, being able to compare objects is important, in particular determining if two
objects are equal or not. Let’s try a comparison of two vectors:
>>> vector1 = Vector([1, 2, 3])
>>> vector2 = Vector([1, 2, 3])
>>> vector1 == vector2
False
>>> vector1 != vector2
True
>>> vector3 = vector1
>>>... | true |
13138f7e7f105cb917d3c28995502f01ace2c46a | harshonyou/SOFT1 | /week4/week4_practical3_5.py | 829 | 4.25 | 4 | '''
Exercise 5: Where’s that bug!
You have just started your placement, and you are given a piece of code to correct. The aim of
the script is to take a 2D list (that is a list of lists) and print a list containing the sum of each
list. For example, given the list in data, the output should be [6, 2, 10].
Modify the co... | true |
7209b64a1bfbca67fa750370a6b2a2f35f04085b | harshonyou/SOFT1 | /week3/week3_ex1_1.py | 870 | 4.125 | 4 | '''
Exercise 1: Simple while loopsExercise 1: Simple while loops
1. Write a program to keep asking for a number until you enter a negative number. At the end, print the sum of all entered numbers.
2. Write a program to keep asking for a number until you enter a negative number. At the end, print the average of all en... | true |
ae485d7078b0a130d25f508fa3bbf2654b288fbd | carlosberrio/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/4-append_write.py | 312 | 4.34375 | 4 | #!/usr/bin/python3
"""Module for append_write method"""
def append_write(filename="", text=""):
"""appends a string <text> at the end of a text file (UTF8) <filename>
and returns the number of characters added:"""
with open(filename, 'a', encoding='utf-8') as file:
return file.write(text)
| true |
129c7dfb7e4704916d6a3c70c7b88de3f4ee5ab4 | carlosberrio/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/2-matrix_divided.py | 1,673 | 4.3125 | 4 | #!/usr/bin/python3
""" Module for matrix_divided method"""
def matrix_divided(matrix, div):
"""Divides all elements of a matrix by div
Args:
matrix: list of lists of numbers (int or float)
div: int or float to divide matrix by
Returns:
list: a new matrix list of lists
Raises:
... | true |
ac98781df6169c661443e347c22760b6a88fad1c | KamalAres/Infytq | /Infytq/Day8/Assgn-55.py | 2,650 | 4.25 | 4 | #PF-Assgn-55
#Sample ticket list - ticket format: "flight_no:source:destination:ticket_no"
#Note: flight_no has the following format - "airline_name followed by three digit number
#Global variable
ticket_list=["AI567:MUM:LON:014","AI077:MUM:LON:056", "BA896:MUM:LON:067", "SI267:MUM:SIN:145","AI077:MUM:CAN:060","SI267... | true |
5a195c58bc440fce91c4a7ebc3a1f9eeb61d1ce1 | Wallabeee/PracticePython | /ex11.py | 706 | 4.21875 | 4 | # Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten,
# a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you.
# Take this opportunity to practice using functions, described below.
def isPrime(num):
... | true |
c565249554b9f07bcf3b5c79d607551ae97cc4fc | rene-d/edupython | /codes/pythagoricien.py | 570 | 4.15625 | 4 | # Recherche d'un triplet pythagoricien d'entiers consécutifs
# https://edupython.tuxfamily.org/sources/view.php?code=pythagoricien
# Créé par AgneS, le 17/06/2013 en Python 3.2
for i in range(100000): # On va tester avec la réciproque de Pythagore
# pour 3 nombres consécutif... | false |
cb76ab641d274b65fb3c310584580943586eb178 | timewaitsfor/LeetCode | /knowledge/array_kn.py | 710 | 4.15625 | 4 | # 1. create an array
a = []
# 2. add element
# time complexity: O(1)
a.append(1)
a.append(2)
a.append(3)
# 3. insert element
# time complexity: O(N)
a.insert(2, 99)
# 4. access element
# time complexity: O(1)
tmp = a[2]
# 5. update element
a[2] = 88
# 6. remove element
# time complexity: O(N)
a.remove(88)
a.pop(1)... | false |
02e8b295591e79c057481be775219e2143915e4f | SaidhbhFoley/Promgramming | /Week04/even.py | 370 | 4.15625 | 4 | #asks the user to enter in a number, and the program will tell the user if the number is even or odd.
#Author: Saidhbh Foley
number = int (input("enter an integer:"))
if (number % 2) == 0:
print ("{} is an even number".format (number))
else:
print ("{} is an odd number".format (number))
i = 0
while i > 0:
... | true |
8295f51f45e58fca6248eef8c1e1582988fd9e64 | IchijikuJP/Kesci_DataScienceIntroduction | /Python进阶/zip函数.py | 564 | 4.5625 | 5 | # zip()函数用于将可迭代对象作为参数, 将对象中对应的元素打包成一个个元组
# 然后返回由这些元组组成的对象, 这样可以节约内存
# 如果各个迭代器的元素个数不一致, 则返回列表长度与最短的对象相同
# zip()示例:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
z = zip(list1, list2)
print(z)
z_list = list(z)
print(z_list)
# 与zip相反, zip(*)可理解为解压, 返回二维矩阵式
un_zip = zip(*z_list)
un_list1, un_list2 = list(un_zip)
print(un_lis... | false |
c158785cfd4d1ef3704194e7a1fea2d1a1210308 | tdchua/dsa | /data_structures/doubly_linkedlist.py | 2,805 | 4.34375 | 4 | #My very own implementation of a doubly linked list!
#by Timothy Joshua Dy Chua
class Node:
def __init__(self, value):
print("Node Created")
self.value = value
self.next = None
self.prev = None
class DLinked_List:
def __init__(self):
self.head = None
self.tail = None
def traverse(self)... | true |
5ab07e8ffa079399d88e13fe33573387051cbc06 | rayanepimentel/CourseraUSP-Python-Parte01 | /Python/week02/Tipos de Dados/exercicioopcional.py | 1,225 | 4.15625 | 4 | '''
Nesta lista de exercícios vamos praticar os conceitos vistos até agora. Cada exercício deve ser resolvido em um arquivo separado e a seguir enviado através da web. A correção automática pode demorar alguns minutos. Você pode submeter a mesma resposta mais de uma vez.
Note que a correção verifica se o resultado cor... | false |
22aa6b4daeb05936eb5fd39b361e2945d02a5f64 | 786awais/assignment_3-geop-592-sharing | /Assignment 3 GEOP 592 | 2,512 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[50]:
#GEOP_592 Assigment_3
#Codes link: https://www.datarmatics.com/data-science/how-to-perform-logistic-regression-in-pythonstep-by-step/
#We are Provided with a data for 6800 micro-earthquake waveforms. 100 features have been extracted form it.
#We need to perform logist... | true |
63b2b212b2e42f539fb802cc95633eae00c34a7f | jskimmons/LearnGit | /Desktop/HomeWork2017/1006/Homework1/problem2.py | 825 | 4.1875 | 4 | # jws2191
''' This program will, given an integer representing a number of years,
print the approximate population given the current population and the
approximate births, deaths, and immigrants per second. '''
# Step 1: store the current population and calculate the rates of births,
# deaths, and immigrations per... | true |
773442a1cdd867d18af6c7578af1f5e208be9a7c | jskimmons/LearnGit | /Desktop/HomeWork2017/1006/Homework2/untitled.py | 552 | 4.28125 | 4 | '''
This is a basic dialog system that prompts the user to
order pizza
@author Joe Skimmons, jws2191
'''
def select_meal():
possible_orders = ["pizza" , "pasta" , "salad"]
meal = input("Hello, would you like pizza, pasta, or salad?\n")
while meal.lower() not in possible_orders:
meal = input("Sorry, ... | true |
2bc4c6523788b6a8707aa33540d01b0fd2731743 | kevin-bot/Python-Kevin-pythom | /Script1.py | 577 | 4.125 | 4 |
#practica para asentuar los conocimientos de dias dom,22 de sep,21:54
'''1.DEFINIR una funcion max() que tome como argumento dos números y
devuelva el mayor de ellos'''
def funcion(numerouno,numerodos):
if numerouno < numerodos:
print(f" {numerodos} es mayor que {numerouno}")
elif numerouno>numerod... | false |
6210f2e37e1ce5e93e7887ffa73c8769fae0a35a | garg10may/Data-Structures-and-Algorithms | /searching/rabinKarp.py | 1,862 | 4.53125 | 5 | #Rabin karp algorithm for string searching
# remember '^' : is exclusive-or (bitwise) not power operator in python
'''
The algorithm for rolling hash used here is as below. Pattern : 'abc', Text : 'abcd'
Consider 'abc' its hash value is calcualted using formula a*x^0 + b*x^1 + c*x^2, where x is prime
Now when we need... | true |
e1be3b9664e172dc71a2e3038a1908c5e49dd57b | Fueled250/Intro-Updated-Python | /intro_updated.py | 881 | 4.1875 | 4 | #S.McDonald
#My first Python program
#intro.py -- asking user for name, age and income
#MODIFIED: 10/18/2016 -- use functions
#create three functions to take care of Input
def get_name():
#capture the reply and store it in 'name' variable
name = input ("what's your name?")
return name
def get... | true |
1c60d291a1d02ee0ebefd3544843c918179e5254 | aiswaryasaravanan/practice | /hackerrank/12-26-reverseLinkedList.py | 956 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def add(self,data):
if not self.head:
self.head=Node(data)
else:
cur=self.head
while cur.next:
... | true |
781b93dd583dc43904e9b3d5aa4d6b06eaa5705b | spno77/random | /Python-programs/oop_examples.py | 1,399 | 4.625 | 5 | """ OOP examples """
class Car:
""" Represent a car """
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descritive name"""
long_name = f"{self.year} {self.make} {self.model}"
... | true |
052193ea7c43ccaf0406b3c34cf08b906d6c74fd | GitDavid/ProjectEuler | /euler.py | 812 | 4.25 | 4 | import math
'''
library created for commonly used Project Euler problems
'''
def is_prime(x):
'''
returns True if x is prime; False if not
basic checks for lower numbers and all primes = 6k +/-1
'''
if x == 1 or x == 0:
return False
elif x <= 3:
return True
elif x % 2 == 0 ... | true |
7e767a59754cc8b272e876948793c1ac39d6642c | felipeonf/Exercises_Python | /exercícios_fixação/070.py | 419 | 4.1875 | 4 | ''' [DESAFIO] Faça um programa que mostre os 10 primeiros elementos da Sequência
de Fibonacci:
1 1 2 3 5 8 13 21...'''
termos = int(input('Digite a quantidade de termos que quer ver: '))
termo = 1
termo_anterior = 0
print(0,end=' ')
print(1,end=' ')
for num in range(3,termos+1):
termo3 = termo_anterior... | false |
940dce299d8c4c9ee07502c6daf12f9933a26ce0 | felipeonf/Exercises_Python | /exercícios_fixação/073.py | 281 | 4.125 | 4 | '''Crie um programa que preencha automaticamente (usando lógica, não apenas
atribuindo diretamente) um vetor numérico com 10 posições, conforme abaixo:
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9'''
lista = []
for num in range(9,-1,-1):
lista.append(num)
print(lista)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.