blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
334d1b51189b1492bb754f0db69a2357cc8e0f15 | abideen305/devCamp-task | /Bonus_Task_2.py | 1,845 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
# program to replace a consonant with its next concosnant
#Starting by definig what is vowel and what is not. Vowel are just: a,e,i,o,u
#defining a function with the name vowel and its argument v
def vowel(v):
#if statement to taste if the word containing any of the... |
67236417da20a2541e962cbd670cf806711b5677 | sabyers1/PyCode | /slideGUI.py | 9,277 | 3.625 | 4 | '''
File: slideGUI.py
File Create: 29th Sep 2017
Author:Sahal Mohamed motiQ
-----
Excerise to make graphical respresentation of slider game
taken from: https://www.youtube.com/watch?v=vzzEP_YI424
-----
Last Modified: 8th May 2020 9:57:28 pm
Modified By: Stephen Byers
-----
No Copyright 2020
'''
#import tkinter as t... |
91993ff702f481e1eecbd8c7d0634aadc805bbc7 | mikomwang/leetcode | /reverse_words_in_string.py | 410 | 4.03125 | 4 | def reverse_words(string):
reversed_string = string[::-1]
result = ""
start_index = 0
for i in range(len(string)):
if reversed_string[i] == " ":
if start_index == 0:
result += reversed_string[i-1::-1]
else:
result += reversed_string[i-1:start_index:-1]
result += " "
start_index = i
result +=... |
42e0def3d30d3e1e585ba97001f73a3370c03fa1 | Eckods/tilegamelib | /tilegamelib/vector.py | 1,256 | 3.90625 | 4 |
class Vector:
def __init__(self, x, y):
self.coord = (x, y)
@property
def x(self):
return self.coord[0]
@property
def y(self):
return self.coord[1]
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
de... |
75f6639f6c7f3397daf5f22e0aec2d162b8f54ff | 621Alice/Oasis | /Sentiment_Classifier/preprocessing/preprocessing_data_12labels.py | 3,047 | 3.5 | 4 | from functions import *
from sklearn.model_selection import train_test_split
#read CSV file
sentiments=[]
contents=[]
with open(p+'/Data/text_emotion.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
contents.append(data_cleaning(row[3]))
sentiments.append(row[1... |
8ff7f3540899662cf0295c6f9d022c863af4cc35 | Zomalala/git | /CCercle.py | 519 | 4 | 4 | #!/usr/local/python3.9
#-*-coding:UTF-8-*-
#définition de la classe Cercle
class Cercle:
#méthode constructeur
def __init__(self, rayon):
self.rayon=float(input("Donner le rayon de votre cercle en cm: "))
#méthode permettant de calculer l'aire d'un cercle
def aire(self,aire_cercle):
self.a... |
9d29292bb6ebbb4cbb1beea06a86beec844f7463 | jorboer/Machine-Learning-Project1 | /Plots/least_squares_degree_plot.py | 848 | 4.0625 | 4 | """
Used to create the plot of least squares with rmse against degrees in the report.
"""
import matplotlib.pyplot as plt
from HelpMethods import helpers, given
from Implementations import implementations
DATA_PATH = ""
RATIO = 0.8
degrees = [1,2,3,4,5,6]
# load the data
y_train, x_train, ids = given.load_csv_data... |
644d94365b60d8775bed21d6bdbbc00b680effaa | Redysz/Python-Class-For-Five-Manipulation | /tests.py | 2,282 | 3.75 | 4 | from five import Five
import unittest
class TestStringMethods(unittest.TestCase):
def setUp(self):
self.five = Five()
def test_operations_on_five(self):
self.assertEqual(5 * 3, self.five * 3)
self.assertEqual(3 * 5, 3 * self.five)
self.assertEqual(5 + 3, self.five + 3)
... |
b62b7eea0b1a0c76287affee442a12866732b34b | ashutoshpandey/python | /SquareModule.py | 226 | 3.734375 | 4 | class Square:
def __init__(self, x): # self is 'this' here, __init__ is constructor
self.x = x
def area(self):
return self.x*self.x
def perimeter(self):
return 4*self.x
|
ee87ee70687c2436a28b146c9a8bc984c418682e | robbinl/python-raspberrypi-begin | /03bLambda.py | 990 | 3.71875 | 4 | # 2019 Robbin Law
try:
print("importing tkinter from Python 3.X")
import tkinter as tk
except:
print("importing tkinter from Python 2.X")
import Tkinter as tk
def func0():
print("This worked but not passing any params")
def func1(p):
print(p)
def main():
win = tk.Tk()
win.title("Using LAMBDA")
win.geometr... |
162278618c07c5a83e7458f9b0cf9c27c9511815 | robbinl/python-raspberrypi-begin | /05HatTkOOP.py | 1,379 | 3.546875 | 4 | # 2019 Robbin Law
try:
print("importing tkinter from Python 3.X")
import tkinter as tk
except:
print("importing tkinter from Python 2.X")
import Tkinter as tk
try:
print("senseHatClass1.py IS loaded in this directory")
from HatClass1 import SenseHatClass
except:
print("senseHatClass1.py IS NOT loaded in this ... |
6d0a43a67dc4871de38addb26cd0b9153a48e1f0 | landwarrior/VariousPythonSample | /rename_files.py | 508 | 3.640625 | 4 | """ファイル名を変更するスクリプト.
サンプルなのでファイル名は適当に変換します。
"""
import glob
import re
import os
PATH = 'D:\\MyDocuments\\test\\*.txt'
def main():
for i, filepath in enumerate(glob.glob(PATH)):
dir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
file_rename = re.sub(r'^.*.txt$', f"hoge{i... |
b3649c03a847823d17ca54f745eeb3a778e303e5 | zelimirmaletic/Parser | /supportLibrary.py | 249 | 3.65625 | 4 | def extractTokenName(string):
i = 1
tokenName = ''
while string[i]!='>':
tokenName += string[i]
i+=1
return tokenName
token = " <ANIMAL> := 'CAT' | 'DOG' | 'PARROT' | 'LAMA' "
print(extractTokenName(token))
|
0cff5e2d99a05b4f8e73ddf165330ff17efb2641 | mmarcosmath/learning_python | /PythonOO/operacaocomString.py | 236 | 3.953125 | 4 | nome = "marcos"
sobre = "silva"
print(nome)
print(sobre)
concatenacao = nome +" "+ sobre
print(concatenacao)
print((concatenacao+" ") * 3)
print(concatenacao.upper())
print(concatenacao.lower())
print(concatenacao.capitalize())
|
f7330413f555d1dfa3164c3a3229e18cac863415 | mmarcosmath/learning_python | /PythonOO/inputs.py | 311 | 4.25 | 4 | nome = input("Digite seu nome: ")
print(nome)
print(nome.upper())
print(nome.capitalize())
print("O nome digitado foi "+nome)
print("O nome digitado foi {}".format(nome))
print("{} foi o nome digitado".format(nome))
sobre = input("Digite seu sobrenome: ")
print("{} {} é o nome completo".format(nome,sobre))
|
2ba51e15ece6658675260b7f47a61bda1681e88c | OrionSuperman/pylot-wishlist | /app/models/User.py | 2,891 | 3.625 | 4 | """
Sample Model File
A Model should be in charge of communicating with the Database.
Define specific model method that query the database for information.
Then call upon these model method in your controller.
Create a model using this template.
"""
from system.core.model import Model
from flask... |
97433547ac2da4227d9c64499727b46c5b05c3f7 | Mayank2134/100daysofDSA | /Stacks/stacksUsingCollection.py | 490 | 4.21875 | 4 | #implementing stack using
#collections.deque
from collections import deque
stack = deque()
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')
stack.append('e')
print('Initial stack:')
print(stack)
# pop() function to pop element from stack i... |
2c82b65475d971fc01e8bea2eaf19f5bb809bf45 | Mayank2134/100daysofDSA | /Python OOPs/ClassRobot.py | 1,140 | 4.03125 | 4 | class Robot:
def __init__(self, name=None, build_year=None):
self.__name = name
self.__build_year = build_year
def say_hi(self):
if self.__name:
print("Hi, I am " + self.__name)
else:
print("Hi, I am a robot without a name")
# Using the setter a... |
2551ac2419113c221485f9981dd413fb112ca7df | Mayank2134/100daysofDSA | /GFG/cloud.py | 1,644 | 4 | 4 | # A child is playing a cloud hopping game. In this game, there are sequentially numbered clouds that can be thunderheads or cumulus clouds. The character must jump from cloud to cloud until it reaches the start again.
# There is an array of clouds, e and an energy level e=100. The character starts from c[0] and uses 1... |
67c52badb31738e645755976fe09ea20cd14e3b1 | Mayank2134/100daysofDSA | /Linked List/insertNode.py | 833 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_llist(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
def push(self, new_data... |
6ecf1fbabb84369c77f36ebfe048aede9077de9f | Mayank2134/100daysofDSA | /Recursion/remove_duplicates.py | 177 | 3.671875 | 4 | def removeDup(s):
l = len(s)
if l == 0 or l == 1:
return s
if s[0] == s[1]:
return removeDup(s[1:])
else:
return s[0] + removeDup(s[1:])
|
d9e47b45e0d851608586d29d3cd9d2565ff85809 | Mayank2134/100daysofDSA | /Stacks/balanced paranthesis.py | 549 | 3.828125 | 4 | def balancepar(string):
s=[]
for i in string:
if i in "({[":
s.append(i)
elif i == ")":
if(not s or s[-1]!="("):
return False
s.pop()
elif i == "}":
if(not s or s[-1]!="{"):
return False
s.pop()
... |
85c2efe630c8cad30d392cf255a394fe6c7079e2 | Mayank2134/100daysofDSA | /Sorting Algorthims/insertionSort.py | 393 | 4.03125 | 4 | # Build longer and longer sorted slices.
# In each iteration arr[0:i is sorted]
def insertion_sort(arr):
n = len(arr)
for i in range(n):
pos = i
while i>0 and arr[pos] < arr[pos-1]:
arr[pos],arr[pos-1] = arr[pos-1], arr[pos]
pos = pos-1 # make the sequence shorter
r... |
a846186aa6f325c8b6cae57e8f2b5696b8592947 | Mayank2134/100daysofDSA | /Stacks/reverse a stack 1.py | 397 | 3.96875 | 4 | def reverse(s1,s2):
if len(s1) ==1:
return
while len(s1) != 1:
data=s1.pop()
s2.append(data)
ele=s1[len(s1)-1]
s1.pop()
while len(s2) != 0:
data=s2.pop()
s1.append(data)
reverse(s1,s2)
s1.append(ele)
s1=list()
s2=list()
s1.append(1)
s1.append(2)
s1.app... |
f3e991cc668b60b26e2adbd6496f25d0c55a6bba | bill090/PythonWithAI4 | /nim/play.py | 1,775 | 3.53125 | 4 | from nim import train, play
while True:
timeText = input('Use time? (y/N) ')
if timeText.lower() == "n":
time = False
break
elif timeText.lower() == "y":
time = True
break
if time == False:
while True:
inNum = input('How many games would you like the AI to pla... |
860002b983b8766c3b116a68f3c3fdf43941ecca | showmen-gupta/algorithms | /dijkstra.py | 984 | 3.703125 | 4 | from priodict import priorityDictionary
def Dijkstra(G,s,e=None):
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = priorityDictionary() # estimated distances of non-final vertices
Q[s] = 0
for v in Q:
D[v] = Q[v]
if v == e: break
for w in G[v... |
8e879ad9d06da392adf59f57b869aa650a5e54d9 | aa-ag/designing-programs | /Lesson_1/poker.py | 1,938 | 4.03125 | 4 | ############------------ IMPORTS ------------############
# ---> TO DO: READ > https://stackoverflow.com/questions/41970795/what-is-the-best-way-to-create-a-deck-of-cards
############------------ FUNCTIONS ------------############
# -----------
# User Instructions
#
# Modify the poker() function to return the best ha... |
36bb0a4894d52dd80ac8cb26b4d221ac3989d52c | duncand0nuts/ISIS-network-benchmarking-script | /ISIS-network-benchmarking-script.py | 578 | 3.640625 | 4 | def file_name_reader(input_file_path):
# open file with list of filenames:
input_file = open (input_file_path, 'r')
#add filenames to a dictionary
filenames = []
for line in input_file:
filenames.append(line)
return filenames
filenames = file_name_reader('filename here')
def grab_files... |
d6f69647cf8e7f37736997f9dc7c432da6997411 | rajat1293/ALL_PROGRAMS | /python/sqrtt.py | 221 | 3.859375 | 4 | x=int(raw_input('enter a value to cal root of'))
y=float(raw_input('enter a guess '))
while True:
if(abs(y*y-x)<=0.001):
print('the root of '+ str(x) + 'is' + str(y))
break
else:
y=(y+x/y)/2
|
defa0148dfaa4e5b1d8d83542bfd04f092c9160e | szEIgo/ShakeSpearSorting | /quickSort.py | 260 | 3.875 | 4 | def qsort(list):
if list == []:
return []
pivot = list[0]
l = qsort([x for x in list[1:] if x < pivot])
u = qsort([x for x in list[1:] if x >= pivot])
return l + [pivot] + u
array = [6,7,3,16,89,5,6,1,2]
qsort(array)
print(array)
|
8869bc3ccadd7df10822ba0674fff5a5c04016c4 | shivanichoudhary12/DSA-series | /heap1.py | 159 | 3.578125 | 4 | from heapq import heappop , heappush , heapify
heap = []
nums = [12,3,5,-2,8,4]
for num in nums:
heappush(heap,num)
while heap:
print(heappop(heap))
|
3f81995adbbbc6c32e77ca7aaa05c91f5dd25d99 | Lexielist/immersive---test | /Prime.py | 204 | 4.15625 | 4 | A = input("Please input a number: ")
print ("1 is not a prime number")
for number in range (2,A):
if num%A == 0:
print (num," is a prime number)
else: print (num,"is not a prime number) |
45a87884c4f3af09f1f2425b7dcffd8619e0645c | walnutkakki/pythonTut | /ds_using_list.py | 469 | 3.625 | 4 | shoplist = ['apple', 'mango', 'bigpie']
print 'I have to buy', len(shoplist), 'things in the supermarket'
print 'What I have to buy is',
for item in shoplist: print item,
print '\n also I have to buy is ',
shoplist.append('rice'),
print shoplist
print '\n'
shoplist.sort()
print '\nthis is lists', shoplist
print'\nt... |
1a411797428698762c8398695fbfecc713e63920 | CarlosCMora/Practica-12-Recursividad | /ej3.py | 659 | 3.546875 | 4 | import turtle
import argparse
def recorrido_recursivo(tortuga,espacio, huella):
if huella>0:
tortuga.stamp()
espacio = espacio+3
tortuga.forward(espacio)
tortuga.right(24)
recorrido_recursivo(tortuga,espacio, huella-1)
ap = argparse.ArgumentParser()
ap.add_a... |
c21826978d8a12b18f0805cc0bbf9d02a6844083 | yuyhong23/python-challenge | /PyPoll/main.py | 4,167 | 3.734375 | 4 | # Import dependencies
import os
import csv
# Path to collect data from the Resources folder, because this python file is in the same location as the Resources folder, '..' is not needed
vote_count_csv = os.path.join('Resources','election_data.csv')
# Declare the keys and their initial values
voter_count = 0
all_candi... |
96ab7e2f2df37f9a61a1c6f4d9c79484973f4540 | Millennial-Polymath/alx-higher_level_programming | /0x0F-python-object_relational_mapping/2-my_filter_states.py | 499 | 3.53125 | 4 | #!/usr/bin/python3
"""
Takes an argument and displays all values in the states table of a database
where name matches the argument
"""
import MySQLdb
from sys import argv
if __name__ == "__main__":
db = MySQLdb.connect(host="localhost", port=3306, user=argv[1],
password=argv[2], database=a... |
a585ac1434cfc382a3d1f1f30850b36b4a0c3e35 | Millennial-Polymath/alx-higher_level_programming | /0x06-python-classes/5-square.py | 1,435 | 4.375 | 4 | #!/usr/bin/python3
""" Module 5 contains: class square """
class Square:
"""
Square: defines a square
Attributes:
size: size of the square.
Method:
__init__: initialialises size attribute in each of class instances
"""
def __init__(self, size=0):
self.__siz... |
1c874d066e4423ee6da3e1e271128f40dd99fc20 | Millennial-Polymath/alx-higher_level_programming | /0x04-python-more_data_structures/100-weight_average.py | 319 | 3.5625 | 4 | #!/usr/bin/python3
def weight_average(my_list=[]):
if my_list:
sum_final = 0
wght = 0
for i in my_list:
b = [tp for tp in i]
product = b[0] * b[1]
wght += b[1]
sum_final += product
average = sum_final / wght
return average
|
c8673156674aa25645982394cf3b2f77b7df07f8 | Millennial-Polymath/alx-higher_level_programming | /0x03-python-data_structures/0-print_list_integer.py~ | 85 | 3.71875 | 4 | #!/usr/bin/python3
def print_list_integer(my_list=[]):
print(x) for x in my_list
|
ca03d15b6dad6fe44d6eedb696d2fa19bda9d93b | eszkatya/test | /negative.py | 574 | 3.78125 | 4 | #itt csak negatívvá kellett tenni egy számot..nem volt semmilyen kitétel. Nem tom bemásolni a feladatot
#mert 3. frissítés után is errort ad a codewars
def make_negative(number):
number = str(number)
if number[0] == "-" or (number == "0"):
return int(number)
else:
number2 = int(nu... |
f9411b270aea54e2d36cfabed30a18f3278a8b1e | eszkatya/test | /boolean.py | 387 | 4.28125 | 4 | #Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.
def bool_to_word(boolean):
if boolean == True:
return 'Yes'
else:
return 'No'
"""ezt is lehetett vna egy sorba, ami még érdekes:
def bool_to_word(bool):
return ['No',... |
332ef74d0a66f02539f4bf81a77411bd7dd364be | stephenscottsmith/CMSI_386_Programming_Languages | /Homework 1 - Python/pythonwarmup.py | 1,864 | 3.828125 | 4 | import sys;
from random import shuffle;
##### MAKE CHANGE #####
#Precondition: the coins parameter must be a positive, whole number
def change (coins) :
quarters, coins = divmod(coins, 25)
dimes, coins = divmod(coins, 10)
nickels, coins = divmod(coins, 5)
pennies, coins = divmod(coins, 1)
return (... |
ffe6ba95357377e19e89889b4be1c391a68947e5 | priyanshu3666/CCV-lab-codes | /Cypher_to_Plain_text.py | 194 | 3.8125 | 4 | cypher=input("enter cypher text to decrypt\n",)
key_ =int(input("Enter key to decrypt\n"))
Text=""
for i in range(0, len(cypher)):
kee =ord(cypher[i]) - key_
Text +=chr(kee)
print(Text) |
1e05f8cfcc33951ec102363ace6262c688952d06 | crucis-onishi/pg1ststep_samplecode | /chap22/chap22_7_2.py | 1,276 | 3.578125 | 4 | # ウィジェットの張り替え
import tkinter as tk
from random import randint
# tk.Frameを継承したApplicationクラスを作成
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master, width=800, height=600)
# ウィンドウの設定
self.master.title("ウィンドウのタイトル")
# 実行内容
self.pack()
... |
55a361ad768c3e1a4fea51f9348e5d3989469528 | crucis-onishi/pg1ststep_samplecode | /chap22/chap22_4_3.py | 831 | 3.84375 | 4 | # 複数のボタンのうちどれが押されたかを判定
import tkinter as tk
root = tk.Tk()
# ウィンドウの設定
root.title("ウィンドウのタイトル")
root.geometry("600x300")
# buttonをクリックした時の処理
def button_clicked(item):
label["text"] = "あなたが押したボタンは " + item
# labelウィジェットを生成・配置
label = tk.Label(root,text="あなたが押したボタンは ほにゃらら", font=("游ゴシック体", "20", "bold"))
label.pl... |
c7e9613d1af0ec7359dc8a175bbd99059b05c66b | iomkarsurve/basicpython | /conditional statements/calculator.py | 309 | 4.25 | 4 | num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
op = input("Enter operator")
if(op=="+"):
print(num1+num2)
elif(op=="-"):
print(num1-num2)
elif(op=="*"):
print(num1*num2)
elif(op=="/"):
print(num1/num2)
else:
print("invalid operator") |
5e8aebce9dd01959e921127b0bcfb0a45f2fae3e | denismironchuk/hakerrank-python | /kickstart/year2021/consecutivePrimes.py | 1,198 | 3.875 | 4 | from math import sqrt
def isPrime(n):
i = 2
while i * i <= n:
if (n % i == 0):
return False
i += 1
return True
def findClosestLowerPrime(n):
while (True):
if isPrime(n):
return n
n -= 1
def findClosestUpperPrime(n):
while (True):
if... |
627ca465262355d0488bebc7b20acdd39483dee7 | denismironchuk/hakerrank-python | /dynamicProgramming/stringReduction.py | 421 | 3.5 | 4 | if __name__ == '__main__':
t = int(input())
for _ in range(t):
s = input()
stat = {'a': 0, 'b': 0, 'c': 0}
for c in s:
stat[c] += 1
if (stat['a'] == len(s) or stat['b'] == len(s) or stat['c'] == len(s)):
print(len(s))
elif (stat['a'] % 2 == stat[... |
1f0e0470ddfa86cc9a7b2edea4233dca7275f837 | denismironchuk/hakerrank-python | /kickstart/year2020/biketour.py | 362 | 3.5 | 4 | if __name__ == '__main__':
T = int(input())
for t in range(1, T + 1):
n = int(input())
heights = list(map(int, input().split()))
res = 0
for i in range(1, len(heights) - 1):
if heights[i] > heights[i - 1] and heights[i] > heights[i + 1]:
res += 1
... |
9fdd32d199e89ea287ddc2162da0aa7227050c8e | devils-ey3/regexSolutionHackerrank | /Application/HackerRank Tweets.py | 203 | 3.875 | 4 | # https://www.hackerrank.com/challenges/hackerrank-tweets/problem
import re
count = 0
for x in range(int(input())):
if re.search('(hackerrank)',input(),re.IGNORECASE):
count+=1
print(count)
|
2fd12f2919baca9283d95439f6d98144d9c791aa | ErickOF/CE1102-Text-Compression-with-Huffman-Coding | /Node.py | 1,939 | 3.984375 | 4 | class Node:
"""Class to represent a tree node.
"""
def __init__ (self, token: str, value: int):
"""Constructor.
Args:
token (str): token or word.
value (int): occurrences of the token.
"""
self.left = None
self.right = None
self.token ... |
7545530cba81bc242913a355c218e8a00857ca88 | camswcraft/coding-dojo | /2017/01-17_rock-paper-scissors_python/rock_paper_scissors.py | 571 | 3.546875 | 4 | SCISSORS = "scissors"
PAPER = "paper"
ROCK = "rock"
DRAW = 0
P1_WIN = 1
P2_WIN = 2
def round(player1, player2):
if player1.hand == player2.hand:
return DRAW
elif player1.hand == ROCK:
if player2.hand == SCISSORS:
return P1_WIN
return P2_WIN
elif player1.hand == PAPER:
... |
a999a013bb714ee7e0f53a6a8c4ea158fd3ffba4 | narasimha678/pythonPractice | /list_tuple_set/setoperations.py | 154 | 3.625 | 4 | friends={"person1","person2","person3"}
abrod={"person1","person2"}
local_friend=friends.difference(abrod)
print(local_friend)
print(friends.union(abrod)) |
fea7862453ac6405a70a75c6744f3c53cc8dfe1d | narasimha678/pythonPractice | /boolean/code.py | 299 | 4.09375 | 4 | print(5==5)
print(5>5)
print(10!= 10)
# comparisons : ==,!=,>,<,>=,<=
friends=["nara","simha"]
abrod=["nara","simha"]
print(friends==abrod)
print(friends is abrod)
print(friends is friends)
# == is used to compare the values inside it
# 'is' -- is used to compare the references of both elements |
b9c60b713c4200cee79eddc03700689d7f846950 | 990321/python_data_structures | /DS3-search/searchPractise.py | 2,149 | 3.96875 | 4 | '''
**练习**:
写一个函数,该函数需要一个列表和我们正在搜索的项作为参数,
并返回一个是否存在的布尔值。found = False
'''
# def sequentialSearch(alist, item):
# pos = 0 # 下标索引
# found = False
# while pos<len(alist) and not found:
# if alist[pos] == item:
# found = True
# else:
# pos = pos + 1
# return found
... |
2e0e5ef285496cbe54c3d4168d707962ffbb90cb | jackrapp/python_challenge | /PyBank/main.py | 1,717 | 3.625 | 4 | #import modules
import csv
import os
budget_data = os.path.join("budget_data.csv")
profit = 0
months = 0
value = 0
increase = 0
decrease = 0
#pull data from csv file in git hub folder
with open(budget_data, newline="") as csvfile:
records = csv.reader(csvfile, delimiter = ",")
next(records)
#calculate
#... |
4ecd6011e6a1e08a961ff3cbf8bd81f6068e6ec1 | jeff-cloud/awra_cms | /packages/awrams/utils/mapping_types.py | 16,616 | 3.734375 | 4 | '''
Defines the datatypes used for analysis and persistence
Variables represent the conceptual objects that may be
used in analysis and modelling
MappedVariable objects refer to the concrete realisation of data
associated with variable(s) within a dataset
e.g "temp_max_day" refers
to the abstract maximum daily temp... |
944d8d7851bb5f27d6fc1e6d5b4043cacbb4e16a | beyzend/learn-sympy | /chapter3.py | 329 | 4.34375 | 4 | days = ["sunday", "monday", "tuesday", "wednesday", "thursday",
"friday", "saturday"]
startDay = 0
whichDay = 0
startDay = int(input("What day is the start of your trip?\n"))
totalDays = int(input("How many days is you trip?\n"))
whichDay = startDay + totalDays
print("The day is: {}".format(days[whichDay % len(... |
bc18a5a87f106a1e215c94cf3f7c06f2427d23c1 | isrcode/CTUPY | /Primeiro_Checkpoint/Consumo_energia.py | 390 | 3.5625 | 4 | consumo = float(input("Digite o cosumo mensal: ").replace(",","."))
kWh = 14
icms = 0
if consumo > 50:
kWh = (consumo * 0.25) + 14
if consumo >= 100 and kWh <= 200:
icms = kWh * 0.13
elif consumo >= 201:
icms = kWh * 0.33
print(
f"Consumo kWh => R${kWh:.2f}\n"
f"ICMS => R${icms:.2f}... |
efcf6824fc518428f94a19dba9af5c74ca37ecc0 | isrcode/CTUPY | /Lista02_Exercicio/ex09.py | 440 | 3.671875 | 4 | p = float(input("Qual o preço do produto? ").replace(',', '.'))
d = float(input("Qual o percentual de desconto a ser aplicado? ").replace(',', '.'))
pn = p - (p/100*d)
print(str(f"O produto custa R${p:.2f} com desconto de {d}% fica por R${pn:.2f}").replace('.', ','))
"""
Se ao invés de um desconto fosse um aumento,... |
a407daa2fa64ba1548a7184a4532f35fd8ac5108 | isrcode/CTUPY | /Lista04_Exercicio/ex_03.py | 748 | 3.953125 | 4 | contador = 1
alunos = int(input("Quantidade de Alunos: "))
nota = 0
soma = 0
abaixo5 = 0
acima5 = 0
while contador <= alunos:
nota = float(input("Nota: "))
if nota <= 5:
abaixo5 += 1
else:
acima5 += 1
soma += nota
contador += 1
print(soma / alunos)
print(
f"{acima5} Alu... |
8e1243bfce31029d5a2f40156f7a6bb9528b23e6 | isrcode/CTUPY | /Lista02_Exercicio/ex14.py | 364 | 3.671875 | 4 | vlAvista = float(input("Qual o valor a vista? "))
vlParcela = float(input("Qual o valor da parcela? "))
"""
100 = 1000
X 970
X = 100*970
1000
X = 97%
100 - X = 3%
3% é o desconto para pagamento a vista no estado de São Paulo.
"""
pcDesconto = 100 - (vlAvista*100)/(vlParcela*10)
print(f"O desconto para p... |
efcf862d3818123fc48d95aed252e8c6d06f39f7 | edaleeta/advent-of-code-2019 | /python/01/part_2_fuel_requirements.py | 1,559 | 3.859375 | 4 | from fuel_requirements import get_fuel_requirements
from fuel_requirements import FILE
# So, for each module mass, calculate its fuel and add it to the total.
# Then, treat the fuel amount you just calculated as the input mass and repeat the process,
# continuing until a fuel requirement is zero or negative. For examp... |
220aef3599c79f52232ed20373f8254f48c4e55d | VivianHC/GUI1208 | /try_controls/try2_label_entry/try_entry_text.py | 596 | 3.8125 | 4 | import tkinter as tk
from tkinter import ttk
# create root window
top_win = tk.Tk()
# naming root window
top_win.title('Hello World Window')
# resize root window
win_size_pos = '1920x1080'
#win_size_pos = '360x60'
top_win.geometry(win_size_pos)
#------------------------------
default_var=tk.StringVar(value='一人之下')
... |
ed079e1bc10380e372fe5489692b8a69e3bab29d | JulianCamacho0/SistemaCuanticoDeParticulaEnUnaLinea | /Proyecto_terminado.py | 7,793 | 3.953125 | 4 | #Operaciones con vectores y matricen en los complejos
#Autor: Julian Camacho
#Enero de 2019
import sys
import math
#--------------------------------------------------------------------------------
#---------------------------- Operaciones numeros complejos -----------------------------
#------------------------------... |
f609b4e9ddd2eb6b9ebe43242062b68951a559e8 | NikKovacic/Domesday | /domesday/spaceship.py | 1,683 | 4 | 4 | import pygame
from pygame.sprite import Sprite
class SpaceShip(Sprite):
"""A class that draw(blit) a spaceship to the screen and move its position"""
def __init__(self, settings, screen):
"""Initialize the spaceship."""
super(SpaceShip, self).__init__()
self.screen = screen
s... |
714981cda6519db2aefa69f575c1d87c454d1c77 | ivan295/Curso-Python-Rafael | /tarea unidad 3/tarea3_ejercicio6.py | 917 | 4.40625 | 4 | """
Utilizando la función range() y la conversión a listas genera las siguientes
listas dinámicamente:
Todos los números del 0 al 10 [0, 1, 2, ..., 10]
Todos los números del -10 al 0 [-10, -9, -8, ..., 0]
Todos los números pares del 0 al 20 [0, 2, 4, ..., 20]
Todos los números impares entre -20... |
ca84077b183fe03b7cfdd07a4f40f0601e85725c | ivan295/Curso-Python-Rafael | /tarea unidad 7/ejercicio4_unidad7.py | 486 | 3.921875 | 4 | """
Localiza el error en el siguiente bloque de código.
Crea una excepción para evitar que el programa se bloquee y
además explica en un mensaje al usuario la causa y/o solución:
resultado = 15 + "20"
"""
# TypeError:
try:
resultado = 15 + "20"
except TypeError as error:
print("error de tipo : ", error.__cla... |
d7df130f5f066ed361698896dc1550e23f1d0ea6 | ivan295/Curso-Python-Rafael | /tarea unidad 4/ejercicio1_unidad4.py | 570 | 4.03125 | 4 | """
Realiza una función llamada area_rectangulo(base, altura) que devuelva el área del
rectangulo a partir de una base y una altura. Calcula el área de un rectángulo
de 15 de base y 10 de altura:
Recordatorio
El área de un rectángulo se obtiene al multiplicar la base por la altura.
"""
def area_re... |
a0ff74491a4357c516fbfad1ba87973f053a9199 | ivan295/Curso-Python-Rafael | /tarea unidad 8/modelo.py | 3,839 | 3.515625 | 4 | class Productos:
def __init__(self, id, nombre, grupo, subgrupo):
self.id = id
self.nombre = nombre
self.grupo = grupo
self.subgrupo = subgrupo
def __str__(self):
return 'Producto :{} {} {} {}'.format(self.id, self.nombre, self.grupo, self.subgrupo)
class Admin(Produc... |
8bd9bbdabd8a962c794c3fa01b2de6437a0268ce | nenusoulgithub/LearnPython | /求知学堂/day8_09-类属性和实例属性.py | 892 | 4.1875 | 4 | # 类属性和实例属性
class Student:
school = "东北师范大学" # 类属性
def __init__(self, name):
self.name = name # 实例属性
def __str__(self):
return "学生%s就读于%s" % (self.name, Student.school)
xiaoming = Student("小明")
print(xiaoming)
print("类属性的地址是%d,内容是%s。" % (id(xiaoming.school), xiaoming.school))
xiaoming.s... |
17f7f333709858f03052d20a93103cb0775b2bc5 | nenusoulgithub/LearnPython | /求知学堂/day11_03_with上下文管理.py | 653 | 3.640625 | 4 | # 按行读取
# with管理的对象会自动释放
with open("111.txt", "r", encoding="utf8") as fo:
for line in fo.readlines():
print(line.strip("\n"))
# 小结
# 文件写入模式:w w+ wb wb+
# 普通文件使用:w w+
# 音频,视频文件使用:wb wb+
# 文件读取模式:r r+ rb rb+
# 读取普通文件:r r+
# 读取图片,视频文件:rb rb+
# 使用with进行文件拷贝
with open("111.txt", "r", encoding="utf8") as old_fi... |
a8bc4dee358f97fe97efbb01cb8c1aa3fdba6078 | nenusoulgithub/LearnPython | /求知学堂/day3_02-字符串操作.py | 2,509 | 4.5625 | 5 | # Python的序列 字符串 列表 元组
# 优点:通过下标访问元素
# 共同点:支持切片
python = "Python"
print("字符串的第一个字符%s" % python[0])
print("字符串的第二个字符%s" % python[1])
for c in python:
print(c, end=" ")
print("\n--------------------------------------")
# 大小写转换
python = "python"
print("将单词的首字母变为大写%s" % python.capitalize())
print("将单词所有字母变为大写%s" % p... |
b50df42287c5962d04b762d0c32feb4a81b72ac6 | nenusoulgithub/LearnPython | /求知学堂/day1_07-逻辑运算符.py | 436 | 4.125 | 4 | # 条件运算符 and or not
a, b, c, d = 5, 8, 2, 9
print("---------------and---------------")
print(a < b and c < d)
print(b > c and d < a)
print("---------------or---------------")
print(a < b or c < d)
print(b > c or d < a)
print(b < c or d < a)
print("---------------not---------------")
print(not a < b)
# 逻辑运算符... |
440fcfd64a488b61d70075862702f93fa7e2505b | trynke/lotto | /lotto.py | 910 | 3.9375 | 4 | import keyboard
import random
def get_barrel(barrels):
if len(barrels) != 0:
rand = random.choice(barrels)
print(rand)
barrels.remove(rand)
else:
print("There aren't any barrels left. Press Esc to close the program, goodbye!")
def get_number_of_barrels():
N = str(input('En... |
5490a336d9f8396d193b48ce6c31b9720b4442e2 | jesjar16/zoo | /zoo.py | 2,834 | 3.828125 | 4 | class Animal:
def __init__(self, name, age, health_level, happiness):
self.name = name
self.age = age
self.health_level = health_level
self.happiness = happiness
def feed(self, klgs):
self.health_level = self.health_level + 10 * klgs
self.happiness = self.happine... |
bafcbcc26ef5a29f3474af8b5d4dc008baa6a6eb | hisanak/python_basics | /7_oop/procedual.py | 713 | 3.875 | 4 | # -*- coding: utf-8 -*
"""
this script is encoded with UTF-8 and contains non ASCII codes, so specify it for python2
"""
animals = [{"name": "cat"}, {"name": "dog"}, {"name": "horse"}]
for animal in animals:
"""
各動物に合わせた処理を、各動物を表すデータの定義とは異なる場所に記述する。
→離れれば離れるほどバグの温床になる
→動物の種類が増えるとif文地獄になる
"""
i... |
c44aa94ce43a77b50f99aa00794b5224db0cb579 | Muneerah1612/WebScraper | /main.py | 1,134 | 3.578125 | 4 | from analyse import CheckUrl
from get import GetRequest
from top_words import GetWords
from barchart import BarChart
class Web:
def WebScrape(self):
''' This function prompts the user to analyse any website of their choice '''
while True:
ask_to_scrape = input('Would you like to scrap... |
2f05c959814934372cf786623921c26f788d0d30 | ed1rac/AulasEstruturasDados | /2019/## Python/Ordenacao e Busca/insertion_sort-v1.py | 805 | 4.1875 | 4 | """
A estrategia do insertion sort é:
1 - iterar usando i de vetor[1] até tamanho do vetor (laço externo) - vetor[i] é o atual
2 - fazer um laço (usando j) de i-1 até 0 e: (laço interno)
3 - se o valor de atual < vetor[j], afasta vetor[j] para direita
4 - quando vetor[j] encontrar um valor menor ou 0, então insere o at... |
c83a1453c9b7f7b594b16591cf11d405d81eb1d9 | ed1rac/AulasEstruturasDados | /UNP/ref/Python/Ordenacao e Busca/busca_binaria2.py | 954 | 3.984375 | 4 | # -*- encoding: utf-8 -*-
"""
Busca binária em Python (procedural)
Autor: Ed.
Data: 07/05/2020
"""
import random
random.seed()
def gera_lista():
lista = random.sample(range(1,100),20)
return lista
def exibe_lista(lista):
print(lista)
def busca_binaria(lista, item):
primeiro = 0
ultimo = len(lista)-1
while... |
71bffca24a654b5fa0e657cdd496073e80091f99 | ed1rac/AulasEstruturasDados | /UNP/ref/Python/Basico-MacBook-Ed/exercicio1MediaAprovadoReprovado.py | 379 | 4.03125 | 4 | nota1 = float(input('Entre com a primeira nota: '))
nota2 = float(input('Entre com a segunda nota: '))
media = (nota1 + nota2)/2
if media > 7:
print('Sua media é: ', media, ' e vc foi aprovado!!')
elif 4 < media < 7:
print('Sua media é: ', media, ' e vc vai fazer FINAL. Estude mais!')
else:
print('Você foi ... |
eb61ba46bf967a9e79600eb9905dfe652a4d0ca6 | ed1rac/AulasEstruturasDados | /2019/## Python/Basico-MacBook-Ed/SlicesString.py | 581 | 4.1875 | 4 | s = 'Edkallenn'
print("Fatias de strings:\n=============")
print(s[2:]) #a partir da segunda posição, começando de zero, para frente - 'kallenn'
print(s[1:]) #a partir da primeira posição, começando de zero, para frente - 'dkallenn'
print(s[-1:]) #slice com a Última posição - 'n'
print(s[-2:]) #slice com as duas última... |
72f2e481576548782cbb00f3ad5256e4383dc7d5 | ed1rac/AulasEstruturasDados | /UNP/ref/Python/Basico/funcoes.py | 432 | 3.71875 | 4 | def mostra_idade(idade):
if idade == 18:
print('Você tem exatamente 18 anos')
elif 20 < idade < 30:
print('Você está entre 20 e 30 anos')
elif idade > 30:
print('Você tem mais de 30 anos')
else:
print('Sua idade é menor que 18')
def ler_idade():
idade = int(input('D... |
53d1afc8ba2931f4f6a4c4df9baaa017b3ebf3b9 | ed1rac/AulasEstruturasDados | /UNP/ref/Python/TADs e Classes/Fila.py | 1,120 | 4.1875 | 4 | class Fila(object):
'uma classe de fila clássica'
def __init__(self):
'instancia uma lista vazia'
self.items = []
def esta_vazia(self):
'retorna True se a lista está vazia, False caso contrário'
return (len(self.items)==0) #se o tamanho for zero
def enfileira(self, item): #enqueue
'ins... |
d975784b292282e44aab27e86b07d0a0a175230d | ed1rac/AulasEstruturasDados | /2019/## Python/TADs e Classes/TAD_ponto.py | 936 | 4.28125 | 4 |
class Ponto(object):
def __init__(self, x, y): #método construtor (cria ponto)
self.x = x
self.y = y
def exibe_ponto(self):
print('Coordenadas -> x: ', self.x, ', y: ', self.y)
def set_x(self, x):
self.x = x
def set_y(self, y):
self.y = y
def get_x... |
38adfd31bf864422f151dff0d6dd65971670d471 | ed1rac/AulasEstruturasDados | /2019/## Python/Basico-MacBook-Ed/nao_e_hello_world0.py | 197 | 3.890625 | 4 | import sys
print('Bem vindo ao Python, versão ', sys.version)
print('Digite um número inteiro: ')
n = int(input())
for i in range(n):
print('Mensagem ', i)
print('Obrigado, e até logo!') |
35443dd8ef2ff501744a0182df0da938446fb276 | ed1rac/AulasEstruturasDados | /UNP/ref/Python/Basico-MacBook-Ed/entrada_dados2.py | 318 | 3.71875 | 4 | # encoding: utf-8
"""
Entrada de dados: outra forma
Por: Ed
"""
idade = int(input('Entre com sua idade em anos: '))
freq_card_max = 206.9- (0.67 * idade)
alvo = 0.65 * freq_card_max
print('Sua frequência cardíaca máxima é: ', freq_card_max)
print('Seu alvo defrequencia cardíaca de queima de gordura é: ', alvo)
|
82c77a502435db9ed166851fce1e823852e87565 | ed1rac/AulasEstruturasDados | /2019/## Python/Basico/vogais.py | 94 | 3.65625 | 4 | frase = input('Digite uma frase: ')
for c in frase:
if c in 'aeiouAEIOU':
print(c) |
35f3d55760fb66d06e317c038e75214facc1850c | johndpope/spy611scripts | /script/pg2gbm.py | 1,333 | 3.859375 | 4 | #!/usr/bin/env python
# ~/spy611/script/pg2gbm.py
# ref:
# http://wiki.postgresql.org/wiki/Using_psycopg2_with_PostgreSQL
# I use this script to study psycopg2.
# I am not sure I will use psycopg2 yet.
import psycopg2
import sys
import pprint
def main():
#Define our connection string
conn_string = "host='loca... |
f5cbc1f3e9f303b718c0c0a688a27527fb69b822 | Parkhomenkoaa/homework | /normal.py | 486 | 3.953125 | 4 |
# 1 задание
a = int(input('введите числовое значение : '))
while a < 0 or a > 10 :
print('не верное значение')
a = int(input('введите число больше 0 и меньше 10 : '))
a = a ** 2
print(a)
# 2 задание
a = int(input('введите значение А '))
b = int(input('введите значение Б '))
a = ... |
0da07b691689b51ace27097ca27a43fe453b3ca4 | vivekdubeyvkd/python-utilities | /min_operations_make_array_element_equal.py | 563 | 3.5625 | 4 | inList1 = [1,1,2,2,2,3,4,4,4]
inList2 = [10,10,10]
inList3 = [1,1,3,4,4,4]
def minOperations(inputList):
myMap = dict.fromkeys(inputList, 0)
minMoves = 0
listLen = len(inputList)
for i in range(listLen):
myMap[inputList[i]] += 1
print(myMap)
for key, value in myMap.items():
x = key
freq = value
if x... |
e1730b223bc66de92afdb0f2f857a1b617a43df9 | vivekdubeyvkd/python-utilities | /writeToFile.py | 462 | 4.40625 | 4 |
# create a new empty file named abc.txt
f = open("abc.txt", "x")
# Open the file "abc.txt" and append the content to file, "a" will also create "abc.txt" file if this file does not exist
f = open("abc.txt", "a")
f.write("Now the file has one more line!")
# Open the file "abc.txt" and overwrite the content of entire... |
53b852960506d94a7ec5d00789d01e485863d547 | vivekdubeyvkd/python-utilities | /createCompressedMessageDigestFromAString.py | 1,239 | 3.703125 | 4 | # This programs counts consecutive occurences of a word in a string and creates a compressed message digest e.g.
# If input string is aabcdrsss, then output will be a2bcdrs3
# If input string is abc, then output will be abc
# If input string is abbbac, then output will be ab3ac
# If input string is abbbacdssssb, then o... |
afc9899cba244fbfb6f16d84dfc806ed523a1e80 | cklll/competitive-programming | /leetcode/max-product-subarray.py | 2,366 | 3.515625 | 4 | # https://leetcode.com/problems/maximum-product-subarray/submissions/
from typing import List
# very stupid approach
class Solution:
def maxProduct(self, nums: List[int]) -> int:
# split to list of list, separated by 0
# it's easier to handle
nums_of_nums = []
current_nums = []
... |
4eba0cdda34e2da8cc65117d9c293f430c66af51 | cklll/competitive-programming | /leetcode/merge-intervals.py | 600 | 3.8125 | 4 | # https://leetcode.com/problems/merge-intervals/
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
result = [intervals[0]]
for interval in intervals:
if result[-1][1] >= interval[0]:
result[... |
901b471831056eeb94da13fef6be5f3522f1a958 | cklll/competitive-programming | /hackerrank/medium-bigger-is-greater.py | 1,131 | 3.640625 | 4 | # https://www.hackerrank.com/challenges/bigger-is-greater/problem
# ref https://www.nayuki.io/page/next-lexicographical-permutation-algorithm
def biggerIsGreater(w):
longest_suffix = w[-1]
pivot_position = len(w) - 1
pivot = ''
for i in range(len(w) - 2, -1, -1):
if w[i] >= w[i + 1]:
... |
e271a5f4c174c031209f3f269efae1fedb9cc80f | cklll/competitive-programming | /uva/10573_the_snail/main.py | 918 | 3.71875 | 4 | def solve(well_height, climb_distance, slide_distance, fatigue_factor):
decrement = climb_distance * (fatigue_factor / 100)
day = 0
current_height = 0
current_climb_distance = climb_distance
while True:
day += 1
current_height += current_climb_distance
if current_height > ... |
c43847e45bc6e8d1ee309034ffe7da342779cab1 | cklll/competitive-programming | /uva/11498_division_of_nlogonia/main.py | 611 | 3.671875 | 4 | def solve(dx, dy, x, y):
if x == dx or y == dy:
return 'divisa'
if x > dx and y > dy:
return 'NE'
if x > dx:
return 'SE'
if x < dx and y > dy:
return 'NO'
if x < dx:
return 'SO'
def run():
while True:
n = int(input())
if n == 0:
... |
8d035c029c32683a8f19f0bdaca24847e2942969 | cklll/competitive-programming | /leetcode/insert-interval.py | 2,625 | 3.71875 | 4 | # https://leetcode.com/problems/insert-interval/
from typing import List
class Solution:
# not overlap
# |----| |----|
# |----|
# newInterval start before interval start
# |---| |------| |------|
# |------|
#
# newInterval start before interval end
# |--... |
3736d3ea7fbeeec550b206c83c18eecf61892f2c | cklll/competitive-programming | /uva/11172_relational_operators/main.py | 301 | 3.578125 | 4 | def solve(a, b):
if a > b:
return '>'
elif b > a:
return '<'
else:
return '='
def run():
n = int(input())
for i in range(n):
a, b = map(int, input().split())
result = solve(a, b)
print(result)
if __name__ == "__main__":
run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.