blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
97b74119ddcbc077e44755d38b27a7e3361edfa5 | matthewdoles/python-practice | /zelle-python/chapter08/syracuse.py | 536 | 4.1875 | 4 |
# exercise 4 - calculate the Syracuse sequence when given a user input
# sequence stops when the number 1 is reached
def syracuse(x, sequence):
if x % 2 == 0:
x = int(x / 2)
sequence.append(x)
elif x % 2 == 1:
x = int(3 * x + 1)
sequence.append(x)
return x
de... |
472dd25b7227f053b3034da924a657c8aff238c4 | himanshushukla254/OPENCV_Python_Codes | /threshold.py | 315 | 3.5 | 4 | # import opencv
import cv2
# Read image
src = cv2.imread("threshold.png", cv2.IMREAD_GRAYSCALE)
# Set threshold and maxValue
thresh = 0
maxValue = 255
# Basic threshold example
th, dst = cv2.threshold(src, thresh, maxValue, cv2.THRESH_BINARY);
cv2.imshow('image',dst)
k=cv2.waitKey(0)
cv2.destroyAllWindows()
|
8d5a6e22cc13f3a0e869d296e1722005d63aba1d | szhou12/MachineLearning4PublicPolicy | /pa2/Preprocess.py | 4,949 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 13 15:32:38 2018
@author: JoshuaZhou
"""
import scipy.stats
import numpy as np
import pandas as pd
def fill_missing(df, cols, mean=True):
'''
Fill in missing values using mean if mean==True or 0 if mean==False.
Inputs:
df:... |
e941cbaf4e482d7da49061c63be957553d268cf1 | bssrdf/pyleet | /F/FloodFill.py | 3,739 | 4.03125 | 4 | '''
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
'''
from queue import Queue... |
91349c2d8c90d86fcbc5d2e1ce155a53c94d8910 | aanndalia/andrew-dalia | /anagram_diff.py | 2,063 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import fileinput
def anagramDiff2(word):
word = word.rstrip('\n')
if not word:
return -1
if len(word) % 2 == 1:
return -1
mid = len(word) / 2
word1 = word[:mid]
word2 = word[mid:]
word1list... |
fd00c250778b1014b678c856fbc011b039c5a452 | ankursheth/python_practice | /fibonacci.py | 594 | 4 | 4 | def fibonacci1(number):
if number == 0:
return 0
elif number == 1:
return 1
else:
return fibonacci1(number-1)+fibonacci1(number-2)
def fibonacci2(number):
x, y = 1, 1
for i in range(number-1):
x, y = y, x+y
return x
def fibonacci3():
x, y = 1, 1
while ... |
3e7e48ec1739d1fb417805ba372dfbf06fe91777 | ccc013/DataStructe-Algorithms_Study | /Python/Leetcodes/binary_tree/jianzhi_offer_68_2_lowestCommonAncestor.py | 938 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2020/12/14 7:45 上午
@Author : luocai
@file : jianzhi_offer_68_2_lowestCommonAncestor.py
@concat : 429546420@qq.com
@site :
@software: PyCharm Community Edition
@desc :
https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/... |
50a008dc38801d47d37e975fba037bbcddb06b93 | chenxu0602/LeetCode | /1114.print-in-order.py | 2,735 | 4.0625 | 4 | #
# @lc app=leetcode id=1114 lang=python3
#
# [1114] Print in Order
#
# https://leetcode.com/problems/print-in-order/description/
#
# concurrency
# Easy (65.64%)
# Likes: 576
# Dislikes: 103
# Total Accepted: 60.6K
# Total Submissions: 91.4K
# Testcase Example: '[1,2,3]'
#
# Suppose we have a class:
#
#
# publ... |
29adb2d797cdd1d43a3928a9fe835736f6c3e85d | kelvin002a/kes-sqlite3 | /script.py | 570 | 4.1875 | 4 | import sqlite3
connection = sqlite3.connect("test.db")
Cursor = connection.cursor()
table1 = """CREATE TABLE IF NOT EXISTS
Movies(movie_name TEXT,Actor_name Text ,actress_name TEXT ,Director_Name TEXT ,Year_of_release INTEGER) """
Cursor.execute(table1)
Cursor.execute("INSERT INTO Movies VALUES ('PIE','Arun','Bo... |
1a2a51b714e82ae71922c9dfb5d3b002923d53b3 | Crow07/python-learning | /python learning/循环/for.py | 390 | 3.984375 | 4 | for i in range(3):
print('loop',i)
for i in range(0,6,2):
print("loop",i)
age_of_crow = 22
count= 0
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age == age_of_crow:
print("yes,all right")
break
elif guess_age > age_of_crow:
print("smaller")
else:
... |
85d6b0e97d344c9a3252c575fb404bb8cca40d4d | cory-evans/calculus | /complex_numbers.py | 1,508 | 3.671875 | 4 | from math import *
def to_polar(c: complex):
r = sqrt(c.real ** 2 + c.imag ** 2)
theta = tanh(abs(c.imag) / abs(c.real))
if c.real < 0 and c.imag >= 0:
theta_real = pi - theta
print('c.real < 0 and c.imag >= 0')
elif c.real < 0 and c.imag < 0:
theta_real = pi + theta
... |
4484d59b49850f2dd950561f9afe0b44ba1e6718 | ycliu912/python-basic | /pyhelloworld/src/class03.py | 844 | 3.921875 | 4 | #-*-coding:utf-8 -*-
'''
Created on 2016年5月10日
@author: liu
'''
class Parent: #定义父类
parentAttr = 100
def __init__(self):
print "调用父类构造函数"
def parentMethod(self):
print "调用父类方法"
def setAttr(self,attr):
Parent.parentAttr = attr
... |
93216b996bbb01741f86b67d237ee18df2e0e961 | Fitzy1098/AI-Search-Assignment | /AI Search 17-10-18.py | 2,131 | 3.65625 | 4 | def readFile(filename):
#filename = "AISearchtestcase.txt" #"NEWAISearchfile012.txt" #
file = open(filename, 'r')
data=file.readlines()
stringdata="".join(data)
return(stringdata)
def getName(stringdata):
stringdata=stringdata.split("=")
name=stringdata[1].lstrip(" ") ... |
e260b5a547f126bfe66252298cfe23cb352d8032 | nushrathumaira/Udacity_DataStructureAlgo | /P2/problem_4.py | 1,192 | 4.21875 | 4 | def swap(input_list, i, j):
temp = input_list[i]
input_list[i] = input_list[j]
input_list[j] = temp
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
start = 0
... |
69517becf55b367b141181fbcc44e32ac154b8a8 | codewithgauri/HacktoberFest | /python/two_sum.py | 537 | 3.609375 | 4 | /*
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
*/
class Solution(object):
def two... |
e24a55e306bee7063d56f2bb5a893ee6dc628653 | cristianjs19/codefights-solutions-Python | /The Core/02 - largestNumber/largestNumber.py | 105 | 3.625 | 4 | def largestNumber(n):
res = ""
for i in range(n):
res = res + "9"
return int(res) |
c1e8ec2d2df231c63b1d1327abacd954d5edba7d | zjxpirate/Daily-Upload-Python | /hash_tables/find_anagrams.py | 519 | 4.3125 | 4 |
import functools, collections
# 2. find anagrams
def find_anagrams(dictionary):
sorted_string_to_anagrams = collections.defaultdict(list)
for s in dictionary:
# sorts the string, uses it as a key, and then appends the original
# string as another value into hash table.
sorted_string_... |
2eba91d9a3642847e949eeebd52d6043a895b644 | ARASKES/Python-practice-2 | /Practice2 tasks/Lesson_9/Task_9_1.py | 364 | 3.8125 | 4 | M = int(input())
N = int(input())
library_books = []
book_list = []
for i in range(M):
library_books.append(input())
for i in range(N):
book_list.append(input())
for book in book_list:
is_found = False
for lb in library_books:
if lb == book:
is_found = True
if is_found:
... |
c112b762be793050ac1f290f63a652427060979a | ihaeeun/Algorithms | /Python/SWExpertAcademy/level3/5601.py | 92 | 3.6875 | 4 | for t in range(int(input())):
n=input()
s='1/'+n+' '
print(f'#{t+1} {s*int(n)}') |
9156f384f1ed2557a2bb5fac10082d966d1a7f69 | jiaxiaoyu7777/ai-game | /chess game.py | 9,041 | 3.734375 | 4 | # 棋盘
#define game
row = 4
maxdepth = 3
playuse = 1
#0: minmax 1: 减枝算法
class Board(object):
def __init__(self):
#self._board = '-'*9 # 坑!!
self._board = ['-' for _ in range(row*row)]
self._history = [] # 棋谱
# 按指定动作,放入棋子
def _move(self, action, take):
if self._board[actio... |
aa540a6c38f81bb77831df7599c4f389743ec6f6 | BBorisov95/python_fund_homeworks | /03-Problem.py | 762 | 3.8125 | 4 | emails = {}
command = input()
while not command == 'Statistics':
command = command.split('->')
if command[0] == 'Add':
if command[1] in emails:
print(f'{command[1]} is already registered')
else:
emails[command[1]] = []
elif command[0] == 'Send':
emails[comm... |
6a743f698af4aa2fd4e36e1c7c2f5f5b17e98e02 | Enoch715/Python--guss-number | /gussnumber.py | 447 | 3.75 | 4 | import random
start = int(input('請決定隨機數字開始值: '))
end = int(input('請決定隨機數字結束值: '))
num = random.randint(start, end) #產生隨機數字
count = 0
while True:
user = int(input('請猜數字: '))
count += 1
if user == num:
print ('恭喜猜對了!!!!共猜測', count, '次')
break
elif user > num:
print('比答案大')
elif user < num:
print('比答案小')
pri... |
f06b7841ea0aaf0a2df3d725bbdf80592acbeed7 | WallysonGalvao/Python | /CursoEmVideo/3 - TwentyOneToThirty/Challenge024.py | 260 | 4.125 | 4 | """Checking The First Letters Of A Text"""
print("Challenge 024")
print("Create a program that read the name of a city and tell if it begin or not with the name 'SANTO'")
city = str(input('What city do you born ?')).strip()
print(city[:5].upper() == 'SANTO')
|
236f0a571e35e0fdf22ef3b25fac867b200a2e73 | rajesh-zero/PracticePrograms | /Python/shortPyPrograms/4.py | 251 | 4.0625 | 4 | #String datatype
#slicing
mystr="hellO how are you bro kaisa chal raha hai zindagi main"
print(mystr[1])#it takes second letter
print(mystr[::-1])
print(len(mystr))#length of mystr
print(mystr[1:5:])
print(mystr.split('l'))
print(mystr.swapcase())
|
0a54a4f3e2d1cfca75e6b8a2b2c3b675e9a773ff | zeerakt/Python-Chatbot | /server.py | 1,672 | 3.65625 | 4 | """
A python Chatbot using Tkiner for the GUI
The program uses TCP sockets, with AF_INTET and SOCK_STREAM flags.
"""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
# Global variables
clients = {}
addresses = {}
HOST = 'localhost'
PORT = 12346
BUFSIZE = 1024
ADDRESS = (HOST, PORT)
SER... |
d6c5a2e742f788ac11fda04bd27908d43747f0be | Jhordancito/Python | /ejercicio1ifelse.py | 303 | 4.03125 | 4 | print("Programa tendra una función llamada DEVUELVEMAX")
num1 = int(input("Introducir el primer Numero:" ))
num2 = int(input("Introducir el segundo Numero:" ))
def DevuelveMax(num1,num2):
if num1>num2:
print(f"El {num1} es mayor")
else:
print(f"El {num2} es mayor")
DevuelveMax(num1,num2) |
c6c811c24068fd92d82c190e42aa1d47fb2c3851 | anlzou/python-test | /python-course/P90_10_19/P90_6.py | 505 | 3.796875 | 4 | import math
#<0
def fun_1():
print("函数无解")
#=0
def fun_2(a,b):
x1 = -b/2*a
print("有一个解:",x1)
#>0
def fun_3(a,b,c):
x1 = (-b+math.sqrt(b**2-4*a*c))/2*a
x2 = (-b-math.sqrt(b**2-4*a*c))/2*a
print("有两个解:%d,%d"%(x1,x2))
def fun(a,b,c):
p = b**2-4*a*c
if p < 0:
fun_1()
elif p ... |
b5d9fec765a1705e92aa13f1431f911f851313f5 | Yakima-Teng/Salute_Python | /python_basic_02/arithmetic_operator_06/arithmetic_operator.py | 10,094 | 4 | 4 | #!/usz/bin/env python
# -*- coding:utf-8 -*-
"""
@file : arithmetic_operator.py
@author : zgf
@brief : python算数运算符
@attention : life is short,I need python
"""
# ========================================= 算术运算符 =========================================
# 和数学中的运算符的优先级一致,在 Python 中进行数学计算时,同样也是:
# 先乘除后... |
6b972f353091c2a416ae1151bf54ae187a082f82 | Shalin-Shekhar/python-challenge | /PyBank/main.py | 2,193 | 4.125 | 4 | # First we'll import the os and csv module
# This will allow us to create file paths across operating systems
import os
import csv
# Write a function that returns the arithmetic average for a list of numbers
def average(numbers):
length = len(numbers)
total = 0.0
for number in numbers:
total += num... |
28274d71e2c20ba52f965a3179a3d62169bc6823 | Novellino89/Testing-program | /Poker di dadi.py | 7,965 | 3.5 | 4 | import random as r
import os
#from Definizione_funzioni import tira,calcola_risultato,Visualizza_Ottenuto
#creazione funzione tira
def tira():
r.seed()
a=r.randint(1,6)
return a
#creazione funzione calcolo risultato
def calcola_risultato(tiro):
coppia=0
tris=0
somma=0
vincente=0
checkcoppia=0... |
f1438c2a955e4f0952b79d5da31b4ef6cbcc1508 | lopeztaelisa/CS2302 | /hashtbl.py | 3,360 | 3.8125 | 4 | #Author: Elisabet Lopez
#CS 2302 10:30AM
#Instructor: Diego Aguirre
#T.A.: Manoj Pravaka Saha
#Lab Assignment 4 Option A
#Last modified: November 11, 2018
#Purpose: This program creates a hash table to store words and their vector description (embedding).
#The hash table solves collisions by chaining. This program inc... |
c0963368d33ad9ea54375931c52fa9038b7451a1 | stoicio/whiteboard | /python/sorting/faster_sorts.py | 637 | 4.4375 | 4 | from data_structures import heap_pq
def heap_sort(list_to_sort, sorting_function):
""" Given a list and a sorting function, uses heap sort to sort the list
Args:
list_to_sort (list) : List containing any abstract data type
sorting_function (function): A function which takes in two args and returns Tru... |
404a1437aaf3c148054ee7c2cf8648cc05e52156 | yxpku/anand-python | /chapter2/pro8-min_max.py | 421 | 3.96875 | 4 | #Python has built-in functions min and max to compute minimum and maximum of a given list. Provide an implementation for these functions. What happens when you call your min and max functions with a list of strings?
def min(list):
list.sort()
return list[0]
def max(list):
list.sort()
return list[-1]
print min([1,... |
3bde04eec167ff1473858c0b929b902dbe023489 | mkp-in/codefights-py | /intro/level2/adjacent_elements_product.py | 358 | 3.703125 | 4 | #
# https://app.codesignal.com/arcade/intro/level-2/xzKiBHjhoinnpdh6m
#
def adjacentElementsProduct(inputArray):
product = -32768
for i in range(0, len(inputArray)-1):
if inputArray[i] * inputArray[i+1] > product:
product = inputArray[i] * inputArray[i+1]
return product
print(adjacent... |
56aefcec8169a9a3853ffa03a585b3aaa4f46423 | samuelyusunwang/PythonStudy | /Think Python/Exercise/Ex_8_5.py | 237 | 4.125 | 4 | # count
def count(word, letter):
'''
count the number of letter in word
'''
count = 0
for x in word:
if x == letter:
count = count + 1
return count
# test code
print(count('abcdabcda', 'a')) |
fe06b9af5e1cee069cc4dbb6b490914cda87884b | Sandy4321/Effective-Quadratures | /effective_quadratures/computestats.py | 3,384 | 4.21875 | 4 | #!/usr/bin/env python
"""Computing Statistics from Polynomial Expansions"""
import numpy as np
from utils import error_function
class Statistics(object):
"""
This class defines a Statistics object
:param numpy matrix coefficients: polynomial coefficients (can be from any of the methods)
:param IndexSe... |
2cf353986b37e9d0f18a8bda9b38ecda1c9660fe | sunandinis/Rosalind-Problems | /Hamming Distance.py | 394 | 3.59375 | 4 | def hamming_distance():
file=open('/Users/dhruvarora/Downloads/rosalind_hamm (1).txt', 'r')
fastafile = [line.rstrip('\n') for line in file.readlines()]
s = fastafile[0]
t = fastafile[1]
hamming_count = 0
for nucleotide in range(0,len(s)):
if s[nucleotide] != t[nucleotide]:
hammi... |
a31f963abe87e2be1dd1004975f2fb29a750c374 | Sarayaar/python01 | /Assignments/sr.assignment3.1.py | 192 | 3.609375 | 4 | hrs = float(raw_input("Enter Hours: "))
rte = float(raw_input("Rate: "))
if hrs > 40:
extra_hrs = hrs - 40
tnh = rte * 1.5
total = (rte * 40) + (extra_hrs * tnh)
else:
total = hrs * rte |
3cb3949fa1cbba0c129190d909a0b62eaedcb6f4 | gmroughton/advent-of-code | /2020/dec_8.py | 2,725 | 3.9375 | 4 | import copy
from pprint import pprint
def program_to_list(filename):
"""
Convert a file into a list representing commands in an assembly-like language
:param filename: File containing instruction set
:return: The program loaded into memory as a list of instructions
"""
output = []
with op... |
e68b722216be4abb5ab7de9f93e69387a2564ac0 | weichuntsai0217/work-note | /programming-interviews/epi-in-python/ch11/12_7_FINDTHE_MIN_AND_MAX_SIMULTANEOUSLY.py | 1,518 | 4.03125 | 4 |
def find_min_max(x):
"""
The time complexity is O(n)
"""
if not x: return None
if len(x) == 1:
return x[0], x[0] # the first is min and the second is max
min_val = x[0]
max_val = x[0]
for i in xrange(1, len(x)):
if x[i] < min_val:
min_val = x[i]
elif x[i] > max_val:
max_val = ... |
ce89d666264232f9ba2012360cfdf595d036d530 | rubakhan9430/PythonTraining | /Week4/practice3.py | 139 | 4.03125 | 4 | value = float(input('Enter a number:'))
while (value > 10 and value < 100):
value = float(input('Enter a number again:'))
print(value)
|
5b92f2ee24280cdcb9e78ce2b0f7703905528941 | Nithanaroy/PythonSnippets | /Uber2.py | 574 | 3.84375 | 4 | """
Given two arrays a and b,
for each i in b:
find the number of numbers in a greater than a[i]
"""
def countGreaterNumbers(a, b):
c = sorted(a)
res = []
for i in b:
res.append(findGreater2(c, a[i - 1]))
return res
def findGreater(a, n):
count = 0
for i in a:
if i > n:
... |
7cebc529be2c188720591880ce65d001d63870a5 | zhtsh/Learning-Algorithms | /python/Sort.py | 3,074 | 3.859375 | 4 | #! /usr/bin/python
# coding=utf8
import sys
import time
import random
def select_sort(data_list):
print("starting select sorting........")
begin_time = time.time()
n = len(data_list)
for i in range(n):
k = i
is_sorted = True
for j in range(i+1, n):
if data_list[j] <... |
3b310c770336c7cd210af8b13e6aa2bf504f4ed6 | tdsymonds/codeeval | /python/easy/(92) penultimate-word.py | 507 | 3.515625 | 4 | import sys
with open(sys.argv[1], 'r') as f:
for line in f.readlines():
if line:
line = line.strip()
# find the last space and trim
last_space = line[::-1].find(' ')
line = line[:-last_space-1]
# find the next last space and trim
... |
6f33db467efb2c903866e39352da668b55b65260 | SteveVallay/coding-bat-py | /coding_bat/w2/string_match.py | 321 | 3.640625 | 4 | def string_match(a,b):
la = len(a)
lb = len(b)
l = min(la,lb)
s = 0
for i in range(0,l-1):
print 'ai+2', a[i:i+2]
if a[i:i+2] == b[i:i+2]:
s+=1
return s
def min(a,b):
if a > b:
return b
else:
return a
print string_match('abcdef','abdcef')... |
978d6ddfe90450d3845c26fb084b9a944e4ff593 | Yosh23/python-scraper | /scrape.py | 315 | 3.546875 | 4 | from bs4 import BeautifulSoup as bs
import lxml
with open('test.html', 'r') as html_file:
content = html_file.read()
soup = bs(content, 'lxml')
titles = soup.find_all('title')
h1s = soup.find_all('h1')
for title in titles:
print(title.text)
for h1 in h1s:
print(h1.text) |
fdead48fb02d6c959e513343e39d6ee2d062f7db | yaposebastien/ProgContact | /contact.py | 420 | 3.671875 | 4 | #!/usr/bin/env python3.6
"""
Ce Script est une reecriture du programme d'un carnet d'addresse en Python.
L'objectif est de sauvegarder les contacts permanemment d'un fichier texte et
le gerer par un menu.
"""
print("Nom du contact ou Saisir Q pour stopper :", end=' ')
nom = input()
print("Telephone du c... |
61398be9729f27558ef6d5d537deab55e5e99df4 | willgrota/CEDERJ_EXERCICIOS | /FP_AD2/questao-4-AD2.py | 1,618 | 3.515625 | 4 |
import struct
TAM = 8
# Subprogramas
def ler(arq):
inteiro = struct.unpack("=i", arq.read(4))[0]
flutuante = struct.unpack("=f", arq.read(4))[0]
return inteiro, flutuante
# Programa Principal
intTest = int(input())
flutTest = float(input())
with open("valores.bin", "r+b") as arq:
arq.seek(0)
... |
1bf68719b0a145721afdab97fdd3e16ea8fa3850 | abhishekzambre/Python_Programs | /DSA/Stacks.py | 1,496 | 3.828125 | 4 | class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage."""
def __init__(self):
"""Create an empty stack."""
self._data = [] # nonpublic list instance
def len (self):
"""Return the number of elements in the stack."""
return len(self. _data)
... |
cfca0089d8ca04371ddf649840fab1a9fb9b9345 | RusKursusGruppen/GRIS | /lib/expinterpreter.py | 1,458 | 3.625 | 4 | class ExpinterpreterException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return "Not a valid expression: " + repr(self.value)
def lexer(string):
result = ['']
for char in string:
if char.isdigit():
if result[-1].isdigit():
... |
553ff635122902861aae01a73c71b4302d63155c | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_168.py | 604 | 4.09375 | 4 | def main():
degree = input("Please enter the temperature: ")
scale = input("Please enter 'C' for Celcius, or 'K' for Kelvin: ")
if degree > ("99") and scale == "C":
print("At this temperature, water is a gas.")
if degree >= ("373.15") and scale == "K":
print("At this temperature, water i... |
eb59c674748a3a747462cfde8d2f5a0fcbe5a657 | gateway17/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 531 | 4.25 | 4 | #!/usr/bin/python3
# Write a function that removes all characters c and C from a string.
# Prototype: def no_c(my_string):
# The function should return the new string
# You are not allowed to import any module
# You are not allowed to use str.replace()
def no_c(my_string):
ctr = 0
new_string = ""... |
7a6dce314eeb28162deeb60475405c04f2bff698 | LiuTianyong/myml | /第一章/coding.py | 1,709 | 3.53125 | 4 | #导入需要用到的库
import numpy as np
import matplotlib.pyplot as plt
#定义储存输入数据(x) 和 目标数据(y) 的数组
x,y = [], []
#遍历数据集,变量sample对应的正是一个个的样本
for sample in open('.//data/prices.txt','r'):
_x, _y = sample.split(',')
#将字符串数据转化为浮点数
x.append(float(_x))
y.append(float(_y))
#读取完数据后,将他们转化为numpy 数组以方便进一步的处理
x, y = np.... |
0386f330e92e65f75188310530de8ecced176aae | wbroach/python_work | /ch_4_range_loops.py | 532 | 3.890625 | 4 | #for value in range(1,1000001):
#print(value)
#millions = list(range(1,1000001))
#print(min(millions))
#print(max(millions))
#print(sum(millions))
#odds = list(range(1,21,2))
#for odd in odds:
#print(odd)
#multiples = list(range(3,31,3))
#for multiple in multiples:
#print(multiple)
#cubes = list(range(1,... |
1379e620591bd5bc57c6df3c13550e03c6b09747 | ongsuwannoo/Pre-Pro-Onsite | /Pancake Shop EP.5.py | 358 | 3.640625 | 4 | """ Pancake Shop EP.5 """
def main():
""" input """
num = float(input())
print("|--------|")
print("|%-8.2f|" %num)
print("|--------|")
print("")
print("|--------|")
print("|%8.2f|" %num)
print("|--------|")
print("")
print("|--------|")
print("|%08.2f|" %num... |
a75e00640e83c0e74a2568712286a116ebae7b09 | taurusyuan/python | /04_高级数据类型/hm_13_字符串定义和遍历.py | 119 | 3.921875 | 4 | str1 = "hello python"
str2 = '他的外号是"大西瓜"'
print(str2)
print(str1[6])
for char in str2:
print(char) |
db1fa395cc8e1b98de1658a0cb86d5a66d8c6dbe | naushadzaman/DecipherDataOrg | /projects/twitter-search-stream-api/twitterstream.py | 3,281 | 3.96875 | 4 | # this program outputs twitter streams with language code, user name, tweet, creation time in a tab seperated output
# usage: python twitterstream.py
# initial skelaton taken from: https://class.coursera.org/datasci-001
#The steps below will help you set up your twitter account to be able to access the live 1% strea... |
f2683732791ca2fb143c1937127e8b7ce87ddb8c | Muhammed-Moinuddin/30daysofcode | /codeday1.py | 1,148 | 4.0625 | 4 | print("hello,world!")
name = "mark"
name = "ace"
print(name)
thanx = "thanks for your input!"
print(thanx)
weight = 150
sum = weight + 150
print(sum)
print(13*4)
print(12/5)
print(12%5)
print(10%3)
print(3%10)
print(3/10)
age = 50
age += 18
print(age)
age *= 2
print(age)
greeting = "Hello"
address = "World"
separators ... |
b8751596c06a2be2d40692d39c7bc2292e78e00a | torresv1/mit_intro_programming | /l4_p5_lo_hi_function.py | 558 | 3.9375 | 4 | # Name: Write a Python function, clip(lo, x, hi) that returns lo if x is less than lo; hi if x
# is greater than hi; and x otherwise. For this problem, you can assume that lo < hi.
# Purpose: Learn to use functions
# Date: 12/14/2013 12:18 PM
# Author: Vladimir Torres-Rivas
def cli... |
257bfab4cd7ce9edb6e93f5a271bf3a99217f043 | jeremiah-hodges/learning.py | /basics/exp.py | 271 | 3.859375 | 4 |
def exp(base, power):
num = 1
for index in range(power):
num = num * base
return num
print(exp(5,3))
def exp3(base, power):
result = 1
while power > 0:
result = base * result
power -= 1
return result
print(exp3(5,3)) |
a10dbd8bdb19c7b557105ec8de31ed4fb53d7b7e | hongta/practice-python | /search/binary_search.py | 1,070 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def binary_search(a, needle):
def _binary_search(lo, hi):
print lo, hi
mid = lo + (hi - lo) //2
if lo > hi:
return False
elif a[mid] < needle:
return _binary_search(mid + 1, hi)
elif a[mid] > needle:
... |
abb9c66974e8d4fb360ed8ce1a3b104e29368397 | matejtarca/MasarykBOT | /tests/mocks/helpers.py | 877 | 3.890625 | 4 |
class MockReturnFunc(object):
"""
This object mocks the returns of a function
It takes a generator and on each call returns
the next value
example:
def true_once():
yield True
yield False
class MockTrueFunc(object):
def __init__(self):
... |
2685e666b9cc393588fd6184461d6f1ab496e51a | SylarK/Python_ | /Road/Dictionaries/main_intro.py | 410 | 4.21875 | 4 | # Dictionaries
# Are indexed by keys, which can be any immutable type.
# All keys are unique in the dictionaries.
# list(d) - dictionary return a list of all the keys used in the dictionary
data = {'John':455620, 'Julia':998653}
data['Joshua'] = 999999
#print(list(data))
#print(sorted(data))
print('John'... |
439c4a01f042bd0e882469e0f0886bf187f9bfc5 | JulyKikuAkita/PythonPrac | /cs15211/InsertintoaBinarySearchTree.py | 3,940 | 4.09375 | 4 | __source__ = 'https://leetcode.com/problems/insert-into-a-binary-search-tree/'
# Time: O(h) h: height of the tree
# Space: O(h)
#
# Description: Leetcode # 701. Insert into a Binary Search Tree
#
# Given the root node of a binary search tree (BST) and a value to be inserted into the tree,
# insert the value into the B... |
7b83e1f07336a3df88cf14b3bed36463e386147d | ChangxingJiang/LeetCode | /未完成题目/0701-0750/0702/0702_Python_1.py | 515 | 3.5 | 4 | # """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
# class ArrayReader:
# def get(self, index: int) -> int:
class Solution:
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtyp... |
67ef86169e16782f1f3b22091a2eaa81b9d51687 | sotirisnik/projecteuler | /prob20.py | 262 | 3.5625 | 4 | memo = {}
def f( x ):
if x == 0:
return 1
if x in memo:
return ( memo[x] )
memo[x] = x*f(x-1)
return ( memo[x] )
tmp = f(100)
ans = 0
while tmp > 0:
ans += ( tmp % 10 )
tmp /= 10
print "%d" % ( ans ) |
54332b7b956b591c6436d94281882076aa41a901 | sumitjain34/flickr-store | /app/utils.py | 502 | 3.59375 | 4 | def solve_pagination(total_pages,page_no):
print "solving pagination"
if page_no > 5 and page_no != total_pages:
start_page = page_no - 4
end_page = start_page + 9
elif page_no <= 5:
start_page = 1
end_page = start_page + 9
else:
end_page = total_pages
start_page = total_pages - 9
if end_page > total_p... |
636852550833715c9b0bbaa18fe7ff6a49371235 | AnimaShadows/advent2020 | /solutions/day_4/day_4_p_2.py | 5,165 | 3.640625 | 4 | #!/usr/bin/python3
from array import *
import re
def populate():
puzzle_input = []
f = open("puzzle_input.txt", "r")
#f = open("puzzle_input_test.txt", "r")
for line in f.read().split("\n\n"):
puzzle_input.append(line)
f.close()
#print (puzzle_input)
return puzzle_input
def validateBirt... |
bf514f745c7054e3023abaaa3c67b7f20d1eb594 | drewripa/python3linuxacademy | /task_1_0.py | 264 | 4.03125 | 4 | def _printer(message, count):
for iteration in range(count):
print(message)
message = input("Please enter message to echo: ")
count = input("Please enter repeat count: ")
if count:
count = int(count)
else:
count = 1
_printer(message,count)
|
ca2406112c66c5d36c85e01bf0ba1bf91c2dda84 | xiatian0918/auto_scripts | /学习脚本/云计算python学习/Python语言基础学习/面向对象与装饰器.py | 699 | 3.953125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# author: xiatian
# 面向对象
class Student:
def __init__(self,name,grade):
self.name = name
self.grade = grade
def introduce(self):
print("hi! I'm %s" %self.name)
print("my grade is: %s" %self.grade)
def improve(self,amount):
... |
53aabafd2dc454d5c3ec0880bcfa176d7f31f759 | Emmalinda/querylabs | /datatypes.py | 479 | 3.90625 | 4 | def data_type(n):
if isinstance(n,str):
#print("entered string, the length is:")
return len(n)
elif isinstance(n,bool):
#print("this is boolean")
return n
elif isinstance(n, int):
num=100
if n<num:
return "less than 100"
elif n>num:
return "more than 100"
#p... |
fe7e9df50d891f461c4a8b88500260dff0261d1b | harris-ippp/hw-6-LauraBer | /e2.py | 1,359 | 3.6875 | 4 |
import requests
address="http://historical.elections.virginia.gov/elections/download/{}/precincts_include:0/"
for line in open("ELECTION_ID"): # run a loop over ELECTION_ID file
# newvar=line.split() # create new variable and split each line where there are white spaces
# print(newvar) # prints these ... |
1527eada1fe9ff9fa7a4d81a21fd90cb5ced293b | lfr4704/ilyanovak-class1 | /testhelper.py | 411 | 3.515625 | 4 | import pandas as pd
import helper
print ("HELLO!")
df = pd.DataFrame({'A':[1,2,3], 'B':['05-08-2020', '07-04-1776', '08-30-1945']})
print('SplitDate\n---Before---\n', df)
df2 = helper.SplitDate(df, 'B')
print('---After---\n', df2, '\n')
a_list = ['8','4','H']
print('ListToSeries\n---Before---\n', df2)
print('The Lis... |
8941ddd6e10555500519a783690d6a6a63dd7058 | HannaKulba/AdaptiveTraining_English | /tasks/part_1/login_and_password.py | 295 | 3.546875 | 4 | lp = [int(i) for i in input().split()]
login = 100500
password = 424242
if login == lp[0] and password == lp[1]:
print("Login success")
elif login == lp[0] and password != lp[1]:
print("Wrong password")
elif login != lp[0]:
print("No user with login " + str(lp[0]) + " found")
|
5852b07b8ba95d578edd34d4c4982966cdd6ea8d | andrew-bydlon/Courses | /Python/ProjectSolutions/DiceRoller.py | 1,600 | 4.03125 | 4 | from random import randint
def DiceRoller(Quantity,Dice,Modifier):
Roll = 0
for i in range(Quantity):
Roll += randint(1,Dice)
return Roll+Modifier
def Main():
ReRoll = 'n'
while True:
if ReRoll == 'n':
Quant = input("How many dice would you like to roll? ")
... |
786043ce7385257d48e8507810b4c47561cd13e7 | 00ZRHun/ShopeeCodeLeague2020_ProgrammingContest | /Q4_LuckyWinner/REJECTED/index (oldest version).py | 935 | 4 | 4 | def append3in1ContentIntoList(itemList3in1Split):
itemList.append(int(itemList3in1Split[0]))
itemList.append(int(itemList3in1Split[1]))
itemList.append(int(itemList3in1Split[2]))
# print(itemList3in1Split)
def find(number):
index = itemListOri.index(number)
fontIndex = index-1
# print(12... |
3a776ac1367c605be833b65feed40a4d80a4df1c | khrystyna21/Python | /lesson11/11.1.py | 1,978 | 3.8125 | 4 |
class Person():
def __init__(self, firstname, lastname, age, weight, height):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.weight = weight
self.height = height
def talk(self):
print(f'Hello, my name is {self.firstname} {self.lastnam... |
bb3b710ba0beebdf4ed313cd6ed1a221ce11db94 | MarshallBriggs/ATS_Python_Procedure | /ATS Print PDFs.py | 4,511 | 3.546875 | 4 | # Import PyPDF2 to print pdfs
from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.generic import BooleanObject, NameObject, IndirectObject
def extract_information(pdf_path):
with open(pdf_path, 'rb') as f:
pdf = PdfFileReader(f)
information = pdf.getDocumentInfo()
number_o... |
2dd98cee525088d2977b371b6ca9e2a3b132a869 | ankita-y/HackerRankProblemSolutions | /Runner-UpScore.py | 427 | 3.625 | 4 | if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
mx1 = arr[0]
mx2 = arr[1]
for num in arr:
if num > mx1:
mx1,mx2 = num,mx1
elif num > mx2 and num != mx1:
mx2 = num
elif mx1 == mx2:
mx2 = num
... |
a97fe9ce3500c428557e220b8f23a29b389b18c5 | dsun092/coding_practice | /cracking/chap3.py | 2,272 | 3.53125 | 4 | class SetOfStacks:
def __init__(self, thresh):
self.limit " thresh
self.stacks " [[]]
def push(self, val):
if len(self.stacks[-1]) "" limit:
self.stacks.append([])
self.stacks[-1].append(val)
def pop(self):
ret " self.stacks[-1].pop()
if len(self... |
761de52cf8b5e6022b76d05f8de3f0eee4a9c628 | Nikkurer/gb_py_basics | /Lesson_5/ex1.py | 573 | 3.734375 | 4 | # Создать программно файл в текстовом формате, записать в него построчно
# данные, вводимые пользователем. Об окончании ввода данных свидетельствует
# пустая строка.
user_data = None
filename = 'user_data.txt'
with open(filename, mode='wt', encoding='utf-8') as f:
while True:
user_data = input('Введите дан... |
c2994014c78964c188649111c40f7de3670510a6 | fabianrmz/python-course | /built-in-data-structures/tuples.py | 209 | 3.71875 | 4 | x = ()
x = (1,2,3,4,5,6,7)
print(x)
x = 1, 1, 3
print(x)
list1 = [3,6,3]
x = tuple(list1)
print(x, type(x))
# not assignment in tuples x[2]=666, inmutables
print(x[2])
y = ([1,2], 3)
del(y[0][1])
print(y) |
e8b4414ba73185039fbf6aba4bd9b29a9b4261a3 | rarose67/Stocks | /stock_class.py | 3,853 | 3.984375 | 4 | from random import uniform
class Stock:
"""This class represents a stock that is traded daily on the stock market."""
def __init__(self, init_symb, init_name, init_shares, init_price, init_var, init_div):
self.symbol = init_symb
self.name = init_name
self.shares = init_shares
s... |
bc32e3330b884fb6d9d9b2d068344d8acdbec3ec | prashuym/IKPrograms | /Recursion-LengthBinaryTree.py | 1,178 | 3.578125 | 4 | class btree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def maxdepth(node):
if node == None: return 0, 0
maxH = minH = 0
treePaths = []
def maxdepthHelper(node, level, path):
nonlocal maxH, minH
# Base condition
# p... |
c5ed8baec7f6c9683006b2d5d738e8b62689a18e | mygetoer/practice | /Nc_Lotto.py | 2,476 | 3.921875 | 4 | #Obelisk
print()
print("NC EDUCATION LOTTERY, LLC")
print("Welcome to the North Carolina Education Lottery's proprietary number selection and bank deposit interface.")
print()
reg_user = input("Are you a certified lottery official?")
if reg_user == "no":
print("Please contact North Carolina Education Lottery Offi... |
2e973d085ff39772aed4b2a5acd51e80c855a577 | bhagavansprasad/students | /mouni/python/basics/3.16.py | 271 | 3.734375 | 4 | k = 0
for i in range(0,3):
for j in range(i,3):
print(" "),
for k in range(65, 65 +(i * 2) + 1):
print chr(k),
print '\n'
for i in range(1,-1,-1):
for j in range(3,i,-1):
print " ",
for k in range(65, 65 +(i * 2) + 1):
print chr(k),
print '\n'
|
68c7ac2e4ef495d56eb3b4a5c54d2043b424f644 | Vladyslav225/lesson_23-24 | /unique_meanings.py | 584 | 3.859375 | 4 | # Разница двух массивов (Уникальные значения)
# Func([1,3,4], [2,4,5]) -> [2, 3, 5]
# Func([1,2,3], [2,4,5]) -> [3, 5]
def create_new_list_1(list_1, list_2):
list_unique_numbers = []
lists =list_1 + list_2
for number in lists:
user_count = lists.count(number)
if user_count ==... |
c91172c46938c0faddcd9aac0881536d82028557 | everqiujuan/python | /day08/code/11_匿名函数.py | 1,327 | 3.875 | 4 |
# 匿名函数: 不知道名字的函数
def fn(n):
return n
f = lambda n:n # 跟上面的函数定义功能一样
print(f(10))
# 求a+b
f2 = lambda a,b: a+b
# def f2(a, b):
# return a+b
print(f2(10, 20))
# 用途
persons = [
{'name': "张三", "age": 33, "score": 90},
{'name': "李四", "age": 20, "score": 70},
{'name': "王五", "age":... |
a3d4e8aa5b661e2d83c557cfc3b9c62687c0c640 | rahulcreddy/hackerrank_python | /74. ginortS.py | 617 | 4 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == "__main__":
user_input = sorted(input())
lower = ""
upper = ""
even = ""
odd = ""
for i in range(len(user_input)):
if(user_input[i].isalpha()):
if(user_input[i].isupper()):
... |
91927982ca1e32e124ee3b957258a3bb1945261b | DenisLo-master/python_basic_11.06.2020 | /homeworks/less5/task5.py | 618 | 3.65625 | 4 | """5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран."""
import random
sum = 0
my_list = [str(random.randrange(10, 100)) for i in range(15)]
line = ' '.join(my_list)
for i in range(len(my_list)... |
54e9f07c8449bd35a189290ee58e1eb99fe0bed9 | SaulGQB/Aprendizaje-Automatico-Proyecto-1 | /outliers_treatment.py | 1,310 | 4.09375 | 4 | def outliers_detect(df, column):
'''Función para detectar outliers a partir de los cuantiles
df: dataframe
column: columna del data frame
-------------------------------------
return: regresa una lista con los indices de los outliers
'''
Q1 = df[column].quantile(0.25)
Q3 = df[column].qu... |
39fd2a6ace06b132935e9016aab56065410be114 | anmolaithinker/Algorithms-Practise | /Greedy/Count_ways_to_reach_nth_stairs.py | 835 | 3.78125 | 4 |
# Amazon Interview ( steps defined 2 or 3 )
# f(n) = f(n-2) + f(n-3)
def getCountsStairs(n):
if (n==0):
return 1
if (n<0):
return 0
two_steps = getCountsStairs(n-2)
three_steps = getCountsStairs(n-3)
return two_steps + three_steps
storage = []
def storageFunc(n):
# (n -> Result)
for i in storage:
i... |
bde13ec8be3b00b8779e32d1ea9e97a850010792 | rakesh08061994/Raka-Python-Code-1 | /Loops_Question (4).py | 546 | 4.5625 | 5 | # Python program to illustrate
# Iterating over a list
# list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] # List is like a bullet box
# for Item in list1: # Item is triger and for loop is like a gun
# print(Item) # loop statement is like fire rounds
# NOTE ... |
81f5369417d2fd260d824c2edb56dfbc417d0a9c | yyqAlisa/python36 | /Python 基础课/day16.py | 1,683 | 3.828125 | 4 | # 题目5:计算从1到某个值以内所有能被3或者17整除的数的和并输出
# list1 = []
# num = int(input('请输入大于1的整数'))
# for i in range(1,num):
# if i%3==0 or i%17==0:
# list1.append(i)
# print(list1)
# print(sum(list1)) #对列表进行求和,每个元素都必须是number
# 题目11:最多循环问99次 “老婆,你爱我吗?”,如果回答的是“爱”,那么就结束循环,否则就继续问。用程序描述这个故事
# 如果最终没有拿到我要的答案,回复一句话 “对不起打扰了”
# 方式一
... |
fc19a682a94a014b1933cd8df5794f2edf5d984d | hollapena/python-data-lab | /data_presenter.py | 2,540 | 3.640625 | 4 | cupcake_invoices=open("CupcakeInvoices.csv")
def all_invoices(cupcake_invoices):
for invoices in cupcake_invoices:
print(invoices)
all_invoices(cupcake_invoices)
cupcake_invoices.seek(0,0)
def find_type(cupcake_invoices):
for invoices in cupcake_invoices:
split_invoices = invoices.split(',')... |
e0c84a9a0679190116ebfcde0906162b918cdc17 | wzc-ob/PycharmProjects | /第九章/迭代器/9-2.py | 208 | 3.65625 | 4 | class Counter:
def __init__(self,x=0):
self.x = x
counter = Counter()
def used_iter():
counter.x +=2
return counter.x
for i in iter(used_iter,10):
print('本次遍历的数值:',i) |
ae8975cb8fb7bfa9ad69473197bbfcaf37e94530 | Adpeen/Some-Random-Stuff-I-created | /idek what this is.py | 1,000 | 4.15625 | 4 | ##AdamGrierson
##26/1/16
print(" hello, its me")
name = "adam"
print(" I saw " + name+ '.')
name = "Dylan"
print(" i also saw " + name + '.')
name = input('What is your name? ')
print('Harry')
print ('she said, "hello!" to us.')
print ("was you not listening?")
message = 'Its Me'
print(message)
... |
364e099365cb0200457445c6c86b0595732d1aeb | fredy-prudente/python-brasil-exercicios | /Estrutura De Decisao/ex14.py | 799 | 3.859375 | 4 | # Faça um programa que lê as duas notas parciais obtidas por um aluno numa disciplina ao longo de um semestre,
# e calcule a sua média. A atribuição de conceitos obedece à tabela abaixo:
n1 = float(input('Digite sua nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
if media >= 9:
print(... |
815a7a55d34b00ca1fdb7b934b77d8aa1910e55c | istiophorus/Codility | /Python/Brackets.py | 1,016 | 3.765625 | 4 | # Brackets
# Task: https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/
# Solution and results: https://app.codility.com/demo/results/training9RBUZY-DVN/
def solution(input):
if input == None:
raise ValueError
if input == '':
return 1
... |
cb76a4667c0837c3a821562a1cf222fcf1f337ee | moustaches/kaftiere | /kaftierev2/objets/objet_geo.py | 6,552 | 3.515625 | 4 | import math
class PointK():
"""class point"""
def __init__(self, longitude=0, latitude=0,hauteur=0, parent=None):
self.parent=parent
self.longitude=longitude
self.latitude=latitude
self.hauteur=hauteur
def distance(self, point):
return math.sqrt(pow(self.lon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.