blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
200951dcb80a93c07f7977e6e3ded87a7fd904f1 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/adrian-led-vazquez-herrera/practica_5/P5_2_1.py | 872 | 4.21875 | 4 | #DAS Práctica 5.2.1
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def num_of_sides(self):
pass
class Triangle(Polygon):
def __init__(self):
self.sides=3
def num_of_sides(self):
return self.sides
class Square(Polygon)... | false |
123a2a8668f3ec4f7e450adb67a93618e91d4027 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/Practica-1/main.py | 408 | 4.3125 | 4 | # Esto es un comentario en Python
# Declaro una variable
x = 5
# Imprimo mi variable
print("x = ", x)
# Operaciones aridmeticas con mi variable
print("x + 5 = ",x + 5) #Suma
print("x - 5 = ",x - 5) #Resta
print("x * 5 = ",x * 5) #Multiplicacion
print("x / 5 = ",x / 5) #Division
print("x % 5 = ",x % 5... | false |
4eda1153098fccefd3e311c6dde550759932a719 | AJChestnut/Python-Projects | /14 Requesting 3 Numbers and then Mathing.py | 2,059 | 4.5625 | 5 | # Assignment 14:
# Write a Python program requesting a name and three numbers from the user. The program will need
# to calculate the following:
#
# the sum of the three numbers
# the result of multiplying the three numbers
# divide the first by the second then multiply by the third
# Print a message greeting the use... | true |
f955b97f3ab252a2885a441f6c99773cd00efed7 | AJChestnut/Python-Projects | /10 Comma Code.py | 2,169 | 4.4375 | 4 | # Assignment 10:
# Say you have a list value like this:
# listToPrint = ['apples', 'bananas', 'tofu', 'cats']
# Write a program that prints a list with all the items separated by a comma and a space,
# with and inserted before the last item. For example, the above list would print 'apples,
# bananas, tofu, and cats'.... | true |
e800aec69c574c6ff705b63f05cd277f2dfe8cb5 | digomes87/tudo-q-der-pra-fazer-js | /py/testesSoltos/listas.py | 1,256 | 4.125 | 4 | # aqui já temos uma lista
type([])
lista1 = [1, 2, 3, 4, 5, 6, 7, 'Diego', 8, 90]
lista2 = ['A', 'B', 'C', 'D']
lista3 = list(range(1, 11))
lista4 = list("ABCDEFGHIJeEEEeee")
lista5 = [2, 432, 12, 54, 65, 3, 56, 234, 24432, 1121]
print(lista1)
print(lista2)
print(lista3)
print(lista4)
print(lista5)
lista5.sort()
pri... | false |
c052253ac099375f8a3d9046395af382dc0c158b | mitchblaser02/Python-Scripts | /Python 3 Scripts/CSVOrganiser/CSVOrganiser.py | 347 | 4.28125 | 4 | #PYTHON CSV ORGANIZER
#MITCH BLASER 2018
i = input("Enter CSV to sort (1, 2, 3): ") #Get the CSV from the user.
p = i.split(", ") #Turn the CSV into tuple.
o = sorted(p) #Set variable o to a sorted version of p.
for i in range(0, len(o)): #Loop for the amount of entries in o.
print(o[i]) #Print out each entry sepe... | true |
4f80de4e3458af59a67a68e96b6b45e1e26bc1e3 | j-sal/python | /3.py | 1,305 | 4.375 | 4 | '''
Lists and tuples are ordered
Tuples are unmutable but can contain mixed typed items
Lists are mutable but don't often contain mixed items
Sets are mutable, unordered and doesn't hold duplicate items,
sets can also do Unions, Intersections, and Differences
Dictionaries are neat
'''
myList = ["coconut","pear","t... | true |
1147a10ab060451acbfe874b78c698435fa592d5 | zmybr/PythonByJoker | /day01-1.py | 1,456 | 4.125 | 4 | #1.温度转换
#C = float(input('请输入一个温度'))
#print((9/5)*C+32)
#2.圆柱体体积
#import math
#pai=math.pi
#radius = float(input("请输入半径"))
#length = float(input('请输入高'))
#area = radius * radius * pai
#volume = area * length
#print("The area is %.4f"%area)
#print("The volume is %.1f"%volume)
#3.英尺转换
#feet = float(input("请输... | true |
21c3ccc8805b353d1c1d2fe92dcf8fbe613b833c | mahesstp/python | /Day3/OOPS/inheritance.py | 716 | 4.1875 | 4 | #!/usr/bin/python
class Parent:
def __init__(self, x=0, y=0):
self.__x = x
self.__y = y
def setValues(self, val1, val2):
self.__x = val1
self.__y = val2
def printValues(self):
print ('Value of x is ', self.__x )
print ('Value of y is ', self.__y )
class C... | false |
7e2fe8e98797d2de13f78b3af3ecbbc6af2f24fd | homeah/myPython | /026.py | 382 | 4.15625 | 4 | '''
【程序26】
题目:利用递归方法求5!。
1.程序分析:递归公式:fn=fn_1*4!
2.程序源代码:
'''
'''
def recursion(n):
if n == 1:
return n
else:
return n*recursion(n-1)
print('5!的结果是%d'%recursion(5))
'''
def recursion(n):
return n if n==1 else n*recursion(n-1)
print('5!的结果是%d'%recursion(5))
| false |
6175197774940e0e5727c59210b9ea73139f6119 | MarioAguilarCordova/LeetCode | /21. Merge Two Sorted Lists.py | 1,812 | 4.15625 | 4 | from typing import List
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def printlist(self, list):
itr = list
while itr:
print(list.val + " , ")
itr = itr.next
def mergeTwoLists(list1, list2):
... | true |
db1dffba9b15cba6aa2536f8f3bc24f6c76bfe55 | allyshoww/python-examples | /exemplos/funcao.py | 1,238 | 4.5 | 4 | # Função é uma sequencia de instruções que realiza uma operação. São blocos de códigos que realizam determinadas tarefas que precisam ser executadas diversas vezes.
# Tem que ser em letras minusculas e underline para espaçamento
# Palavra reservada: def
# Escopo Global: Pode ser acessada por todas as funções que estão ... | false |
8a41efdf82e7a7737cec68b57eba8f5d2f5bce5c | allyshoww/python-examples | /exemplos/classes.py | 893 | 4.4375 | 4 | # Classes definem caracteristicas e o comportamento dos seus objetos. Classe não é objeto.
# Cada caracteristica é representada por um atributo.
# Cada comportamento é estabelecido por um metodo.
# Exemplo:
class Dog():
def __init__(self, nome, raca, idade):
self.nome = nome
self.raca = raca
... | false |
555d058cd1706c702280037b4263de42b8c6c64d | dmserrano/python101 | /foundations/exercises/randomSquared.py | 635 | 4.3125 | 4 | import random;
# Using the random module and the range method, generate a list of 20 random numbers between 0 and 49.
random_numbers = list();
def create_random_list ():
'''
This function creates 20 random numbers from 0-49.
'''
for x in range(0,20):
random_numbers.append(random.randint(0,49))... | true |
f38c54d511dddb4daf577c004168368c6d7d94b8 | Fuchj/Python | /src/FirstDay/列表练习/FirstDay.py | 2,017 | 4.15625 | 4 |
"""列表练习"""
#name = "Hello Python Crash Course world!"
#print(name.title())
#name = "ada lovelace"
#print(name.title())
age = 23
#数字和字符串拼接,会发生错误
#message = "Happy " + age + "rd Birthday!"
#使用str 把非字符串的类型转换为字符串
message = "Happy " + str(age) + "rd Birthday!"
print(message)
print("-------------------------------------... | false |
2b352b8bb78329976f0790e7a499a97e2d2d9dd2 | siawyoung/practice | /problems/zip-list.py | 1,328 | 4.125 | 4 | # Write a function that takes a singly linked list L, and reorders the elements of L to form a new list representing zip(L). Your function should use 0(1) additional storage. The only field you can change in a node is next.
# e.g. given a list 1 2 3 4 5, it should become 1 5 2 4 3
class Node:
def __init__(self, d... | true |
7c77a7a8c7c90c1f626f96f392f3a9e3e6a58b60 | siawyoung/practice | /problems/delete-single-linked-node.py | 674 | 4.15625 | 4 |
# Delete a node from a linked list, given only a reference to the node to be deleted.
# We can mimic a deletion by copying the value of the next node to the node to be deleted, before deleting the next node.
# not a true deletion
class LinkedListNode:
def __init__(self, value):
self.value = value
... | true |
05c6d092439df7574bfb7b265007007b42816154 | siawyoung/practice | /problems/reverse-words.py | 986 | 4.15625 | 4 |
# Code a function that receives a string composed by words separated by spaces and returns a string where words appear in the same order but than the original string, but every word is inverted.
# Example, for this input string
# @"the boy ran"
# the output would be
# @"eht yob nar"
# Tell the complexity of the s... | true |
9b73167d9095286071a4e5d2b9d61d1643ef874d | bluepine/topcoder | /cracking-the-coding-interview-python-master/3_5_myqueue.py | 1,147 | 4.34375 | 4 | #!/usr/bin/env python
"""
Implement a queue with two stacks in the MyQueue class.
This should never be used, though -- the deque data structure from the
standard library collections module should be used instead.
"""
class MyQueue(object):
def __init__(self):
self.first = []
self.second = []
... | true |
b72125acc6f31cb0d2e9a8e1881137c5d6974ae4 | bluepine/topcoder | /algortihms_challenges-master/general/backwards_linked_list.py | 1,474 | 4.125 | 4 | """
Reverse linked list
Input: linked list
Output: reversed linked list
"""
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def __str__(self):
res =... | true |
ccb57c809f7dba7cca387727438fbe8631579269 | bluepine/topcoder | /algortihms_challenges-master/general/matrix.py | 1,706 | 4.21875 | 4 | """
1.7.
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column is set to 0
Idea:
a) Have an additional matrix and go trough all elements in MxN matrix and set zeroes
b) For each element you go trough - check if it is on a 'zero line' (has zero on
it's column or row - do AND... | true |
8dd5870f0967b67a0ad2b81f71d521e6c6657e4d | bluepine/topcoder | /ctci-master/python/Chapter 1/Question1_3/ChapQ1.3.py | 1,529 | 4.125 | 4 | #Given two strings, write a method to decide if one is a permutation of the other.
# O(n^2)
def isPermutation(s1, s2):
if len(s1)!=len(s2):
return False
else:
for char in s1:
if s2.find(char)==-1:
return False
else:
s2.replace(char,"",1)
... | true |
470543e4625aff4f2aeb99636a0880821f36f7ac | WaltXin/PythonProject | /Dijkstra_shortest_path_Heap/Dijkstra_shortest_path_Heap.py | 2,719 | 4.15625 | 4 | from collections import defaultdict
def push(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
shiftup(heap, 0, len(heap)-1)
def pop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate... | true |
33b0b54194338915d510c2b76cf0ada76ac053a6 | digvijay-16cs013/FSDP2019 | /Day_03/weeks.py | 429 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 9 15:56:28 2019
@author: Administrator
"""
days_of_week = input('Enter days of week => ') .split(', ')
weeks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
for index, day in enumerate(weeks):
if day not in days_of_week:
da... | true |
4042f285972f9bdf7d7d6c24cbbe8ae4cfe7baaa | digvijay-16cs013/FSDP2019 | /Day_11/operations_numpy.py | 1,309 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 21 23:29:54 2019
@author: Administrator
"""
# importing Counter from collections module
from collections import Counter
# importing numerical python (numpy) abbreviated as np
import numpy as np
# some values
values = np.array([13, 18, 13, 14, 13, 16, 14, 21, 13])
# c... | true |
35e551aa21266be0b9af0e54b2b205799e5b9b32 | digvijay-16cs013/FSDP2019 | /Day_06/odd_product.py | 332 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 14 14:25:35 2019
@author: Administrator
"""
from functools import reduce
numbers = list(map(int, input('Enter space separated integers : ').split()))
product_odd = reduce(lambda x, y : x * y, list(filter(lambda x: x % 2 != 0, numbers)))
print('product of odd numbers :', ... | true |
9346fd05be19a27fec2239194d70c986cfc3db5e | digvijay-16cs013/FSDP2019 | /Day_01/string.py | 401 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 7 17:44:40 2019
@author: Administrator
"""
# name from user
name = input('Enter first and last name with a space between them : ')
# finding index of space using find method
index = name.find(' ')
# taking first Name and last name separately
first_name = name[:index]
... | true |
689f0134064076fa90882d24fc5af086a42a8978 | digvijay-16cs013/FSDP2019 | /Day_05/regex1.py | 402 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 11 16:04:05 2019
@author: Administrator
"""
# regular expression number
import re
# scan number
float_number = input('Enter anything to check if it is floating point number : ')
# to check match
if re.match(r'^[+-]?\d*\.\d+$', float_number):
# if expression fo... | true |
ad3edf6b16e89cb83c59c1a5c25a03306de64efc | emilianoNM/Tecnicas3 | /Reposiciones/Cuevas Cuauhtle Luis Fernando/Reposicion 13_08_2018/TabladeMultiplicar.py | 242 | 4.125 | 4 | #Este programa crea una tabla de multiplicar con un numero que introduzcas
Numero = int(input("Introduzca el numero que quiera generar la tabla"))
# use for loop to iterate 10 times
for i in range(1,11):
print(Numero,'x',i,'=',Numero*i)
| false |
fe615e7872db45b6fb309c9383f661d9dd1ccb9e | emilianoNM/Tecnicas3 | /RepoEderGLEZ/cumpleaños.py | 304 | 4.125 | 4 |
# coding: utf-8
# In[ ]:
def main():
a_curso = input ("Ingresa el anio en curso: ")
for i in range (3):
nombre = raw_input ("Nombre de la persona: ")
nacimiento = input ("Anio de nacimiento: ")
print nombre, "cumple", (a_curso - nacimiento), "anios en el", a_curso
| false |
98fef15129c66c8a64de2cd051605a7405a202a5 | ElijahMcKay/Blockchain | /standupQ.py | 1,399 | 4.21875 | 4 | """
You've been hired to write the software to count the votes for a local election.
Write a function `countVotes` that receives an array of (unique) names, each one
representing a vote for that person. Your function should return the name of the
winner of the election. In the case of a tie, the person whose name comes... | true |
4c0c8b1478e505dd5734d3e902bea1d520dd80bc | paulonteri/google-get-ahead-africa | /exercises/longest_path_in_tree/longest_path_in_tree.py | 1,489 | 4.21875 | 4 | """
Longest Path in Tree:
Write a function that computes the length of the longest path of consecutive integers in a tree.
A node in the tree has a value and a set of children nodes. A tree has no cycles and each node has exactly one parent.
A path where each node has a value 1 greater than its parent is a path of co... | true |
a099cc0e7d05dc81ab396016072ad08e25ab60d3 | attorneyatlawl/Codewars | /Python/Tribonacci_Sequence.py | 282 | 4.1875 | 4 | ''' Tribonacci sequence'''
def tribonacci(signature, n):
while len(signature) < n:
signature.append(sum(signature[-3:]))
return signature[:n]
# Other
def tribonacci(signature, n):
res = signature[:n]
for i in range(n - 3): res.append(sum(res[-3:]))
return res | false |
3eb607c7fc1499c0d2aa9d28e25c8a32549cab54 | celeritas17/python_puzzles | /is_rotation.py | 634 | 4.25 | 4 | from sys import argv, exit
# is_rotation: Returns True if string t is a rotation of string s
# (e.g., 'llohe' is a rotation of 'hello').
def is_rotation(s, t):
if len(s) != len(t):
return False
if not s[0] in t:
return False
count_length = i = 0
t_len = len(t)
while t[i] != s[0]:
i += 1
while count_lengt... | true |
5fb2788df1a6c3db25a31bfb310813353e6f31db | tjshaffer21/katas | /project_euler/python/p16.py | 575 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Problem 16 - Power digit sum
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
def pow_sum(x, n):
""" Calculate the sum of the power.
Parameters
x : int : The bas... | true |
8fe165a793c2598d567fb11e5b55d238a1e7d6b1 | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/Ruohan/lesson03/list_lab.py | 2,570 | 4.15625 | 4 | #! /usr/bin/env python3
'''Exercise about list'''
#series 1
#Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”.
#Display the list
print('============= series 1 ===============')
list_fruit = ['Apples', 'Pears', 'Oranges', 'Peaches']
print(list_fruit)
#Ask the user for another fruit and add it to t... | true |
cffa371c3a06d349d8f638195dc9c255abb5c47e | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/tammyd/lesson03/strformat_lab.py | 2,226 | 4.375 | 4 | #!/usr/bin/env python3
'''
String Formatting Lab Exercise
'''
#take the following four element tuple: ( 2, 123.4567, 10000, 12345.67)
t = (2, 123.4567, 10000, 12345.67)
#print("My string =", t)
print("Goal: file_002 : 123.46, 1.00e+04, 1.23e+04")
print()
#Task one
#and produce: 'file_002 : 123.46, 1.00e+04, 1... | false |
daeba6dd81960befa2f59d9d98d9b930a3ff923e | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/aravichander/lesson03/strformat_lab.py | 1,052 | 4.1875 | 4 | tuple1 = (2,123.4567,10000, 12345.67)
#print(type(tuple1))
#Spent some time trying to understand the syntax of the string formats
# print("First element of the tuple is: file_{:03}".format(tuple1[0]))
# print("Second element of the tuple is: {0:.2f}".format(tuple1[1]))
# print("Second element of the tuple is: {1:.2f}".... | true |
2869bbf863d02a4c45295e841b3b6a0ee524eb1e | StefaRueRome/LaboratorioVCSRemoto | /main.py | 433 | 4.15625 | 4 | print("Solución de una ecuación cuadrática")
a=int(input("Ingrese el primer valor:"))
b=int(input("Ingrese el segundo valor:"))
c=int(input("Ingrese el tercer valor:"))
d=(((b*b)-(4*a*c))**1/2)
x1=(((-1*b)+(d**1/2))/2*a)
x2=(((-1*b)-(d**1/2))/2*a)
if d>0:
print("La solución positiva es:",x1,"y la solución negativa es:... | false |
e7ac3c7f1d793a46b3f9c3645cb994102c877344 | rayt579/epi_hackathon | /ch16/warmup.py | 1,005 | 4.125 | 4 | '''
Find the maximum sum of all subarrays of a given array of integers
'''
def kadane_algorithm(A):
current_max = A[0]
global_max = A[0]
for i in range(1, len(A)):
current_max = max(A[i], current_max + A[i])
global_max = max(global_max, current_max)
return global_max
import itertool... | false |
0d57a53bcb7165dc4d122e213a2a43e9fb208f4b | spoonsandhangers/tablesTablesTables | /table1.py | 1,454 | 4.375 | 4 | """
Creating tables in Tkinter.
There is no table widget but we can use a function from ttk
called treeview.
You must import ttk from tkinter
Then add a Frame to the root window.
Create a Treeview object with the correct number of columns (see other attributes)
Create a list of headings for the columns
iterate throug... | true |
f30401120620f23c26b3a62a26f20d95253512cd | victorrrp/python-avancado | /python 3/aula18_poo/meta.py | 854 | 4.28125 | 4 | '''
EM PYTHON TUDO É UM OBJETO: incluindo classes.
Metaclasses são as 'classes' que criam classes.
type é uma metaclasse??
'''
class Meta(type): #Criando uma metaclasse
def __new__(mcs, name, bases, namespace):
if name == 'A':
return type.__new__(mcs, name, bases, namespace)
... | false |
78a1be7aaefdd04084cc106ac164e29be1a6c79a | victorrrp/python-avancado | /python 3/aula13_poo/app.py | 618 | 4.21875 | 4 | '''
Polimorfismo de sobreposição: é o principio que permite que classes derivadas de uma mesma
superclasse tenham métodos iguais (de mesma assinatura) mas comportamentos
diferentes.
Mesma assinatura = Mesma quatidade e tipo de parâmetros
'''
#exemplo de polimorfismo
from abc import ABC, abstractmethod
cla... | false |
e64e382a1de818cf5d47d3e4af81e0395c5bf769 | anuj0721/100-days-of-code | /code/python/day-1/FactorialRecursion.py | 246 | 4.1875 | 4 | def fact(n):
if (n < 0):
return "not available/exist."
elif (n == 1 or n == 0):
return 1
else:
return n*fact(n-1)
num = int(input("Enter a number: "))
f = fact(num)
print("factorial of",num,"is ",f)
| true |
84e1af8bef6874e22dc74fd31f75913736989c88 | anuj0721/100-days-of-code | /code/python/day-52/minimum_element_of_main_list_that_is_max_of_other_list.py | 1,084 | 4.1875 | 4 | main_list = [number for number in input("Enter Main list values separated by space: ").split()]
list_i = int(input("How many other list you want to enter: "))
for value in range(1,list_i+1):
globals()['my_list%s' %value] = [number for number in input("Enter values separated by space: ").split()]
#find maximum elem... | true |
9f45e0268108c93f6e2b3fb5d323943300db1617 | anuj0721/100-days-of-code | /code/python/day-60/print_stars_in_D_shape.py | 491 | 4.3125 | 4 | rows = int(input("How many rows?: "))
if rows <= 0:
raise ValueError("Rows can not be negative or zero")
cols = int(input("How many columns?: "))
if cols <= 0:
raise ValueError("Columns can not be negative or zero")
for row in range(0,rows):
for col in range(0,cols):
if (((row != 0 and row != rows-... | true |
ba423af0aeed7a70d4a96bc3e766042c7f3a0569 | anuj0721/100-days-of-code | /code/python/day-12/FirstNevenNaturalNumbersAndInReverseOrder.py | 232 | 4.21875 | 4 | n = int(input("How many even natural numbers you want?: "))
for i in range(1,((2*n)+1)):
if i%2==0:
print(i,end=" ")
print()
print("In Reverse Order-")
for i in range(2*n,0,-1):
if i%2==0:
print(i,end=" ")
| false |
add852bf6dbf84eb3087e565e6b2f2f2229369c6 | t0futac0/ICTPRG-Python | /Selection/selectionQ2.py | 331 | 4.125 | 4 | ## Write a program that asks the user for their year of birth,
## Checks if they are of legal drinking age
## and tells the user to come into the bar.
age_verification = int(input("What is your year of birth? "))
if age_verification >= 2002:
print("Do a U-Turn!")
else:
print("Please come straight through to... | true |
d48fff9caca448449499ef613502d239c110ef09 | t0futac0/ICTPRG-Python | /String Manipulation/Python String Manipulation.py | 349 | 4.46875 | 4 | #Python String Manipulation
#Write a program that asks the user for their full name, splits it up into words and outputs each word on a new line.
#For names with 2 words (eg, 'Fred Frank') this would output Fred, then frank on two lines.
full_name = input("Please enter your full name ")
name_list = full_name.split()
... | true |
99cd74851c03956263024aa1aa6003a492698a9b | trentwoodbury/anagram_finder | /AnagramChecker.py | 1,012 | 4.21875 | 4 | from collections import Counter
class AnagramChecker:
'''
This is a class that is able to efficiently check if two words are anagrams.
'''
def __init__(self):
self.words_are_anagrams = None
def check_if_words_are_anagram(self, word_1, word_2):
'''
Checks if word_1 and word... | true |
45742e4a60ab176f29b0fa51064e06ddad195d22 | cifpfbmoll/practica-6-python-klz0 | /P6E2_sgonzalez.py | 538 | 4.25 | 4 | # Práctica 6 - EJERCICIOS WHILE Y LISTAS
# P6E2_sgonzalez
# Escribe un programa que te pida números y los guarde en una lista.
# Para terminar de introducir número, simplemente escribe "Salir".
# El programa termina escribiendo la lista de números.
lista = []
numero = int(input("Escribe un número "))
print("Cuando hay... | false |
b94dac47b5f8622d93785ca4c2ec9930135b524e | lee-shun/learn_py | /section1/params_fun.py | 1,741 | 4.15625 | 4 | #位置参数
def power(x):
return x*x
print('power={}'.format(power(5)))
#默认参数
def power2(x, n=2):
s = 1
for i in range(n):
i += 1
s = s*x
return s
print('power2={}'.format(power2(6)))
#默认参数的坑
def add_end(L=[]):
L.append('endd')
return L
print(add_end())
"""
当函数定义的时候,动态语言已经将... | false |
c2e2504487ef0213246eed2e75d3a1a76ed5aaa8 | Alexey-Ushakov/practice | /str_tuple_list_dict_set/str.py | 1,839 | 4.21875 | 4 | a = "hello world" # Это строка
print(len(a)) # len это длинна строки
b = "I have Fun"
print(a+b) # Конотация соединение строк так как нет пробела то соединяет слитно
print(a*3) # Умножение, повторяет строку столько сколькон ам надо раз
# Срезы если нам нужно что то взять из строки
print(a[:5]) # В квадратных скобк... | false |
d071703773d8586c8f9547d4397f05f179f7e862 | jttyeung/hackbright | /cs-data-struct-2/sorting.py | 2,247 | 4.4375 | 4 | #Sorting
def bubble_sort(lst):
"""Returns a sorted list using a optimized bubble sort algorithm
i.e. using a variable to track if there hasn't been a swap.
>>> bubble_sort([3, 5, 7, 2, 4, 1])
[1, 2, 3, 4, 5, 7]
"""
sorted_list = []
for i in range(len(lst) - 1):
for j in r... | true |
011419b7055a1fcb8738998c5cd373eb115eb824 | wchen308/practice_algo | /largest_factor.py | 234 | 4.25 | 4 | import math
def largest_factor(n):
"""
Return the largest factor of n that is smaller than n
"""
div = 2
while div <= math.sqrt(n):
if n % div == 0:
return n / div
else:
div += 1
return 1
print(largest_factor(13)) | true |
36058b7dcd271f8672f7265e559935c47c065d7d | Flooorent/review | /cs/leetcode/array/merge_intervals.py | 1,244 | 4.125 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are... | true |
f76fbc46587b2c5c14f7eefcbe1a1f5da3218f05 | khcal1/Python-Basics | /Dinner Party.py | 1,649 | 4.65625 | 5 | '''This program displays the uses of List
Start by inviting three people to a dinner party'''
import os
import sys
import random
guest_list = ['Socrates', 'King Tutt', 'Bas']
for guest in guest_list:
print("{}, Welcome to the party.".format(guest))
'''One person cannot make it to the party.
Delete that... | true |
3beea4e5175b907e8ce2e5c5f0e84b6434ba8a97 | jbrandes/PythonPLCLogic | /plc.py | 733 | 4.34375 | 4 |
def AND(IN1, IN2):
if IN1 == "on" and IN2 == "on":
print("motor is on")
else:
print("motor is off")
def NOT(IN1, IN2):
if IN1 == "on":
print("motor is off")
else:
print("motor is on")
def OR(IN1, IN2):
if IN1 or IN2 == "on":
... | false |
3866457894ea4ef4cc1586c71fead89ff192a3e6 | pranaysapkale007/Python | /Basic_Python_Code/Basic Codes/Prime Number.py | 239 | 4.1875 | 4 | # number which is only divisible to itself
# 2, 3, 5, 7, 15, 29
number = 3
flag = False
for i in range(2, number):
if number % i == 0:
flag = True
if flag:
print("Number is not prime")
else:
print("Number is prime")
| true |
2e2f54a81a31c5d557e044b4392a929979b0dc44 | pranaysapkale007/Python | /Basic_Python_Code/Basic Codes/Palindrome.py | 368 | 4.25 | 4 | # String Palindrome
str = 'nayan'
pal_str = str[::-1]
if str == pal_str:
print("String is palindrome")
else:
print("String is not palindrome")
# Number palindrome
number = 12321
rev = 0
num = number
while num != 0:
rem = num % 10
rev = rev * 10 + rem
num = num // 10
if number == rev:
print... | false |
36390b2bd3234a89c3d601e26fb3b65ebe76f748 | iftikhar1995/Python-DesignPatterns | /Creational/Builder/ComputerBuilder/SubObjects/hard_disk.py | 895 | 4.25 | 4 | class HardDisk:
"""
HardDisk of a computer
"""
def __init__(self, capacity: str) -> None:
self.__capacity = capacity
def capacity(self) -> str:
"""
A helper function that will return the capacity of the hard disk.
:return: The capacity of the hard disk.
:rt... | true |
64e3cc39235c702f5324759a285d73871e86a624 | boris-kolesnikov/python_exercises | /if-elif-else_(or-and).py | 1,559 | 4.21875 | 4 | #Посиановка задачи:
# Определить возрастную категорию по значению возраста
if
#ЕСЛИ возраст < 5:
# print('Baby')
elif
#ИНАЧЕ ЕСЛИ возраст < 12:
# print('Schoolboy')
elif
#ИНАЧЕ ЕСЛИ возраст < 19:
# print('Guy')
else
#ИНАЧЕ:
# print("Возрослый чел")
#---------------------... | false |
dc1f8e95e109b452741be9c9e55eb5d2bb286cfd | khinthetnwektn/Python-Class | /Function/doc.py | 622 | 4.28125 | 4 | def paper():
''' 1. There will ve situations where your program has to interest with the user.
For example, you would want to take some results back.'''
''' 2. There will be situations where your program has to interest with the user.
For example, you would want to take some results back. '''
print(paper.__doc__)... | true |
6372e0d8949a79d7142020d7ccbbd6fe222e8e15 | vasimkachhi/Python_Code_Sneppets | /webCrawlingbs4.py | 1,992 | 4.125 | 4 | """
This code crawls two sites and extracts tables and its content using beautiful soup and urllib2
Crawling or web scrapping example
1) http://zevross.com/blog/2014/05/16/using-the-python-library-beautifulsoup-to-extract-data-from-a-webpage-applied-to-world-cup-rankings/
2) https://en.wikipedia.org/wik... | true |
a44243ca5d9fd973635179eadec648c70123479b | diegohsales/EstudoSobrePython | /Any e All.py | 1,825 | 4.15625 | 4 | '''
Python tem duas funções muito interessantes: ANY e ALL.
-> A função 'ANY' recebe uma lista (ou outro objeto interável) e retorna
'True' se algum dos elementos for avaliado como 'True'.
-> Já 'ALL' só retorna 'True' se todos os elementos forem avaliados como 'True' ou se ainda se o iterável está vazio. Veja:
>... | false |
01d508d1de383063706939f10b4536af1ac98f0c | diegohsales/EstudoSobrePython | /Map.py | 1,278 | 4.4375 | 4 | """
Map
Com Map, fazemos mapeamentos de valores para função.
import math
def area(r):
# Calcula a area de um circulo com um raio 'r'. #
return math.pi * (r ** 2)
print(area(2))
print(area(5.3))
raios = [2, 5, 7.1, 0.3, 10, 44]
#Forma Comum de calcular a área
areas = []
for r in raios:
areas.append((... | false |
cc992a4441c076d3403b1c48de01c215caa24353 | diegohsales/EstudoSobrePython | /Exercicio 02 Herança.py | 1,262 | 4.46875 | 4 | """
Crie a classe Animal com os atributos nome, cor e numero_patas. Crie também o método
exibir_dados, que imprime na tela uma espécie de relatório informando os dados do animal.
Crie uma classe Cachorro que herda da classe Animal e que possui como atributo adicional a raça do cachorro.
Crie também o método exibir_da... | false |
5db5a914e667c8b19ae0c67de1ebf085e60931c9 | eclipse-ib/Software-University-Fundamentals_Module | /03-Lists_Basics/2-Strange_zoo.py | 492 | 4.125 | 4 | ## Решение по условие, в което е показано как се сменят отделните елементи в даден лист:
tail = input()
body = input()
head = input()
meerkat = [tail, body, head]
#№ meerkat[0], meerkat[-1] = meerkat[-1], meerkat[0]
meerkat[0], meerkat[2] = meerkat[2], meerkat[0]
print(meerkat)
## Много опростен вариант:
tail = in... | false |
6c41734cd5f2e23ee52c2152d3676ff0bb00a42e | durgeshtrivedi/Python | /FlowControl.py | 586 | 4.40625 | 4 | # -*- coding: utf-8 -*-
#%%
def flowControl():
name = input("what is your name")
age = int(input("whats your age,{}".format(name)))
if age > 18:
print("You have the rights for voting")
else:
print("Come after {}".format(18 - age))
if 16 <= age <= 65:
prin... | true |
023a932e90e2c2bfcb8f60916bf3f876d6031a8f | ygkoumas/algorithms | /match-game/__main__.py | 1,820 | 4.21875 | 4 | # Simulate a card game called "match" between two computer players using N packs of cards.
# The cards being shuffled.
# Cards are revealed one by one from the top of the pile.
# The matching condition can be the face value of the card, the suit, or both.
# When two matching cards are played sequentially, a player is c... | true |
a09dd584e8e71badeaba7b5473bea545db030e26 | niuonas/DataStructuresPython | /Range.py | 795 | 4.71875 | 5 | #Sequence representing an arithmetic progression of integers
#Range determines what arguments mean by counting them
# range(stop) - only one element
# range(start,stop) - two elements
# range(start,stop,step) - three elements
range(5) #the value provided as argument is the end of the range but is not included
... | true |
922d2a3006bf9c2a159dd9ebce4f127c1e0e5984 | RBazelais/coding-dojo | /Python/python_fundementals/StringAndList.py | 1,698 | 4.28125 | 4 | '''
Find and replace
print the position of the first instance of the word "day".
Then create a new string where the word "day" is replaced
with the word "month".
'''
words = "It's thanksgiving day. It's my birthday,too!"
str1 = words.replace("day", "month")
#print str1
#Min and Max
#Print the min and max values in a... | true |
ef6582736336126502424ec7a7252b0df6723fa4 | gortaina/100DaysOfCode | /code/Calcuradora_Simples.py | 903 | 4.21875 | 4 |
def start():
print("\n******************* Python Calculator *******************")
print("Selecione o número da operação desejada:\n")
print("1 - Soma")
print("2 - Subtração")
print("3 - Multiplicação")
print("4 - Divisão")
def calcular(option, num1, num2 ):
print("\n")
if op... | false |
2eb391025229727a3c28bc4ccc37d389eff8c234 | Masheenist/Python | /lesson_code/ex42_Is-A_Has-A_Objects_and_Classes/ex42.py | 2,010 | 4.21875 | 4 | # Make a class named Animal that is-a(n) object
class Animal(object):
pass
# Make a class named Dog that is-a(n) Animal
class Dog(Animal):
def __init__(self, name):
# from self, get the name attribute and set it to name
self.name = name
# Make a class named Cat that is-a(n) Animal
class Cat(A... | true |
b1dce264796bd68b9397b48e5b7a4685827f0745 | Masheenist/Python | /lesson_code/ex20_Functions_and_Files/ex20.py | 1,119 | 4.25 | 4 | # get argv from sys module
from sys import argv
# have argv unpack to argument variables
script, input_file = argv
# fxn takes an open(ed) file as arg & reads it and prints
def print_all(f):
print(f.read())
# seek(0) moves to 0 byte (first byte) in the file
def rewind(f):
f.seek(0)
# readline() reads one... | true |
d99f911cf8714289dc500c1f0712f705a7bd34a4 | Masheenist/Python | /lesson_code/ex44_Inheritance_vs_Composition/ex44b.py | 681 | 4.65625 | 5 | # OVERRIDE EXPLICITLY
# =============================================================================
# The problem with having functions called implicitly is sometimes you want
# the child to behave differently.
# In this case we want to override the function in the child, thereby replacing
# the functionality. To do... | true |
17bbdd091df55ce376ba30b2412d3a25e3f3d885 | jonathangray92/universe-simulator | /vector.py | 2,100 | 4.34375 | 4 | """
This module contains a 2d Vector class that can be used to represent a point
in 2d space. Simple vector mathemetics is implemented.
"""
class Vector(object):
""" 2d vectors can represent position, velocity, etc. """
#################
# Magic Methods #
#################
def __init__(self, x, y):
""" Vect... | true |
30fb93535b4d03784f87e40067091aa9c3349b93 | rudyredhat/PyEssTrainingLL | /Ch06/06_01/constructor.py | 1,637 | 4.34375 | 4 | #!/usr/bin/env python3
class Animal:
# here is the class constructor
# special method name with __init__ = with acts as an initializer or constructor
def __init__(self, type, name, sound): # self is the first argument, that whats makes it a obj method
# we have **kwargs and we can set the default valu... | true |
0b65a0a5a1d3446f7156ed36d54c86653f637119 | brentshermana/CompetativeProgramming | /src/puzzles/InterviewKickstart/dynamic_programming/count-ways-to-reach-nth-stair.py | 721 | 4.25 | 4 | # a person can take some number of stairs for each step. Count
# the number of ways to reach the nth step
# there is 1 way to reach the first stair
# there are two ways to reach the second stair
# there are 111 12 21 three ways to reach the third stair
# to formulate this as a table, if we are at step i, which we can... | true |
b4186605cdbb29642bd68ee3731379c18b9d770f | brentshermana/CompetativeProgramming | /src/puzzles/leetcode/leetcode_binarytreelongestconsecutivesequence/__init__.py | 1,618 | 4.1875 | 4 | # Given a binary tree, find the length of the longest consecutive sequence path.
#
# The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
#
# Example 1:
#
# Input... | true |
7427a978ff9bcd065cdc21e70ada6a14f5b823e5 | khinthandarkyaw98/Python_Practice | /random_permutation.py | 681 | 4.15625 | 4 | """
A permutation refers to an arrangement of elements.
e.g. [3,2, 1] is a permutaion of [1, 2, 3] and vice-versa.
The numpy random module provides two methods for this:
shuffle() and permutation().
"""
# shuffling arrays
# shuffle()
from numpy import random
import numpy as np
arr = np.array([1, 2, 3, ... | true |
d24a450b4b9645e09fdf19d679997d9c83e03e2c | khinthandarkyaw98/Python_Practice | /python_tuto_functions.py | 1,472 | 4.4375 | 4 | # creating a function
def my_func():
print("Hello")
my_func()
# pass an argument
def my_function(fname):
print(fname + "Refsnes")
my_function('Emil')
# pass two arguments
def my_function(fname, lname):
print(fname + " " + lname)
my_function('Emil', 'Refsnes')
"""
if you do not know how many ... | true |
ac13bb44dc4a015f00fd70bddc3f9bff608dafaf | khinthandarkyaw98/Python_Practice | /python_tuto_file.py | 1,721 | 4.34375 | 4 | # file
# open('filename','mode')
# opening a file
f = open('file.txt')
# open a file and read as a text
f = open('file.txt', 'rt')
# read the file
f = open('file.txt', 'r')
print(f.read())
# read only parts of the file
f = open('file.txt', 'r')
print(f.read(5))
# return the first characters of the ... | true |
a5115410d54da81229153b78e33b869795ffcb46 | khinthandarkyaw98/Python_Practice | /multiple_regression.py | 2,281 | 4.5 | 4 | # predict the CO2 emission of a car based on
# the size of the engine. but
# with multiple regression we can throw in more variables,
# like the weight of the car, to make the prediction more accurate.
import pandas
# the pandas module allows us to read csv files
# and return a DataFrame object
df = pand... | true |
f287078bdad6f01d1f61cab2b3167ba0538a5d26 | khinthandarkyaw98/Python_Practice | /numpy_summation.py | 703 | 4.3125 | 4 | # add() is done between two elements : return an array
# sum([]) happens over n elements : return an element
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
newarr = np.add(arr1, arr2)
print("add():", newarr)
newarr = np.sum([arr1, arr2])
# note that sum([])
print("sum(): ... | true |
f6940513aac4dd6e5b640244a6d26fd6c66972bf | mfarukkoc/AlgorithmsDaily | /Problem-10/python_utkryuk.py | 358 | 4.15625 | 4 | '''
Author : Utkarsh Gupta
College : Birla Institute of Technology, Mesra
Year/Department : III/IT
E-Mail Id : utkryuk@gmail.com
'''
def reverseString(inputString):
inputWords = inputString.split()
inputWords = inputWords[::-1]
for index in range(len(inputWords)):
print(inputWords[index], end=' ')
... | false |
2bc5ddd31eb3c8b55ae65c73497831e25fa81ed1 | BorisDundakov/Python--Programming-Basics | /02. Conditional Statements-Lab/02. Greater Number.py | 428 | 4.15625 | 4 | # Да се напише програма, която чете две цели числа въведени от потребителя и отпечатва по-голямото от
# двете.
# Примерен вход и изход
# вход:
# 5
# 3
# Изход:
# 5
first_number = int(input())
second_number = int(input())
if first_number > second_number:
print(first_number)
else:
print(second_number)
| false |
4dae3e9211206ce3f4fc3b3633d13cd2054c57f2 | ahmed-gamal97/Problem-Solving | /leetcode/Reverse Integer.py | 569 | 4.15625 | 4 | # Given a 32-bit signed integer, reverse digits of an integer.
# Example 1:
# Input: 123
# Output: 321
# Example 2:
# Input: -123
#Output: -321
# Example 3:
# Input: 120
# Output: 21
def reverse(x: int) -> int:
result = []
sum = 0
is_neg = 0
if x < 1:
x = x * -1
is_neg ... | true |
12c0d1426d06df87835a304862bdd3f83f980001 | daheige/python3 | /part2/yield_demo.py | 1,526 | 4.15625 | 4 | # coding:utf-8
# 在 Python 中,这种一边循环一边计算
# 的机制,称为生成器:generator
# 函数是顺序执行,遇到 return 语句或者最后
# 一行函数语句就返回。而变成 generator 的函数,在每次调用 next() 的时候执行,遇到 yield
# 语句返回,再次执行时从上次返回的 yield 语句处继续执行。
def odd():
print('step1')
yield (1)
print('step2')
yield (2)
o = odd()
print(next(o))
print(next(o))
# 通过迭代器实现反向打印
cla... | false |
67dad33c948cb704c1e09c22299aac2e5bf53eaf | AMAN123956/Python-Daily-Learning | /Day1/main.py | 560 | 4.4375 | 4 | # Print Function
print():
# example:
print("Hello World!!!")
# " " > Tells that it is not a code but it is a string
# String Manipulation
# You can create a new line using '\n'
print("Hello World!\n Myself Aman Dixit!")
# String Concatenation
print("Hello"+"Aman")
# Input Function
#example
name=input("What is your na... | true |
91f1517d926936c6e0e54c8685e23db3a754ee45 | AMAN123956/Python-Daily-Learning | /Day10/docstringmain.py | 478 | 4.25 | 4 | #Docstring
# =================================================================
# Uses:
# 1.Can Also be used as multiline-comment
# 2.Are a way to create a little bit of documentation for our function
# 3.Comes after function definition
#example
def format_name(f_name,l_name):
'''Take a first and last name and for... | true |
8c2fe6dee7e6dbe4dd64751f7c9ce02241923856 | AMAN123956/Python-Daily-Learning | /Day4/lists.py | 407 | 4.3125 | 4 | # Python Lists
# =========================================================================
# Are like array
#Example
fruits=["Aman","Abhishek","Virat"]
# We can use index as negative values
print(fruits[-1])
# it will return Last Value of the List
#Appending items to the end of list
# Syntax: name_of_list.append("it... | true |
7ba10a012f50f3b2e86b97b31570f1090637c288 | CAVIND46016/Project-Euler | /Problem4.py | 592 | 4.125 | 4 | #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def check_Palindrome(_num):
return str(_num) == str(_num)[::-1];
def main():
product = 0;
listPa... | true |
9869e6edbef66fbf51646c8311167180acca98e6 | kandarp29/python | /py20.py | 407 | 4.15625 | 4 | ojjus = []
b = input("number of elements in the list")
b = int(b)
for i in range(0,b):
c = input("Insert list elements = ")
ojjus.append(c)
print("Your list is " ,ojjus)
def sorting(a):
for j in range(0,b):
if a == ojjus[j]:
print("your element is in the list ")
else:... | true |
6da8b025d3ebd4523aac45174c9145a71ff20996 | jessidepp17/hort503 | /assignments/A02/ex06.py | 1,094 | 4.40625 | 4 | # define variables
types_of_people = 10
# x is a variable that ouputs a string with embedded variable
x = f"There are {types_of_people} types of people."
# more variables and their values
binary = "binary"
do_not = "don't"
# y is another sting with embedded variables
y = f"Those who know {binary} and those who {do_not... | true |
204113bb64e0651f3d3d725f85c6b500cfd8b4d8 | YashikaNavin/Numpy | /2.NumpyArray.py | 855 | 4.4375 | 4 | import numpy as np
# Creating numpy array
# 1st way:- create a list and then provide that list as argument in array()
mylist=[1,2,3,4,5]
a=np.array(mylist)
print(a)
# 2nd way:- directly pass the list as an argument within the array()
b=np.array([6.5,7.2,8.6,9,10])
print(b)
# Creating one more numpy array
... | true |
6bfdecf7ceb2e8cb56bfe700e9fc297d4e0db764 | smitacloud/Python3Demos | /02AD/01Collections_container/enum_demo.py | 1,377 | 4.28125 | 4 | '''
Another useful collection is the enum object.
It is available in the enum module, in Python 3.4 and up
(also available as a backport in PyPI named enum34.)
Enums (enumerated type) are basically a way to organize various things.
Let’s consider the User namedtuple. It had a type field.
The problem is, the typ... | true |
244e325d5a0e7a09b4803dad17bb82ccf4de5a3e | smitacloud/Python3Demos | /02AD/03Sequence_Operation/generator_object.py | 610 | 4.53125 | 5 | #Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).
# A Python program to demonstrate use of
# generator object with next()
# A ge... | true |
6f301ecfb26f2282a3af41eecbeb60d0ddfc18de | smitacloud/Python3Demos | /loopsAndConditions/Armstrong.py | 752 | 4.53125 | 5 | '''
A positive integer is called an Armstrong number of order n if
abcd... = an + bn + cn + dn + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
'''
# Python program to c... | true |
13cd22596ee928e94ba041050deaaeaacf8a88c7 | ayman-elkassas/Python-Notebooks | /3-OOP and DSA/6-Stack and queue/Lib/Stack.py | 742 | 4.25 | 4 | class stack:
"""
This is class stack for operations stack
push,pop,top,is_empty,len
"""
def __init__(self):
self._data = []
def push(self,e):
self._data.append(e)
def pop(self):
if self.is_empty():
raise Exception("Empty stack")
return self._data... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.