blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7ea462ab48138a58f7ec2fcc9621c9ff0123b91a | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Trees/Binary Tree To DLL/binary_tree_to_dll.py | 2,995 | 4.3125 | 4 | """
Binary trees are a type of data tree data structure in which a node can only have 0,1 or 2 children only.
Linked list is a type of linear data structure in which one object/node along with data, also contains the address of next object/node.
Doubly linked list is a type of linked list in which a node points to both... | true |
28b801fcac4ab98370601886f27c42a5609535f0 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Backtracking/Sudoku Solver/sudoku.py | 2,810 | 4.125 | 4 | def print_grid(arr):
for i in range(9):
for j in range(9):
print(arr[i][j], end=" "),
print()
# Function to Find the entry in the Grid that is still not used
def find_empty_location(arr, l):
for row in range(9):
for col in range(9):
if arr[row][col] == 0:
... | true |
61cceb2f1eb17b506be7da7bd67c2f8404a6b4ce | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/leetcode/Subtree_of_another_Tree.py | 1,208 | 4.15625 | 4 | # Given two non-empty binary trees s and t, check whether tree t has exactly the same structure
# and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all
# of this node's descendants. The tree s could also be considered as a subtree of itself.
#
# Example 1:
# Given tree s:
#
# ... | true |
de89caf4b942e789f946e8fb69bb933bdb883f9c | bgoonz/UsefulResourceRepo2.0 | /_Job-Search/InterviewPractice-master/InterviewPractice-master/Python/capsLock.py | 517 | 4.15625 | 4 | # Complete the pressAForCapsLock function below.
def pressAForCapsLock(message):
letters = []
found = False
for i in message:
if i is "a" or i is "A":
found = not found
continue
if found is True:
letters.append(i.upper())
else:
lett... | true |
1d52e5100932c35be77dca0eedf505cf6bc6fdae | bgoonz/UsefulResourceRepo2.0 | /_RESOURCES/my-gists/MAIN_GIST_FOLDER/76acedd4d2/76acedd4d2c1d58a424e1fe33a9aa011af6c62d3908fdeee020629a38a6f599f/08-LongestSemiAlternatingSubString.py | 1,861 | 4.28125 | 4 | # You are given a string s of length n containing only characters a and b.
# A substring of s called a semi-alternating substring if it does not
# contain three identical consecutive characters.
# Return the length of the longest semi-alternating substring.
# Example 1: Input: "baaabbabbb" | Output: 7
# Explanati... | true |
215f93970c2e5982b41356f0381d785563c06962 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/my-gists/_CURRENT/edcbe51ff1/prime.py | 261 | 4.21875 | 4 | # if a number is prime or not
def prime_num():
value = int(input('please type a number: '))
for num in range(2,value):
if value % num == 0:
return f'{value} is not a prime number'
return f'{value} is a prime number'
print(prime_num()) | false |
446eded13c97935e5b53597b35ec1118e0a4df91 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/my-gists/ARCHIVE/by-extension/python/merge_sort.py | 1,728 | 4.21875 | 4 | import timeit
from random import randint
def merge_sort(collection, length, counter):
if len(collection) > 1:
middle_position = len(collection) // 2
left = collection[:middle_position]
right = collection[middle_position:]
counter = merge_sort(left, length, counter)
counter ... | true |
891e45259cac6b0f22ac6d993dfb527569b2931b | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/PYTHON_PRAC/learn-python/src/control_flow/test_while.py | 960 | 4.53125 | 5 | """WHILE statement
@see: https://docs.python.org/3/tutorial/controlflow.html
@see: https://docs.python.org/3/reference/compound_stmts.html#the-while-statement
The while loop executes as long as the condition remains true. In Python, like in C, any
non-zero integer value is true; zero is false. The condition may also ... | true |
d729ab8c086b66934ac65d667801a3e8a0b6dcd2 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/algorithms-master/algorithms/graph/prims_minimum_spanning.py | 943 | 4.1875 | 4 | """
This Prim's Algorithm Code is for finding weight of minimum spanning tree
of a connected graph.
For argument graph, it should be a dictionary type
such as
graph = {
'a': [ [3, 'b'], [8,'c'] ],
'b': [ [3, 'a'], [5, 'd'] ],
'c': [ [8, 'a'], [2, 'd'], [4, 'e'] ],
'd': [ [5, 'b'], [2, 'c'], [6, 'e'] ],
... | false |
067b10f83c7b00d42b1d23184af4b6e3ce29a732 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/ashishdotme/programming-problems/python/recursion-examples/06-product-of-list.py | 598 | 4.34375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created by Ashish Patel
Copyright © 2017 ashish.me
ashishsushilpatel@gmail.com
"""
"""
Write the below function recursively
# prod(L): number -> number
# prod(L) is the product of numbers in list L
# should return 1 if list is empty
def prod(L):
product, i = 1,0
... | true |
2f21c4f01170a9826b62ac8773cf607df88b1b88 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/algorithms-master/algorithms/matrix/crout_matrix_decomposition.py | 1,298 | 4.125 | 4 | """
Crout matrix decomposition is used to find two matrices that, when multiplied
give our input matrix, so L * U = A.
L stands for lower and L has non-zero elements only on diagonal and below.
U stands for upper and U has non-zero elements only on diagonal and above.
This can for example be used to solve systems of l... | true |
e00af86d7504f79df399d6008c017ff23a9a36c0 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/stack/valid_parenthesis.py | 556 | 4.125 | 4 | """
Given a string containing just the characters
'(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
The brackets must close in the correct order,
"()" and "()[]{}" are all valid but "(]" and "([)]" are not.
"""
def is_valid(s: str) -> bool:
stack = []
dic = {")": "(",
"}": "{"... | true |
92c60c6141e1215c2d130b9d37bccf2a1e9b8ada | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Arrays/Divisor Sum/divisor_sum.py | 633 | 4.40625 | 4 | """
Aim: Calculate the sum of all the divisors of the entered number and display it.
"""
# function to find out all divisors and add them up
def divisorSum(n):
temp = []
for i in range(1, n + 1):
# condition for finding factors
if n % i == 0:
temp.append(i)
# adding all divisor... | true |
b75d2ff11f681b2d8ceb3896c14de6257e2ed051 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Trees/Expression Tree Evaluation/expression_tree_evaluation.py | 2,499 | 4.625 | 5 | # The expression tree is a binary tree in which each internal node corresponds to the operator like +,-,*,/,^ and
# each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) - 3,5,9,2 will be leaf nodes
# and +,+,* will be internal and root nodes. It can be used to represent an expressi... | true |
e3624ed59b0788f845692017723c3004bf6480fb | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/Overflow/_Learning/02_unordered_lists.py | 1,506 | 4.40625 | 4 | # In order to implement an unordered list, we will construct what is commonly known as a
# Linked List. We need to be sure that we can maintain the relative positioning of the
# items. However, there is no requirement that we maintain that positioning in contiguous
# memory.
# ---------------------------------------... | true |
3761502dbbdf79559a617c2c053a009aaa29e8d1 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/Overflow/Beginners-Python-Examples-master/useful_scripts/password_generator.py | 1,410 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Now-a-days, hashes of our passwords are
# flowing on internet, but to avoid password
# getting discovered by whoever got their hands
# on them, a password should contain:
# 1. Least 8 characters
# 2. No words, instead randomly chosen characters
# 3. Ch... | true |
54b4af276b100f7461cc66399402005726a15b79 | bgoonz/UsefulResourceRepo2.0 | /_OVERFLOW/Resource-Store/01_Questions/_Python/pigLatin.py | 601 | 4.15625 | 4 | # Pig Latin Word Altering Game
# function to convert word in pig latin form
def alterWords():
wordToAlter = str(input("Word To Translate : "))
alteredWord = (
wordToAlter[1:] + wordToAlter[0:2] + "y"
) # translating word to pig latin
if len(wordToAlter) < 46:
print(alteredWord)
else... | true |
bb1075bd0a0bcaf938e4f45eeb705dbdb751df42 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/learn-python/src/functions/test_lambda_expressions.py | 1,342 | 4.59375 | 5 | """Lambda Expressions
@see: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions
Small anonymous functions can be created with the lambda keyword. Lambda functions can be used
wherever function objects are required. They are syntactically restricted to a single expression.
Semantically, they are jus... | true |
893f815791a090130faf05d42e959acd64ebcb25 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/map/word_pattern.py | 1,175 | 4.25 | 4 | """
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a
letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat... | true |
ae27520913674390e809620c54463d13c4e88d63 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CS35_IntroPython_GP/day3/intro/11_args.py | 2,852 | 4.34375 | 4 | # Experiment with positional arguments, arbitrary arguments, and keyword
# arguments.
# Write a function f1 that takes two integer positional arguments and returns
# the sum. This is what you'd consider to be a regular, normal function.
<<<<<<< HEAD
def f1(a, b):
return a + b
=======
def f1(a, b):
return a + b... | true |
de268aba734cf2c5da11ead13b3e83802fd39809 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/ciriculumn/week-17/python/my-intro-BG/2/Module14FileMissingErrorChallengeSolution.py | 1,112 | 4.34375 | 4 | # import libraries we will use
import sys
# Declare variables
filename = ""
fileContents = ""
# Ask the user for the filename
filename = input("PLease specify the name of the file to read ")
# open the file, since you may get an error when you attempt to open the file
# For example the file specified may not exist
#... | true |
a05b3c15ce1004e4df54f1425f52c445d7ee97ef | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Data-Structures/1-Python/strings/decode_string.py | 1,207 | 4.15625 | 4 | # Given an encoded string, return it's decoded string.
# The encoding rule is: k[encoded_string], where the encoded_string
# inside the square brackets is being repeated exactly k times.
# Note that k is guaranteed to be a positive integer.
# You may assume that the input string is always valid; No extra white spaces... | true |
c98e8b74c3374fb90d5ebe1b75c661147b793a10 | bgoonz/UsefulResourceRepo2.0 | /_RESOURCES/my-gists/__CONTAINER/36edf2915f/36edf2915f396/cloning a list.py | 247 | 4.125 | 4 | # Python program to copy or clone a list
# Using the Slice Operator
def Cloning(li1):
li_copy = li1[:]
return li_copy
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
| true |
7c74890541d696de85faa5a01f6838e86909e460 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_Another-One/ArithmeticAnalysis/NewtonRaphsonMethod.py | 944 | 4.125 | 4 | # Implementing Newton Raphson method in python
# Author: Haseeb
from sympy import diff
from decimal import Decimal
from math import sin, cos, exp
def NewtonRaphson(func, a):
""" Finds root from the point 'a' onwards by Newton-Raphson method """
while True:
x = a
c = Decimal(a) - (Decimal(eval... | true |
8d010e336acfd86fe9c1660ec0a8daa5e96c9d97 | DYarizadeh/My-Beginner-Python-Codes- | /Factoral.py | 241 | 4.15625 | 4 | def Factoral():
n = int(input("Input a number to take the factoral of: "))
if n < 0:
return None
product = 1
for i in range (1,n+1):
product *= i
print(i,product)
Factoral()
| true |
91d5e51709447c56ac07dffdddf2af84c08faa98 | hitulshah/python-code-for-beginners | /list.py | 1,485 | 4.3125 | 4 | #fibonacci sequence
# term = int(input('Enter terms:'))
# n1 = 0
# n2 = 1
# if term <= 0 :
# print('Please enter valid term')
# elif term == 1 :
# print(n1)
# else :
# for i in range(term) :
# print(n1)
# x = n1 + n2
# n1 = n2
# n2 = x
#list and files examples
# fnam... | true |
d429625575170c30a12a6fed8853dccc3adf4897 | ojaaaaas/llist | /insertion.py | 1,246 | 4.28125 | 4 | #to insert a node in a linked list
class Node:
def __init__(self,data):
self.data = data
self.next = None
class linkedList:
def __init__(self):
self.head = None
#in the front
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.he... | true |
08e5bc3146fe645582fc769a88c5171b3e81a4ed | myhabr/HW2 | /task2_def_var1.py | 844 | 4.25 | 4 | #Вариант 1, функции
#Даны четыре действительных числа: x1, y1, x2, y2.
#Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2).
#Считайте четыре действительных числа и выведите результат работы этой функции.
x1, y1, x2, y2 = map(float, input("Введите x1, y1, x2, y2 через пробел... | false |
aebf92f28db51768c9367bb0eb9ff48a7a5fe176 | Pyrodox/EasterDay_AlmostAnyYear | /Date_of_Easter.py | 1,388 | 4.25 | 4 | from Shift15.Restart_Function import confirm_restart
print("Calculate the date for Easter for a certain year.")
def easterdate(user_input):
if user_input == 1954 or user_input == 1981 or user_input == 2049 or user_input == 2076:
user_input = user_input - 7
a = user_input % 19
b =... | false |
c20b3f2791e46bdf8d0d36a231cb910eb308d7e6 | exequielmoneva/Small-Python-Exercises | /Small Python Exercises/impresion en triangulo.py | 377 | 4.1875 | 4 | #Calculate and print the number (without using strings) in order to create a triangle until N-1
for i in range(1,int(input("Insert the size of the triangle: "))):
print((10**(i)//9)*i)#This is a way to get the number without the str()
"""
Explanation for (10**(i)//9)*i:
example for number 2:
10**2 = 100
100/22... | true |
5a1b3b9c6ea33d83ac87571a95d83d4f7cf36d5f | daniel-dc-cd/AMMAshi-Saudi-Digital-Academy---Data-Science-Immersive---Bootcamps | /07_week/02_day_assignment/05_intermediate_function_1.py | 2,279 | 4.21875 | 4 | #============================================
# Arwa Ashi - HW 2 - Week 7 - Oct 19, 2020
#============================================
# random.random() returns a random floating number between 0.000 and 1.000
# random.random() * 50 returns a random floating number between 0.000 and 50.000, i.e. scaling the range of r... | true |
7282997020b9c81cf7591af4d63f81a124617bc9 | daniel-dc-cd/AMMAshi-Saudi-Digital-Academy---Data-Science-Immersive---Bootcamps | /07_week/03_day_assignment/assignment_module_1.py | 1,186 | 4.46875 | 4 | #===================================================
# Arwa Ashi - HW 3 - Week 7 - Oct 19, 2020
#===================================================
#==================================================================
# In each cell complete the task using basic Python functions
#=======================================... | true |
97c85007fd951698ae1461901a5b81daf46c59e5 | 2narayana/Automate-the-boring-stuff-with-Python---Practical-projects | /005 - PasswordLocker.py | 1,566 | 4.4375 | 4 | #! python3
# This program saves passwords and sends to the clipboard the desired password when executed.
# To open it, we type "5 - PasswordLocker" <argument> on cmd prompt.
# "5 - PasswordLocker.bat" must be downloaded along with PasswordLocker.py so that the command above works.
PASSWORDS = {'email': 'F7minlBD... | true |
a145c849ce706b4943e412b66b740df18c9c42b0 | AEI11/PythonNotes | /circle.py | 652 | 4.125 | 4 | # create a class
class Circle:
# create a class variable
pi = 3.14
# create a method (function defined inside of a clas) with 2 arguments
#self is implicitly passed
# radius is explicitly passed when we call the method
def area(self, radius):
# returns the class variable on the class * ... | true |
e8fff60820753fa85e18992c5b3b850be01405f1 | Hya-cinthus/GEC-Python-camp-201806-master | /level2/level2Exercises.py | 1,630 | 4.3125 | 4 | #Ex. 1
#write a function that tests whether a number is prime or not.
#hint: use the modulo operator (%)
#hint: n=1 and n=2 are separate cases. 1 is not prime and 2 is prime.
#Ex. 2
#write a function that computes the Least Common Multiple of two numbers
#Ex. 3
#write a program that prints this pa... | true |
6415ea8be338eb96b5d04a49f6241733265954b5 | Hya-cinthus/GEC-Python-camp-201806-master | /level1/noMultiplesOf3-demo.py | 336 | 4.4375 | 4 | #noMultiplesOf3.py
#write a program that prints out all numbers
#from 0 to 100
#that are NOT multiples of 3.
#modulo operator: the remainder of a division
#print(3%3) #gives us 0
#print(4%3) #gives us 1
#print(5%3) #gives us 2
#print(6%3) #gives us 0 (6 is divisible by 3)
x = 0
for x in range(101):
if (x%3!=0):
... | true |
08ebfd6a2aa1f2dd12850d272b99609b3a0e8a84 | tatsuyaokunaga/diveintocode-term0 | /03-02-python-set.py | 1,217 | 4.28125 | 4 | course_dict = {
'AIコース': {'Aさん', 'Cさん', 'Dさん'},
'Railsコース': {'Bさん', 'Cさん', 'Eさん'},
'Railsチュートリアルコース': {'Gさん', 'Fさん', 'Eさん'},
'JS': {'Aさん', 'Gさん', 'Hさん'},
}
def find_person(want_to_find_person):
"""
受講生がどのコースに在籍しているかを出力する。
まずはフローチャートを書いて、どのようにアルゴリズムを解いていくか考えてみましょう。
"""
# ここにコードを書いてみ... | false |
b274ae7106e79fb4d9a8185fd5af8046c75b3982 | spyderlabs/OpenSource-2020 | /Python/bubble_sort.py | 2,385 | 4.28125 | 4 | """
This is a function that takes a numeric list as a parameter and returns the sorted list.
It does not modify the given list, as it works with a copy of it.
It is a demonstrative algorithm, used for informational and learning purposes.
It is open to changes, but keep the code clear and... | true |
f2871acea16906fa59c0d086375ae0fe1975f937 | spyderlabs/OpenSource-2020 | /Python/binary_search.py | 1,968 | 4.28125 | 4 | print('''INSTRUCTIONS FOR ADAPTED CODE:
can run a binary search in the following ways:
1) in python shell:
run code as is
2) in your terminal:
open a command line / terminal
cd to the path of binary_search.py
type your list (e.g. 1 2 4 10 12) and key (e.g. 4) in t... | true |
37c0b5c7bff1a01f8ff8f4220ca0813e12e45137 | RajatRajdeep/DSA | /Sorting/insertion_sort.py | 358 | 4.25 | 4 | def insertion_sort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = i-1
while val<arr[j] and j>=0:
arr[j+1] = arr[j]
j-=1
arr[j+1] = val
return arr
if __name__ == "__main__":
arr = [1, 2, 0, 10, 5, 0, -1, -100, 19, 10, 0]
print("Using In... | false |
0ba8ab8dd079c11acd0440120bdaf321250b7c15 | Deepanshus98/D_S_A | /btLEFTVIEWOFBT.py | 1,160 | 4.28125 | 4 | # A class to store a binary tree node
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
# Recursive function to print the left view of a given binary tree
def leftView(root, level=1, last_level=0):
# base case:... | true |
31c35ef90615947354bc91315d77e85935ce1922 | Deepanshus98/D_S_A | /BSTsearchgivenkeyinBST.py | 1,700 | 4.25 | 4 | # A class to store a BST node
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
# Recursive function to insert a key into a BST
def insert(root, key):
# if the root is None, create a new node and return it
... | true |
52014cac130bed41ee581f4656a31cbf4009276b | garethkusky/CityCourseSpring | /week8/eliminateDupes.py | 743 | 4.21875 | 4 | __author__ = 'acpb968'
#Write a function that returns a new list by eliminating the duplicate values in the list. Use the
#following function header:
#def eliminateDuplicates(lst):
#Write a test program that reads in a list of integers, invokes the function, and displays the result.
#Here is the sample run of the progr... | true |
f3c08fc78df72a2000b8b69d6e5024f5b0006694 | zenmeder/leetcode | /222.py | 1,307 | 4.125 | 4 | #!/usr/local/bin/ python3
# -*- coding:utf-8 -*-
# __author__ = "zenmeder"
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def countNodes(self, root):
"""
:type root: TreeNode
... | false |
cb620a7862c383c7a43123f2c3c9bf0473e3db60 | DiksonSantos/GeekUniversity_Python | /157_Tipagem_de_Dados_Dinamixa_x_Estatica.py | 531 | 4.125 | 4 | """
Tipagem Dinamica -> Quer dizer que não precisa definir uma variavel x=10 como inteira,
o Python já sabe disso. Não é como no Java por exemplo.
Tipagem Estatica -> Java , que já define na criação da variavel qual sera seu tipo Ex:
int, str, e por ai vai.
Como esta linguagem (Java) por exemplo, é compilada, O Java ... | false |
fdd12c6a9553c670c3a6dac9e03db551e202e698 | DiksonSantos/GeekUniversity_Python | /Continuacao_Do_Curso_Em_Python_3_8/Aula_167_OperadorWalrus.py | 619 | 4.40625 | 4 | '''
Permite fazer a atrb e retorno de val numa unica expressão
'''
#Sintax:
# -> variavel := expressão
print(nome := "Dikson")
#3.7
print(nome, 'Santos')
'''
#3.7
cesta = []
fruta = input('Fruta: ')
while fruta != 'Jaca':
cesta.append(fruta)
fruta = input('Informe a fruta: ').capitalize()
if fruta == ... | false |
431587b9650f3ba79d44cd5522c5ed4f67669931 | DiksonSantos/GeekUniversity_Python | /37_Modulo_Collections_Counter.py | 1,279 | 4.15625 | 4 | from collections import Counter
'''A Função Counter enumera as ocorrencias dentro de Tuplas Dicionarios Ou Listas (qualquer
um destes (ou os ITERAVEIS)'''
lista = (1,1,1,1,1,2,2,2,2,23,3,3,3,3,3,4,4,4,4,45,5,5,5,5,)
res = Counter(lista)
print(res) #Imprimiu -> 1 apareceu 5 vezes. 3= 5 Ocorrencias. E assim por diante
... | false |
6634a1bb9b694dd57b222e06598f10ca7d2485ca | DiksonSantos/GeekUniversity_Python | /57_Set_Comprehension.py | 860 | 4.34375 | 4 | #Set Comprehension
lista = [1,2,3]
set = {1,2,3}
num = {num for num in range(0,9)}
#print(num)
numeros = {x**2 for x in range(10)}
#print(numeros)
#Convertendo Dicionario em Lista:
#No caso da variavel 'numeros' NÃO deu certo. Precisam haver chaaves e valores para se especificar que se quer.
chave_valor = {'Chave... | false |
239e12a7516b0d1217ef1585ca81db8ce03ce270 | DiksonSantos/GeekUniversity_Python | /131_Escrevendo_Em_Arquivos_CSV.py | 2,152 | 4.125 | 4 | """
# Writer gera Um Objeto para que possamos escrever num arquivo CSV.
#Writerow -> Escreve Linha Por Linha. Este método Recebe Uma Lista.
from csv import writer
# Aqui na abertura o 'w' Se usado Num mesmo arquivo (Já escrito), vai apaga-lo e Re-escrever Tudo.
# O 'a' Acrescenta o que for digitado de novo ao que já ... | false |
ec8d40b6b6ccd56c2762f861b966a5eee56904a4 | DiksonSantos/GeekUniversity_Python | /23_AND_OR_NOT_IS.py | 1,058 | 4.375 | 4 | '''
Estruturas Logicas
'''
'''
numeros = int(input("Digite_Numero"))
#numeros = [10,20,30]
Mais_Numeros = [10,40,50]
if numeros not in Mais_Numeros:
print("Não Tem")
else:
print("Tem")
'''
'''
for x in numeros:
if x in Mais_Numeros:
print("Tem")
if x not in Mais_Numeros:
print("Não Te... | false |
01be969de4bcf42b9d0227b7629baa5cec4b98e3 | tonyraymartinez/pythonProjects | /areaCalc.py | 1,649 | 4.21875 | 4 | import math
shape = raw_input("What shape will you be getting the area for?\n"+
"enter 'r' for rectangle,\n"+
"enter 's' for square,\n"+
"enter 'c' for circle,\n"+
"enter 'e' for ellipse\n"+
"enter 't' for triangle\n: ")
shape = s... | true |
89f1563c1efac611e9df0e3dd06327762a221a81 | vnpavlukov/Study | /Books/2_Vasilev_Python_on_exaples/Test_13_3.18_proizvodnaya.py | 656 | 4.15625 | 4 | def D(f): # функция для вычисления производной
def df(x, dx=0.001):
return (f(x + dx) - f(x)) / dx
return df
def f1(x): # функция для дифференцирования
return x ** 2
def f2(x):
return 1 / (1 + x)
def show(F, Nmax, Xmax, dx, f):
for i in range(Nmax + 1):
x = i * Xmax / Nmax
... | false |
1992808b41d66492a3180d7e832509a10d730ec8 | vnpavlukov/Study | /Geekbrains/2 четверть/html_css/1 четверть/Основы языка Python/pavlukov_vladimir_dz4/task_5_sum_of_numbers.py | 751 | 4.15625 | 4 | """5. Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные
числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка.
Подсказка: использовать функцию reduce()."""
from functools import reduce
even_lis... | false |
7cf88548d9e1f63dc4531020d4620234eccd2852 | vnpavlukov/Study | /Geekbrains/1 четверть/Основы языка Python/pavlukov_vladimir_dz1/task_5_economic_efficiency.py | 1,403 | 4.21875 | 4 | """5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает
фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибы... | false |
c0b8f30f7560d6f0fef0ca9cb7202a050758d896 | glenjantz/DojoAssignments | /Python/pythonfundamentals/trypython/tuplepractice.py | 465 | 4.1875 | 4 | capitals = {} #create an empty dictionary then add values
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"
# print capitals
# print capitals["svk"]
# for data in capitals:
# print data
# for key in capitals.iterkeys():
# print key
# for val in capitals.itervalues():
# ... | false |
4ff3a8c5abab7e8f59c7151d15dc9a74a0dd7ff0 | glenjantz/DojoAssignments | /pythonreview/oop/car.py | 1,349 | 4.15625 | 4 | # Create a class called Car. In the__init__(), allow the user to specify the following attributes: price, speed, fuel, mileage.
# If the price is greater than 10,000, set the tax to be 15%. Otherwise, set the tax to be 12%.
# Create six different instances of the class Car. In the class have a method called display_al... | true |
da0157620558c8403cb9ce95cb9cc6ef883c4b58 | mmweber2/hackerrank | /dropbox.py | 1,850 | 4.21875 | 4 | # Based on a problem from Dropbox:
# http://hr.gs/redbluebluered
def wordpattern(pattern, input, word_map=None):
"""Determines if pattern matches input.
Given a pattern string and an input string, determine if the pattern matches the input,
such that each character in pattern maps to a substring of in... | true |
b12a2d50c75c115b4141a90ecb3228e97678ef12 | 3people/sorting-visualizer | /sorting.py | 1,557 | 4.125 | 4 | from animate import draw
def bubbleSort(data):
data_length = len(data)
for i in range(data_length - 1):
for j in range(data_length - i - 1):
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
draw(j+1, data)
def selectionSort(data):
data_l... | false |
bf556141a20e2fe990dd93a720de386c23623877 | aktersabina122/Story_Generator_Python | /Story_generator_Python.py | 1,162 | 4.4375 | 4 |
# Challenge One (Input and String Formatting)
# You and a partner will try to use your knowledge of Python to create a MadLib function.
# HOW-TO: Create a multi-line string variable called my_story which contains a short story about an animal in a specific borough of New York, performing some action involving o... | true |
0698789bdda90a3f1b455a79375c6950c6d63bd9 | caalive/PythonLearn | /stroperate/shoppingcar2.py | 1,570 | 4.125 | 4 |
product_list = [('Iphone',5900),
('Mac Pro',12000),
('Coffee',50),
('Book',40)]
shopping_list = [];
def print_product_list():
for index,item in enumerate(product_list):
print(index,item)
def print_shopping_list():
for item in shopping_list:
pr... | true |
d06ee8dbbe3ee90a32dea1db820f7dc9102e4eb9 | wbabicz/lpthw-exercises | /ex15.py | 681 | 4.3125 | 4 | # from sys import argv
# script, filename = argv
# # Opens the filename passed in and assigns it to the variable txt.
# txt = open(filename)
# # Prints out the name of the file.
# print " Here's your file %r:" % filename
# # Reads the text from file and prints it.
# print txt.read()
#print "Type the fil... | true |
01217e399dc5d841f9423affbf46f513c574ec88 | Darshan-code-tech/CMPE282 | /set_get.py | 637 | 4.1875 | 4 | class Getter_Setter(object):
def __init__(self,name,age):
self.name = name
self.age = age
self.__var = 13
def college(self):
print(self.name , self.age)
def setter(self,nums):
self.__var = nums
def getter(self):
return self.__var
if __n... | false |
1ceeab4b174534c56451b46d31881141a641f2d2 | Shruthi410/coffee-machine | /main.py | 2,462 | 4.21875 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
... | true |
ea2adc967d52fdd81ba44c29677ccba708393979 | JB0925/Python_Syntax | /words.py | 991 | 4.375 | 4 | from typing import List
my_words = ['cat', 'dog', 'ear', 'car', 'elephant']
def uppercase_words(words: List[str] = my_words) -> None:
"""Print out each string in a list in all caps"""
for word in words:
print(word.upper())
print(uppercase_words())
def only_words_that_start_with_e(words: List[str] =... | true |
72c0ab964261776ef9d679c41932c345fd3dbdd5 | Rikoairlan57/Mesin-Sorting | /app.py | 1,603 | 4.21875 | 4 | from selection_sort import selectionsort
from bubble_sort import bubblesort
from merge_sort import mergesort
from insertion_sort import insertionsort
while True:
print("# Menu")
print("1. Selection Sort")
print("2. Bubble Sort")
print("3. Merge Sort")
print("4. Insertion Sort")
print("5. Credi... | false |
2f94e530bd1c00a5b185f33996d7eb3f64879d36 | AnupBagade/Hackerrank | /Algorithms/String/reverse_string.py | 341 | 4.375 | 4 | """
Reverse a string using recurssion
"""
def reverse_string(s):
if len(s) == 0:
return s
else:
return reverse_string(s[1:]) + s[0]
if __name__ == '__main__':
input_string = input('Please enter string to be reversed ')
result = reverse_string(input_string)
print('String reversed ... | true |
2472183f0d0853dfe2a3949e784b8bdc5d23f289 | AnupBagade/Hackerrank | /Algorithms/DailyinterviewPro/longest_consecutive_sequence.py | 1,206 | 4.28125 | 4 | """
You are given an array of integers. Return the length of the longest
consecutive elements sequence in the array.
For example, the input array [100, 4, 200, 1, 3, 2] has the longest consecutive
sequence 1, 2, 3, 4, and thus, you should return its length, 4.
def longest_consecutive(nums):
# code.
print longest_... | true |
04633470b57fcf55cae2fd005a87fed153ab1509 | eidehua/ctci-practice | /Python/Data Structures/Arrays and Strings/1.1.py | 2,839 | 4.3125 | 4 | # Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
# assumption: assume uppercase and lowercase are different characters
def has_unique_chars(str):
counts = {} # dictionary to see if we have seen the character already
for i in range... | true |
f24cdb1fe4f60c375ecdc0d39ce7d32d7ee561de | Logeist/Projects | /Solutions/calc.py | 458 | 4.125 | 4 | def main():
a = float(input("Enter your first term: "))
b = float(input("Enter your second term: "))
op = input("Enter your operation (valid: + - * /): ")
for i in op:
if i == '+':
result = a + b
print(result)
elif i == '-':
result = a - b
print(result)
elif i == '*':
result = a * b
print(re... | false |
0809ca6802fee1cc1ef0974245103df2d39998c4 | insidepower/pythontest | /s60/009stringMani.py | 718 | 4.28125 | 4 | txt = "I like Python"
print txt[2:6] # like
print txt.find("like") # 2
if txt.find("love") == -1:
print "What's wrong with you?"
print txt.replace("like", "love") ## new string
print txt.upper() # I LIKE PYTHON
print "Length", len(txt) ## 13
txt2 = ""
if txt2:
print "txt2 contains characters"
el... | true |
46bc17759e7b3472aa698890b6efb858a43cef88 | Snehasis124/PythonTutorials | /ForLoop.py | 332 | 4.4375 | 4 | #10TH PROGRAM
#INTRODUCTION TO FORLOOP
new_list = ['Hello' , 'Good Morning']
word = input("Add your word ")
new_list.append(word)
for value in new_list:
print(value)
# A DEMO PROGRAM
def menu(list, question):
for entry in list: print( 1 + list.index(entry), print (")") + entry )
return input(question) -... | true |
2287851d9eae7e8571f9b5af63db2d5d9fd800f1 | jamiejamiebobamie/CS-1.3-Core-Data-Structures | /project/CallRoutingProject_scenario1.py | 1,719 | 4.28125 | 4 | """
SCENARIO #1
As there is no order to the routes in the route file, the entirety of the file
has to be read.
Open the file. Iterate through it. Searching each digit of each route.
If the program reaches the end of a route, we check to see if that route is cheaper than the current
lowest price and change the lowest ... | true |
ab289ec04193676086b1d75f52bcb24277a51d3e | go2bed/python-simple-neural-network | /com.chadov/MathFormulaNeuralNetwork.py | 1,608 | 4.25 | 4 | from numpy import *
# Teaching the computer to predict the output
# of a mathematical expression without "knowing"
# exact formula (a+b)*2
class NeuralNetwork(object):
def __init__(self):
random.seed(1)
self.weights = 2 * random.random((2, 1)) - 1
# Takes the inputs and corresponding
# ... | true |
3a0bddbcaf7d7237f96b889d784d988007b52000 | EvgenMaevsky/prometheus_py | /super-fibonacci.py | 308 | 4.125 | 4 | def super_fibonacci(n,m):
fibonacci_list=[]
for step in range(m):
fibonacci_list.append(1)
for j in range(n+1):
last_element = 0
for i in range(m):
last_element+=fibonacci_list[i+j]
fibonacci_list.append(last_element)
return(fibonacci_list[n-1])
print(super_fibonacci(9, 3)) | false |
c280d8d38c950ece6999026b6aa9705c35a24e21 | josethz00/python_basic | /numbers.py | 723 | 4.25 | 4 | import math
pi = math.pi
print('{:.2f}'.format(pi)) #formating decimal numbers by the right way
print(f'{pi:.4f}') #formating decimal numbers by a simple way
num1 = input("Please enter the first number") #this way, the value will be gotten as default(as a string)
num2 = input("Please enter the second number") #this ... | true |
950d8358a2248895e9262524ce4a657150a26276 | cvvlvv/Python_Exercise | /Day_2.py | 688 | 4.125 | 4 |
# coding: utf-8
# Day 2:
# Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display them.
# In[ ]:
def PrimeFactors ():
n = int(input("Please give a number."))
PrimeFactors = []
prime = []
for i in range(2,n+1):
for j in range(2,i):
... | true |
2a7c353e880dfc5d4212f874ecac167e484b0fd9 | LouiseCerqueira/python3-exercicios-cursoemvideo | /python3_exercicios_feitos/Desafio065.py | 785 | 4.21875 | 4 | #Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média
#entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário
#se ele quer ou não continuar a digitar valores.
soma = 0
contador = 0
media = maior = menor = 0
resp = 'S'
whil... | false |
be93860585ad761e0d7ec698b524d8736735f00b | LouiseCerqueira/python3-exercicios-cursoemvideo | /python3_exercicios_feitos/Desafio059.py | 1,055 | 4.28125 | 4 | # Crie um programa que leia dois valores e mostre um menu na tela:
#[1] somar [2] multiplicar [3] maior [4] novos números [5] sair do programa
#Seu programa deverá realizar a operação solicitada em cada caso
from random import randint
val1 = int(input('Valor 1: '))
val2 = int(input('Valor 2: '))
print('='*10)
print('... | false |
39eda1352d4fee20921bd18bdeb7d4cbf9c1cc3b | xytracy/python | /ex15.py | 358 | 4.25 | 4 | from sys import argv
script,filename=argv
txt= open(filename)
#open is a command taht reaads our text file
print"here's your file %r:" %filename
print txt.read()
#the "." (dot) is to add a command
print"type the filename again:"
file_again=raw_input(">")
txt_again=open(file_again)
print txt_again.... | true |
acedccda8b6286d03e1813e0df26c8ff05565e6b | danielgulloa/CTCI | /Python/Chapter1/check_Permutation.py | 459 | 4.25 | 4 | '''
Implement a function which reverses a string
(The original question is Implement a function void reverse(char+ str) in C or C++ which reverses a null-terminated string)
'''
def reverse(mystring):
newstr="";
n=len(mystring)
for i in range(n):
newstr+=mystring[n-i-1]
return newstr;
testCases=['anagram', 'hel... | true |
42e2b68c7dcf1e750f63220c8441f7296c337b37 | HarishGajjar/Python-Projects-for-beginners | /calculator.py | 416 | 4.28125 | 4 | num1 = float(input("Enter first number: "))
op = input("Enter operator sign: ")
num2 = float(input("Enter second number: "))
if op == "+":
print(num1, "+", num2 ,"=", num1+num2)
elif op == "-":
print(num1, "-", num2 ,"=", num1-num2)
elif op == "*":
print(num1, "*", num2 ,"=", num1*num2)
elif op =... | false |
980d1824dc8c6d9ecd0744025d777ccc0c559465 | mcdonald5764/CTI110 | /P5T2_FeetToInches_DarinMcDonald.py | 492 | 4.3125 | 4 | # Convert inches to feet
# 10/30
# CTI-110 P5T2_FeetToInches
# Darin McDonald
#
# Set a conversion value
# Get input from the user on how many feet there are
# Multiply feet and the conversion varible to get feet to inches
# Display how many inches per foot
inches_per_foot = 12
def main():
feet ... | true |
2b9f0439ddf165d662c5c8e9d351f23105e6adf5 | mcdonald5764/CTI110 | /P3HW2_Shipping_McDonald.py | 1,215 | 4.375 | 4 | # CTI-110
# P3HW2 - Shipping Charges
# Darin McDonald
# 9/27
#
# Get a number of pounds input from the user
# Check to see if the weight is less than or equal to 2
# Display the cost of the weight multipled by the first rate per pound
# Check to see if the weight is more than 2 but less than or equal to 6
#... | true |
39800d6716379faff17289213dbd0c9da03dca1b | Chayanonl3m/BlackBelt_level1 | /workshop_assign/workshop1.py | 351 | 4.40625 | 4 | birthday ={
"Albert Einstein" : "9/12/1995",
"Benjamin Franklin" : "16/2/1990",
"Ada Lovelace" : "26/11/2011",
}
print ("Welcome to the birthday dictionary. We know the birthdays of: ")
for key,value in birthday.items():
print (key)
name = input("Who's birthday do you want to look up?")
if name in bir... | false |
3a05a1b5aa614dff3bc38af5550c24787799b870 | gaul/src | /interview/needles.py | 1,094 | 4.15625 | 4 | #!/usr/bin/env python
'''\
Given two strings, remove all characters contained in the latter from
the former. Note that order is preserved. For example:
"ab", "b" -> "a"
"abcdabcd", "acec" -> "bdbd"
What is the run-time of your algorithm? How much memory does it use? Is it
optimal?
linear search... | true |
08ac0896c2ba4ffa89ecccca61971fb93c1db3ab | negaryuki/phyton-class-2019 | /Homework/Assignment - BMI.py | 493 | 4.34375 | 4 | print("Welcome to Negar's BMI calculator !\n (^o^)/")
print('Please enter your weight(Kg):')
weight = float(input())
print('Almost there, now please enter your height(m):')
height = float(input())
BMI = weight / (height * height)
print('and your BMI is: ', BMI)
if BMI <= 18.5:
print('Result is : Underweight :(')... | true |
d078650393b437da6f97ab813e133f232c466912 | kmusgro1/pythonteachingcode | /P1M4kristymusgrove.py | 695 | 4.125 | 4 | # [ ] create, call and test the str_analysis() function
statement = ""
def str_analysis(statement):
while True:
statement = input("enter a word or number: ")
if statement.isdigit():
statement=int(statement)
if statement > 99:
print(statement,"is a bi... | true |
e432237f67c107fe532b66635511262226b941be | vpc20/python-strings-and-things | /CharacterFrequency.py | 1,473 | 4.28125 | 4 | # Write a function that takes a piece of text in the form of a string and returns the letter
# frequency count for the text. This count excludes numbers, spaces and all punctuation marks.
# Upper and lower case versions of a character are equivalent and the result should all be in
# lowercase.
#
# The function should r... | true |
fea80af6d6eeaae82c2ca1dbdcc09824037d6a10 | lorian-fate/environment | /FILE/files/proof_project.py | 2,142 | 4.125 | 4 |
#Ejercicio 3
#Escribir un programa que guarde en un diccionario los precios de las frutas de la tabla,
#pregunte al usuario por una fruta, un número de kilos y muestre por pantalla el precio
#de ese número de kilos de fruta. Si la fruta no está en el diccionario debe mostrar un
#mensaje informando de ello.
#Fruta... | false |
3a71f044ad80d32140424a35875893031f4628a5 | Enid-Sky/python-fundamentals | /appendMethod.py | 729 | 4.75 | 5 | # Call .append() on an existing list to add a new item to the end
# With append you can add integers, dictionaries, tuples, floating points, and any objects.
# Python lists reserve extra space for new items at the end of the list. A call to .append() will place new items in the available space.
mixed = [1, 2] #... | true |
4e81722ba13316ddac1e06937e2cd90648b46bbd | rlaecio/CursoEmVideo | /aulas/aula07a.py | 658 | 4.125 | 4 | n1 = float(input('Digite o primeiro numero: '))
n2 = float(input('Digite o segundo numero: '))
s = n1 + n2
print('A soma de {} e {} é igual a {}' .format(n1, n2, s))
s = n1 - n2
print('A subtração de {} por {} é igual {}' .format(n1, n2, s))
s = n1 * n2
print('A mutiplicação de {} por {} é igual a {}' .format(n1, n2, s... | false |
ed3dbf83cd4ff785dcff60effe7a85128d81f0bf | nniroula/Python_Data_Structures | /26_vowel_count/vowel_count.py | 870 | 4.125 | 4 | def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
new_dict = dict()
for letters in phrase:
... | false |
d3168910671560a02d8267ebf6dcecf09ef156b1 | Eli-liang-liang/python_code | /Algorithms/queue.py | 931 | 4.15625 | 4 | class Queue():
# 初始化队列为空列表
def __init__(self):
self.queue1 = []
# 判断队列是否为空,返回布尔值
def is_empty(self):
pass
# 返回队列头部元素(即将出队的那个)
def top(self):
return(self.queue1[0])
# 返回队列的大小
def size(self):
return len(self.queue1)
# 把新的元素堆进队列里面(程序员... | false |
2d14fbb76b0c71fadb9a4ab965b5b6e3d31924dd | ellelater/Baruch-PreMFE-Python | /Level_1/Level_1_ROOT_FOLDER/1.2/1.2.10/n1.2.10.py | 827 | 4.4375 | 4 | """
This program demonstrates the time cost of creating lists with for-loop and comprehension.
"""
import time
def main():
# 10a creates the list with for-loop
start1 = time.time()
lst1 = []
for i in range(10000000):
if i % 10 == 0:
lst1.append(i)
print "Time cost of loop:", t... | true |
6900f2506f65c3924e81c990fb17ad572af5f0f6 | ellelater/Baruch-PreMFE-Python | /level4/4.1/4.1.1/4.1.1_main.py | 2,468 | 4.5625 | 5 | '''
This program is to demonstrate string functions.
'''
s = ' The Python course is the best course that I have ever taken. '
# 4.1.1 a Display the length of the string.
print 'The length of the string is {0}'.format(len(s))
# 4.1.1 b Find the index of the first 'o' in the string.
print "The index of the first 'o... | true |
0f518da02a2c3835460a45a752ab4a6f2cceddd3 | 530893915/Algorithm-and-data-structure- | /排序/快速排序(Python程序员面试算法宝典).py | 1,329 | 4.15625 | 4 | #coding:utf8
# 快速排序:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。
# 从数列中挑出一个元素,称为 “基准”(pivot);
# 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;
# 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
# 这里的代码演示的是两头向中间扫描进行排序
def quick_sort(lists,left... | false |
d4b5a7c35bef700a79030ff18060cb42998b43d2 | haibincoder/PythonNotes | /leetcode/478.py | 1,451 | 4.28125 | 4 | """
478. 在圆内随机生成点
给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。
说明:
输入值和输出值都将是浮点数。
圆的半径和圆心的 x、y 坐标将作为参数传递给类的构造函数。
圆周上的点也认为是在圆中。
randPoint 返回一个包含随机点的x坐标和y坐标的大小为2的数组。
示例 1:
输入:
["Solution","randPoint","randPoint","randPoint"]
[[1,0,0],[],[],[]]
输出: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]
示例 ... | false |
53fdc52d3af5394a3dcf8ace9ad9c3335b25a6da | haibincoder/PythonNotes | /leetcode/0867.py | 913 | 4.3125 | 4 | """
给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。
矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
输入:matrix = [[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
"""
from typing import List
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[in... | false |
318db59f35f6b6334ff53123ba857a79e7cd0be5 | danielambr/Curso-Python | /Aula11.py | 669 | 4.125 | 4 | nome = str(input("Insira seu nome\n")).strip() #o método remove os espaços antes do nome
print(f"Olá {nome}")
nome2 = str(input("Insira seu nome\n")).strip("n") #o método remove os espaços
print(f"Olá {nome2}")
nome3 = str(input("Insira seu nome\n")).capitalize() #o método coloca a primeira letra em maiúsculo
nome4... | false |
0f778b2a6514a9a7b2218dd688c789f8f09d70fd | bohdan-holodiuk/python_core | /lesson5/hw5/Counting_sheep.py | 842 | 4.3125 | 4 | """
Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).
For example,
[True, True, True, False,
True, True, True, True ,
True, False, True, False,
True, False, False, True ,
True... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.