blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4d31976d15ea95738eb2fb85f9ac83846519cff1 | sanshitsharma/pySamples | /leetcode/rotate_list.py | 2,599 | 4.03125 | 4 | #!/usr/bin/env python
'''
Problem #61
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example... |
9b72a44ded8cefd98ae6d1d098748a68d229fcc1 | BlakeBagwell/week_one | /Beginning/solutions/guess_julie2.py | 1,257 | 4.03125 | 4 | import random
secret_number = random.randint(1, 10)
count = 4
print "I am thinking of a number between 1 and 10."
print "You have 5 guesses left."
while count >= 0:
while True:
try:
guess = int(raw_input("What's the number? "))
break
except ValueError:
print "That's n... |
64eab1af99025285536311c6d28156e72d2c3848 | basupandey/Python | /compare.py | 327 | 4.15625 | 4 | num1 = int(input("Enter the first number "))
num2 = int(input("Enter the second number "))
num3 = int(input("Enter the last number "))
if num1 > num2:
if num1>num3:
g=num1
else:
g=num2
else:
if num2>num3:
g=num2
else:
g=num3
print("The greatest number is:"+g)
print(type(... |
8e86a9eae23105d5e1fdce77bdef7411d41f3808 | Niikcety/HackBG | /Week3/Monday/cash_desk.py | 2,935 | 3.625 | 4 | class Bill:
def __init__(self, amount):
if amount < 0:
raise ValueError('Negative Value')
elif not isinstance(amount, int):
raise TypeError('Amount not an integer')
else:
self.amount = amount
def __int__(self):
return self.amount
def __st... |
3ad5aadddb71767c05c8ae4293677bc1c427a4b4 | dendisuhubdy/Xpedite | /scripts/lib/xpedite/analytics/treeCollections.py | 8,478 | 3.875 | 4 | """
Module to build a hierarchical categories of collections
TreeCollection is a hierarchical structure, where a collection is recursively
broken into sub-collections, based on arbitrary classifiers.
The sub-collections are stored as children of the source collection
and will only contain a subset of object in the sou... |
56904c1e2e0161a34b44ba7a0cc605c0682826da | lightmen/leetcode | /python/tree/binary-tree-level-order-traversal.py | 678 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
self.ret = []
if root is None:
return self.ret
q = [roo... |
6b1ff1a9ca2a776e49e3f6ac4ecb29d983634513 | DavidirwinNI/Grok-Introduction-to-Programming-Python | /3 – Making decisions/3 - In the black.py | 96 | 3.734375 | 4 | n = int(input('Number: '))
if n >= 0:
print('In the black :)')
else:
print('In the red :(')
|
bac34b6ec37a30fa9f1951604c519dd675cbc0a4 | magmom7/algo | /queue/17608.py | 292 | 3.53125 | 4 | import sys
height = []
N = int(sys.stdin.readline())
n = current_h = before_h = 0
for i in range(N):
height.append(int(sys.stdin.readline()))
for _ in range(N):
current_h = height.pop()
if current_h > before_h:
n += 1
before_h = current_h
print(n)
|
58db77e5a2fc0a49e7cbf2390c2116973d5cec28 | kadhirash/leetcode | /problems/group_anagrams/solution.py | 1,206 | 3.90625 | 4 | import collections
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# group anagram strs together, in any order
# only lower-case english letters -> 26
# each freq. of letters in each word repeats only once
# pu... |
1945994d36ed104c37f94d2918c502cc8d9240bc | subnr01/Programming_interviews | /programming-challanges-master/codeeval/096_swap-case.py | 697 | 4.28125 | 4 | #!/usr/bin/env python
"""
Swap Case
Challenge Description:
Write a program which swaps letters' case in a sentence. All non-letter characters should remain the same.
Input sample:
Your program should accept as its first argument a path to a filename. Input example is the following
Hello world!
JavaScript ... |
9624dacb88c49f4b2b84aeae3bb666843a71243e | Secret-Python-Project/snake | /snake.py | 3,551 | 3.640625 | 4 | import curses
from curses import wrapper
from random import randint
# Game Configuration
play_space_h = 20
play_space_w = 40
timer = 2000
game_tick = 100
class Snake: # A class is needed so that we can spawn a new snake object in our game, perhaps when Life Lost?
head = 'O' # A class variable shared by all inst... |
d3e9789dedf1d4f95170372af235aac0f7778925 | daniel-reich/turbo-robot | /EWZqYT4QGMYotfQTu_13.py | 2,299 | 4.1875 | 4 | """
Tap code is a way to communicate messages via a series of taps (or knocks) for
each letter in the message. Letters are arranged in a 5x5 _polybius square_ ,
with the letter "K" being moved to the space with "C".
1 2 3 4 5
1 A B C\K D E
2 F G H I J
3 L M N O P
4 Q R S ... |
0c9bdb0fa0a63400fb9338e658dc95502136dca5 | banthaherder/machine-learning-coursework | /p1-data-preprocessing/data_preprocessing_template.py | 933 | 3.515625 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np # A library of mathmetical tools!
import matplotlib.pyplot as plt # A library for plotting data!
import pandas as pd # A library for importing and managing datasets!
# Import a dataset (DON'T FORGET TO SET THE W.D.)
dataset = pd.read_csv('Data... |
0a01dcacf3fd2b8563c79db976256db9039f2990 | ksdfg/mit-stuff | /t9/ai/a_star.py | 5,429 | 4.125 | 4 | from copy import deepcopy
from typing import List, Optional
class Node:
def __init__(self, state: List[List[str]], level: int, goal: List[List[str]], parent=None):
"""
Initialize the node with the state, level of the node and the calculated f-score
:param state: Matrix representing the giv... |
688c89451b753cee4fcdc8bab501546b1ebb229a | jkaalexkei/TrabajosEnPython | /ejemplos/miprimerarcihvo.py | 755 | 4.0625 | 4 | print ("hola mundo")
#TIPOS DE DATOS EN PYTHON
PYTHON ES CASE SENSITIVE
TIPOS DE DATOS
STRING "...", '...', """...""", '''...'''
COMANDO TYPE PERMITE IMPRMIR EL TIPO DE DATO DE UN VALOR
UNIR O CONCATENAR STRING:
"Palabra 1" + "Palabra 2"
->int,
->float,
->boolean,
-->None
->LIST(LISTAR DATOS) EJEMPLO --> [10,"20"... |
92b72bd477a039d4ba200d5be0f1219f31d63478 | uvenil/PythonKurs201806 | /___Python/Carsten/p03_lambda/m04_filtern.py | 543 | 3.578125 | 4 | celsius = [0.7, 2.1, 4.2, 8.2, 12.5, 15.6, 16.9, 16.3, 13.6, 9.5, 4.6, 2.3]
def mindestens15(temperatur):
return temperatur >= 15
def zwischen5und10(temperatur):
return 5<= temperatur and temperatur <= 10
def filtern(liste, kriterium):
gefiltert = []
for element in celsius:
if krit... |
4c08fcf76dd204f33a405c6440fbefd74a2795f7 | mllewellynjones/command_line_tasks | /filehandler.py | 2,541 | 3.71875 | 4 | import pickle
from logging import FileHandler
class FileHandler():
"""
Responsible for reading and writing to a pickle file
Args:
filename (str): the file for this filehandler to use
"""
def __init__(self, filename):
self.filename = filename
def parse_fi... |
4be3c36f22190d822ae4be3bc764213eb0248657 | ccollado7/Curso-Python-Pildoras-Informaticas | /15. Video 18 - Bucles - continue, pass y else/practicas_bucles1.py | 727 | 3.921875 | 4 | nombre = "Pildoras Informaticas" #Defino la variable nombre y contiene un string
print(len(nombre)) #Cuento la cantidad de caracteres. El espacio en blanco tambien se cuenta
# A continuacion utilizando el bucle for cuanto la cantidad de caracteres de la variable nombre. Da igual resultado que utilizar len()
contad... |
df6e28be93d3e14739219a797022200ab94c0962 | padamcs36/Introduction_to_Python_By_Daniel | /Chapter 9 GUI's Programming Using TKinter/MenuDemo.py | 2,760 | 3.875 | 4 | from tkinter import *
class SimpleCalculator:
def __init__(self):
root = Tk()
root.title('Simple Calculator')
mainMenu = Menu(root)
root.config(menu = mainMenu) #Display the menu bar.
# Create a pull-down menu, and add it to the menu bar
OperationSubMenu ... |
ffafefb5a5cbf34d3002725d87fe4a0bac204344 | badubizzle/pythonds | /lesson9/trie.py | 6,806 | 4.03125 | 4 | class TrieNode(object):
def __init__(self, character=None):
self._children = {}
self.is_word = False
self.word = None
self.character = character
class MyTrie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
parent_node = self.ro... |
106bc497fec81823250a248de6912a5c3458fcbf | Omkar-M/Coffee-Machine | /Problems/The Louvre/task.py | 377 | 3.9375 | 4 | class Painting:
def __init__(self, title1, artist1, year1):
self.title = title1
self.artist = artist1
self.year = year1
def print_value(self):
print(f'"{self.title}" by {self.artist} ({self.year}) hangs in the Louvre.')
title, artist, year = [input() for x in range(3)]
paintin... |
2131d52ceddf151df410db8f97b3d0c561d0947a | KBerUX/OODPy | /Functions.py | 326 | 3.75 | 4 | # always start function with def and then function name
# def functionname():
# code has to be indented inside the function
# two or more words use underscore and use lowercase
def say_hi(name, age):
return print("Hello " + name + " you are " + str(age))
# this calls the function
say_hi("Adi", 21)
say_hi("Kist"... |
d917134f18b3577878803a4899e96bc3b7e597e2 | Shishiranjan/Python-Basics | /lists_tuples.py | 494 | 3.9375 | 4 | #Lists and tuples
# Tuple are immutable i.e. it cannot be changed further
'''
def example():
return 14, 16
a, b = example()
print(a)
print(b)
'''
Ccranjan = [6, 5, 9, 1, 7, 13, 15, 17]
print(Ccranjan)
print(Ccranjan[5])
Ccranjan.append(16)
print(Ccranjan)
Ccranjan.insert(4,23)
print(Ccran... |
e565000b4b604e43b2c1342d300f717d37a1abe9 | liaowucisheng/self-study-Python | /01周/python程序/找出所有水仙花数.py | 448 | 3.78125 | 4 | """
水仙花数也被称为超完全数字不变数、自恋数、自幂数、阿姆斯特朗数,它是一个3位数,
该数字每个位上数字的立方之和正好等于它本身,例如:$1^3 + 5^3+ 3^3=153$。
"""
# python中,'//'是整除地意思,例如:345 // 10 = 34, 5434 // 1000 = 5
for i in range(100, 1000):
j = i % 10
k = i // 10 % 10
l = i // 100 % 10
if i == j ** 3 + k ** 3 + l ** 3:
print(i)
|
fa328bc84e1edfcd7b544604c575ffdd9bb5cb59 | miaopei/MachineLearning | /LeetCode/github_leetcode/Python/palindrome-linked-list.py | 1,154 | 4.09375 | 4 | # Time: O(n)
# Space: O(1)
#
# Given a singly linked list, determine if it is a palindrome.
#
# Follow up:
# Could you do it in O(n) time and O(1) space?
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
class Solution:
# @par... |
226d57b498e22d194272b7cb3a3bb320d4ea5d59 | ruhsane/CS2.2-Graphs-Challenges | /challenge_1/c1_tests.py | 3,115 | 3.671875 | 4 | import unittest
from challenge_1 import Graph
from challenge_1 import Vertex
class VertexTest(unittest.TestCase):
def test_init(self):
# Tests the initialization of the Vertex class
v1 = "a"
vertex = Vertex(v1)
self.assertEqual(vertex.id, "a")
self.assertDictEqual(vertex.... |
9b5d044401f6397336f93befec1c3daec3ce1176 | felipesantos10/Python | /mundoUM/aula7.py | 787 | 4.1875 | 4 | #Nessa aula, vamos aprender quais são os operadores aritméticos do Python e também sua ordem de precedência dentro de expressões matemáticas. Veja como funcionam os operadores de adição, subtração, multiplicação, divisão, exponenciação e quociente na linguagem Python.adores
# + adição
# - subtração
# * multiplicaçã... |
7bdd0e085aa615dae165d3554accb8232d87f88b | kiranparakkalkalam/graphsearch | /src/graph_utils.py | 626 | 3.75 | 4 | import random
import networkx as nx
from graph import Graph
def generate_random_graph(no_of_nodes, probability=0.5):
'''
This generates random graph based on the Erdos-Renyl G(N, P) model
An edge exists between nodes for a probability P.
:Parameters
:no_of_nodes: <int> : No of vertices in the gra... |
eee6ece1e401e57e73c484041f3560b51e046e5f | Alferdize/Data-Structure-and-Algorithms | /Hackerrank/Pattern_Matching.py | 796 | 3.65625 | 4 | class Solution:
def solve(self, text, pattern):
def search(i, j, mapping):
if i == len(text) or j == len(pattern):
return i == len(text) and j == len(pattern)
elif pattern[j] in mapping:
word = mapping[pattern[j]]
return (
... |
b4b8eac35d7f7f1b0d5df332b74130a7c425179e | tech-cow/big4 | /algorithm_AKA_谷歌我来了/cc150/chapter1_array/3_urlify.py | 1,729 | 4.09375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#================================================================================
# Author: Yu Zhou
# CTCI 1.3 URLify:
# Write a method to replace all spaces in a string with '%20'.
# You may assume that the string has sufficient space at the end to hold
# the additional ... |
be615729ffbe94b0feb37acede7700f123241708 | jxhangithub/lintcode | /Medium/170. Rotate List/Solution.py | 945 | 4.0625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: the List
@param k: rotate to the right k places
@return: the list after rotation
"""
def rotateRight(self, head, k):
... |
6bfac036bda04a037f4672c418134ffbab5ae7ce | HalfMoonFatty/Interview-Questions | /128. Longest Consecutive Sequence.py | 1,961 | 3.78125 | 4 | '''
Problem:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
'''
'''
Solution 1:
Time: O(n)
... |
a2dacd9e37eda61aa557277691c904e6612641e5 | Cleber-Woheriton/Python-Mundo-1---2- | /desafioAula042.py | 970 | 4.0625 | 4 | import time
#(Desafio 42) Refaça o desafio 35, acrescentando o recurso de informar qual tipo de
#triãngulo será formado. "Equilátero- Todos os lados iguais\ Isósceles- Dois lados iguais\
# Escaleno- Todos os lados diferentes."
print('-='*10, '\033[30;43m Área do Triângulo\033[m', '=-'*10)
valor = [[], [], []]
for x in... |
703b846804532e2ae655a9652f9dbece9e30040d | candopi-team1/Candopi-programming101 | /7_data_structures_and_algorithms/sorts_python/merge_sort.py | 3,386 | 4.09375 | 4 | """
// ==> #
function ==> def
==> nothing
} ==>:
&& ==> and
concat ==> extend
push ==> append
"""
def merge(leftA, rightA):
results= []; leftIndex= 0; rightIndex= 0;
while (leftIndex < len(leftA) and rightIndex < len(rightA) ) :
if( leftA[leftIndex]<rightA[rightIndex... |
0a9580f657cbd2fb0862fb087d3a18d1c8a447be | ryf123/interview | /airbnb_2d_iterator.py | 2,128 | 3.953125 | 4 | # Given an array of arrays, implement an iterator class to allow the client to traverse and remove elements in the array list. This iterator should provide three public class member functions:
# boolean hasNext()
# return true or false if there is another element in the set
# int next()
# return the value of the n... |
1fffc8203a7e6dce43442fe4c25803c1e5da94d1 | Srajangpt1/SER-574_RedTeam | /github_module/metadata_analysis/commit_frequency.py | 4,482 | 3.75 | 4 | #!/usr/bin/env python
"""
Implementation of an internal API for analyzing frequency of commits for a user
in a git project.
"""
__author__ = "Ruben Acuna"
__copyright__ = "Copyright 2019, SER574 Red Team"
import datetime
import sqlite3
def get_commit_count_interval(git_id, username, interval_start, interval_end... |
c6e28b432fa231a0356c979b34f23bfa6b015767 | angelika22/problemele_1-6 | /prob 3.py | 96 | 3.59375 | 4 | l=5
P=12*l
A=6*(l**2)
V=(l**3)
print("P=", 12*l)
print("A=", 6*(l**2))
print("V=", (l**3)) |
72fc8869ba07c4bdfbeb0555e34c95e548dbbd6c | mlleo/algo_study | /greedy/algo_study_greedy_8.py | 197 | 3.515625 | 4 | n = int(input())
coin_list = list(map(int, input().split()))
coin_list.sort()
result = 1
for coin in coin_list:
if result < coin:
break
result += coin
print(result)
|
5ea74685617e7d5bceaddb01dfc81dd0c37e5f2f | RobertNguyen125/Datacamp---manipulatingDataFrame | /4_categoricalGroupby/13_groupbyAndFilteringPratise.py | 1,310 | 3.8125 | 4 | import pandas as pd
# using .apply()
titanic = pd.read_csv('/Users/apple/desktop/manipulatingDataFrames/dataset/titanic.csv')
print(titanic.head())
# analyse the survival rates from 'C' deck, containing most passengers
# groupby('sex') then use apply
by_sex = titanic.groupby('sex')
def c_deck_survival(gr):
c_pa... |
2579ee5c5f1cf2d4006eed08227bb029e93b7b07 | EoJin-Kim/CodingTest | /구현/럭키 스트레이트.py | 186 | 3.546875 | 4 | n=input()
result1=0
result2=0
for i in n[:len(n)//2]:
result1+=int(i)
for i in n[len(n)//2:]:
result2+=int(i)
if result2==result1:
print("LUCKY")
else:
print("READY") |
0eed8c7121d63f02b372f0d8a0c0af56a7803da5 | najeex/Competitive-Programming | /10. Number Theory - 1 Primes and Factorization/Optimized_prime_factorization.py | 202 | 3.59375 | 4 | N = int(input())
factors = []
i = 2
while i*i<=N:
if N%i == 0:
while N%i == 0:
factors.append(i)
N //= i
i+=1
if N!=1:
factors.append(N)
print(factors)
|
65cbecf20280ef6df874cfdd1cf2c10d4926cef1 | DongChanKIM2/Algorithm | /SWEA/SWEA_2005_파스칼삼각형2.py | 397 | 3.578125 | 4 | T = int(input())
for tc in range(1, T + 1):
N = int(input())
triangle = []
for i in range(N):
triangle.append([1] * (i + 1))
print(triangle)
for i in range(2, N):
for j in range(1, i):
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
print(triangle)
... |
3ac6906e7066b9042fed7bfe949c8d020a0a3a0a | avoss19/Module-9 | /9.3.2/Euler6.py | 686 | 3.890625 | 4 | # Project Euler
# Problem 6 - Sum square difference
# https://projecteuler.net/problem=6
# Engineering 2 9.3.2
# Created by Andrew Voss
# Create list with numbers 1-10
a = []
i = 1
while i <= 10:
a.append(i)
i += 1
# Create second list with numbers 1-10
b = a
# sum of "a" and square it
# The square of the ... |
f1d832ec44e444e540e0ffa33024a85c70b17147 | tloader11/TICT-V1PROG-15 | /Les 6/6_3.py | 406 | 3.546875 | 4 | invoer = "5-9-7-1-7-8-3-2-4-8-7-9"
getallen = invoer.split("-")
getallen.sort()
for i in range(0,len(getallen)):
getallen[i] = int(getallen[i])
print("Gesorteerde list van ints:",getallen)
print("Het grootste getal is",invoer[-1],"en het kleinste getal is",invoer[0])
print("Aantal getallen:", len(getallen) ,"en Som... |
b773db8e472e94c31bbe3c8660e4871b9c299be0 | StefanoChiodino/pin-generator | /src/rules/test_reverse_sequence.py | 408 | 4.0625 | 4 | from src.helpers import get_pin_digits
def test_reverse_sequence(pin):
""" Raise ValueError if reversed digits in the PIN are consecutive. """
digits = get_pin_digits(pin)
reverse_digits = digits[::-1]
for i in range(0, len(reverse_digits) - 1):
if reverse_digits[i] + 1 != reverse_digits[i + 1... |
2310333c7473fca046479085e7b8f8fddc306906 | bwbryant1/School_Projects | /bitwise_encryption/bitwise_encryption.py | 4,112 | 3.9375 | 4 | """
Credits = {"author_name": "Brandon Bryant", "date": "3/31/2017", "description": "A short program to perform bitwise operations on RGB values of pixels in a PNG","resources_used":"python 2.7,PIL"}
"""
import sys
import random as rand
from PIL import Image
DEBUG = False
#DEBUG = True
def main_pro():
mode = "" #We ... |
fb9dc12e823c6bfd773b8c26f74ac051e2025f14 | kcarollee/Problem-Solving | /Python/practice_stuff/intermediate_py/stack_review.py | 1,327 | 3.640625 | 4 | #An exception class dealing with empty sequencies
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def pop(self):
if self.is_empty(... |
83451b17596bafeda10a91dc3563f1ae208c4711 | nandadao/Python_note | /note/download_note/first_month/day07/demo01.py | 186 | 4.0625 | 4 | """
for for
练习:exercise01
"""
# 外层循环控制行
for r in range(3):
# 内层循环控制列
for c in range(5):
print("*", end=" ")
print() # 换行
|
2b8b687524a6ea4685567ca91553cbc00d1e119b | escuelainformatica/python16agosto | /grafico.py | 694 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np # rapido
import pandas as pd # potencia
plt.rcdefaults()
fig, ax = plt.subplots() # figura, y el eje
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') # tupla ()
y_pos = np.arange(len(people)) # 0,1,2,3,4
performance = 3 + 10 * np.random.rand(len(people)) ... |
741ab0203e4f267b2a4da39a2912abbd356f8129 | pablodarius/mod02_pyhton_course | /Python Exercises/3_question3.py | 765 | 4.09375 | 4 | import unittest
# Given 2 strings, s1, and s2 return a new string made of the first, middle and last char each input string
def add_ini_middle_fin(s1, s2):
result = ""
result += s1[0] + s2[0]
result += s1[len(s1) // 2] + s2[len(s2) // 2]
result += s1[-1] + s2[-1]
return result
class testing(unit... |
b6dca1f06e8cf584f378d26c216d43680939df1f | ONSdigital/ras-common | /ons_ras_common/ons_cryptographer.py | 2,489 | 3.84375 | 4 | """
Simple AES256 Cryptographer routine to handle string encryption
License: MIT
Copyright (c) 2017 Crown Copyright (Office for National Statistics)
"""
from Crypto import Random
from Crypto.Cipher import AES
from hashlib import sha256
from base64 import b64encode, b64decode
from os import getenv
class ONSC... |
8a77f9a840abc4a353bf74a37f4492034ddbcc1d | SrEstroncio38/EjerciciosAJ | /Ej7DivideYVencerasXa.py | 365 | 3.578125 | 4 | def expA(x, a):
print('te')
if a == 0:
return 1
if a == 1:
return x
if a % 2 == 0:
total = expA(x, a/2)
return total*total
else:
total = expA(x, (a-1)/2)
return total*total*x
x = int(input('Introduce la base: '))
a = int(input('Introduce el exponente:... |
c4e950a6959db895f7eb8038f3df52004452b390 | C4st3ll4n/classificacoes | /exercicios/ex14.py | 904 | 3.890625 | 4 | def adicao(n1a, n2a):
return n1a + n2a
def subtracao(n1s, n2s):
return n1s - n2s
def divisao(n1d, n2d):
return n1d / n2d
def multiplicacao(n1m, n2m):
return n1m * n2m
while True:
n1 = int(input("1º número -> "))
n2 = int(input("2º número -> "))
op = str(input(("\nSELECIONE UMA OPER... |
88d4a3fa2ff6e4b73ca923b4491e044193edcd0c | antoniosereno95/Python_Curso_em_Video | /Exercicios/ex_053.py | 360 | 3.78125 | 4 | f = input('frase: ')
f.lower().strip()
f = f.replace(' ','')
palavra = f.split() #transforma em lista
print(palavra)
junto = ''.join(palavra) #pega a lista e tranforma em palavra denovo
print(junto)
inverso = ''
for i in range(len(junto)-1, -1 , -1):
inverso = inverso + junto[i]
if inverso == junto:
print('p... |
2f912243525ae13d7e1e6f0bcfda6b6dc8a22fc1 | compilepeace/DS_AND_ALGORITHMS | /DS_with_python/reccursion/template_list_input.py | 274 | 3.703125 | 4 | import sys
sys.setrecursionlimit(5000)
user_input = input("Enter the numbers (space separated) : ")
# Using list comprehension to cook a fresh list of integer values in the user_input string
input_list = [int(i) for i in user_input.strip().split(" ")]
print(input_list)
|
984c4f4faed6bd98be8b1173bc03da3ff075e373 | xndong/standforCS224n | /n_gram.py | 3,914 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 17:23:07 2019
@author: DongXiaoning
"""
import re
# bigram
def generate_ngrams(corpus, n=2):
# Convert to lowercases
corpus = corpus.lower()
# Replace all none alphanumeric characters with spaces
corpus = re.sub(r'[^a-zA-Z0-9\s]'... |
df085c7f9f1ce78b5f7aab8a14f663ec06d64e68 | Hussein-Mansour/ICS3UR-Unit2-02-python | /basic_math.py | 688 | 4.40625 | 4 | #!/usr/bin/env python3
# Created by: Hussein Mansour
# Created on: Sun,Apr26/2020
# This program does basic math
def main():
# input:
length_of_rectangle = int(input("enter the length of the rectangle (mm) :"))
width_of_rectangle = int(input("enter the width of the rectangle (mm) :"))
# process... |
2104240806bed49e6ba9ac4d7d56dda4e9bf1dc9 | sawyou19/ti103_project | /main.py | 674 | 3.71875 | 4 | import random
import math
import test_import
num = random.randint(0,1000)
play = True
print(num)
print(test_import.ma_variable)
while play:
guess = input("Devinez un nombre entre 1 et 1000 ou 'q' pour quitter: ")
if guess == 'q':
break
elif not guess.isnumeric():
print("Vous devez entre... |
8611bac0797d9f27ea5b2de6e776f92e52e22951 | abhi302005/the-bank-app | /login.py | 2,437 | 3.921875 | 4 |
def login():
import json
records=dict()
file=open("bank.json",mode="r+",encoding='utf-8')
records=json.load(file)
file.close()
entered_user=input("please enter the username\n")
if entered_user in records:
entered_password=input("please enter your password")
if entered_passwo... |
74d7ec82f44a1286606e091cb89eceadcedb52cb | lvolkmann/couch-to-coder-python-exercises | /Loops/iterating_with_for_FIXME.py | 371 | 4.375 | 4 | """
Iterate over the examples of each of the data structures below. Predict the output generated by iterating over each data structure and calling print.
Lists
grade_lst = ['A', 'A', 'B', 'F']
Strings
word_to_spell = "dog"
Range Function (kind of a list)
range(1, 4)
"""
# List:
grade_lst = ['A', 'A', 'B', 'F']
# ... |
ec61407796ec1ad1d0c0cdc77b5f4505e7ef3965 | anonimato404/hacker-rank-python | /easy/21_capitalize.py | 167 | 4.0625 | 4 | def capitalize(string: str):
return " ".join([word.capitalize() for word in string.split(" ")])
if __name__ == "__main__":
print(capitalize("sabare reque"))
|
8cddfebdc1efc3fbbb902010e06b00e377782c55 | HearyShen/SudaArchive | /12 Chinese Information Processing (CIP)/Exercises/实验5/ex5/ex5_3.py | 921 | 3.5 | 4 | # coding: utf-8
#
# @title: ex5_3 - CIP exercise
# @description: search with zimb.txt only
# @author: SHEN Jiayun
# @createDate: 2017/12/7
# @updateDate: 2017/12/7
def pinyinToWords(pinyin):
file = open("zimb.txt", mode="r", encoding="UTF-16")
words = None # default as None object
for line in file:
... |
ccbdd8024578686b7fc74c0a326e38bfc1c81751 | ssarkar2/codingPractice | /hackerrank/Domains/Algorithms/Strings/easy_pangrams/pangrams.py | 444 | 3.796875 | 4 | #https://www.hackerrank.com/challenges/pangrams
import sys
def f(str):
flag = [0]*26
count = 0
for i in str:
if i != ' ':
t = ord(i.lower()) - 97
if flag[t] == 0:
count += 1
flag[t] = 1
if count == 26:
print... |
2786ff27ae25662b58277543a4c47425b67407c0 | iamrochit/The-Artificial-Intelligence-Infrastructure-Workshop | /Chapter03/Exercise03.02/spark_etl.py | 750 | 3.65625 | 4 | from pyspark.sql import SparkSession
from pyspark.sql.functions import col, split, size
spark = SparkSession.builder.appName("Packt").getOrCreate()
data = spark.read.csv('../../Datasets/netflix_titles_nov_2019.csv', header='true')
# data.show()
# take only the movies
movies = data.filter((col('type') == 'Movie') & (... |
b42e30f4683e816df314840183cd3d76c3ad18d5 | tushars01/data-structures | /Linked_List/Singly linked list/Linked List Set 3 (Deleting a node)2.py | 2,329 | 4.21875 | 4 | #Linked List | Set 3 (Deleting a node)
#Problem statement
#######################################################################
#Given a ‘key’, delete the first occurrence of this key in linked list.
#######################################################################
class Node:
def __init__(self, data):
... |
99cbc4cdd808c4b5b56a1c6952fa0f56df856ee8 | 8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions | /Chapter09/0004_read_using_with.py | 367 | 4.15625 | 4 | """
Program 9.2
Read and Print Each Line in "japan.txt" File Using
with Statement.
"""
def read_file():
print("Printing each line in text file")
with open("Chapter09/japan.txt") as file_handler:
for each_line in file_handler:
print(each_line, end="")
print()
def main():
read_... |
7d7034610bf7def9fcf4c416c917cb977e692079 | JamesDCage/100-Challenging-Python-Problems | /Problem5etc.py | 10,392 | 4.1875 | 4 | # Question 5 - skipped (has to do with classes)
# Question 6
# Level 2
# Question:
# Write a program that calculates and prints the value according to the given formula:
# Q = Square root of [(2 * C * D)/H]
# Following are the fixed values of C and H:
# C is 50. H is 30.
# D is the variable whose values should be inp... |
804924763b3ee8f6ca21dc337da7309eb689aa4f | sanghunBaek/algorithm | /algorithm/baekjoon/20_4344.py | 743 | 3.78125 | 4 | # 소수 출력하는거 소수점 부분
# float 형이면 %0.3f 머이런식으로해서 해결 가능하다
# 소수 3째자리까지 출력의 예시 %0.3f"% result[i]
# 배열이랑 sum 함수 쓸때 슬라이싱으로 일정부분만 합하는것도 가능하다
import sys
num = int(sys.stdin.readline().rstrip())
result =[]
for i in range(num):
numlist = sys.stdin.readline().rstrip().split(" ")
numlist = list(map(int, numlist))
avg =... |
f634d770583906f8709b70f5868a0ed373a68d89 | thiagomfl/python-studies | /project-1/circle-area-v13.py | 773 | 3.671875 | 4 | from math import pi
import sys
import errno
class TerminalColor:
ERRO = '\033[91m'
NORMAL = '\033[0m'
def circle(radius):
return pi * float(radius) ** 2
def circleHelp():
if sys.argv[1]:
print(TerminalColor.ERRO + 'The radius must be a numerical value.' + TerminalColor.NORMAL)
else:
... |
ff558ea890d4061d3aff21ea93739d8e506d9e51 | innovationcode/Data-Structures | /linked_list/linked_list.py | 2,592 | 3.859375 | 4 | """
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
retu... |
b3cb3699dbe92e58fbaf7591e98ac1b204c0b6ae | makfazlic/CommonAlgosAndDataStructures | /algoritms/searches/O(n)/linear_search.py | 581 | 3.828125 | 4 | # Searching algo with linear complexity
# T(n) = O(n)
import random
# Algorithms
def find_in_list(A, key):
for item in A:
if item == key:
return True
return False
# Unit tests
def test(number_of_tests):
while number_of_tests > 0:
array = []
array_size = random.randint(0... |
931b6b544bdbd7d02dbfdc870cfbc5932df4625e | aman27/DS | /DS_python/LinkedList/LinkedListCreation.py | 2,403 | 4.15625 | 4 | #Node Class
class Node:
#Function to initilize the node object
def __init__(self, data):
self.data = data #Assign data to node
self.next = None #Initialize next
#node as null
#LinkedList Class
class LinkedList:
#Function to initialize the LinkedList
#object
def __init__(self):
self.head = None... |
f7d0f66cab3637b40e632650ea550411dd703bc6 | vuggesaikalyan/Hackerank-Algorithms-python | /String Validators.py | 894 | 3.671875 | 4 | def alphanum(s):
count=0
for i in range(len(s)):
if s[i].isalnum():
count=count+1
print("True")
break
if count==0:
print("False")
def alpha(s):
count=0
for i in range(len(s)):
if s[i].isalpha():
count=count+1
print("True")
break
if count==0:
print(... |
57e94a263328f9702f3521e8fb73bebb2d16580c | moqi112358/leetcode | /solutions/0287-find-the-duplicate-number/find-the-duplicate-number.py | 1,397 | 3.890625 | 4 | # Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.
#
# There is only one repeated number in nums, return this repeated number.
#
#
# Example 1:
# Input: nums = [1,3,4,2,2]
# Output: 2
# Example 2:
# Input: nums = [3,1,3,4,2]
# Output: 3
# Example 3:
# Inpu... |
5c80fc96fb56620f252d00559feb0630767dc116 | dsrlabs/PCC | /CH 7/7_1_RentalCar.py | 156 | 3.828125 | 4 | print()
rental_car = input("Hello, what kind of vehicle would you like to rent?")
print("\nSure, let me see if I can find you a" + rental_car + ".")
print() |
c4685f5f284573e5c97ff86f907a07c696961a71 | Bertani-pixel/Esercizi_2020-2021 | /32.py | 226 | 3.828125 | 4 | a=int(input("Scrivi a: "))
b=int(input("Scrivi b: "))
if a==0:
if b==0:
print("Indeterminata")
else:
print("Impossibile")
else:
if b==0:
print("x = 0")
else:
print("x =", -(b/a)) |
0468c836f733de517dcd9a97669632070f04dcc4 | Viola8/Python-Exercises | /str17.py | 342 | 3.796875 | 4 | # Write a Python function to get a string made of 4 copies
# of the last two characters of a specified string (length must be at least 2).
def ending_copy(word):
if len(word)<2:
return
else:
return word[-2:] * 4
print(ending_copy("n"))
# OUTPUT: None
print(ending_copy("Python"))
... |
859ec594a6c1e927d24957e3bdf4164ff069e861 | leandro-alvesc/estudos_python | /guppe/iteradores_e_geradores/iterador_customizado.py | 582 | 4 | 4 | """
Escrevendo um iterador customizado
# Iterando
con = Contador(1, 5)
it = iter(con)
print(next(con))
print(next(con))
print(next(con))
print(next(con))
"""
class Contador:
def __init__(self, menor, maior):
self.menor = menor
self.maior = maior
def __iter__(self):
return self
... |
aa2beffcaa401942366b63c382ceea3ac5e313c7 | palash2594/A-star-and-IDDFS-algorithm | /Vertex.py | 365 | 3.671875 | 4 | class Vertex:
__slots__ = "obstacle", "value", "edges"
def __init__(self, value, obstacle=False):
self.value = value
self.obstacle = obstacle
self.edges = dict()
def __str__(self):
return str(self.value) + " " + str(self.obstacle) + " " + str(self.edges)
vertex = Vertex(1,... |
52c0f63d50ba31dad927816aa8e65d702b4e9a2f | chintu0019/DCU-CA146-2021 | /CA146-test/markers/ex2-histogram.py/ex2-histogram.py | 426 | 3.5 | 4 | #!/usr/bin/env python
a = []
s = raw_input()
while s != "end":
a.append(int(s))
s = raw_input()
maximum = 0
i = 0
while i < len(a):
if maximum < a[i]:
maximum = a[i]
i = i + 1
i = 0
while i < maximum:
value = maximum - i
s = "|"
j = 0
while j < len(a):
if value <= a[j]:
... |
c712a003ee603304a391147fa19135daf019b4c5 | sachincool/DsAlgo-ND | /solutions.py | 7,579 | 4.125 | 4 | #! /usr/bin/python
def Question1(s,t):
"""Given two strings s and t, determine whether some anagram of t is a substring of s. For example: if s = "udacity" and t = "ad", then the function returns True. Your function definition should look like: question1(s, t) and return a boolean True or False."""
if len(s)=... |
68619612e283b1971d56ccf5ac999a958cf37bd0 | purusharth777/Python-Gui-Practise | /tut19.py | 509 | 3.546875 | 4 | from tkinter import *
import tkinter.messagebox as tmg
root=Tk()
def getdollars():
print(myslider2.get())
tmg.showinfo("Amount credit",f"We have created {myslider2.get()}")
root.geometry("455x455")
root.title("Slider")
# myslider=Scale(root,from_=0,to=100)
# myslider.pack()
Label(text="How many dollars you want... |
5cbb0a1c755e3b5d7ac7e317fd90bf33d47c11d4 | edongyun/python | /씨마스 정보 교과서/거품정렬.py | 712 | 3.71875 | 4 | def bubbleSort(arr):
비교 = 0
교환 = 0
for i in range(0, len(arr)-1): # 반복횟수 : (0, 5) = 5회
for j in range(0, len(arr)-1-i): # 반복횟수 : 5, 4, 3, 2, 1
비교 += 1
if arr[j] < arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j] # 자리 바꿈
교환 += 1
... |
bc9dca1c1439ce2d30d0293548a6258efb2cb720 | disha111/Python_Beginners | /idea to code/demo.py | 240 | 4 | 4 | f=open("file.txt",'r')
result=f.readlines()
#print(result)
for line in result:
string=result
if(string[0]==string[-1]):
print("The string is a palindrome" ,string)
else:
print("Not a palindrome",string)
f.close() |
d76de60dd7b2c16731c742045a0a4f78c21d249b | Rajmanglam/tutorials | /tutorial 72 Object Introspection.py | 1,005 | 4.15625 | 4 | class employee:
def __init__(self,fname,lname):
self.fname=fname
self.lname=lname
def explain(self):
return f"This employee's name is {self.fname} and his last name is {self.lname}"
@property
def email(self):
if self.fname==None or self.lname==None:
return ('e... |
ec0b2e87202242868fb8d87b5cbb6d83998eff6d | Manit1/ML-SalaryPredictor | /salary.py | 714 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 26 11:51:04 2018
@author: Manit
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data=pd.read_csv("Salary_Data.csv")
data.head()
#Collecting X and Y
X=data.iloc[:,:-1].values
Y=data.iloc[:,1].values
#split dataset into two... |
0fb212f045518b371fb8c5cfe6a774f6d1837861 | miguelfmc/lip-reading | /src/model.py | 7,670 | 3.765625 | 4 | """
CS289A INTRODUCTION TO MACHINE LEARNING
MACHINE LEARNING FOR LIP READING
Authors: Alejandro Molina & Miguel Fernandez Montes
Model
"""
import torch
import torch.nn.functional as F
class Encoder(torch.nn.Module):
"""
The Encoder module is heavily based on the WATCH module from Chung et al. (2016).
Th... |
01ed6e2af94da9f6f20dd9359e5e14eadaceae8e | krshubham/compete | /college_life/codeforces/problemset/236a.py | 112 | 3.53125 | 4 | s = [i for i in input()];
s = set(s);
if(len(s)%2 == 0):
print('CHAT WITH HER!');
else:
print('IGNORE HIM!');
|
e6c0e53de1664e9493ef51a5054ff0b28ad22223 | Devika-Baddani/python-program | /multiplication table.py | 123 | 3.921875 | 4 | n = int(input("enter the number to print the table for: "))
for i in range(1,11):
r = n*i
print(n,"*",i,"=",r)
|
ded45ed565eae0f8f82c03820567d53ad4b71fc1 | L200180101/Algostruk_D | /Modul_8/4.py | 2,180 | 3.765625 | 4 | ####################1
import heapq
class PriorityQueue(object):
def __init__(self):
self.qlist = []
def __len__(self):
return len(self.qlist)
def isEmpty(self):
return len(self) == 0
def enqueue(self,data,priority):
heapq.heappush(self.qlist, (priority,data))
self... |
246a10fb5c4ba9e5e5b094dd1ceb97d6e324028b | DingHe/python-ml | /dataAnalysis_src/ch5_pandas/testpandas.py | 550 | 4 | 4 | #coding=utf-8
'''
Created on 2016年11月29日
@author: Administrator
'''
from pandas import Series,DataFrame
import pandas as pd
obj=Series([4,7,-5,3])
print obj
print obj.values
print obj.index
obj2=Series([4,7,-5,3],index=['a','b','c','d'])
print obj2
print obj2.index
data={'state':['Ohio','Ohio','Ohio... |
5e816a4e892916a663185930b34c14b99446b5e9 | samcreed/pikachu | /Project Euler/Problem036.py | 195 | 3.53125 | 4 | # Problem 36: Double-base palindromes
def is_palindrome(n):
return n == n[::-1]
sum = 0
for i in range(1000000):
if is_palindrome(str(i)) and is_palindrome(bin(i)[2:]):
sum += i
print sum |
b1095c87acd9aa5e3c6f3ea95a355c6b9c7f5b6a | jdtayyub/HLC-Work-Python-Multi-Obstacle | /objects/rectangle.py | 1,239 | 3.796875 | 4 | from object import Object
import pandas as pd
class Rectangle(Object):
"""Class defining any physical object in 3 dimensions
Values of the abstract properties
* **_x,_y,_z** = "Center point of an object"
* **_objects** = "a dictionary of objects of the 'physical object' class"
... |
1a3f4f4211d51b94653872c35770b9224bc2ab64 | ruxia/LeetCode | /pascal'sTriangle118118.py | 503 | 3.65625 | 4 | class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
nums=[[1]]
for i in range(1,numRows):
temp = [1]
for j in range(i-1):
temp.a... |
f6f81263c615593c8d671cdffd1039448d61f16b | dave31415/US-Bike-Sharing-Data-Analysis | /bikes/bike_sharing_data_ui.py | 7,261 | 3.5 | 4 | import streamlit as st
import pandas as pd
import numpy as np
import os
from collections import Counter
from bikes import data_wrangeling_and_filtering as dwaf
def get_data_dir():
this_dir = os.path.dirname(__file__)
return os.path.realpath("%s/../data/" % this_dir)
def get_filename(city_name):
return "... |
5178916bae89a5cd8cc7a530b76d4af820713e18 | jacyyang04/Learn-Python-the-Hard-Way | /ex24.py | 2,428 | 4.09375 | 4 | from sys import exit
#defining function for gold_room()
#prompts user input to execute if statements
def gold_room():
print("This room is full of gold. Mow much do you take?")
next = input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("You need to enter a... |
42410378acf37e4815c2594b2e1aface4caace5c | maomao905/algo | /course-schedule.py | 1,738 | 3.84375 | 4 | """
topological sort
(graph) task -> child tasks
(counter) task -> num of parent tasks (num of dependent tasks)
if counter[x] == 0:
q.append8(x)
pop x from queue
x is the root task (x has not dependent task, so we can start from here)
decrement counter for x's child tasks (we have done task x, one parent task is ... |
0a355b40ff70acc988498bddebca7a29aa2b7a4f | msouto/20172-redes-2v-programacao-redes | /01_revisao_python/06_strings.py | 98 | 3.578125 | 4 | s='42'
x=int(s)+5 #soma
print(x)
print(type(x))
x=s+str(5) #concatenacao
print(x)
print(type(x))
|
c61602022fe4ddba395cbe0ca6da02e3e65ca478 | hyperdonutloop/Intro-Python-II | /src/room.py | 923 | 3.734375 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
# setting values to None so that if there is no attribute given, there won't be an error. If a room doesn't have an exit in one direction, then no error.
class Room:
def __init__(self, name, description, n_to=None, s_to... |
f49eca1611bee4e4c6611e1023dd92dd36a25857 | edisonesc/le-train | /Python/elif.py | 108 | 3.75 | 4 | x = 5
y = 10
z = 99
if x>y:
print('x')
elif x < z:
print ('z')
else:
print('false')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.