blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
691bb78aad0da55bd049ecd68fc5fb95db3c2786 | javad-torkzadeh/linux-programming | /checkPassword.py | 947 | 3.796875 | 4 | #def check_password (password):
# alpha = 1
# digit = 1
# special = 1
#lenth(password)
#token_list = password.split("?")
#if len(token_list) > 1:
# return False
#
#
#else :
# special = special + 1
# if digit > 1 and alpha > 1 and special > 1:
# ... |
358b06e567d603b0e7afa03e8108956544e5c63f | javad-torkzadeh/linux-programming | /dictionar.py | 459 | 3.6875 | 4 | def string (str2):
a = 0
e = 0
u = 0
i = 0
o = 0
for counter in range(len(str2)):
if str2[counter] == "a":
a = a + 1
if str2[counter] == "e":
e = e + 1
if str2[counter] == "u":
u = u + 1
if str2[counter] == "i":
i = ... |
641aca3e416e9932def5a28ffae4ebab4225bc09 | Alselim/Tree | /forest.py | 3,121 | 3.671875 | 4 | from tkinter import Tk, Canvas, Frame, BOTH
import random
class Object:
def __init__(self, x, y, color_trunk, colors_needles):
self.x = x
self.y = y
self.colors_needles = colors_needles
self.color_trunk = color_trunk
class Tree(Object):
def __init__(self, x, y, color_trunk, c... |
6c3deceb09c23c81f0f54a414ba22e6efd700a45 | stcybrdgs/PythonScrapers | /beautifulSoup/scraperTest.py | 800 | 3.734375 | 4 | # scraperTest.py
# testing a python/beautifulSoup screen scraper
# import libraries
import urllib.request
import urllib.error
from urllib.request import urlopen
from bs4 import BeautifulSoup
# specify the url
quote_page = 'https://www.bloomberg.com/quote/SPX:IND'
# query the website and return the html to the variab... |
b104efd043c5f32c5891909dc492e157276199c4 | coloratto/Medical-Entities-Similarity-Measurements | /implementation/classes/Classification.py | 1,342 | 4.09375 | 4 | # !/usr/bin/env python3
class Classification:
def __init__(self):
self.description = ''
self.direct_parent = ''
self.kingdom = ''
self.superclass = ''
self.class_type =''
self.subclass = ''
def __init__(self, description, direct_parent, kingdom, superclass, clas... |
dd0f8a2df17eee0aa58f83c851c0f4961c6d2073 | geniousisme/CodingInterview | /Company Interview/SC/snapchat2/word_abbreviation.py | 1,384 | 3.71875 | 4 | class TrieNode(object):
def __init__(self):
self.unique = True
self.children = {}
class TrieTree(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
p = self.root
for w in word:
if w not in p.children:
p.children[... |
666995aac65c5b638fd20b51f8e7472351c76924 | geniousisme/CodingInterview | /leetCode/Python2/69-Sqrt.py | 438 | 3.515625 | 4 | class Solution:
# @param x, an integer
# @return an integer
def mySqrt(self, x):
if x == 0:
return 0
start = 1; end = x / 2 + 1
while( start + 1 < end ):
center = ( start + end ) / 2
if center ** 2 == x:
return center
el... |
50977960f608946999c5f5f3217b1d5d341966d0 | geniousisme/CodingInterview | /leetCode/Python/134-gasStation.py | 1,926 | 3.8125 | 4 | # Time: O(n)
# Space: O(1)
#
# There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
#
# You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1).
# You begin the journey with an empty tank at one of the gas stat... |
645f6748339ea4926aacca22b2491a4f3e12f4fa | geniousisme/CodingInterview | /leetCode/Python/114-flattenBinaryTreeToLinkedList.py | 1,670 | 4.3125 | 4 | # Time: O(n)
# Space: O(h), h is height of binary tree
#
# Given a binary tree, flatten it to a linked list in-place.
#
# For example,
# Given
#
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# ... |
2742285f50795ff4960c0e6c571d16e932f8f669 | geniousisme/CodingInterview | /leetCode/Python/113-pathSumII.py | 2,484 | 3.859375 | 4 | # Time: O(n)
# Space: O(h), h is height of binary tree
#
# Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
#
# For example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13... |
bcb586021b6949b90976ea270b7100bba0306467 | geniousisme/CodingInterview | /Company Interview/FB/binaryPlusOne.py | 561 | 3.640625 | 4 | class Solution(object):
def binaryPlusOne(self, num):
return self.add(num, 1)
def add(self, a, b): # recursive
if b == 0:
return a
sum = a ^ b
carry = (a & b) << 1
return self.add(sum, carry)
def add(self, a, b): # iterative
while b:
... |
83329fd8494d107357ea367a32f6a90364a70552 | geniousisme/CodingInterview | /Company Interview/FB/sortColors.py | 818 | 3.78125 | 4 | class Solution(object):
def sortColors(self, nums):
if not nums:
return nums
zero_idx = i = 0; two_idx = len(nums) - 1
while i <= two_idx: # notice! must be i <= two_idx
if nums[i] == 0:
nums[i], nums[zero_idx] = nums[zero_idx], nums[i]
... |
49e4fb95d955a2e56c8fa207c976f83ac36eb6d4 | geniousisme/CodingInterview | /Company Interview/SC/SimpleWord.py | 971 | 3.625 | 4 | def simpleWords(words):
word_dict = {}
for word in words:
word_dict[word] = 1
res = []
for i, word in enumerate(words):
word_dict[word] = 0
if not is_compound_word(word, word_dict):
res.append(word)
word_dict[word] = 1
return res
def is_compound_word(... |
ff4f17da0bc19227478620a718ae3fa2f15a9b15 | geniousisme/CodingInterview | /Company Interview/SC/textJustifier.py | 2,799 | 3.890625 | 4 | '''
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L cha... |
17d165f16d0ad9ee406cd2825d08708c9a0e8540 | geniousisme/CodingInterview | /leetCode/Python/22-generateParentheses.py | 1,566 | 3.703125 | 4 | # Time: O(4^n / n^(3/2)) ~= Catalan numbers
# Space: O(n)
#
# Given n pairs of parentheses, write a function to generate
# all combinations of well-formed parentheses.
#
# For example, given n = 3, a solution set is:
#
# "((()))", "(()())", "(())()", "()(())", "()()()"
#
class Solution1:
# @param an integer
#... |
a278909ae650e8bf4ea307e75f7edd102fdff0a6 | geniousisme/CodingInterview | /leetCode/Python2/206-reverseLnkedList.py | 1,058 | 3.84375 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseI(self, head): # iterative
start = None
while head:
nxt = head.next
head.next = start
start = head
head = nxt
r... |
98ee42935f23b7d7dc1ae6052873e2df1c5d6c9d | geniousisme/CodingInterview | /leetCode/Python2/15-threeSum.py | 1,528 | 3.53125 | 4 | '''
time: O(N**2)
space: O(1)
1. sort nums
2. start from zero, and search for other nums with two ptr method which sum up as zero.
3. avoid repated
'''
# notice: this one has many detail, need to practice more!
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rty... |
af76bde28675e6369f94cfd25d1fc0de49459d5f | geniousisme/CodingInterview | /leetCode/Python2/16-3SumCloset.py | 1,679 | 3.5 | 4 | class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# This question is very similar to 3Sum, but we just need to
# calculate the closet sum in this nums
nums.sort()
min_di... |
09f25de17d8d8fb6723bad27c617ef353593bea4 | geniousisme/CodingInterview | /Company Interview/SC/printMatrixZigZag.py | 884 | 3.625 | 4 | class Solution(object):
# @param: a matrix of integers
# @return: a list of integers
def printZMatrix(self, matrix):
if not matrix:
return None
col_num = len(matrix)
row_num = len(matrix[0])
m = col_num - 1
n = row_num - 1
result = []
for i... |
f90cb628299ce4229218bf1bed10b236ad5a139d | geniousisme/CodingInterview | /leetCode/Python/213-houseRobberyII.py | 1,942 | 3.53125 | 4 | # Time: O(n)
# Space: O(1)
#
# Note: This is an extension of House Robber.
#
# After robbing those houses on that street, the thief has found himself a new place
# for his thievery so that he will not get too much attention. This time, all houses
# at this place are arranged in a circle. That means the first house is ... |
22cff6e7c39235179839f6edc4621f0747c08f29 | geniousisme/CodingInterview | /CLRS/quickSort.py | 1,128 | 4.1875 | 4 | import random
def quicksortInPlace(nums, start, end): # in-place version
if start > end:
return
pivot = random.choice(nums)
left = start
right = end
while left <= right:
while nums[left] < pivot:
left += 1
while nums[right] > pivot:
right -= 1
... |
ab394b0794463c31e9b128eb24de6f6cfca734c8 | geniousisme/CodingInterview | /CLRS/countingSort.py | 837 | 3.5625 | 4 | class CountingSort(object):
def __init__(self):
self.max_val = 0
self.length = 0
def count_sort(self, nums):
if nums:
self.max_val = max(nums)
self.length = len(nums)
count = [0 for i in xrange(self.max_val + 1)]
for n in nums:
... |
e68ab1ce22cf727c9832e8b85495c70100781eef | geniousisme/CodingInterview | /Company Interview/FB/kPoints.py | 590 | 3.546875 | 4 | import heapq
class Solution(object):
def kClosestPoint(self, points, target_point, k):
heap = []
for point in points:
heapq.heappush(heap, (self.distance(point, target_point), point))
for i in xrange(k):
print heapq.heappop(heap)[1]
def distance(self, point1, po... |
c8d8c234a24feed08a3cc835d94ede8e1bab3364 | geniousisme/CodingInterview | /leetCode/Python/300-lengthOfLongestIncreasingSequence.py | 2,470 | 3.6875 | 4 | # Time: O(nlogn)
# Space: O(n)
#
# Given an unsorted array of integers,
# find the length of longest increasing subsequence.
#
# For example,
# Given [10, 9, 2, 5, 3, 7, 101, 18],
# The longest increasing subsequence is [2, 3, 7, 101],
# therefore the length is 4. Note that there may be more
# than one LIS combination... |
ebf887450aba3d6c733db0177a6dde88aff8e5e7 | geniousisme/CodingInterview | /leetCode/Python2/121-bestTimeToBuyAndSellStock.py | 524 | 3.703125 | 4 | class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
min_price = 9999
max_profit = 0 # notice the situation of prices is []
for price in prices:
if price < min_price:
min_price = price
... |
93dfe909cb19601762759604118eab24b5ef6a70 | geniousisme/CodingInterview | /leetCode/Python/243-shortestWordDistance.py | 1,315 | 4.09375 | 4 | # Given a list of words and two words word1 and word2,
# return the shortest distance between these two words in the list.
# For example,
# Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
# Given word1 = "coding", word2 = "practice", return 3.
# Given word1 = "makes", word2 = "coding", return... |
1aa3a5a7c61dd2f3a33b68398d59f3a3a4e45d27 | geniousisme/CodingInterview | /Company Interview/FB/simplifyPath.py | 582 | 3.734375 | 4 | # Given an absolute path for a file (Unix-style), simplify it.
# For example,
# path = "/home/", => "/home"
# path = "/a/./b/../../c/", => "/c"
class Solution(object):
'''
Time: O(n)
Space: O(n)
'''
def simplifyPath(self, path):
stack = []; tokens = path.split('/')
for token in t... |
03fbc8561be6272d17060f23903eb4cd2799c039 | geniousisme/CodingInterview | /leetCode/Python/129-SumRootToLeafNumbers.py | 1,993 | 4.0625 | 4 |
# Time: O(n)
# Space: O(h), h is height of binary tree
#
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
#
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
#
# Find the total sum of all root-to-leaf numbers.
#
# For example,
#
#... |
230af6f93ad5d641b3862086cbc116fb5a2ab50a | geniousisme/CodingInterview | /leetCode/Python2/17-letterCombinationsOfPhoneNumber.py | 2,554 | 3.671875 | 4 | class Solution1(object): # iterative
def __init__(self):
self.digit_letter_dict = \
{
'0':[""],
'1':[""],
'2':['a', 'b', 'c'],
'3':['d', 'e', 'f'],
... |
d0045bfbfc5fecea3c700032b3573b812af71124 | SuvirajD/HackerRank-Python-Solutions | /Easy/Introduction to Sets.py | 186 | 3.671875 | 4 | def average(array):
myset = set(array)
mylist = list(myset)
length = len(mylist)
sum = 0
for i in mylist:
sum = sum + i
avg = sum/length
return avg
|
988fd259b5aa67a5c66a4fc0b2cc29fca09abc30 | Gaffelmannen/Scripts | /DynamicProgramming/Fibonacci/fib.py | 2,560 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
class FibonacciBase:
def __init__(self):
self.name = "Not set"
def fib(self):
pass
class FibonacciSimple(FibonacciBase):
def __init__(self, depth):
self.name = "Fibonacci - Naive"
self.depth = depth
def fib(self... |
9d33504c311daee381ceb129f14176c707495671 | bmihovski/linkedin_unit_testing_in_python | /scripts/chp2/video3/mapmaker_exceptions_start.py | 872 | 3.8125 | 4 |
class Point():
def __init__(self, name, latitude, longitude):
if not isinstance(name, str):
raise ValueError("Invalid city name type")
self.name = name
if not (-90 <= latitude <= 90) or not (-180 <= longitude <= 180):
raise ValueError("Invalid latitude, longitude com... |
1ccef02587a12c01fc34623891d1a78311899ab3 | flavioUENP/aula1 | /Exe16.py | 184 | 3.53125 | 4 | ganho=float(input("Digite quanto você ganha por hora: "))
horas=int(input("Digite suas horas trabalhados no mês: "))
ganhototal=(ganho*horas)
print("Você ganhou: ", ganhototal,"R$") |
d22dc4e249069ecbed9e94fa9b34fc3a1a94b903 | flavioUENP/aula1 | /Exe5.py | 157 | 3.671875 | 4 | preçop=float(input("Digite o preço do produto: "))
quant=int(input("Digite a quantidade comprada: "))
total=(preçop*quant)
print("Total a pagar: ", total) |
b736501262cbf0b938a50b879c466a71497eff8f | flavioUENP/aula1 | /Exe7.py | 423 | 4.03125 | 4 | #n1=nota1
#n2=nota2
#n3=nota3
#p1=peso1
#p2=peso2
#p3=peso3
n1=float(input("Digite a primeira nota: "))
n2=float(input("Digite a segunda nota: "))
n3=float(input("Digite a terceira nota: "))
p1=1
p2=2
p3=5
mediafinal=7
media=(n1*p1+n2*p2+n3*p3)/(p1+p2+p3)
if media<mediafinal:
print("Você foi reprovado!")
print(... |
49484580cb84fee7ff6c480aad35892b5665af3b | QuantumArjun/Outreach-Tracker | /OutreachTracker.py | 2,611 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
import csv
#Fields to modify
inputFile = 'lvf_early_vote_02_messages.csv' #Change to name of input file
outputFile = 'output.csv'
beginningTime = "17"
endTime = "20"
#In the Data Dictionary, the email is stored as the key, and the [message, date] is stored as the value
dataDict ... |
1b596042a8e4f29fca35650f367d8caa7a7c809e | alex-dr/animalid | /animalid/__init__.py | 1,187 | 4.09375 | 4 | """Utility for importing text files as Python lists.
This module makes it possible to treat text files of words as module
attributes.
Every file in the lists/ directory will be read and converted to a list of
strings, which will become a module attribute with the same name as the name
of the file, minus the .txt exte... |
669e5d695be03e5e90872a5d5d69746751b1e93a | aprola/aprola-tutorials | /run.py | 634 | 3.5 | 4 | from utils.random import randomArrayGenerator2
from utils.random import randomArrayGeneratorWithDuplicates
from sorting.mergesort import mergesort
from sorting.quicksort import quicksort
from sorting.radix import radix
from sorting.counting import countingsort
from assingments.nishu.mergesort import mergeSort
from assi... |
00bdda516447dc3535f88dfb78e39944476c6a8e | dsfirth/mazes | /src/grid.py | 1,741 | 3.6875 | 4 | from src.cell import Cell
class Grid:
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.__grid = self.prepare_grid()
self.configure_cells()
def __getitem__(self, tuple):
row, column = tuple
return self.__grid[row][column] if 0 <= ... |
f8e13efa2515a5bf92b727793b91d0c3b2d69618 | hanlsin/udacity-sdc-term1-project2 | /src/preprocess_data.py | 2,157 | 3.546875 | 4 | ### Preprocess the data here.
# Preprocessing steps could include normalization, converting to grayscale, etc.
import cv2
import matplotlib.pyplot as plt
import numpy as np
from load_data import show_images, image_shape, X_train, y_train, X_test, y_test
# convert image to the gray scale image.
def convert_to_gray(imag... |
ad29d01362ba6acd4fe85cc1fdbb692b39983112 | Rreuben/password | /user_data_test.py | 1,030 | 4.03125 | 4 | '''Unit test module for User class'''
import unittest
from user_data import User
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
def setUp(self):
... |
88e4fabf00ff835932ac22b6a7028e49552ff6cb | maxb00/Sizer-Python | /dictionaries.py | 1,881 | 3.90625 | 4 | # Name:
# Section:
# hw3.py
# ********** Exercise 3.3 **********
# Define your dictionary here - populate with classes from last term
my_classes = {'6.01':'Introduction to EECS'}
def add_class(class_num, desc):
my_classes[class_num] = desc
# Here, use add_class to add the classes you're taking next term
add_... |
816a48b708007169542848b1b1ff70f789f53b2d | satyamgupta8340/pythonassignment3 | /assign3q3.py | 493 | 4.125 | 4 | # 3.Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters
def findnum(string):
r={'u_case':0, 'l_case':0}
for i in string:
if i.isupper():
r['u_case']+=1
elif i.islower():
r['l_case']+=1
else:
... |
edf07d83be32851b0d5c7dcf36622f6a74658438 | bearxiong99/tools | /body/body.py | 6,635 | 3.515625 | 4 | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
#
# \file
# body.py
# \author
# Marcus Lunden <marcus.lunden@bithappens.com>
# \desc
# This prints a number of lines from the eg middle of a textfile.
#
# Examples:
# print line 17 and 30 more:
# body 17 30 helloworld.c
# p... |
d5182b9453e6dee010839e13013df8d436d21e08 | vkuznet/DBConsistencyCheck | /python_files/csv_functions.py | 2,301 | 3.734375 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
Contains functions that assist in CSV file creation.
"""
def rearrange(row):
"Rearrange contents of inconsistent_blocks table's rows to match CSV format"
rearranged_row = []
#id,database,block_name,number_of_files,Size,state,id,database,block_name,number_of_files,Si... |
6d8a825350911f8a570142b1e46caaa99641995c | fonkamloic/AIPND-revision | /intropyproject-classify-pet-images/classify_images.py | 2,707 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND-revision/intropyproject-classify-pet-images/classify_images.py
#
# PROGRAMMER: Fonkam Loic
# DATE CREATED: 03/01/2020
# REVISED DATE: 25/01/2020
# PURPOSE: Create a function classify_ima... |
a201b460ca8e617fd800547402f9235237b52716 | TomHarned/fooled_by_covid | /src/filter_and_display_graph.py | 992 | 4.09375 | 4 | import pandas as pd
import plotly.express as px
from import_and_calculate import group_filter_and_calculate
def display_graph(df: pd.DataFrame,
state: str = 'All') -> pd.DataFrame:
"""
Takes the full cleaned COVID data set and filters it by state
Inputs:
df (pd.DataFra... |
98057aa49db4be3822e1f2dfe1349491791047f3 | Jin-W-FS/solve-project-euler | /0045.py | 595 | 3.84375 | 4 | from itertools import count
def Triangle():
for n in count(1):
yield n * (n+1) // 2
def Pentagonal():
for n in count(1):
yield n * (3*n-1) // 2
def Hexagonal():
for n in count(1):
yield n * (2*n-1)
iters = [Triangle(), Pentagonal(), Hexagonal()]
cur = [ne... |
dd84e41cced3c40bbd877d274c107e23e7e179a2 | anshul-musing/basic_cs_algorithms | /test_stacks.py | 1,093 | 4.40625 | 4 |
from src.stack import Stack
def testStack():
'''
Here we test algorithms for stacks
We test pushing, popping, and checking if
a stack is empty
Stack is implemented as a python list
It's not the best implementation as we'll
show that the stack will be empty yet it
will be occupying m... |
0f0159b9a8bcf13a9b6f8dbff7da66c41524e5d1 | anshul-musing/basic_cs_algorithms | /test_bst.py | 4,507 | 4.40625 | 4 |
from src.binary_search_tree import BinarySearchTree
def testBinarySearchTree():
'''
Here we test algorithms for a binary search tree
We test
a) insert in a tree
b) finding minimum, maximum in a tree
c) displaying a tree using in-order, pre-order,
post-order walk, and level-order wa... |
a65aeb777089079b1cef1017f59dca10a9f69bc6 | msAzhar/examples | /python/vwlupcasecnstntdwncase.py | 413 | 3.765625 | 4 | # Listedeki kelimenin sesli harflerini büyüten ve sessiz harflerini
# küçülten program:
wordlist = ["ali", "ayse", "mehmet", "ahmet"]
newwordlist = []
for i in range(len(wordlist)):
l = ""
for x in wordlist[i]:
if x in "aeiouAEIOU":
l += x.upper()
if x not in "aeiouAEIOU0123456789":... |
23e13832e7e6af4df883e6594f78cdf9e71a53e2 | ironxmind/SkillBox | /3.6 homework/task3.py | 673 | 4.09375 | 4 | print('Задача 3. Животные')
# Что нужно сделать
# Создайте две переменные с именами «Первое животное» и «Второе животное» на английском языке.
# Запишите в первую переменную слово «Заяц», а во вторую — «Черепаха».
# Используя эти переменные, выведите на экран текст «Заяц спит, Черепаха идёт» в одну строку.
first_ani... |
3c7cdafed5b9553c9861bf69f25e0aee5d6adb23 | lefreire/mcmc | /inverse_transform_sampling.py | 913 | 3.546875 | 4 | import matplotlib.pyplot as plt
import numpy as np
def exponential_mc(alpha=1, n=100000):
unif = np.random.uniform(size=n)
exp_values = -np.log(unif)/alpha
p = 1. * np.arange(len(exp_values)) / (len(exp_values) - 1)
data_sorted = np.sort(exp_values)
plt.figure(figsize=(12,8))
plt.plot(data_sorted, p)
... |
0416ae704e4d1b82cc27a5453ffd4c9011bf2c59 | Shumpy09/practicepython.org | /1-character-input.py | 185 | 3.578125 | 4 | name = str(input("Podaj swoje imie: "))
age = int(input("Podja swoj wiek: "))
hund_age = 100 - age
print(f"Twoje imie to {name}. Masz {age} lat. 100 lat skonczysz za {hund_age} lat.")
|
1900af2475a5f1c779a181e029ce98dd9b0a9b1b | rkdls/algorithm | /problem_30.py | 1,331 | 4.0625 | 4 | '''
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers ... |
e9a9f0f190eecda8844c5d98a4dfbdf9dc20d7b2 | acm-kccitm/Python | /Lists/combinations.py | 634 | 3.984375 | 4 | test_list = ["geekforgeeks", [5, 4, 3, 4], "is",
["best", "good", "better", "average"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing size of inner Optional list
K = 4
res = []
cnt = 0
while cnt <= K - 1:
temp = []
# inner elemen... |
860dea63033f83a640f6b6ba38044fa2e2cb4389 | acm-kccitm/Python | /Bit Algorithms/countOne.py | 438 | 3.90625 | 4 | def countOne(n):
count = 0
while(n):
n = n & (n-1)
count = count+1
return count
print("the number of ones in the binary representation of 5 are ", countOne(5))
print("the number of ones in the binary representation of 7 are ", countOne(7))
print("the number of ones in the binary represen... |
c9c52b3dace20d5345aadf73a3f463b5c5c904a3 | jsore/notes | /v2/python-crash-course/python_work/filesys/remember_me.py | 1,373 | 3.921875 | 4 | # basic json manipulation
# load a username if one has been stored previously or
# prompt for one and store it
import json
def get_stored_username():
"""Get stored username if available."""
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except F... |
d49500ba4fc50c34107fc817f003c4ccf0dc6848 | jsore/notes | /v2/python-crash-course/python_work/filesys/pi_string.py | 486 | 3.9375 | 4 | # print pi to a million digits
filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(f"{pi_string[:52]}...")
print(len(pi_string))
# does my birthday appear anywhwere in pi
birthday = input("... |
d53123d67c4f7e60776edbaf17f02967ba5039a6 | jsore/notes | /v2/python-crash-course/python_work/filesys/files.py | 1,591 | 4.28125 | 4 | ##
# read an entire file, basic syntax
##
filename = 'file.txt'
# read a file into memory
with open(filename) as file_object:
contents = file_object.read()
print(contents)
# or, to strip the newline and whitespace Python adds
print(contents.rstrip())
##
# read line by line
##
filename = 'file.txt'
with open(... |
34d0e6a6fa674cbc4d4efe3ca43150694f0073a4 | han31223/2dgphan | /수업 자료/3차과제/py_03_03_2019182043_2 - 2.py | 510 | 3.6875 | 4 | import turtle
turtle.shape('turtle')
for n in range(1) :
for n in range(6) :
turtle.forward(300)
turtle.right(180)
turtle.forward(300)
turtle.right(90)
turtle.penup()
turtle.forward(60)
turtle.right(90)
turtle.pendown()
turtle.penup()
turtle.right(90)
turtle.forward(60)
turtle.pendown()
for n in r... |
2b4b23aaecc3282dfbcc8dfe3aed79f55299d792 | anaskhan28/Python-practice-codes | /Chapter 12/11_04_pr.py | 216 | 3.703125 | 4 | num = int(input("Enter the number that you want a multiplication table\n "))
table = [num*i for i in range(1, 11)]
print(table)
with open ("tables.txt", "a") as f:
f.write(str(table))
f.write("\n")
|
0a6301d5540dc2676c5f3e06fec5ab52b5246e00 | anaskhan28/Python-practice-codes | /Chapter 3/05_03_pr.py | 141 | 3.765625 | 4 | st = "This is a string with double spaces ok"
# doublespaces = st.find(" ")
# print(doublespaces)
st = st.replace(" ", " ")
print(st) |
1c6ed1c87107bf571f652b7e8e5d11c6342bba78 | anaskhan28/Python-practice-codes | /Chapter 4/04_01_fruit_store.py | 307 | 3.890625 | 4 | f1 = input("Enter the fruit name:")
f2 = input("Enter the fruit name:")
f3 = input("Enter the fruit name:")
f4 = input("Enter the fruit name:")
f5 = input("Enter the fruit name:")
f6 = input("Enter the fruit name:")
f7 = input("Enter the fruit name:")
myfruitlist = [f1,f2,f3,f4,f5,f6,f7]
print(myfruitlist) |
fa248d35b3f707f85b1dfa46a0cc49d8c2c63c3b | anaskhan28/Python-practice-codes | /Chapter 2/03_input_function.py | 108 | 3.71875 | 4 | a = input('Enter the name :')
a = int(a) # converts into an integer (If possible)
print(a)
print(type(a))
|
931449512a0ce0166c66d414bd33520e9c61dce2 | anaskhan28/Python-practice-codes | /Chapter 7/10_04_pr.py | 237 | 4.125 | 4 | num = int(input("Enter your number: "))
prime = True
for i in range(2,num):
if (num%i == 0):
prime = False
break
if prime:
print("This is a prime number")
else:
print("This is not a prime number")
|
3d31fa3ab68a8571170aeafcfbf44b9ae1dfd14a | anaskhan28/Python-practice-codes | /Chapter 3/02_string_function.py | 292 | 4.09375 | 4 | story = '''Once upon a time there was a Greek leader
who standup for people's freedom and his name is Aesop Fables'''
# string function
print(len(story))
print(story.endswith('Fables'))
print(story.count('a'))
print(story.capitalize())
print(story.find('time'))
print(story.replace("his", "Aesop")) |
84b6b52a089e02770453bde68ebe07bfe1d80bcd | mohammadasim/rest_api_python | /list_comprehension.py | 111 | 3.9375 | 4 | # This is a process of creating a list programatically
my_list = [x for x in range(5) if x%2==0]
print(my_list) |
64f127ed713060fdea2bfbafa67b912be2cc77e8 | mohammadasim/rest_api_python | /flask_restful_section6/code/models/store.py | 1,817 | 3.90625 | 4 | from db import db
class StoreModel(db.Model):
'''
With the inclusion of db.Model we are telling SQLAlchemy that this is model object that it has to map
'''
__tablename__ = "stores"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
items = db.relationship('ItemMode... |
b59d71e4f04704d9ae3761abb8f1add3fdea92e4 | HarshSharma009/Python | /maze.py | 1,350 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 14:45:52 2020
@author: Harsh Sharma
"""
maze=[[0, '1', '0', '1', '1', '1', '0', 1],
['1', '1', '0', '1', '1', '0', '1', '1'],
['1', '0', '0', '1', '0', '0', '1', '0'],
['1', '0', '0', '1', '1', '0', '1', '0'],
['1', '0', '0',... |
b5d206666961f7f6dab279c8d96540f5021641d0 | HarshSharma009/Python | /sum_of_subset.py | 2,417 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 22:46:06 2020
@author: Harsh Sharma
"""
l=list(map(int,input().split()))
tar=int(input())
n=len(l)
import itertools
import operator
from functools import reduce
'''Using of package creating combination with 1 to N(len of array)
and then checking for sum ... |
dc83aea4995a0523330f2b262d56ca3d2b081abc | HarshSharma009/Python | /linked.py | 3,140 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 1 22:03:55 2020
@author: Harsh Sharma
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def isempty(self):
if self.head is No... |
747e00794e6fa73e71c2f546cadfff11ff5b7b7a | chebypax/Python-course | /lesson3/task1.py | 311 | 3.734375 | 4 | def div_func(num_1, num_2):
return round(num_1 / num_2, 2)
num_1 = int(input('Введите первое число: '))
num_2 = int(input('Введите второе число: '))
try:
print(div_func(num_1, num_2))
except ZeroDivisionError:
print('На ноль делить нельзя!')
|
881da70d6e89fbf841529b583fd48db8ccf9b79d | jerryc137th/py_lab | /lab2_4.py | 303 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 16:27:44 2021
@author: Poorish Charoenkul
"""
len_tri = input("Length of 3 sides:").split(",")
a,b,c = float(len_tri[0]),float(len_tri[1]),float(len_tri[2])
if a+b>c and a+c>b and b+c>a:
print("Triangle: True")
else:
print("Triangle: False") |
3f3a145d8fa76073eb0e73abb189af2ff200d29e | joostsijm/songpy | /src/toNeat.py | 1,114 | 3.53125 | 4 | #!/usr/bin/env python3.6
import re
import sys
# Maps a string such as 'The Beatles' to 'the_beatles'.
def toNeat(s, args):
# Put spaces between and remove blank characters.
blankCharsPad = r"()\[\],.\\\?\#/\!\$\:\;"
blankCharsNoPad = r"'\""
s = re.sub(r"([" + blankCharsPad + r"])([^ ])", "\\1 \\2", s)... |
b1fbbfb722aced6a72fe0b0912a330b8d69b5f43 | kadavr95/bp-lab1 | /task2.py | 2,225 | 3.515625 | 4 | import random as rand
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neural_network import MLPRegressor
from mpl_toolkits.mplot3d import axes3d, Axes3D
# размер обучающей выборки
TRAIN_SET_SIZE = 10000
# размер тестовой выборки
TEST_SET_SIZE = 500
# функция, которую необходимо аппроксимировать
def ... |
6e0cb781fde4830e4146217b7f3456977ce166b1 | sosimon/AoC16 | /day8/day8.py | 1,379 | 3.765625 | 4 | from collections import deque
SCREEN_WIDTH = 50
SCREEN_HEIGHT = 6
def create_grid():
return [[0] * SCREEN_WIDTH for row in xrange(SCREEN_HEIGHT)]
def rotate(l, n):
return l[-n:] + l[:-n]
def rect(grid, x, y):
for j in xrange(y):
for i in xrange(x):
grid[j][i] = 1
return grid
if ... |
d98be0a150b4f707cfa848f6c08ce8986b72d45a | ravishankar920/class-ladst | /87.py | 96 | 3.796875 | 4 | #printing tables
n=int(input("enter a number"))
i=1
while(i<=10):
print(n,"x",i,"=",n*i)
i=i+1 |
53d445aaa336f563ba4f53a3c1792ab07a0850b9 | alexandernzach/Assesment1 | /simple conversation.py | 1,655 | 4.21875 | 4 | #This program will be a simple conversation between the program and the user.
conv=input("Would you like to have a conversation with me?")
if conv=="yes": # I enjoy using If-statements so a part of this conversation will contain them. Plus it makes the program feel more flexible and/or realistic in my opinion.
... |
3cc5c78537d74e0767fcd27d1780431401a908ea | madison-python/google-survey | /google_survey/tidy.py | 2,261 | 3.71875 | 4 | from collections import namedtuple
import pandas
def tidy_responses(wide_responses):
"""Tranform Google Survey responses from wide to long format.
Args:
wide_responses: pandas.DataFrame of survey responses in wide format,
with one survey-taker per row, and different questions in different... |
fbe056a494f781d54ccea3e43e66ae284c4e575b | MechAchu/PS9 | /PS9/PS9-3/2D-MD.py | 1,032 | 3.734375 | 4 | from array import *
import matplotlib.pyplot as plt
N = int(input("Enter N: "))
dt = float(input("Enter dt: "))
x = float(input("Enter Initial x: "))
y = float(input("Enter Initial y: "))
vx = float(input("Enter Initial vx: "))
vy = float(input("Enter Initial vy: "))
time = array('f', [0.])
xsave = array('... |
2c364003355790591c459b8c6ce4f4dd7d9938dd | tpaul016/nba-betting | /controller.py | 528 | 3.734375 | 4 |
#Examples of how to access DB
import DbRead
#Create a dictionary that contains the standings of that team at that time
newDict = DbRead.getTeamStandings("2017-11-30", "Chicago Bulls")
#Print the number of assists that the Chicago bulls had up to that date
print(newDict["assists"])
#Create a dictionary that contain... |
e821ea43019eb63e1aa1c97dcea2a8accd13ea6d | rafamonge/Practica | /Chapter1/1_2_check_permutation.py | 979 | 3.59375 | 4 | # %%
from collections import defaultdict
# %%
def permutation_sort(s1, s2):
"""
Time: N log N
Space: 1
"""
return sorted(s1) == sorted(s2)
def permutation_dict(s1, s2):
"""
Time: N
Space: N
"""
d = {}
if len(s1) != len(s2):
return False
for c in s1:
... |
7796729b33f2240d5d1367c637378f0bd9984c19 | lunng/CS434_A3 | /src/tree.py | 16,239 | 3.859375 | 4 | import numpy as np
import math
class Node():
"""
Node of decision tree
Parameters:
-----------
prediction: int
Class prediction at this node
feature: int
Index of feature used for splitting on
split: int
Categorical value for the threshold to split on for the feature
left_tree: Node
Left subtree
... |
d4fbf72b164a4ef2c9b74afb41efc200e4a9d37d | AlejandroAguilar1807/AgenciaModelaje | /Modelaje/Artista.py | 739 | 3.5 | 4 | from Persona import Persona
class Artista(Persona):
def __init__(self,nombre="desconocido",genero="desconocido",pertenece="desconocido"):
Persona.__init__(self, nombre)
self.genero= genero
self.pertenece= pertenece
def getGenero(self):
return self.genero
def set... |
6694eb231ba8c72fbb491cf1ff90e4ae47780534 | TanJunYuan123/DPL5211Tri2110 | /Lab 4.7.py | 577 | 4.3125 | 4 | # student ID: 1201200431 #
# student Name: Tan Jun Yuan #
studnames = ["John", "Viktor", "Mary"] [::-1]
for name in studnames:
print(name)
studnames = ["John", "Viktor", "Mary"]
for name in reversed(studnames):
print(name)
studnames = ["John", "Viktor", "Mary"]
for name in range(2,-1,-1):
... |
2ce7e79d0c5824ac9690d03683957857c7b7e55b | TanJunYuan123/DPL5211Tri2110 | /Lab 5.3.py | 1,029 | 4.0625 | 4 | # student ID: 1201200431 #
# student Name: Tan Jun Yuan #
def cm_to_meter(centimeter):
meter = centimeter / 100
return meter
def get_cm():
cm = float(input("\nEnter centimeter : "))
m = cm_to_meter(cm)
print("\n{:.2f} centimeters equals to {:.2f} meters ".format(cm, m))
def meter_to_c... |
905defa6cd563b05cce825d712ca41246bf6f5c6 | TanJunYuan123/DPL5211Tri2110 | /Lab 2.1.py | 209 | 3.859375 | 4 | # Student ID: 1201200431
# Student Name: Tan Jun Yuan
kilo = float(input("Please enter the value of kilogram : "))
gram = kilo * 1000
print("for {:.0f} kilogram is equivalent to {:.0f} gram".format(kilo,gram)) |
5bcad00ba1ea5a178ad5745b8b5ae95bbb442ae7 | SamEpp/Toolbox-Flask | /flask_app.py | 794 | 3.53125 | 4 | """
This is my flask code that makes my website, the "result page", and the "not enough information page"
"""
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
@app.route('/', methods = ['POST', 'GET'])
def hello_world():
return render_template('index.html')
... |
edf6a657ad24821c24983ddeeecbbc1b646ce9db | zhangfeng6701/python | /classTest1.py | 590 | 3.765625 | 4 | class Parent:
'Parent Class ...'
parentAttr = 100
def __init__(self):
print("Parent")
def parentMethod(self):
print("ParentMethod")
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent", Parent.parentAt... |
9be5269bf49a2853adcacf4d9ec0049937a755c7 | Zhenye-Na/algs-tpl | /src/basic/Main_Sorting/Merge_Sort.py | 2,859 | 3.75 | 4 | class Solution:
"""
@param A: an integer array
@return: nothing
"""
def sortIntegers2(self, A):
# write your code here
tmp = [0] * len(A)
self.mergeSort(A, tmp, 0, len(A)-1)
def mergeSort(self, A, tmp, start, end):
# base case
if start >= end:
... |
167d089ddc2d4150971ebc076ba8642cb01ca50d | jhofscheier/gen-flat-const-dim2 | /Z_Delta2_triangles/pretty_concat/pretty_concat.py | 2,601 | 4.28125 | 4 | """Utility functions to concatenate multi-line strings horizontally."""
# Author: Johannes Hofscheier.
from functools import reduce
def str_to_rect(str_list, height=None, width=None, whitespace=' '):
"""Transforms a list of strings into a list of strings of length width
(appending spaces to shorter lines... |
2f31a943c6ec2475879d84bb325314cab0b1ac86 | mpaisner/projects | /the game/battle/battle.py | 1,302 | 3.71875 | 4 |
class Unit:
def freeze(self):
raise Exception("not implemented")
#creates a static copy of the unit. The copy's "original()" method will return this unit
def original(self):
return self
RESERVE = -2 #meaning of reserve changes depending on unit's owner (i.e. your reserve or mine)
DEPLOYING = -1 #troops wh... |
4cf05073ca1f65956cc4a7b5f011eaf96997cc73 | behiveapp/bifrost | /src/lib/utils.py | 319 | 3.765625 | 4 | def underscore_to_camelcase(value):
def camelcase():
yield str
while True:
yield str.capitalize
c = camelcase()
return "".join(next(c)(x) if x else '_' for x in value.split("_"))
def normalize_field(field):
value = field[1:] if field[0] == '_' else field
return underscore_to_camelcase(value) |
c5c5978961e04743c98c208e82f604a848a93cef | HarrisonMS/JsChallenges | /Python/codewars/to_camel_case.py | 282 | 3.90625 | 4 | def to_camel_case(text):
if not text:
return text
s = text.replace("-", " ").replace("_", " ")
s = s.split(' ')
return f"{s[0]}{''.join(i.capitalize() for i in s[1:])}"
def to_camel_case(s):
return s[0] + s.title().translate(None, "-_")[1:] if s else s |
54b9d67edb52a9f7176a8e728bd668a76caa1dc7 | HarrisonMS/JsChallenges | /Python/test.py | 955 | 3.65625 | 4 | stack = []
if sequence == "" or sequence == None:
return None
elif len(sequence) % 2 != 0:
return False
else:
for x in sequence:
if x == "{":
stack.append("{")
elif x == "}" and stack[-1] == "{":
stack.pop()
elif... |
fef7489686e19f5d62e46af2261f011865897356 | HarrisonMS/JsChallenges | /Python/data_structures/code_signal.py | 1,206 | 3.796875 | 4 | #
# Binary trees are already defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def height(root):
if root is None:
return 0
return max(height(root.left), height(root.right)) + 1
def balancedBinaryTree(root):
... |
ddc0e34841a302121138ade6e9d8619a157c02a4 | HarrisonMS/JsChallenges | /Python/equal_parens.py | 656 | 3.640625 | 4 | # def validParenthesesSequence(str):
# if len(str) % 2 is not 0:
# return False
# stack = []
# for i in range(len(str)):
# par = str[i]
# if par == "(":
# stack.append(par)
# if par == ")" and len(stack):
# stack.remove(stack[0])
# if stack == []:
... |
f04675066c1a91813235b12b80124979de4099bb | HarrisonMS/JsChallenges | /Python/insert_into_llist.py | 559 | 3.671875 | 4 | # Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
def insertValueIntoSortedLinkedList(self, value):
l_list= [value]
while self is not None:
l_list += self.value,
self = self.next
re... |
bd3cc9f897fb8d28f414ab3da93f5e97ffd48dc4 | HarrisonMS/JsChallenges | /Python/valid_parentheses.py | 600 | 4.125 | 4 | def valid_parentheses(string):
# if len(string) % 2 is not 0:
# return False
#your code here
#create a list to act as our stack
stack = []
#loop through our string
for character in string:
#if "(" append to our stack
if character == "(":
stack.append(cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.