blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
25d00cea5d15095e481f258fd98d1f14cebe8364 | Jean-Bi/100DaysOfCodePython | /Day 17/quiz-game-start/quiz_brain.py | 1,943 | 3.875 | 4 | class QuizBrain:
def __init__(self, question_list):
"""Constructs a new QuizBrain object."""
# The attribute question_number is initialized to 0
self.question_number = 0
# The attribute question_list is initialized with the value of the parameter question_list
self.question... |
52906a1ae003271a1a440a30f80a69776d09f732 | hyejinHong0602/BOJ | /prac/WEEK1_교재실습.py | 1,870 | 3.96875 | 4 | #교재 실습
# print('세 정수의 최대값을 구합니다')
# a=int(input('정수 a값을 입력하세요:'))
# b=int(input('정수 b값을 입력하세요.'))
# c=int(input('정수 c값을 입력하세요.'))
#
# maximum=a
# if b>maximum : maximum=b
# if c>maximum : maximum=c
# print(maximum)
# def max3(a,b,c):
# maximum=a;
# if b>maximum:maximum=b
# if c>maximum:maximum=c
# ret... |
f0a1f1826cdfbd4f5f044134facae8c5175cb6ee | Hugocorreaa/Python | /Curso em Vídeo/Desafios/Mundo 2/ex041 - Classificando Atletas.py | 1,024 | 4.125 | 4 | """ A Confederação Nacional de Natação precisa de um program que leia o ano de nascimento
de um atleta e mostre sua categoria, de acordo com a idade:
-Até 9 anos: Mirim
-Até 14 anos: Infantil
-Até 19 anos: Junior
-Até 25 anos: Sênior
-Acima: Master
"""
from datetime import date
nasc = int(input("Qual ano de nasciment... |
d6e58b3c17d06c279908a0860004dc4fafc9e7fe | mradu97/python-programmes | /add_of_matrix.py | 823 | 3.765625 | 4 | l1=[[0,0],[0,0]]
l2=[[0,0],[0,0]]
l3=[[0,0],[0,0]]
i=0
while(i<=1):
j=0
while(j<=1):
l1[i][j] =int(input("Enter value"))
j = j + 1
i = i +1
i=0
while(i<=1):
j=0
while(j<=1):
l2[i][j] =int(input("Enter value"))
j = j + 1
i = i +1
i=0
whil... |
8d13b5faae362f9ea4d2f461a97120447b7574ed | Rukeith/leetcode | /461. Hamming Distance/solution.py | 240 | 3.59375 | 4 | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
diff = x ^ y
result = 0
while diff != 0:
if diff % 2 != 0:
result += 1
diff >>= 1
return result
|
66bb8b561876c3824857297fa5e173f22ddf999e | haiyaoxliu/old | /workspace/cs/Missionaries and Cannibals..py | 897 | 3.640625 | 4 | moves = [ (2,0,1), (1,0,1), (1,1,1), (0,1,1), (0,2,1) ]
missionaries = 0
cannibals = 1
boat = 2
def solve(state, path):
if state == [0,0,-1]:
print 'solution:',path+[state]
return True
elif check(state,path):
for move in moves:
new = solve([state[missionaries] - state[boat] ... |
cb34bd25a6d62adb12842ab175fcffe83600a9c4 | anonythrowaway/google-code-sample | /python/src/video_playlist.py | 1,198 | 4.1875 | 4 | """A video playlist class."""
class Playlist:
"""A class used to represent a Playlist."""
def __init__(self, name):
self._name = name
self._videos = list()
@property
def name(self):
return self._name
def add_video(self, video, playlist_name):
if video not in se... |
947c08138c5c260b3b980689faa6c751f030b863 | ramyasutraye/Python-6 | /2.py | 115 | 4.03125 | 4 | a=int(input("enter no"))
if a%2==0:
print("even")
elif a<=0:
print("invalid")
else:
print("odd4") |
4ade9a5642b1da17f4fe980a1801fb86cb04a901 | ncaew/mytest1 | /guard/timer.py | 1,872 | 3.9375 | 4 | import threading
class Timer(object):
""" timer to count down, notify every step"""
def __init__(self, step, timeout):
self._step = step
self._step_action = None
self._step_action_args = None
self._timeout = timeout
self._timeout_action = None
self._tmargs = No... |
73cee0ced6185306292e96f9ab04ff73888a1034 | Neeraj-kaushik/coding_ninja | /pattern14.py | 408 | 3.609375 | 4 | n= int(input())
n1=(n+1)/2
n2=n/2
i=1
while i<=n1:
space=1
while space<=i-1:
print(' ',end="")
space+=1
j=1
while j<=i:
print("*",' ',end="")
j=j+1
print()
i=i+1
i=1
while i<=n2:
space=1
while space<=n2-i:
print(' ',end="")
space+=1
j=1... |
882676658b32eb43e8e56162222b1ae7549f7627 | 09ubberboy90/PythonProjects | /graph/pack/__init__.py | 333 | 3.8125 | 4 | def test():
n = 2
x = 3
y = 4
n_increase = 0
x_increase = 0
y_increase = 0
while n_increase < n :
while x_increase < x :
while y_increase < y :
print("%d "% n)
y_increase +=1
x_increase += 1
n += 1
print(n... |
be9b57cf253b8d0083fc79b487c274231f440523 | mofei952/leetcode_python | /dynamic_programming/198 House Robber.py | 1,266 | 3.9375 | 4 | """
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them is that
adjacent houses have security system connected and it will automatically
contact the police if two adjacent houses were broken ... |
631f1365a5674df691bf34fd22acc74989eaca32 | onclick360-blog/CS5590_PyDL | /Module1/In_Class_Exercise/ICE1/Source/reverse.py | 495 | 4.15625 | 4 | '''
author : ruthvic
created : 1/25/2019 9:00PM
'''
def string_reverse(tmp_str):
rev_str = ''
index = len(tmp_str) # get length of string
while index > 0:
# we do a rev traversal from last index
rev_str += tmp_str[ index - 1 ]
index = index - 1
return rev_str
# standard input to... |
880f393e4a918b7f11d8ab72d8a19d237c85ca14 | zhangray758/python-final | /day02_final/str1.py | 235 | 3.515625 | 4 | # Author: ray.zhang
age=28
while True:
age=(input(">>>>:").strip())
if len(age) == 0:
continue
elif age.isdigit(): #注意:isdigit是str的方法。
print(age,type(age))
else:
break |
d9e2671dd906571f1f140bc8c1d554ebc08ffef4 | kenzzuli/hm_15 | /05_python高级/13_python提高-2/05_新式类中三种装饰器-练习.py | 845 | 3.859375 | 4 | # 实际开发中使用三种装饰器
class Goods:
def __init__(self, original_price, discount):
self.original_price = original_price
self.discount = discount
@property
def real_price(self):
return self.discount * self.original_price
@real_price.setter
def real_price(self, price):
self.or... |
ef985f75da429348f7050dcbf07aa2adff3150c5 | fabiod905/Resolvendo-problemas-com-Python | /Desafios-com-Python/FIBONACCI.py | 377 | 3.859375 | 4 | n = int(input('Digite um número menor que 46:'))
while n >= 46:
n = int(input('Digite um número menor que 46:'))
lista = []
lista.append(0)
lista.append(1)
lista.append(1)
x = 2
while lista[x] < n:
num = lista[x] + lista[x-1]
lista.append(num)
num = 0
x += 1
lista.pop()
num_elementos = len(lista... |
272823a64feb39ebc138882f6b7be77f48052ccc | R161559/NEERUGATTI-NAVEENA | /operatin on sine and cos.py | 790 | 3.609375 | 4 | # a program to generate sine , cosine fuctions and to do some of the operations on them
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,3*np.pi,0.1)
y=np.sin(x)
plt.subplot(5,1,1)
plt.plot(x,y,'r')
plt.title('sine')
plt.xlabel('amplitude')
plt.ylabel('time')
z=np.cos(x)
plt.subplot(5,1,2)
plt.plot(x,z... |
75a4093feca39b2989327cb0a9b58060755a24a2 | CodingDojoDallas/python_oct_2017 | /Cooper_leibow/Python/fundamentals/fun_with_functions.py | 636 | 4.03125 | 4 | def oddEven(digit):
if digit % 2 == 0:
print "Number is", num, ". This is an even number"
else:
print "Number is", num, ". This is an odd number"
num = 45
oddEven(num)
def multiply(numbers, times):
for i in range(len(numbers)):
numbers[i] *= times
print numbers
return numbe... |
4c7809fa00fbb39753adf1535a53f616b41a10d6 | jonathan-ku/SPOJ | /SPOJ/ADDREV.py | 495 | 3.890625 | 4 | '''
Created on 2014-12-20
@author: Jonathan
'''
def add_reverse(x, y):
x = list(x)
y = list(y)
x.reverse()
y.reverse()
x_reverse = "".join(x)
y_reverse = "".join(y)
z = list(str(int(x_reverse) + int(y_reverse)))
z.reverse()
return int("".join(z))
if __name__ == '__main__':
... |
c637b565dbaecc055c1a5768a594a2c9371f65b8 | ap3526/unitConversion | /unit_conversion.py | 1,928 | 4.25 | 4 | #Made by Akash Patel CS-171-A Lab Section 063
#Prints user interface according to homework insructions
print('Welcome to the Unit Conversion Wizard')
print('This program can convert between any of the following lengths:')
print('inches')
print('feet')
print('yards')
print('miles')
print('leagues')
print('centimeters')
... |
e21700195ee52b4fd765a8e2f0c7f5b0de1f8cdb | darshanpatel44/DataStructure | /Q1.py | 237 | 3.625 | 4 | def CEF(L1,L2):
Output = []
for i in L1:
for j in L2:
if i != j:
continue
else:
Output.append(i)
return Output
L1=[1,2,3,5,8]
L2=[1,2,7,3,6]
print(CEF(L1,L2))
|
41b8732b002a69d3f22a3fde231feb73efc3291c | DaveKaretnyk/parsing-utils2 | /check-python33-manual/samples/miscellaneous/sample1.py | 2,461 | 3.75 | 4 |
def free_func_1(x=3):
return x+1
def free_func_2():
return 1
def free_func_3():
def my_local_func():
return 0
return my_local_func() + 1
def free_func_4():
def my_local_func():
def another_local_func():
return 1
return another_local_func() + 1
return... |
632082b71cad67f6e84f13dfa6158b2d73f0eb60 | WillRonny/learn-python3 | /code/qua(函数练习).py | 217 | 3.53125 | 4 | import math #记得导入函数包math
def q(a,b,c):
d = b*b-4*a*c
if d >= 0:
x1 = (-b+math.sqrt(d))/(2*a)
x2 = (-b-math.sqrt(d))/(2*a)
return x1,x2
else:
print("wujie")
print(q(1,5,3)) |
40f453831e668020571c0e7ac4230aced9d7eac5 | ersimon/2018-05-29-AMNH-CCA | /Day3Python/sample_workflow/read.py~ | 455 | 4.0625 | 4 | '''Here we store some sample ways to read in data and spit out the pieces that we want from the dataset let's assume all of the data we are using has a header and columns so we can read it in using pandas read_csv method
let's create a function to read in our kind of data set, then returns an x and y value that we care... |
2ea522a1e50336ae47b687230a3607f9c288ffc6 | EugeneStill/PythonCodeChallenges | /dijkstra.py | 2,214 | 4.15625 | 4 | import heapq
import unittest
# This class represents a directed graph using adjacency list representation
class Graph(object):
def __init__(self, V: int):
self.V = V
self.graph = [[] for _ in range(V)]
def addEdge(self, u: int, v: int, w: int):
self.graph[u].append((v, w))
sel... |
cadfb0d98ae61b621263a8d5e6a72745de8e93d2 | Balakumar5599/Assessment | /alternate_method_problem_1.py | 370 | 3.84375 | 4 | def color_pair(color_string):
count=[]
distinct_char=set(color_string)
for char in distinct_char:
count.append(color_string.count(char))
for item in count:
if item%2!=0:
return False
else:
return True
color_string=input("Enter the string: ")
print("Pa... |
421e3375214aba98254d2a38409075bd743cbcd8 | duongcao74/PythonHW | /hw9/covid-19.py | 4,886 | 3.953125 | 4 | # ----------------------------------------------------------------------
# Name: COVID19
# Purpose: Practice crawling web pages with beautiful soup, re, and
# urllib
#
# Author(s): Haitao Huang, Duong Cao
# ----------------------------------------------------------------------
"""
Implement a ... |
036b968c1101fbd5cfb0f51edc4334a682f41f39 | voiceteam1/voice | /linwanyan/homework2.3.py | 207 | 3.71875 | 4 | # -*- coding:utf-8 -*-
l1 = [[1,1,1],[2,2,2],[3,3,3]]
for i in l1:
print (i)
num = 0
for i in range(3):
for j in range(3):
a=l1[i]
b =a[j]
if i==j:
num+=b
print ('对角线之和为%d'%num)
|
08fc8afbab442d582fb0c46e8ec0712cc751f5cb | jpallavi23/Smart-Interviews | /06_SI_Basic-Hackerrank/08_Count Vowels and Consonants.py | 506 | 4.1875 | 4 | '''
Given a string, print count of vowels and consonants of the string.
Input Format
Input contains a string of upperscase and lowercase characters - S.
Constraints
1 <= len(S) <= 100
Output Format
Print count of vowels and consonants for the given string, separated by space.
Sample Input 0
abxbbiaaspw
Sample Outp... |
be07062a6fd3dcea21c334b71d05cf046000db07 | markomav/Wave-1 | /Compound Interest.py | 208 | 3.546875 | 4 | def interest(P):
I = 1.04
A1 = P * I**1
A2 = P * I**2
A3 = P * I**3
return('1st Year: $' + str(A1*100//1/100) + ', 2nd Year: $' + str(A2*100//1/100) + ', 3rd Year: $' + str(A3*100//1/100)) |
f2f785134ac8e6f6bfde21e8dcd160e75643b025 | kblicharski/ctci-solutions | /Chapter 2 | Linked Lists/ds/lists.py | 313 | 3.578125 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self) -> str:
return self.data
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def __len__(self) -> int:
return self.size
|
30941e1a16927e95e7e89bd27f4c759b32283b07 | CedArctic/VP-Tree | /utilities.py | 2,339 | 3.90625 | 4 | # Imports
import random, math
# Generates an array of random points on a two dimensional plane
def random_points(pointsNum):
a = []
for i in range(0, pointsNum):
a.append(Point(random.random(), random.random()))
return a
# Base class for a point
class Point:
def __init__(self, x, y):
... |
5c110754e347b12c53deb10ca61634da5ebd8ef0 | Jack-Flynn/01_lucky_unicorn | /pythonProject/01_rounds_and_payment.py | 516 | 3.859375 | 4 | # Show Rules
print("Costs: $1 per round, up to 10 rounds")
def num_check(question, low, high):
error = "Please enter a whole number between 1 and 10"
valid = False
while not valid:
try:
response = int(input(question))
if low < response <= high:
return resp... |
c14656db421f1b81becb41a3ae603e3c4ed07437 | zhuyul/ConnectFour-Game | /functions_for_both.py | 2,474 | 3.84375 | 4 | import connectfour
# Print Module
# The board should always be shown in a fixed format
# The game should repeatly remind the player of whose turn is next
def print_screen(game_state: connectfour.ConnectFourGameState) -> None:
''' Print the board in a fixed format, '.' represents no piece
'''
for i in ra... |
9bff042b80dcc39b9ff74dac81f6fab305093622 | Aiyane/aiyane-LeetCode | /101-150/单词拆分2.py | 1,677 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 单词拆分2.py
"""
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
"cats and dog",
"cat sand dog"
]
示例 2:
输入:
s = "... |
979c75911ce5f17aca87bdf4e8ff21df4d817922 | gitmengzh/100-Python-exercises | /100/q13.py | 485 | 3.734375 | 4 | '''
输入一个句子,然后计算字母和数字的个数
'''
input_string = input()
dict1 = {"DIGITS":0,"LETTERS":0}
for i in input_string:
if i.isdigit():
dict1["DIGITS"]+=1
if i.isalpha():
dict1["LETTERS"]+=1
else:
pass
print("DIGITS:",dict1["DIGITS"],"LETTERS:",dict1["LETTERS"],type(i))
'''
学习点: 对于字符串,可以遍历... |
47197139b18dac63a59ce14dbdcc1e0ef1cb7be5 | VinayHaryan/String | /q33.py | 1,871 | 4 | 4 | '''
REMOVE ALL CONSECUTIVE DUPLICATES FROM THE STRING
given a string s, remove all the consecutive duplicates.
note that this probleam is different from here we keep one
character and remove all subsequent same characters
Examples:
Input : aaaaabbbbbb
Output : ab
Input : geeksforgeeks
Output : geksfor... |
55eb302879eabb9f2ef70c14a4153b1cd26fece0 | ConnorYoto/COM701-Python-Data-Structures-and-Algorithms | /Merge Sort on a Linked List/MergeSort_LinkedList.py | 2,746 | 3.96875 | 4 | class Node:
def __init__(self, head = None, tail = None):
self.head = head
self.tail = tail
def setHead(self, head):
self.head = head
def setTail(self, node):
self.tail = node
def getHead(self):
return self.head
def getTail(self):
... |
f43b66902a14a6fa61629fd9ccc18e677a494fb8 | KonstantinosVasilopoulos/MatchingGame | /main.py | 3,077 | 4.03125 | 4 | import random
import functions
# Welcome the player(s)
print('Welcome to the Matching Game')
# Get player count
player_count = functions.get_player_count()
# Get the difficulty level and set the board dimensions and cards
DIFFICULTY_LEVEL = functions.get_difficulty_level()
if DIFFICULTY_LEVEL == '1':
m = 4
... |
14cd6832ba8565b57a1248e17af7aad5691ee704 | zy15662UNUK/Homework | /camel_case.py | 757 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 3 22:39:25 2017
@author: James
"""
def camel_case(string):
"""
Write simple .camelcase method (camel_case function in PHP) for strings. All words must have their first letter capitalized without spaces.
For instance:
camelcase("hello case") => Hel... |
7a1a0ae6ab3856756efc5b431eacb2d1146e9315 | kiran-isaac/Voting-sytem | /vote.py | 3,345 | 3.71875 | 4 | import userInput
def voteFor(studentID):
cursor.execute(("SELECT votes FROM candidates WHERE studentID='{0}'").format(studentID))
voteCount = cursor.fetchone()["votes"]
cursor.execute(("UPDATE candidates "
"SET votes={0} "
"WHERE studentID={1}".format(voteCount+1 if voteCount else ... |
2a5087884164070bdb82aa13d12dab0863f8089c | zmayw/studious-waddle | /Application_python/algorithm_sorting/indexMaxHeap.py | 2,397 | 3.625 | 4 | #coding=utf-8
import random
class MaxHeap:
def __init__(self,capacity):
self.capacity = capacity
self.indexes = []
self.data = []
self.count = 0
def __shiftUp(self,k):
#当前节点与父节点进行大小比较,如果小于父节点,则调换位置
while(k > 0 and self.data[self.indexes[(k-1)/2]] < self.data[se... |
aebf9bbb1d764ce97990751abebc62d5b4977501 | ezhilarasi-g/code | /43player.py | 93 | 3.546875 | 4 | #ezhil
a,b=map(str,input().split())
if a.find(b)==-1:
print("no")
else:
print("yes")
|
dafa905b1b2a8abb6997d5e77564e11889028dd3 | dyiar/Sprint-Challenge--Data-Structures-Python | /names/heap.py | 1,618 | 3.71875 | 4 | class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
self.storage.append(value)
self._bubble_up(len(self.storage)-1)
def delete(self):
self.storage[0], self.storage[-1] = self.storage[-1], self.storage[0]
deletedValue = self.storage.pop(-1)
... |
540216f1c817cfc3c3bcf2197ae6f4b30f7beeb9 | vega832/tr06_vega_cristina | /vega/doble_02.py | 461 | 3.578125 | 4 | #ejercicio 02
import os
#delclarion de variables
trabajador,renumeracion_mensual="",0
#INPUT VIA OS
trabajador=os.sys.argv[1]
renumeracion_mensual=int(os.sys.argv[2])
#PROCESSING
#si el la renumeracion mensual es mayor 100
#mostrar tiene renumeracion anual
#caso contrario se muestra "no tiene renumeracion anual"
if (r... |
cf4732669097279f738dbf54d546ec3daf4973ea | niuniu6niuniu/Leetcode | /LC-Defanged_IP.py | 876 | 3.71875 | 4 | # Given a valid (IPv4) IP address, return a defanged version of that IP address.
# A defanged IP address replaces every period "." with "[.]".
# Example 1:
# Input: address = "1.1.1.1"
# Output: "1[.]1[.]1[.]1"
# Example 2:
# Input: address = "255.100.50.0"
# Output: "255[.]100[.]50[.]0"
class Solution:
... |
357c6249a100de27c334605cd39fad1cfb308c89 | andrei406/Meus-PycharmProjects-de-Iniciante | /PythonExercicios/ex031.py | 287 | 3.75 | 4 | n1 = int(input('Digite a distância em km para ser calculado o preço da passagem:'))
print('0,50 por quilometro se for uma viagem de até 200Km, superior, 0,45')
if n1 <= 200:
print('O preço é {:.2f}R$'.format(n1 * 0.50))
else:
print('O preço é {:.2f}R$'.format(n1 * 0.45))
|
eea90206039d83e9ee3b27ada1d281219ef14295 | rntva/JumpToPython | /Test_2018-01-03/csv_test.py | 5,999 | 3.6875 | 4 | import csv
import math
def get_csv_row_instance(primary_key, printing=1):
try:
primary_key_index = data[0].index(primary_key)
except:
print("No Primary Key Found - Row")
return None
get_row_instance = []
instance_type = ""
for row in data[1:]:
if printing == 1: pri... |
773c87838a5ac1238533963b5a4a6696a37c9d27 | jrlindeman-geophysicist/hello-world | /oddeven.py | 630 | 4.09375 | 4 | #!/usr/bin/python
number = int(raw_input("Please enter a number: "))
if number % 4 == 0:
print("Your number (%r) is divisible by 4.\n") % number
elif number % 2 == 0:
print("Your number (%r) is even.\n") % number
elif number % 2 != 0:
print("Your number (%r) is odd.\n") % number
print("Now I will ask for two addit... |
0065e232beaa46ac2455c3cdb8156a597811fcce | benjaminkweku/Intro_To_Python | /Dev-Python/conditional.py | 346 | 4.125 | 4 | i = 8
if(i % 2 == 0): # % is modulo
print ("Even Number")
else:
print ("Odd Number")
def evens():
list = []
start = int(input("Enter Minimum Number"))
finish = int(input("Enter Maximum Number"))
for num in range(start,finish):#+1)
if (num % 2 == 0):
list.append(num)
... |
885936acb3237650efac25bd5c7918a0ba68c741 | AmbujaAK/practice | /python/nptel-Aug'18/week2/ques1.py | 236 | 3.515625 | 4 | # ques 1
def intreverse(n):
x = n
ans = 0
while n > 0:
r = n%10
ans = ans * 10 + r
n = n//10
l = len(str(x))
ans = ('%0' + str(l) + 'd') % ans
return ans
num = intreverse(3000)
print(num) |
a595154d474bcf796584069a94e2350e1a10bc32 | stathis-alexander/ac-2018 | /day3/aoc-3-2.py | 1,891 | 3.5 | 4 | #!/usr/bin/python
# This is the solution to part one of Advent of Code, day 3.
f = open("input.txt",'r')
lines = list(f)
f.close()
patches = []
for line in lines:
temp = line.split()
startstr = temp[2]
dimstr = temp[3]
startstr = startstr[:-1]
coords = [int(x) for x in startstr.split(",")]
dims = [int(... |
0d6251db6051527d4b34875eed44ff5eaf614cfd | kyungchul/openbigdata | /01_jumptopy/chap04/149.py | 254 | 3.515625 | 4 | def sum_add_mul(a,b):
return a+b,a*b
result = sum_add_mul(3,4)
print(result)
print("덧셈 연산 결과: "+str(result[0]))
if result[0] > 0:
print("덧셈 분석 결과 양의 결과입니다.")
print("곳셈 연산 결과: "+str(result[1]))
|
cd47857b8c7bdc94c512abac0136feebc7a0140d | oarecat/PythonPractice | /FilteredWords.py | 478 | 3.875 | 4 | #第0011题:敏感词文本文件filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出Freedom,否则打印出Human Rights.
userInput = input("请输入文字:")
#增加的encoding = "utf-8"表示读取文件时按照UTF-8的编码方式
filterWords = open("C:\\GitHub\\PythonPractice\\filtered_words.txt" , "r" , encoding="utf-8").read().split(",")
if userInput in filterWords:
print ("Freedom... |
446af91da59abe40ea599252c71685ba8b603581 | csherfield/PythonTrainingExercises | /Advanced/RomeoAndJuliet/util/parser.py | 4,808 | 3.578125 | 4 | """Parser for Romeo and Juliet.
Created on 18 Mar 2015
@author: paulross
"""
from Exercises.RomeoAndJuliet.util import play
def _is_stage_direction(line):
"""Returns True if the line is a stage direction."""
line = line.strip()
return line.startswith('[') and line.endswith(']')
def get_scenes():
"""... |
1ea9934cd2982059e37166715964a986ce404f3d | sharathcshekhar/singleswitch | /prototypes/keypress.py | 439 | 3.953125 | 4 | import Tkinter as tk
# Demonstration of how to use Tkinter to capture keypress events
def keypress(event):
if event.keysym == 'Escape':
root.destroy()
x = event.char
if x == "w":
print "W for Wonderful!!!"
elif x == "a":
print "A for APPLE!"
elif x == "d":
print "D ... |
eb431990fb827849f56e3ee454fa739ea7439d8e | arthijayaraman-lab/crease_ga | /crease_ga/utils/initial_pop.py | 802 | 3.59375 | 4 | import numpy as np
def initial_pop(popnumber, nloci, numvars):
'''
Produce a generation of (binary) chromosomes.
Parameters
----------
popnumber: int
Number of individuals in a population.
nloci: int
Number of binary bits to represent each parameter in a chromosome.
numv... |
b5b4cdb25cb26776db1cb2cb8fadbaa1e2ac7744 | kongtianyi/cabbird | /leetcode/minimum_moves_to_equal_array_elements_II.py | 466 | 3.578125 | 4 | def minMoves2(nums):
_min=min(nums)
_max=max(nums)
res=1<<31
for i in range(_min,_max+1):
t=sum([abs(j-i) for j in nums])
if t<res:
res=t
return res
def _minMoves2(nums):
nums.sort()
median=nums[len(nums)/2]
return sum(abs(n-median) for n in nums)
... |
19e6c2b167f74de02c5d3c807842ca89291905d6 | GUSuper60/Binary-Beast_08 | /BOB_.KHATU_STRING.py | 1,247 | 4.15625 | 4 | '''
Bob and Khatu both love the string. Bob has a string S and Khatu has a string T. They want to make both string S and T to anagrams of each other. Khatu can apply two operations to convert string T to anagram of string S which are given below:
1.) Delete one character from the string T.
2.) Add one character from... |
e7c87a1679654f126a28605e596f081a2de6ee22 | eliseuegewarth/uri-exercises | /beginner/1016/1016.py | 65 | 3.59375 | 4 |
x = int(input())
time = x * 2
print("{} minutos".format(time))
|
7027a9e71a149de5a2e5b629573f1f8bc15e39a5 | erinszabo/260week_1 | /chapter_1.py | 1,636 | 3.828125 | 4 | import random
"""
Chapter 1.10
"""
print()
print()
print("self_check_1:")
# the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
wordlist = ['cat', 'dog', 'rabbit']
letterlist = []
for aword in wordlist:
for aletter in aword:
if aletter not in letterlist:
letterlist.append(aletter)... |
ff63557ed48c541a63031a23037f5457093e337a | JakePrasad/memo | /fib.py | 392 | 3.765625 | 4 | init = parser.add_argument('--n', type=int)
args = parser.parse_args()
init = args.n
___
def isBase(curr):
return curr == 0 or curr == 1
___
def fBase(curr):
return curr
___
lambda n: n-1
lambda n: n-2
___
def merge(subproblems): return sum(subproblems)
# Format of this file
# Base values
# ___
# Subproblems - n ... |
e6136334e00b1f07de6bc554c330ae42539bb333 | jasonwee/asus-rt-n14uhp-mrtg | /src/bin/SingletonPatternNew.py | 744 | 3.515625 | 4 | #!/usr/bin/python3.4
# http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html
class OnlyOne(object):
class __OnlyOne:
def __init__(self):
self.val = None
def __str__(self):
return 'self' + self.val
instance = None
def __new__(cls): #__new__ alw... |
9be3a944952112dd47d162ed48c7610c141108a6 | Dikshitha0812/class-105 | /std.py | 1,194 | 4.09375 | 4 | import pandas as pd
import statistics
import plotly.express as px
import math
data = pd.read_csv("./class1.csv")
markslist = data["Marks"].tolist()
print(markslist)
#HOW TO STANDARD DEVIATION
# first step you find the mean of the desired column.i.e. markslist
# second step you do subtraction of each marks... |
8eeb9402a5d2bb4d57447a8d47c72868250b2e24 | knuu/competitive-programming | /hackerrank/algorithm/from-paragraphs-to-sentences.py | 408 | 3.8125 | 4 | def is_end(w):
if w == "Dr.":
return False
elif len(w) == 2 and w[0].isupper():
return False
elif w[-1] in '.!?':
return True
else:
return False
S = list(input())
for i, s in enumerate(S):
if i < len(S)-1 and s in '.!?' and S[i+1].isupper():
S[i] = s + ' '
S ... |
d0d3608ad304a3a68362d3e88e4103cede709d22 | NikDestrave/Python_Algos_Homework | /Lesson_1.9.py | 878 | 4.15625 | 4 | """
Задание 9. Вводятся три разных числа. Найти, какое из них является средним
(больше одного, но меньше другого).
Подсказка: можно добавить проверку, что введены равные числа
"""
NUMBER_A = int(input('Введите первое число: '))
NUMBER_B = int(input('Введите второе число: '))
NUMBER_C = int(input('Введите третье число:... |
73663b5c265c56aae2b64d369262c50d3fee3455 | phoenix9373/Algorithm | /2020/자료구조/그래프의 최소 비용 문제/크루스칼 알고리즘.py | 1,010 | 3.734375 | 4 | tree = {}
rank = {}
def make_set(node):
tree[node] = node
rank[node] = 0
def find_set(node):
if node != tree[node]:
tree[node] = find_set(tree[node])
return tree[node]
def union(u, v):
root1 = find_set(u)
root2 = find_set(v)
if rank[root1] > rank[root2]:
tree[root2] = ... |
c9e3ed1b7a6ffa9e32ae7d3d725749da65a8e8d8 | a-gon/problem_solutions | /kth_largest.py | 388 | 3.703125 | 4 | import heapq
def kth_largest(a, k):
heapq.heapify(a)
result = None
for _ in range(k):
result = heapq.heappop(a)
return result
def kth_largest_(a, k):
result = None
sorted_array = sorted(a)
for _ in range(k):
result = sorted_array.pop(0)
return result
print(kth_largest(... |
3975256b18a99bdee7942545034673835916e426 | James-Oswald/IEEE-Professional-Development-Night | /5-3-21/planetTwisted.py | 355 | 3.671875 | 4 | #https://www.codewars.com/kata/58068479c27998b11900056e
def twistedSort(arr):
rv = arr.copy()
rv.sort(key=lambda e:int(str(e).replace("3", "x").replace("7", "3").replace("x", "7")))
return rv
print(twistedSort([1,2,3,4,5,6,7,8,9])) #[1,2,7,4,5,6,3,8,9]
print(twistedSort([12,13,14])) #[12,14,13]
print(twi... |
93407eb1c7030730bde7da5e5525a634adc3deeb | nikhildarocha/schaums-outline-prob-stats | /python/1.6/ex1.6_mean_median.py | 1,319 | 3.796875 | 4 | import numpy as np
import statistics
data = np.array([25000, 30000, 40000, 153000])
frequency = np.array([5, 7, 3, 1])
mul = data*frequency
print(mul)
total = sum(frequency)
print(total)
mean = sum(mul)/total
print(mean)
for i in range(len(frequency)-1):
frequency[i+1] = frequency[i] + frequency[i+1]
... |
8585416810b61b95a7c3fba9f3a64e95297edfe6 | pawelk82/HackerRank | /Python/Numpy/Transpose_and_Flatten.py | 635 | 4.28125 | 4 | #! /usr/bin/python3
'''
Task
You are given a N X M integer array matrix with space
separated elements (N = rows and M = columns).
Your task is to print the transpose and flatten results.
Input Format
The first line contains the space separated values of N and M.
The next N lines contains the space separated elemen... |
9b47b359317fd4fa442ff09abbbb052b0e578b88 | structuredcreations/Formal_Learning | /python_basics/C1_w5_if_else_groups.py | 453 | 3.96875 | 4 | ENT_SCORE=input("Enter score between 0 and 1")
ENT_SCORE_F=float(ENT_SCORE)
#print(ENT_SCORE_F)
if ENT_SCORE_F < 0.0 :
print("Number below 0")
elif ENT_SCORE_F > 1.0 :
print("Number above 1")
else:
if ENT_SCORE_F>=.9:
print("A")
elif ENT_SCORE_F>=.8:
print('B')
elif ENT_SCORE_F>=.7... |
c4155f3b449bad23249ba42d3d97201ef397240c | lichengchengchloe/leetcodePracticePy | /RemoveDuplicates.py | 594 | 3.609375 | 4 | # -*- coding: UTF-8 -*-
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
def removeDuplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n==0:
return 0
# 有序数组的重复项肯定是挨在一起的,将不重复的数字赋值到重复项即可
p = 0
q = 1
while q<n:
if nums... |
4fef1486743e0ce9db27202f458f974f7045c296 | himanshu-singh14/FSDP2019 | /Day 11, 20-May-2019/Program/space_numpy.py | 539 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 20 16:21:16 2019
@author: HIMANSHU SINGH
"""
"""
Code Challenge
Name:
Space Seperated data
Filename:
space_numpy.py
Problem Statement:
You are given a 9 space separated numbers.
Write a python code to convert it into a 3x3 NumPy array of integers.... |
9ea9e90fb5bea2d8ad9a8b97f054ae6a27a553af | sahiljohari/basic_programming | /Linked list/reverseList.py | 1,236 | 4.21875 | 4 | # Reverse a linked list in-place
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# recursive
def reverse(head, prev = None):
'''
Time complexity: O(n)
Space complexity: O(n)
'''
if head is None:
return prev
next = head.next
... |
fff286d05416333d104ced110748c9a13903f882 | Lay4U/RTOS_StepByStep | /Python for Secret Agents/0420OS_Code/Others/bonus_ex_1.py | 932 | 3.65625 | 4 | """Chapter 2, Example 2
HTTP GET with FORM
"""
import http.client
import urllib.parse
import contextlib
import pprint
host = "finance.yahoo.com"
form = {
's': 'YHOO',
'ql': '1',
}
query = urllib.parse.urlencode( form )
print( query )
with contextlib.closing( http.client.HTTPConnection( host ) ) as connectio... |
fb47a23ad30dfd0ef95a58c450969c5796386e1e | sfdye/leetcode | /wiggle-sort-ii.py | 285 | 3.625 | 4 | class Solution:
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i, num in enumerate(sorted(nums)[::-1]):
nums[(i * 2 + 1) % (len(nums) | 1)] = num
|
f8080d17d2a140bc79dd41b01e81f6304b768b56 | mominaadar/DataStructure-implementations | /a04.py | 4,426 | 3.6875 | 4 | class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class Ring:
def __init__(self):
self.head = None
def __str__(self):
ret = '['
temp = self.head
while temp:
ret += str(temp.val) + ', '
temp = temp.next... |
5f953697d2f9562ee9cc1eb9ff0b24d5a45aba31 | LipsaJ/PythonPrograms | /_InterviewPrep/dataframe05.py | 717 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 9 20:08:36 2021
@author: stlp
"""
## Replace values in Pandas dataframe using regex
import pandas as pd
df = pd.DataFrame({'City':['New York', 'Parague', 'New Delhi', 'Venice', 'new Orleans'],
'Event':['Music', 'Poetry', 'The... |
077a9ed68f8b663b12481c5e5f49814c7fb94810 | yaroslav-tsarenko/simplepythonproject | /f_01.py | 248 | 4 | 4 | a=int(input("Введыть першу сторону:"))
b=int(input("Введыть другу сторону:"))
c=int(input("Введыть третю сторону:"))
p=(a+b+c)/2
s=(p*(p-a)*(p-b)*(p-c)**0.5)
print("S:",s)
print("P:",a+b+c)
|
c3eb5f25351f90a0c498b5c60574bb5e65b8f152 | Zac-Taylor/Python-2016 | /HW3_PartA.py | 419 | 4.125 | 4 | smallest= 0x
count = 0
smallest = int(input("Enter an integer or empty string to end: "))
count = 1
inputStr=input("Enter an integer or empty string to end: ")
while inputStr != "":
value = int(inputStr)
if value < smallest:
smallest = value
count = count + 1
inputStr=input("Enter an integer o... |
e55e0702afd61a06fa31bd0476998686d0d62fbe | hasadna/okscraper | /okscraper/storages.py | 3,113 | 4.09375 | 4 |
class BaseStorage(object):
"""
Abstract class, implementing classes must define the following methods:
* store - store data
* commit - (optional, commit the data)
* get - (optioanl, return stored data or pointer to stored data)
"""
def store(self):
raise Exc... |
b137461fcd332235f41c68c9c830b274418e8581 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4147/codes/1593_1802.py | 174 | 3.828125 | 4 | from math import*
v = float(input("Pontos de vida: "))
vd1 = int(input("Dado 1: "))
vd2 = int(input("Dado 2: "))
d = int(sqrt(5 * vd1) + (pi ** (vd2 / 3)))
print(int(v - d)) |
14731d266fc8e5168e1715a51b23743cf341e91e | Trapman/trading | /money flow multiplier/money_flow_multiplier.py | 1,590 | 3.734375 | 4 | """
Creating & Back-testing the Strategy
Now, we can proceed to back-test the Money Flow Multiplier strategy on some currency pairs within the hourly time frame. The trading conditions are therefore:
Go long (Buy) whenever the Money Flow Multiplier touches the lower barrier at -90.00 with the previous two values above ... |
bdd39a4cadcfa63d78f734a1413f9f6a602e1ee0 | zhouyswo/zzjz_py | /com/zzjz/senior/iteratorAndCoroutine.py | 4,896 | 3.875 | 4 | # 迭代器
# 可迭代(iterable):直接作用于for循环的变量
# 迭代器(iterator):不仅可以用于for循环,还可以被next调用
# list 是典型的可迭代对象,但不是迭代器
# 可迭代的对象不一定是迭代器,迭代器一定是可迭代对象
# 可通过isinstance判断
from collections import Iterable
from collections import Iterator
l = [1, 2, 3, 4]
# print(isinstance(l,Iterable))
# print(isinstance(l,Iterator))
# 可迭代对象转换为迭代器
# it = ite... |
5f9ccbd0b6d5df8ca78f0ce689ef73f71c08f8e2 | PdxCodeGuild/20170724-FullStack-Night | /Code/sam/python/Lab12_practice4.py | 376 | 4.125 | 4 | x = 2 # setting x equal to 2
i = 0 # setting i equal to 0
for i in range(21): # creating a for loop in range of 21
exponent = x ** i # creating a variable and setting it to x ** i
print(exponent)
i += 1 ... |
44ea12790778062af23981786ec8361e4590393b | luisavitoria/introducao-curso-basico-python | /code/COH-PIAH.py | 4,833 | 4 | 4 | import re
def main():
ass_cp = le_assinatura()
textos = le_textos()
infectado = avalia_textos(textos, ass_cp)
print("O autor do texto",infectado,"está infectado com COH-PIAH")
def le_assinatura():
'''A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comp... |
ea885394228ef3465935c3020ef4f732bc5e1a5a | Kanefav/exercicios | /ex079.py | 232 | 3.84375 | 4 | lista = []
tlist = 0
while True:
num = lista.append(int(input('Digite um valor: ')))
cont = str(input('Quer continuar? [S/N] ')).upper()
if cont == 'N':
break
else:
continue
lista.sort()
print(lista)
|
0032616a6e196f84fdec6ff9267dee28006af2d1 | wsyhGL/Python | /python/fun_print.py | 169 | 3.71875 | 4 | def fun_add(a,b):
result = a+b
print("%d+%d=%d"%(a,b,result))
num = int(input("请输入数字1:"))
num1 = int(input("请输入数字2:"))
fun_add(num,num1)
|
12527b261943cc4df52b8c59398ccf26e3c58fea | Aludeku/Python-course-backup | /lista exercícios/PythonTeste/desafio090.py | 479 | 3.84375 | 4 | aluno = {}
aluno['nome'] = str(input('Nome: '))
aluno['media'] = float(input(f'Média de {aluno["nome"]}: '))
if aluno['media'] >= 7:
aluno['status'] = 'aprovado'
elif 5 <= aluno['media'] <= 7:
aluno['status'] = 'recuperação'
else:
aluno['status'] = 'reprovado'
print('-=' * 20)
print(f' -O nome é igual a {a... |
e851e472a115704f46016f6f77db2bff6dd03e24 | ArthurLCastro/Python | /Adição de dados em MySQL com Python/add_linha_em_tabela_MySQL.py | 636 | 3.53125 | 4 | # Adicionar linha em Tabela MySQL com Python
# Arthur Castro
# 09 de abril de 2018
import mysql.connector
print("---------- Cadastro de Clientes ----------")
nome = raw_input("Nome: ")
email = raw_input("e-mail: ")
fone = raw_input("Telefone: ")
print("------------------------------------------")
conn = mysql.connec... |
85644eb8d750180453643b52aed7136bd3c4685f | SSalaPla/dynamical-systems-with-applications-using-python | /Anaconda-files/Program_3c.py | 296 | 3.6875 | 4 | # Program 3c: Finding critical points.
# See Example 9.
import sympy as sm
x, y = sm.symbols('x, y')
P = x*(1-x/2-y)
Q = y*(x-1-y/2)
# Set P(x,y)=0 and Q(x,y)=0.
Peqn = sm.Eq(P, 0)
Qeqn = sm.Eq(Q, 0)
# Locate critical points.
criticalpoints = sm.solve((Peqn, Qeqn), x, y)
print(criticalpoints) |
48b28a588d7e6b0572613e1245ad59e458cdd8c1 | Satyajit99p/sample-differentiation-and-integration-using-Sympy-python-module | /derivative_trial_1.py | 1,285 | 3.96875 | 4 | from sympy import*
x = Symbol('x')
def linear_function():
print('welcome to linear function differentiation')
a=int (input('enter coefficient of degree 2:'))
b=int(input('enter constatnt:'))
return(diff(a*x+b))
def quadractic_function():
print('welcome to quadractic function di... |
e31817d62b776436a16c50fd681c4d2b8624d515 | Aasthaengg/IBMdataset | /Python_codes/p02419/s041976628.py | 177 | 3.78125 | 4 | w = input().lower()
text = ''
while True:
t = input()
if t == 'END_OF_TEXT':
break
text += t.lower() + ' '
print(len([t for t in text.split(' ') if t == w])) |
7efb91bdcc88df5085f86b2326a94a21d8c991d6 | xuefeihexue/IPND_project4 | /media.py | 1,193 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import webbrowser
# Crete a Movie class
class Movie:
def __init__(
self,
movie_title,
movie_storyline,
poster_image,
trailer_youtube,
):
''' When a initial function is called, it will create a new space for the mov... |
f457cd3c7346dfed8ad422b3b12f1732ea90fd0d | ghj3/lpie | /untitled38.py | 301 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 22:55:21 2018
@author: k3sekido
"""
class Clock(object):
def __init__(self, time):
self.time = time
def print_time(self):
time = '6:30'
print(self.time)
clock = Clock('5:30')
clock.print_time() |
54e0970ec836655490bf75aa1e01dd03f5ea76e4 | franghie/pytutorial | /ref_value_demo.py | 595 | 3.703125 | 4 | # All variable is a reference. In order to write a value, need to dereference. Scalar -> Need to use key or index
llist = [['a', 'b'], ['c'], ['d', 'e']]
for loc in llist:
loc = ['a','b','c']
print(llist)
llist = [['a', 'b'], ['c'], ['d', 'e']]
for loc in llist:
loc[0] = '1'
print(llist)
m = {'a'... |
f13c5da112a519aa9afce470116623aca88dc30c | alex2rive3/practicaPython | /suma numeros inpares.py | 293 | 3.8125 | 4 | numero = 20
acumulador =0
if numero%2==0:
numero = numero-1
for x in range(numero,0,-2):
print(x)
acumulador += x
else:
for x in range (numero,0,-2):
print(x)
acumulador += x
print("La suma de los n primeros numeros impares es ", acumulador)
input() |
49dd52170155b4285192ee7b3cab9c88d5947854 | mpirnat/aoc2016 | /day21/day21.py | 4,906 | 3.953125 | 4 | #!/usr/bin/env python
"""
Solve day 21 of Advent of Code.
http://adventofcode.com/2016/day/21
"""
from collections import deque
from itertools import permutations
grammar = {
('swap', 'position'): lambda x: (swap_position, [int(x[2]), int(x[5])]),
('swap', 'letter'): lambda x: (swap_char, [x[2], x[5]]),
... |
54c4224ebdfb29022fb115c25d74c82a91ede283 | DotPeriodCom/100-Days-of-Python | /Day 2 - Understanding Data Types/Day 2 - Code Lessons/day-2-end.py | 476 | 4.03125 | 4 | a = float(123)
print(type(a))
# print(70 + float("100.5"))
print(str(70) + str(100))
# a = str(123)
# print(type(a))
# num_char = len(input("What is your name?"))
# new_num_char = str(num_char)
# print("Your name has " + new_num_char + " characters.")
# print("Your name has " + num_char + " characters.")
# print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.