blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2c6c08f97ea799ee9afc8bc6cc25f7f764e66d9f | mianguanwu/PySpark_tutorial | /data_frame/basic_exercise.py | 880 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
example from spark official document
"""
import os
from pyspark.sql import SparkSession
os.environ["PYSPARK_PYTHON"] = "/usr/bin/python3"
os.environ["PYSPARK_DRIVER_PYTHON"] = "/usr/bin/python3"
os.environ['PYSPARK_SUBMIT_ARGS'] = \
'--packages org.apache.spark:spark-... |
7ecdb8efa0e752c0bd0ecd3fd4996687219eb617 | CriistianRod/basicpy | /break_continue.py | 584 | 3.5 | 4 | def run():
# for contador in range(1000):
# if contador % 2 != 0:
# continue
# print(contador)
# for i in range(10000):
# print(i)
# if i == 5678:
# break
# texto = input('Escribe un texto: ')
# for letra in texto:
# if letra == 'o':
... |
95f64791b97af372ed64912da0ff92d862250bbf | SoorejRB/Anandolody-python-exercises | /chapter 2/chapter2_problem6.py | 121 | 3.9375 | 4 | # reverse a list
x = [ 22,55,33]
# print(reverse(x)) not working
x.sort()
print(x)
x.sort(reverse=True)
print(x) |
9a09d9260888b4e118991ebbba51a4ccf019ca53 | klistwan/project_euler | /012.py | 436 | 3.6875 | 4 | #What is the value of the first triangle number to have over 500 divisors?
import prime
def triangle(n): return n*(n+1)/2
def num_of_divisors(num): return reduce(lambda k,y: k*y, [k+1 for k in prime.factorization(num).values()])
def main(index = 100):
while 1:
current = triangle(index)
current_div... |
df5716bda9637e27b0e820b11e8be1fa49ef5add | klistwan/project_euler | /60.py | 1,472 | 3.765625 | 4 | from math import sqrt
from itertools import combinations, permutations
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r, f = int(sqrt(n)), 5
while f<= r:
if n%f == 0: return False
if n%(f+2) ==... |
0e2c1e6aae24313953f787b3f4b783484cc882a8 | klistwan/project_euler | /022.py | 447 | 3.734375 | 4 | #What is the total of all the name scores in the file, 022.txt?
def compute_score(name):
"""Calculuates the score of a name, where A = 1, ... Z = 26"""
return sum(map(lambda k: ord(k)-64, list(name)))
def main():
names = sorted(file("022.txt","r").read()[1:-1].split('","'))
name_scores = map(lambd... |
41d2803ce4ce76b1761bf0ea64a510a9bf2aafa3 | gva-jjoyce/gva_data | /gva/flows/operators/filter_operator.py | 961 | 3.90625 | 4 | """
Filter Operator
Filters records, returns the record for matching records and returns 'None'
for non-matching records.
The Filter Operator takes one configuration item at creation - a Callable
(function) which takes the data as a dictionary as it's only parameter and
returns 'true' to retain the record, or... |
17f35f58a74a074454afa00e65d35bfe9c2ffe7c | gva-jjoyce/gva_data | /gva/utils/trace_blocks.py | 2,710 | 3.890625 | 4 | """
Trace Blocks
As data moves between the flows, Trace Blocks is used to create a record of
operation being run. This should provide assurance that the data has not been
tampered with as it passes through the flow.
It uses an approach similar to a block-chain in that each block includes a
hash of the previou... |
f35e5923ef0a409e2da71af148865affebdaedf4 | gva-jjoyce/gva_data | /tests/performance/timer.py | 312 | 3.5625 | 4 | import time
class Timer(object):
def __init__(self, name="unnamed"):
self.name = name
def __enter__(self):
self.start = time.perf_counter()
def __exit__(self, type, value, traceback):
print("{} took {} seconds".format(self.name, time.perf_counter() - self.start)) |
533f6643fcb2ca8428f4331ada8871481b49e9c5 | fbaroni/algorithmic-toolbox | /2_maximum_pairwise_product/sample_generator_max_pairwise_product.py | 393 | 3.90625 | 4 | # python3
from random import randint
if __name__ == '__main__':
print("Enter the total of numbers to generate the sample for the algorithm")
input_number = int(input())
numbers_to_test = [None] * input_number
for index, number in enumerate(numbers_to_test):
numbers_to_test[index] = randint(1,99)... |
728eb185fd2c7793f26f33e60cd3c7119bc3828d | yoniavn/VSCODE | /PYTHON/stractured.py | 446 | 4.21875 | 4 |
# list - is mutable (add,delete...)
x = [1, 2, 3, 4]
x.append("yoni")
print(x)
# tuple - cant be changed
y = (1, 2, 3, 4, 5)
print(y)
# dictionary
dic = {'a': 1, 'b': 2}
print(dic)
def printList(l):
for i in l:
print()
def main():
letters = ['1', '2', '1', '2', '1', '2']
print(' : '.join(let... |
c91270295db3916514df3ab98b478db95254737a | benkk331/CPTAC | /CPTAC/Ovarian/utilities.py | 16,533 | 3.53125 | 4 | import pandas as pd
import numpy as np
class Utilities:
def __init__(self):
pass
def compare_gene(self, df1, df2, gene, key_id_map):
"""
Parameters
df1: omics dataframe (proteomics) to be selected from
df2: other omics dataframe (transcriptomics) to be selected from
... |
c89694b3391ff817ea4235f91f8a9100a72d52d4 | sevenbean/Machine-Learning | /面向对象编程/类方法和类属性/Tools.py | 309 | 3.53125 | 4 | class Tools:
count=0
def __init__(self,name):
self.name=name
# 类属性
Tools.count+=1
@classmethod
def show_count(cls):
print("工具的数量%d"%(Tools.count))
tool1=Tools("铁锤")
tool2=Tools("榔头")
tool3=Tools("菜刀")
Tools.show_count() |
54fc9410656c16ab2c1f1ab3810f3bac12b0dfe3 | sevenbean/Machine-Learning | /网络爬虫/BeautifulSoup/BeautifulSoup3.py | 1,162 | 3.5 | 4 | import requests
from bs4 import BeautifulSoup
html = """
<html>
<head><title>标题</title></head>
<body>
<p class="title" name="dromouse"><b>标题</b></p>
<div name="divlink">
<p>
<a href="http://example.com/1" class="sister" id="link1">链接1</a>
<a href="http://example.com/2" class="sister" id="link2">链接2<... |
057b17ec2d60509a49367083972b9dd9436e7677 | shekhar-joshi/Assignments | /compute.py | 341 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 27 00:46:20 2018
@author: shekhar
Write a function to compute 5/0 and use try/except to catch the exceptions.
"""
def compute():
return 5/0
try:
compute()
except ZeroDivisionError:
print( "division by zero!!!!!!! " )
finally:
p... |
db07a4fce4ea8cdb1eaa7d9049eb816e1d8cac8f | Denvol10/lesson1 | /peremen.py | 410 | 4.28125 | 4 | # Переменные
a = 2
print(a + 3) # 5
# a = b значит "записать значение b в переменную a"
a = 2
a = a + 1
print(a) # 3
'''
Правило именования переменных:
1. На английском(не называть транслитом);
2. snake_case
3. Отражать точный смысл
4. Обычно существительные
''' |
a438b0efcbeedf94e6f3c8ad364004dd25d5b125 | dimeskigj/game-of-life | /gameoflife.py | 3,336 | 3.90625 | 4 | """
The Game of Life, also known simply as Life,
is a cellular automaton devised by the British mathematician John Horton Conway in 1970.
It is a zero-player game, meaning that its evolution is determined by its initial state,
requiring no further input.
One interacts with the Game of Life by creating an initial config... |
500082ff7e91cb5db105454f1aea57eea82fde6a | elugens/leet-code-python | /two_sums.py | 554 | 3.8125 | 4 | '''
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Input: [1, 3, 2, 2], 4
Output: [0,1]
'''
class Solution:
def twoSum(self, nums, target):
... |
1d6a64bd3b580c308fe537a13380fe9c14fe7c0d | elugens/leet-code-python | /code_templates/BinarySearch/find_minimum_rotated_array.py | 1,291 | 3.5625 | 4 | # Find Minimum in Rotated Sorted Array [4,5,6,7,0,1,2]
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left = 0
right = len(nums)-1
# base case - find out if nums has only one value at index 0
# return tha... |
ed8fccc4e5810f6767cf7742d2828318a8812263 | elugens/leet-code-python | /binarysearch.py | 473 | 3.90625 | 4 | # Binary Search on an orderd list
def search(nums, target):
first = 0
last = len(nums)-1
found = False
while first <= last and not found:
mid = (first+last)//2
if nums[mid] == target:
found = True
else:
if target < nums[mid]:
last = mi... |
ff529e36ceed0654d9a531e284010393f8a8c4bb | elugens/leet-code-python | /Recursion/word_split.py | 1,111 | 4.3125 | 4 | # Problem 3
# -----------------
# Create a function called word_split() which takes in a string phrase and a
# set list_of_words. The function will then determine if it is possible to split
# the string in a way in which words can be made from the list of words. You can
# assume the phrase will only contain words found... |
fc06412eeed2c1f0f78afdee26e4092dc8d3ea24 | elugens/leet-code-python | /Arrays n Sequences/find_the_missing_number2.py | 493 | 3.671875 | 4 | import collections
def finder2(arr1, arr2):
# Using default dict to avoid key errors
d = collections.defaultdict(int)
breakpoint()
# Add a count for every instance in Array 1
for num in arr2:
d[num] += 1
# Check if num not in dictionary
for num in arr1:
if d[num] == 0:
... |
35e37340d42b20416c576f8a7521b222ae19d07d | harshavardhanak/ComputerNetworking | /Lab8/Lab8.py | 1,763 | 3.984375 | 4 | class Network:
def __init__(self, n):
self.matrix = []
self.n = n
def addlink(self, u, v, w):
self.matrix.append((u, v, w))
def printtable(self, dist, src):
print("Vector Table of {}".format(chr(ord('A')+src)))
print("{0}\t{1}".format("Dest", "cost"))
... |
6ddffa5f003a322dee549b1aee9da6ee9f780371 | RicardoR22/Tweet-Generator | /Code/histogram_dictionary.py | 562 | 4.15625 | 4 | from histogram_functions import get_words
def count_words(words_list):
"""Count occurences in the given list of words_list
and return that data structure"""
word_counts = {}
for word in words_list:
# check if we saw this word before
if word in word_counts:
# increase its cou... |
18af17c39f8d253c580a87d47965a734347b3fdc | RicardoR22/Tweet-Generator | /Code/histogram_lists.py | 953 | 4.09375 | 4 | from histogram_functions import get_words
def count_words(words_list):
"""Count occurences in the given list of words_list
and return that data structure"""
word_counts = []
for word in words_list:
# check if we saw this word before
for list in word_counts:
# increase its c... |
82f752147f144d731de92040ea7aa3479f672863 | OhsterTohster/Project-Euler | /Python/q7.py | 878 | 3.859375 | 4 | # What is the 10 001st prime number?
#idk whats wrong with the code but something is wrong somewhere because 10001st prime number would mean 10001 elements in the list and thus
# primeNumbers[10000] right?
import math
def checkPrime(num):
isPrime = True
if (num % 2 == 0):
isPrime = False
return... |
a7f2bc6e50a631af23f1e9eacbbbce9fa3faf104 | IvanicsSz/python-lightweight-erp-3rd-tw | /common.py | 1,822 | 3.984375 | 4 | # implement commonly used functions here
import string
import random
# generate and return a unique and random string
# other expectation:
# - at least 2 special char()expect: ';'), 2 number, 2 lower and 2 upper case letter
# - it must be unique in the list
#
# @table: list of list
# @generated: string - generated ra... |
37b2a41de74f4bbdf2674f42a31cdd69fa8e68e1 | el-hult/adventofcode2019 | /day06/day6_lib.py | 2,735 | 3.703125 | 4 | from collections import namedtuple
from typing import Dict, List, Callable
Node = namedtuple('Node', 'name parent children data')
def make_tree_from_adj_list(adj_list):
root = 'COM'
nodes: Dict['str', Node] = {root: Node(root, None, [], {})}
for parent, child in adj_list:
node = Node(child, pare... |
ff619235455a64ff796c4b7c19b6c52345b5f067 | muondu/Election-Platform | /Voter.py | 3,317 | 4.125 | 4 | import sqlite3
def Voter():
candidate = sqlite3.connect('candidates.db')
can = candidate.cursor()
donn = sqlite3.connect('voter.db')
d = donn.cursor()
conn = sqlite3.connect('voting.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS voted(name TEXT)')
d.execute('CREATE TABLE I... |
40ce79c2be533f0e0e0cb144c6bb47a8fa356a49 | JoeHall97/PathFinder | /Python/PathFinder.py | 5,147 | 3.78125 | 4 | """
Created on Wed Aug 21 17:11:14 2019
@author: Joseph Hall
"""
from math import sqrt
from sys import argv
class Map:
def __init__(self,map: list[str],path: list[str]) -> None:
self.map = map
self.curr_pos = []
self.path = path
self.start_pos = self.__getStartPos()
self.go... |
e2aa7df1981591961ce86a0ae6ec86de66bb0341 | akumarkk/Algorithms | /twenty_eight/2_matrix_region_sum/matrix_region_sum.py | 1,701 | 4.09375 | 4 | # Time complexity : O(m * n)
# Space complexity : O(m * n)
def print_matrix(matrix):
for row in matrix:
print(row)
def matrix_sum(matrix):
#x = 0, y=0
n_rows = len(matrix)
n_cols = len(matrix[0])
print("Rows = ", n_rows, " Columns = ", n_cols)
# Create sum_matrix with all 0's
sum_matr... |
26a52c038fffd009435c42c10f23fc54cd971482 | RussellStauffer/developers | /Item_46.py | 772 | 4.0625 | 4 | # Python Item 46.
#
# Use Python 2.7
#
# Demonstration of the Python Range function.
#
# Software Developer: Russell Stauffer
# Date: 01 May 2017
#
#======================================================================
# Part One
# Print items 0,1,2,3
#
for i in range(0,4):
print i
#=================... |
d6c4982be3ad8ee30d54ba5ca428c63b71c4b30f | Gupocca/CSCD110 | /poker/PokerFinal.py | 4,914 | 3.515625 | 4 | from Card import *
import datetime
class Hand():
def __init__(self):
self.values = [] # create value list
for c in range(5): # draw hand
card = Card()
while card in self.values: # must be unique
card = Card()
self.values.append(card) # add to lis... |
5bd5bfc1887c623a4aab8a613fe0a4f705fc9879 | adriculous/pythonbible | /while.py | 218 | 4.0625 | 4 | # playing around with loopy loops - count from 1 to 10
L = []
while len(L) <3:
new_name = input("Please add a new name: ").strip().capitalize()
L.append(new_name)
print("Sorry, list is full.")
print(L)
|
9d3083df49a761cd73e3fae4c6d7128ebd113978 | renkeji/leetcode | /python/src/main/python/Q015.py | 1,482 | 3.578125 | 4 | from src.main.python.Solution import Solution
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
# Find all unique triplets in the array which gives the sum of zero.
#
# Note:
# Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
# The solution set... |
19480df23eb7b8111cf1e2ffadc6712a3f66a281 | renkeji/leetcode | /python/src/main/python/Q032.py | 1,063 | 3.71875 | 4 | from src.main.python.Solution import Solution
# Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed)
# parentheses substring.
#
# For "(()", the longest valid parentheses substring is "()", which has length = 2.
#
# Another example is ")()())", where the longest... |
09ce63378ccfd087fb05fd0e80dd26e7e0b14d22 | renkeji/leetcode | /python/src/main/python/Q123.py | 1,131 | 3.75 | 4 | from src.main.python.Solution import Solution
# Say you have an array for which the ith element is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit. You may complete at most two transactions.
#
# Note:
# You may not engage in multiple transactions at the same time (ie, you must... |
64282b236720ea9745a5362a0df8f2a72dc2f60b | renkeji/leetcode | /python/src/main/python/Q113.py | 1,099 | 3.90625 | 4 | from src.main.python.Solution import Solution
# 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 4
# / \ \
# ... |
6b2a262d6ee41a6a0b7bd08f64dc0a24db8dfe94 | renkeji/leetcode | /python/src/main/python/Q002.py | 1,102 | 3.84375 | 4 | from src.main.python.Solution import Solution
from src.main.python.datastructures.ListNode import ListNode
# You are given two linked lists representing two non-negative numbers.
# The digits are stored in reverse order and each of their nodes contain a single digit.
# Add the two numbers and return it as a linked lis... |
dd09b9ff24c52057208c6feaa0f9ae8f8ca3e054 | renkeji/leetcode | /python/src/test/python/test_q006.py | 298 | 3.5625 | 4 | from unittest import TestCase
from src.main.python.Q006 import Q006
class TestQ006(TestCase):
def test_convert(self):
solution = Q006()
s = "PAYPALISHIRING"
numRows = 3
expected = "PAHNAPLSIIGYIR"
actual = solution.convert(s, numRows)
self.assertEqual(expected, actual)
|
f408829302226da12a8c228c8de5241a6a039aec | renkeji/leetcode | /python/src/main/python/Q038.py | 1,005 | 3.953125 | 4 | from src.main.python.Solution import Solution
# The count-and-say sequence is the sequence of integers beginning as follows:
# 1, 11, 21, 1211, 111221, ...
#
# 1 is read off as "one 1" or 11.
# 11 is read off as "two 1s" or 21.
# 21 is read off as "one 2, then one 1" or 1211.
# Given an integer n, generate the nth seq... |
ca097540c541bf8950acda127e4fbb89b114163e | renkeji/leetcode | /python/src/main/python/Q009.py | 1,233 | 4.09375 | 4 | import math
from src.main.python.Solution import Solution
# Determine whether an integer is a palindrome. Do this without extra space.
#
# Some hints:
# Could negative integers be palindromes? (ie, -1)
#
# If you are thinking of converting the integer to string, note the restriction of using extra space.
#
# You coul... |
61032acc754588d6d7108ed7d3ba23f8561474d2 | renkeji/leetcode | /python/src/main/python/Q110.py | 817 | 4.15625 | 4 | from src.main.python.Solution import Solution
# Given a binary tree, determine if it is height-balanced.
#
# For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees
# of every node never differ by more than 1.
class Q110(Solution):
def isBalanced(self, r... |
f4286e2dd9239a4c3d3bdef724efb5b4b956bffb | VitaliiHudukhin/ithub | /lesson6_tasks/task6_base_01.py | 1,642 | 3.96875 | 4 | from random import random,randint
school = {
'1A': 30,
'1B': 30,
'2B': 25,
'6B': 31,
'7C': 33,
}
print('Valuable commands in this program: ')
valuableCommands = ['change number','new class','delete class','total amount','exit']
for i in valuableCommands:
print(i)
inputData = ""
while inputData.l... |
f6090db7af95ace48db52f89466a13d328070c66 | VitaliiHudukhin/ithub | /lesson2_tasks/task2_01.py | 970 | 4.21875 | 4 | print('Let\'s try to find a max number of three given')
#проверяем число на float
#проверяем число на nan, если ошибка - False
def is_number(strg):
is_number = True
try:
num = float(strg)
is_number = num == num
except ValueError:
is_number = False
num = False
return is_nu... |
0edb2d1857af22eb3434d1bac76fc302b0423efb | VitaliiHudukhin/ithub | /lesson4_tasks/task4_base_02.py | 685 | 4.03125 | 4 |
def is_int(strg):
try:
int(strg)
return int(strg)
except ValueError:
print("Entered data isn't int")
print("Please, enter an int number: ")
number = is_int(input())
while number == None:
print("Please, enter correct number: ")
number = is_int(input())
isPositive = True if numb... |
69a2d5a59cad01f7351963c9b25dbbfa03a92d70 | VitaliiHudukhin/ithub | /lesson3_tasks/task3_advanced_02.py | 318 | 4.1875 | 4 | print('Let\'s find factorial of entered number')
def factor(n):
factorial = 1
if n == 1:
return factorial
elif n <1:
factorial = 'Bad input data'
else:
for i in range(2, n + 1):
factorial *= i
return factorial
n = factor(int(input()))
print('Result is '+str(n)) |
88f19b46ef32ef0ad5dfdc1080a160debc62c152 | vladson/bioinftools | /rearrangements.py | 9,298 | 3.625 | 4 | import re
import dna
class Permutation:
def __init__(self, representation, dst = False):
"""
@param repr: list or str
@param dst: list (opt)
@return: Permutaion
>>> Permutation([-3, 4, 1, 5, -2])
(-3 +4 +1 +5 -2)
>>> Permutation(' (-3 +4 +1 +5 -2) ')
... |
d5ef48b313e1eaaadaf270ad0d507b49039caac1 | FreeDiscovery/FreeDiscovery | /examples/python/categorization_interpretation.py | 2,113 | 3.75 | 4 | """
Categorization Interpretation Example
-------------------------------------
A visual interpretation for the binary categorization outcome for a single document
by looking at the relative contribution of individual words
"""
from __future__ import print_function
import os
from sklearn.datasets import fetch_20newsg... |
de659ac07f9a3748f4a56839556c592c292a1d16 | scottt142/Python---Secuityish | /prog tut 11 part 2.py | 888 | 4.0625 | 4 | def main():
# dictionary of username : hashed_password
users = {
"mim" : 149,
"mls" : 162,
"bon" : 9
}
# attempt a login
success = login(users)
if success:
print("Successful login")
else:
print("Could not login")
def login(users):
# ask for a... |
c28adb7515b130ea500b54784f58e08050eea878 | mayraberrones94/Flujo-en-Redes | /Reporte2/rep2.py | 2,646 | 3.609375 | 4 | from random import random
from math import sqrt
class Grafo:
def __init__(self):
self.n = None
self.x = dict() #
self.y = dict() #
self.P = []
self.pesos = []
self.nodo2 = []
self.nodo3 = []
self.Ari = [] #
self.archivo = None #
def puntos(self, num):
self.n = num
for nodo in range(self.... |
2b141c83c179c28675b490988ee4ff6279863ce3 | mazzalaialan/Python | /Coursera Course/3 - Programación Orientada a Objetos con Python/Ejercicios/caja.py | 8,513 | 3.765625 | 4 | #-*- coding: utf-8-*-
import sys
# *******************************************
# *********primera parte Gerente*************
# *******************************************
articulos={}
fulltotal=0
def ingreso_productos():
caja=True
while caja==True:
opcion =raw_input("Desea ingresar un producto SI/NO... |
110684361f456bd137abb19f8d5147695e859112 | mazzalaialan/Python | /Coursera Course/2 - Estructuras de datos en Python/Modulo4/ta-te-ti.py | 2,783 | 3.515625 | 4 | t=[['_','_','_'],['_','_','_'],['_','_','_']]
s='|'
cont=0
print(s,t[0][0],s,t[0][1],s,t[0][2],s)
print(s,t[1][0],s,t[1][1],s,t[1][2],s)
print(s,t[2][0],s,t[2][1],s,t[2][2],s)
simb=input('Indique con que simbolo quiere jugar (X/O): ')
if simb != 'X' and simb !='O':
while simb != 'X' and simb !='O':
print('L... |
73f30c86c17480141cdcd52cf27773c7693faa57 | mazzalaialan/Python | /Curso Polotic/Clase 2 Estructuras de Datos con Python/TamanioCadenayCantA.py | 324 | 3.921875 | 4 | """Escribe un programa en Python que acepte una cadena de caracteres y cuente el tamaño de la
cadena y cuantas veces aparece la letra A (mayuscula y minúscula)"""
cadena = input("Ingresar la cadena de texto a validar: ")
print("El tamaño de cadena es:", len(cadena), "y la cantidad de A es:", cadena.lower().count('a'))... |
189ba96890ad52caeea10f7bb1c9307f0ee19d3f | hihiroo/Game | /blackJack.py | 5,142 | 3.65625 | 4 | #블랙잭
#프로그래밍 기초 수업 과제
import random
def load_members():
file = open("members.txt","r")
members = {}
for line in file:
name, passwd, tries, wins, chips = line.strip('\n').split(',')
members[name] = (passwd,int(tries),int(wins),int(chips))
file.close()
return members
def login(membe... |
0a002b2379d7aa19acc37bb95718968c04d403b9 | Mrityunjay87/DSMP19_GA | /GreyAtom/SuperHero Project/Hackathon.py | 310 | 3.625 | 4 |
#Python Mini Challenge
#Fibonacci Sequence
import math
import numpy as np
def check_fib(num):
num_sqr_plus=np.sqrt((5*num*num) + 4)
num_sqr_minus=np.sqrt((5*num*num) - 4)
return (num_sqr_plus - math.floor(num_sqr_plus)==0)|(num_sqr_minus - math.floor(num_sqr_minus)==0)
|
dc3e35533c858891cd9775ca217b036e8ad6866a | Mrityunjay87/DSMP19_GA | /GreyAtom/Day7/Function_defination.py | 2,917 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 15 12:10:17 2020
@author: Mrityunjay1.Pandey
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 15 09:42:43 2020
@author: Mrityunjay1.Pandey
"""
import pandas as pd
#Function Defination
test1="sample text"
def splitword(data):
temp={}
data.lo... |
19285b09b1041be9c17bdc36dae44a9f1da9a133 | Rodas-Nega/hungryness-python | /main.py | 435 | 3.9375 | 4 | # Created By: Rodas N.
# Created On: Sept 28 2020
#
# This program displays the "hungryness" variable using if and else if commands.
hungryness = 0
def on_forever():
global hungryness
if input.button_is_pressed(Button.A):
hungryness = hungryness + 1
basic.show_number(hungryness)
elif input... |
440033c0c89af574eb5dfa8d1b15cc90b6524094 | mzwandile316/Level_0 | /Task 6.py | 1,010 | 3.9375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
num_1=int(input("Enter 1st number: "));
num_2=int(input("Enter 2nd number: "));
num_3=int(input("Enter 3rd number: "));
def maxium():
if(num_1>=num_2) and (num_1>=num_3):
largest = num_1
elif(num_2>=num_1) and (num_2>=num_3):
largest = nu... |
46c1aa93828ecd5f89a4919983f144a9de5c0545 | Ushakek/Little_Games | /01_game_what_a_num.py | 724 | 4.09375 | 4 | import random
def rand_num():
x = random.randint(1, 10)
return x
print('Hi, today I gonna play with you. Now i will think about number, and you will go guess this number\n I think...')
user_exit = 'y'
while user_exit != 'n' and 'N':
my_num = rand_num()
print('You can start!')
user_input = 0
w... |
a4f83eacad0f4af34e84fdb2bc8153aa25fccc0c | Vickyyzz/76-270 | /LR Model For Diagnosing Breast Cancer.py | 1,382 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from sklearn import datasets
# Load the data
data_set = datasets.load_breast_cancer()
# Print out the feature names
print ('Feature names:')
print(data_set.feature_names)
print('\n')
# Print out the labels/classifications
print ('Classification outcomes:')
print(dat... |
da99c9e04f428807d8a8ade14920aae82638f3f4 | MatheusKauan/matheus-python | /pacote-download/atividades-python/genero.py | 212 | 3.890625 | 4 | genero = input('Qual o seu sexo? f- Feminino m- Masculino ')
if genero == 'f':
print('Você é do sexo feminino!')
elif genero == 'm':
print('Você é do sexo masculino')
else:
print('Sexo inválido') |
746c7b8057ce68f82f927df489d04e9a2f04ebab | malmiski/bipartite_match | /bipartite_graph_generate.py | 790 | 3.578125 | 4 | from random import random
from math import cos, sin, sqrt
import sys
def gen_circle_rand(x,y,r):
rad = r*sqrt(random())
theta = random()*2*3.14159
return (x + rad*cos(theta), y + rad*sin(theta))
def generate(center_a_x, center_a_y, radius_1, center_b_x, center_b_y, radius_2, n, name):
a = []
b = []
... |
f787c8deba2cb741922dfe235a5a9662a0af27ba | HannahKnights/the-snake-and-the-mouse | /a-portable-paradise.py | 2,568 | 4.46875 | 4 | from lots_of_useful.things import *
"""
This python script will "read" a poem called `A portable paradise` by
Roger Robinson (https://nationalpoetryday.co.uk/poem/a-portable-paradise/)
Features of the display of this poem:
- Each line of the poem will be "read" separately
- Each line of the poem will be inden... |
e6d7d29d98317555b2af0776dd5baaa674eaf818 | HannahKnights/the-snake-and-the-mouse | /introductions/3-arrangements.py | 819 | 4.34375 | 4 | """
python (the snake):
- some words have special meaning to python:
- if
- for
- until
- while
- etc..
- if they find those words they expect a certain structure should follow
- if it's not there then they won't know what to do
* some 'words' have a particular struc... |
866a6752cfc31f42d90372b529ec4b40798a52c4 | HannahKnights/the-snake-and-the-mouse | /example-spacing.py | 449 | 3.53125 | 4 | """
A poem which looks like a staircase
python example-spacing.py
"""
from lots_of_useful.things import *
new_page()
print('a')
print(' simple')
print(' piece')
print(' of')
print(' text')
print(' which')
print(' looks')
print(' ... |
d2a5b4dff6650fe9c324443da4e621e84552c944 | chengxxxxwang/Blog | /python/e001.py | 411 | 4 | 4 | #!/usr/bin/python
#python version:2.7.2
print "Hello world!"
i = 5
print i
i = i + 1
print i
s = '''This is a multi-line string
This is the second line'''
print s
i = 7; print i;
s = 'This ia a string \
This continues the string'
print s
width = 5
height = 2
area = width * height
print 'area is', ar... |
3b520ae90d164b35b7ef52ba2b27eed6fbcd0d0e | pamelot/restaurant-ratings | /restaurant-ratings.py | 759 | 3.515625 | 4 | # your code goes here
restaurant_ratings = {}
scores = open("./scores.txt")
for line in scores:
restaurant, ratings = line.split(":")
restaurant_ratings[restaurant.strip()] = ratings.strip()
for restaurant in sorted(restaurant_ratings):
ratings = restaurant_ratings[restaurant]
print "Restaurant %s i... |
6997ca7ba795519a277c3a189d3f61ae9e6ef336 | tabris1103/inf1340_2014_asst1 | /test_exercise3.py | 2,197 | 3.796875 | 4 | #!/usr/bin/env python3
""" Module to test exercise3.py """
__author__ = 'Kyungho Jung & Christine Oh'
__status__ = "Completed"
# imports one per line
import pytest
from exercise3 import decide_rps
# Test procedures to check whether the decide_rps function outputs
# correct game results when player1 and player2 inpu... |
55d7600951abe87fbac24332f6ffd1431781770b | janliex/Data-Structure-Algorithm | /Leetcode/707_Design Linked List_06170201.py | 2,359 | 4.09375 | 4 | """定義Node"""
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
"""定義LinkedList"""
class MyLinkedList:
"""
基本結構
"""
def __init__(self):
self.head=None
self.tail=None
self.size=0
"""
取得某位置... |
a7b11bbbc3f61a5cd6145b4c7d87ba434cdb3686 | GauthamAjayKannan/coding | /MAX-HEAP.py | 2,398 | 3.65625 | 4 | class MaxHeap:
def __init__(self,capacity):
self.storage=[]
self.size=0
self.capacity=capacity
def hasParent(self,index):
return (index-1)//2>=0
def getParentIndex(self,index):
return (index-1)//2
def getParent(self,index):
if self.hasParent(index):
... |
c1dcabda16d5a0e4636ee01a18cdd4009019ecd7 | GauthamAjayKannan/coding | /zoho10.py | 208 | 3.5 | 4 | n=input()
i=1
sum=0
while i<=5:
sum=str(int(n)+int(n[::-1]))
if sum==sum[::-1]:
print(sum)
break
i+=1
n=sum
else:
print(-1)
|
8524eb5e734932c346419c91bb51ede806f6ec9c | sathishkumark27/LearningNewCPPFeatures | /graphs_python/list_ckeck.py | 123 | 3.59375 | 4 | l = [1,2,3]
for i in range(len(l)):
print("i = %d, l[i] = %d" %(i, l[i]))
if (l[i] == 1):
l.pop(i)
print(l) |
e50ac7b99c94d5d947e3fadd676e7159c7dff632 | heatherstafford/unit5 | /dictionaryDemo.py | 289 | 4.0625 | 4 | #Heather Stafford
#4/25/18
#dictionaryDemo.py - most list practice
words = ['computer','mortify','dog','firetruck','yes','python','cat']
words.sort()
num = int(input('What number word do you want? '))
if num<= 0 or num >= len(words)+1:
print('Invalid number')
else:
print(words[num - 1])
|
9c7ffa65a21cd11688fed98ec6440bf8cfe02ddc | Hemangi3598/p18.py | /p5.py | 335 | 4 | 4 | # wapp with using arithmetic operators
a=3; b=4;
print(a)
print(b)
print(a-b)
print(a+b)
print(a*b)
print(a/b)
print(a//b)
print(a**b)
print(a%b)
# if we have to write a/b in round then we have to write print(round(a/b,2))
# if we have to take nos from user then type a=float(input("enter a")); b=float(input... |
6be985c31bee23e33f77baa9fa86100eb1bd6d89 | Ramshil/musical-eureka | /estimate.py | 367 | 3.703125 | 4 | import math
import random
def wallis(n):
product=1
for i in range(1,n+1):
k=float(4*math.pow(i,2))
product*=(k/(k-1))
pi=2*product
return pi
def monte_carlo(n):
count=0
for i in range(1,n+1):
x=random.random()
y=random.random()
z=math.pow(x,2)+math.pow(y,2)
distance=math.sqrt(z)
if distance<1:... |
f3c12c95d58ae296635dcd2ff64d6dbc76c32626 | SunilKumar-ugra/image_processing_bot | /test.py | 45 | 3.5 | 4 | numbers = [1,2,3,4]
print(numbers.reverse()) |
1e61751a82e8ada4343b9238f2ac0317ce673a3a | JunYinghu/selenium-website-test-automation | /Backup/hr/elearning/dateTimedeltas.py | 2,940 | 3.734375 | 4 | import calendar
from datetime import date
from datetime import datetime
from datetime import timedelta
file = "testing"
# format datetime
def caludate():
now = datetime.now()
print now.strftime("%Y")
print now.strftime("%y")
print now.strftime("%a,%d,%B,%y")
print now.strftime("%c")
print now.... |
2dbee712457b4f2d72f7a43fb7eaf6163bff8ff5 | JunYinghu/selenium-website-test-automation | /Backup/Assignment_junying/backupfobooking/airbook/airbook/utils/date_cal.py | 1,130 | 3.59375 | 4 | from datetime import datetime
def datecovert(d, r):
depature_date_dict = {1: '2017-7', 2: '2017-12', 3: '2018-7', 4: '2018-12', 5: "2019-7", 6: "2019-12"}
return_date_dict = {1: '2017-7', 2: '2017-12', 3: '2018-7', 4: '2018-12', 5: "2019-7", 6: "2019-12"}
depature_date = depature_date_dict.get(d, "")
... |
bb327f9d1fbb418946bbb72f10f18ce51641c396 | yashika-5/FlaskWork | /Flask_With_Database/CRUD.py | 1,147 | 3.5 | 4 | from basic import db,User
from datetime import date
# CREATE
student1 = User('Charlie',22,date(1999,8,5),'Male')
db.session.add(student1)
db.session.commit()
# READ
all_students = User.query.all() # list of student objects in table
print(all_students)
print('\n')
# SELECT BY ID
studentById = User.query.get(1)
if stu... |
38169ebe0bf63302d4a992579f447734c10f3f1a | darouwan/photo_recognize | /recognize_main.py | 1,094 | 3.546875 | 4 | import sys
from model_util import *
if __name__ == "__main__":
training_path = sys.argv[1]
test_path = sys.argv[2]
print("Training KNN classifier...")
classifier = train(training_path, model_save_path="trained_knn_model.clf", n_neighbors=2)
print("Training complete!")
# STEP 2: Using the trai... |
5c241af5756d372fab6366c9c0cea96dc8c4799c | swigder/word_segmentation | /word_segmentation/bigram_word_segmenter.py | 3,347 | 4.25 | 4 | from utilities.utilities import bisect_string
class BigramWordSegmenter:
"""
Segments a sentence containing no spaces into a list of words, by finding the segmentation that maximizes the bigram
probability. The score for of each possible sentence is the bigram probability of the sentence (probability of ... |
fcadae0c7418165a154f84d1ced893cd40e44df3 | swigder/word_segmentation | /word_segmentation/brown_cmu_unigram_provider.py | 1,323 | 3.53125 | 4 | from nltk.corpus import brown, cmudict
import nltk
from utilities.utilities import binary_search
class BrownCmuUnigramProvider:
"""
Provides unigram counts for words in the Brown corpus. Keeps corpus in memory for speed.
"""
words = [word.casefold() for word in cmudict.words()]
brown_words = [w... |
62748fb96117f100823384d6c6c504ca1607bac4 | csp9527/ThinkInRedis | /section03/String_test.py | 827 | 3.640625 | 4 | ## 字符串
# 字符串可以存储以下三种类型的值
# 字节串、整数、浮点数
import redis
conn = redis.Redis()
print(conn.get('key'))
print(conn.incr('key'))
print(conn.incr('key', 15))
conn.decr('key', 5)
print(conn.get('key'))
conn.set('key', '13')
print(conn.incr('key'))
print('-------------------')
conn.set('new-string-key', '')
conn.append('new-string... |
798b1d95900d3759475bbd229067d2af3a537e57 | jgarte/stuff | /python/miscellaneous/rock_paper_scissors.py | 935 | 3.90625 | 4 | import random
rps = ["Rock", "Paper", "Scissors"]
computer = random.choice(rps).title()
user = False
while user is False:
user = input("Rock, Paper, Scissors... ").title()
if user == computer:
print("Tie!")
elif user == "Rock":
if computer == "Paper":
print(f"You ... |
a49cfd6c46ac4cd83d0116a53381e2290add107a | jgarte/stuff | /python/miscellaneous/weight.py | 420 | 4.15625 | 4 | def weight_convert(weight, unit):
if unit.upper() == "L":
final_weight = weight * 0.45
unit = "kilos"
elif unit.upper() == "K":
final_weight = weight // 0.45
unit = "pounds"
output = f"You are {final_weight} {unit}"
return output
if __name__ == "__main__":
weight = ... |
b03b7bda8c9914c243768fff9f261846043b304d | jgarte/stuff | /python/miscellaneous/even_numbers.py | 569 | 4.25 | 4 | def even_number(start, end):
count = 0
number_list = []
type = input("From OR Between : ").lower()
if type == "from":
end += 1
elif type == "between":
end -= 2 for number in range(start, end):
if number % 2 == 0:
number_list.append(number)
... |
07463bdf86ab4a88c37fb738115770f6ab709388 | ahavrylyuk/hackerrank | /python3/maxsubarray.py | 851 | 3.65625 | 4 | #! /usr/bin/env python
def max_subsum(n, a):
positive_sum, current_sum, best_sum = (0,) * 3
has_positive = False
max_negative = a[0]
for i in range(n):
if a[i] > 0:
has_positive = True
positive_sum += a[i]
elif a[i] > max_negative:
max_negative = a[i... |
8f43496c92dddd7866a3493e5dbbbaa631e74d59 | ahavrylyuk/hackerrank | /python3/flipping_bits.py | 691 | 3.921875 | 4 | #! /usr/bin/env python
def binary(value):
""" return array of 32 binary bits """
res = []
while value > 0:
res.append(value % 2)
value = value // 2
return [0] * (32 - len(res)) + res[::-1]
def flip_elements(iterable):
return [1 if e == 0 else 0 for e in iterable]
def decimal(bi... |
4fe5965dfcd299d2a5ce25611fad114fda9c89d8 | ahavrylyuk/hackerrank | /python3/sherlock_and_the_beast.py | 460 | 3.625 | 4 | #! /usr/bin/env python
def decent(n):
count5, count3 = n // 3, 0
is_decent = lambda: 3 * count5 + 5 * count3 == n
while count5 > 0 and count3 <= n // 5:
if is_decent():
break
count3 += 1
count5 = (n - 5 * count3) // 3
if is_decent():
return '555' * count5 + ... |
a9d89e879a18b9141f9284e0240f454562b6599d | ahavrylyuk/hackerrank | /python3/palindrome_index.py | 399 | 3.6875 | 4 | #! /usr/bin/env python
def is_pal(s):
return s == s[::-1]
def p_index(s):
i, j = 0, len(s) - 1
while i < j and s[i] == s[j]:
i += 1
j -= 1
if i == j:
return -1
if is_pal(s[i + 1: j + 1]):
return i
if is_pal(s[i: j]):
return j
if __name__ == '__main__... |
949bc28a82e2d4f916c9d24398f7d14b3dbb1ef7 | ahavrylyuk/hackerrank | /python3/acm_icpc_team.py | 467 | 3.859375 | 4 | #! /usr/bin/env python
def get_team(n, m, person):
teams = []
for i in range(n - 1):
for j in range(i + 1, n):
teams.append(bin(person[i] | person[j]).count('1'))
max_topic = max(teams)
return (max_topic, teams.count(max_topic))
if __name__ == '__main__':
n, m = map(int, inpu... |
27fa2d0adbffe9cab25c00a232001f96391a43fd | ahavrylyuk/hackerrank | /python3/halloween_party.py | 248 | 3.546875 | 4 | #! /usr/bin/env python
def max_pieces(k):
horizontal = int(k / 2)
vertical = k - horizontal
return horizontal * vertical
if __name__ == '__main__':
t = int(input())
for _ in range(t):
print(max_pieces(int(input())))
|
7415884d1ee601807983075d278c99ca27e3c48e | ahavrylyuk/hackerrank | /python3/common_child.py | 423 | 3.5 | 4 | #! /usr/bin/env python
def common_sub(a, b):
prev = [0] * len(b)
for i, ai in enumerate(a):
current = [0] * len(b)
for j, bj in enumerate(b):
if j > 0:
current[j] = prev[j - 1] + 1 if ai == bj \
else max(current[j - 1], prev[j])
prev = cu... |
fa3d93fb09183d99a2b2c2cc8f3f50d6e0d04335 | NicholasAllair/ITI1120 | /exam prep/tst2.py | 229 | 3.625 | 4 | def min_or_max_index (lst, TF):
s_lst = lst.sort()
print (s_lst[0])
if TF == True:
min_value = s_lst[0]
pos = lst.index(min_value)
return (min_value,pos)
|
499ef523e46734a5cd4aef2dc0b7dfaf5ec29252 | NicholasAllair/ITI1120 | /Assignments/A2_8147249/part_1_8147249.py | 5,191 | 3.890625 | 4 | import math
import random
def primary_school_quiz(flag, n):
def performTest (mark,n):
score = mark / n
if score >= 0.9:
print("Congradualtions" +name+ "! You'll probably get an A tomorrow. Now go eat you dinner and go to sleep.")
elif (score >... |
c39eb9819bead3531df1dc429736ad3611222aab | NicholasAllair/ITI1120 | /Labs/lab11-solutions/prog_ex1.py | 284 | 3.609375 | 4 | def m(i):
'''(int)->number
returns the sum 1/3+2/5+3/7+...+i/(2i+1)
Precondition: i>=1
'''
if i == 1:
return 1 / 3
else:
return m(i - 1) + i * 1 / (2 * i + 1)
for i in range(1, 11):
print('m('+str(i)+')=', m (i) )
|
8c543ea2d28fa3e673189c3e96fd57e4d9a426d1 | daim77/engeto_repo | /palyndrom.py | 554 | 3.859375 | 4 | # tento program pozna zda uzivatel zadal palyndrom
# header
# print('=' * 40)
# print('Tento program testuje zda zadany vyraz je PALYNDROM ci nikoliv')
# print('=' * 40)
# # zadani promene
# slovo = input('Zadej slovo: ')
# my_word_reverse = list(slovo)
# my_word_reverse.reverse()
# print('Slovo', slovo, ':')
# if my_w... |
896b54abf3e32711a23221b592e40939bfaa7187 | daim77/engeto_repo | /index.py | 469 | 3.5625 | 4 | # Extrahuj a vytiskni prvních 5 písmen
print('=' * 20)
my_index = "indexování"
prvnich_pet = my_index[:5] # petku lze nahradit promennou INT
print('first five letters: ', prvnich_pet)
# Extrahuj a vytiskni posledních 5 písmen
print('=' * 20)
poslednich_pet = my_index[5:]
print('last five letters: ', poslednich_pet)
... |
172a680e1a803890507d4b2e165fa6ecf420e84c | daim77/engeto_repo | /generatory.py | 938 | 3.703125 | 4 | # def my_range(start, stop, step=1):
# test = (lambda x, y: x < y and step > 0,
# lambda x, y: x > y and step < 0)[start > stop]
#
# while test(start, stop):
# yield start
# start += step
#
#
# gen = my_range(0, 10)
# # for i in gen:
# # print(i)
# print(next(gen))
# print(next(g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.