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 |
|---|---|---|---|---|---|---|
f2c2437da25595a859012339d8c125c9e42b75b9 | susumanin/pimp_my_vocab | /read_dic_from_file.py | 290 | 3.71875 | 4 | f = open('/Users/mak/Documents/python_scripts/vocab/rank_word_count', 'r',
encoding='utf-8')
list_of_words = f.readlines()
k = 0
for line in list_of_words:
splitted_line = line.split(' ')
print(splitted_line[1])
k = k + 1
if k == 3:
break
#just comment
|
7ac060f0eaedadd5c18d3dce33afa776639f45f2 | TranD2020/Backup | /lists.py | 1,315 | 4.34375 | 4 | # Make a list
myClasses = ["Algebra", "English", "World History"]
print(myClasses)
# add an item to the list
# append or insert
# append will add to the back of the list
myClasses.append("Coding")
print(myClasses)
favClass = input("What is your favorite class? ")
myClasses.append(favClass)
print(myClasses)... |
aa5d7c78bc0e77b5ad660b713b65b918ae20707d | TranD2020/Backup | /practice3.py | 393 | 4.375 | 4 | print("Hello, this is the Custom Calendar.")
day = input("What is today(monday/tuesday/wednesday/thursday/friday/saturday/sunday): ")
if day == "monday":
print("It's Monday, the weekend is over")
elif day == "friday":
print("It's Friday, the weekend is close")
elif day == "saturday" or "sunday":
print("It... |
809401d9e32038a2fe6c622e86f7d7946a02c285 | rovm/python | /exUnit15.py | 429 | 3.765625 | 4 | #elif 사용하기
#if 조건식:
# 코드1
#elif 조건식:
# 코드2
x = 20
if x == 10:
print('x는 10입니다.')
elif x == 20:
print('x는 20입니다.')
#if, elif, else 모두 사용하기
#if 조건식:
# 코드1
#elif 조건식:
# 코드2
#else:
# 코드3
x = 30
if x == 10:
print('x는 10입니다.')
elif x == 20:
print('x는 20입니다.')
else:
print('10, 20이 아닙니다.... |
942c1de6b2cd12ea00767202e564276d4ee8d35e | rovm/python | /exUnit23.py | 1,573 | 3.609375 | 4 | #차원 리스트를 만들고 요소에 접근하기
a = [[10,20],[30,40],[50,60]]
print(a)
#차원 리스트의 요소에 접근하기
print(a[0][0])
print(a[1][1])
print(a[2][1])
a[0][1] = 1000
print(a[0][1])
#톱니형 리스트
a = [[10,20],
[500,600,700],
[9],
[30,40],
[8],
[800,900,1000]]
print(a)
a = []
a.append([])
a[0].append(10)
a[0].append(20)
a.ap... |
7c0d9497d3deb1ede76f20356746c7b2fef6aeda | rovm/python | /exUnit8.py | 1,241 | 3.828125 | 4 | #불과 비교 연산자 사용
print(True) # True
print(False) # False
#비교 연산자의 판단 결과
print(3>1) # True
#숫자가 같은지 다른지 비교하기
print(10 == 10) # True
print(10 != 5) # True
#문자열이 같은지 다른지 비교하기
print('Python' == 'Python') # True
print('Python' == 'python') # False
print('Python' != 'python') # True
#부등호 사용하기
print(10 > 20) # False
print(10... |
4ba51f3ed911a640d970756e474179a2a30d95a9 | rovm/python | /exUnit14.py | 1,211 | 4.03125 | 4 | #else 사용하기
#if 조건식:
# 코드1
#else:
# 코드2
#else 들여쓰기
x = 10
if x == 10:
print('10입니다.')
else:
print('x에 들어있는 숫자는')
print('10이 아닙니다.')
#if 조건문의 동작 방식 알아보기
if True:
print('참')
else:
print('거짓')
if False:
print('참')
else:
print('거짓')
if None:
print('참')
else:
print('거... |
a795152079fe503c87516ab5b753c0c33c504c73 | gouri21/c97 | /c97.py | 491 | 4.25 | 4 | import random
print("number guessing game")
number = random.randint(1,9)
chances = 0
print("guess a number between 1 and 9")
while chances<5:
guess = int(input("enter your guess"))
if guess == number:
print("congratulations you won!")
break
elif guess<number:
print("guess a number hi... |
3e87a798b347ccaeb5f47d4c9e2b529d102a2d19 | isabelleon07/Curso-de-bioinformatica | /Ejercicios iniciales Python/Ejercicio_condicional_if.py | 364 | 3.84375 | 4 | #Ejercicio condicional if
#Iniciamos codigo
print('buscar el nucleotido C')
nucleotide = "C"
print(nucleotide)
print('Iniciamos busqueda de nucleotidos')
if (nucleotide == "A"):
print ("ADENINA")
elif (nucleotide == "C"):
print ("CITOSINA")
elif (nucleotide == "T"):
print ("TIMINA")
elif (nucleotide == "G"):
pri... |
e0883ed37e79623f17ea2eaae85cc49b05e012ea | BigPPython/Name | /name.py | 1,110 | 4.125 | 4 | # Code: 1
# Create a program that takes a string name input,
# and prints the name right after.
# Make sure to include a salutation.
import sys
a = '''**********************************
*WHAT IS YOUR SEXUAL ORIENTATION?*
*TYPE *
*M FOR MALE *
*F FOR FEMALE ... |
45096e6beb71ccc46aaf648e29f6e2daebb27756 | kartikv97/ENPM661 | /PROJECT3/proj3_groupnumber6_vrep_python/Phase_4/vrep/utils.py | 4,972 | 3.578125 | 4 |
import numpy as np
# Function to inputs from the user.
def get_User_Input(node):
axis = ["X", "Y"]
flag = False
final_input = np.zeros(2)
while flag is False:
count = 0
for a in axis:
input_val = input("\nEnter the value of " + str(node)+ " "+ str(a) + " co-ordinate:")
... |
5c353a0bd6101726ecbac1411fc53a96e030fdae | sarah98k/Classworkfall2021 | /LDL_analysis.py | 1,045 | 3.78125 | 4 | #LDL_analysis.py
def LDL_analysis():
print("Blood Calculator")
keep_running = True
while keep_running:
print("Make a choice")
print("2 - LDL Analysis")
print("9 - Quit")
choice = int(input("Make a choice: "))
print(type(choice))
if choice == 9:
ke... |
54aeea612b0a17afc9d99d620f679d4eabcc6839 | Ricky-Castro/python | /Iterando strings com while em Python.py | 356 | 3.71875 | 4 | """
Interando strings com while em Python
"""
minha_string = 'o rato roeu a roupa do rei de roma.'
tamanho_string = len(minha_string)
# print(minha_string.count('r'))
c = 0
nova = ''
while c < tamanho_string:
if minha_string[c] == 'r':
nova += minha_string[c].upper()
else:
nova += minha_... |
55def0298e0d7156b3d9d54f9297e47e98b887e6 | Ricky-Castro/python | /Aula4/Aula4.py | 343 | 3.890625 | 4 | """
Tipos de dados
str = string = texto 'assim' ou "assim"
int = inteiro = números inteiros (123456)
float = real/ponto flutuante = 10.0 1.5
bool = booleano/lógico = verdadeiro ou falso (true or false) ex: 10 == 10
"""
# print('L' == 'n', type('L' == 'L'))
print(type('Henrique'), bool('Henrique'))
print('sou maior... |
2a1eb0097bac67dab676129cb23d21d13480ef3f | aayushinamdeo31/Python_Intern-SecurityBrigade | /task_4.py | 2,032 | 3.953125 | 4 | # Task 4
# Rock Paper Scissors
# Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input),
# compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game.
# Remember the rules:
#
# - Rock beats scissors
# - Scissors beats paper
# - P... |
654cfb734b5a55ae5e6867262e80d3cd57c3a24d | Cr0n1c/google_foobar | /queue_to_do.py | 1,373 | 3.859375 | 4 | class UnitTest:
def __init__(self, start, length, expected_result):
self.start = start
self.length = length
self.expected_result = expected_result
def answer(start, length):
"""
:param start: starting number for the line
:param length: number of people to go through
:retur... |
4440afe77a0084e110f2976dba48473b78abd5d5 | CaMeLCa5e/Multithreading | /threadingFlag.py | 1,206 | 3.84375 | 4 | #!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self.threadID, name, q):
threading.Thread.__init__(self)
self.name = name
self.q = q
def run(self):
print "starting" + self.name
process_data(self.name, self.q)
print "exiting" + se... |
8a9635f53c7e01f16f3370db41f680fb524239cd | Alexandra-Sontu/cele-15-probleme | /problema11 IF.py | 1,111 | 3.90625 | 4 | """Se dau trei numere. Să se afişeze aceste numere unul sub altul, afişând în dreptul fiecăruia unul dintre cuvintele PAR sau
IMPAR. Exemplu : Date de intrare : 45 3 24 Date de ieşire : 45 impar 3 impar 24 par."""
a=int(input("primul numar"))
b=int(input("al doilea numar"))
c=int(input("al treilea numar"))
if ((a%... |
0b4b9ce3988a8d648ab13d5acf09bdfc5af3bc04 | etucker-colorado/Network-Comparison | /feature_extractors/mean_geodesic.py | 648 | 3.65625 | 4 | import numpy as np
def mean_geodesic_distance(G,weighted=True):
"""
input: python i-graph Graph object
output: the mean geodesic distance (shortest path) of graph G
"""
if weighted:
weights = "weight" # an attribute for edge weight. You may change this depending on the gml file
else:
... |
80f8b55008c94b32c569da784ed225407456753d | justinlooney/singnet | /agent/sn_agent/utils.py | 869 | 3.640625 | 4 | def import_string(import_name):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:esca... |
1979ccbc469047d41e4a38cc0d04c8b6ea0b63d1 | littlecmason/bin | /decrypter.py | 463 | 3.9375 | 4 | while True:
print("need something decrypted? say it here or say 'how do I incrypt somethin")
decode = input("g?' ")
if decode == "how do I incrypt something?":
print("you type your message that you want to send, then type 4 random cha")
print("racters in between each letter of your message."... |
a4c8d150151de0a6a1122a667368bb1950952c6b | littlecmason/bin | /personmaker.py | 1,991 | 3.5625 | 4 | import random
def backround():
name = random.choice(["Bella","Lucy","Chris","Gabe","Ben","Rob","Susan","Sue"])
age = random.randint(18,40)
color = random.choice(["red","orange","yellow","green","blue","purple"])
free = random.choice(["go fishing", "ride my bike", "play minecraft", "code"])
ft = ran... |
6fa3f2e14425d7386869c010b2435d398667f199 | AshishShinde-18/tkinterCode_snippet | /number.py | 408 | 3.734375 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
def ok():
s = int(e1.get())
if s < 0:
messagebox.showinfo(root, "no is negative")
else:
messagebox.showinfo(root, "no is positive")
l1 = Label(root, text="No")
e1 = Entry(root)
b1 = Button(root, text="B", command=ok)
l1.g... |
5e020215b64532cd24bfd5ab3bde11073609bcf6 | AshishShinde-18/tkinterCode_snippet | /emailvalid.py | 651 | 3.75 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
def val():
t1 = e1.get()
t2 = e2.get()
if t1 == " " or t2 == " ":
messagebox.showinfo(root, "Email Id InValid")
elif t1 != t2:
messagebox.showinfo(root, "Email Id InValid")
else:
messagebox.showinfo(root, ... |
f68dccaa819f08c2db5029bc6e54b3a4c0e5c31a | RodrigoBorges93/DataStructureUdemy | /O(1).py | 593 | 3.859375 | 4 | # O(1) or O of 1 or Constant Time is when we have an array of x elements, but we just take 1 single item in the array, no matter how many items there are in the array
# Example:
items = ['item' for i in range(0,10000)]
def grabber(array):
print(array[0])
grabber(items)
# So, no matter how many items we add at th... |
b99056a50027c7e084f5381a955afbb969f1a360 | thtprof/uni-not-hesaplama | /not-hesaplama.py | 1,454 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
A --- 85-100
BA --- 75-84
BB --- 74-60
CB --- 55-59
CC --- 50-54
FF --- 0-49
Vize, Final
Ortalama= Vize*0,4 + Final*0,6
Ortalamanız = 50 , Harf Notunuz = CC
"""
def hesapla():
vizeNotu=float(input("Vize notu gir : "))
finalNotu=float(input("Final notu gir :"... |
95e3466023fda3700fc10180deae04bbb3c4ffc2 | Mahesh78/ANLY560 | /ANLY_560_Mahesh_Week4_HW2_sakila.py | 671 | 3.703125 | 4 | """
Using the Sakila database, create a query that displays
the film title and description, as well the actor first and last name
for all films that begin with the letters 'zo'.
@author: Mahesh
"""
import pymysql
db = pymysql.connect("localhost","root","harris","sakila")
cursor = db.cursor()
cursor.execute('''SELE... |
be9f6ca8e3ecb7a642b18a36340770573d351f98 | anascko/scripts | /PYTHON/PyLearn/src/fd.py | 1,862 | 3.546875 | 4 | #! /usr/bin/python
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__ = "root"
__date__ = "$Mar 9, 2015 3:05:52 PM$"
import os
if __name__ == "__main__":
'''
os.lseek(fd, p... |
cc6ec37ae5ee900175e0a14ac765178f864dbc8c | moazzam3890/100DaysOfCode-Python | /100DaysOfCoding/snake_game/scoreboard.py | 1,200 | 3.734375 | 4 | from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Arial", 20, "normal")
COLOR = "white"
POSITION = (0, 270)
class Score(Turtle):
def __init__(self):
super().__init__()
self.clear()
self.score = 0
self.high_score = 0
self.update_high_score()
self.penup()
... |
56fe827e3266d6f6095fe78a33d02983362dd17b | moazzam3890/100DaysOfCode-Python | /100DaysOfCoding/Miles_to_KM_converter/main.py | 729 | 3.875 | 4 | from tkinter import *
def calculation():
miles = float(user_input.get())
km = miles * 1.609
label_4.config(text=km)
window = Tk()
window.title("Miles to Kilo Meter Converter")
window.minsize(width=100, height=100)
# User Input:
user_input = Entry(width=10)
user_input.grid(column=1, row=0)
# button:
bu... |
218cb738de0e5d32fede42c392dfc1ed956c7cbc | moazzam3890/100DaysOfCode-Python | /100DaysOfCoding/pong_game/main.py | 1,227 | 3.578125 | 4 | from turtle import Screen
from paddle import Paddle
from ball import Ball
import time
from scoreboard import Score
score = Score()
screen = Screen()
screen.setup(800, 600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)
r_paddle = Paddle((360, 0))
l_paddle = Paddle((-360, 0))
ball = Ball()
screen.list... |
5cf92bdd9fbd1820297c63dcb370a5d7b3bb1129 | SKosztolanyi/Python-exercises | /11_For loop simple universal form.py | 345 | 4.25 | 4 | greeting = 'Hello!'
count = 0
# This is universal python for loop function form
# The "letter" is <identifier> and "greeting" is <sequence>
# the "in" is crucial. "letter" can be changed for any word and the function still works
for letter in greeting:
count += 1
if count % 2 == 0:
print letter
p... |
00e7870eeea04f3bc2a50720cb6e281f4f3a3efb | SKosztolanyi/Python-exercises | /56_Defining a function to find the key with the most values in dictionary.py | 680 | 3.890625 | 4 | # a procedure, called biggest, which returns the key corresponding
# to the entry with the largest number of values associated with it.
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
# Your Co... |
11cea43282d93c8ff11abe1bd833275be18744c6 | SKosztolanyi/Python-exercises | /88_Tuples_basics.py | 1,136 | 4.6875 | 5 | # Tuples are non-changable lists, we can iterate through them
# Tuples are immutable, but lists are mutable.
# String is also immutable - once created, it's content cannot be changed
# We cannot sort, append or reverse a tuple
# We can only count or index a tuple
# The main advantage of a tuple is, they are more effic... |
4815bb6d1fd68902be40c383bedb74252e235890 | SKosztolanyi/Python-exercises | /35_L5 Defining iterativelygreatest common divisor.py | 312 | 3.765625 | 4 | def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
num = max(a,b)
while a <= a and b <=b:
a/num and b/num
if a%num==0 and b%num==0:
break
num-=1
return num |
c67e7420960dcc32cc4e2c520776ae221b1c6354 | SKosztolanyi/Python-exercises | /Uni stuff/IP_Q1_kvadraticka funkcia.py | 1,062 | 3.796875 | 4 | def f(x):
result = (-5*(x**5)) + (69*(x**2)) - 47
return result
print f(2)
print f(1)
print f(0)
print f(3)
def max_of_2(a, b):
if a > b:
return a
else:
return b
def max_of_3(a, b, c):
return max_of_2(a, max_of_2(b, c))
# I was correcting syntax here
import math
def proje... |
bc4e0eaf2af0a02cef3f31335e29ce5176c35e2d | SKosztolanyi/Python-exercises | /16_L3_Part5a For loop and ranges.py | 403 | 3.953125 | 4 | #L3 5A
for num in range(1, 11, -1):
if num%2==0:
print num
print "Goodbye!"
# L3 5B
print "Hello!"
for i in reversed(range(2, 11, 2)):
print i
# L3 5C
# End is defined variable
# I want the last number to be included, therefore I give end+1
# If end wasn't defined, I would just put there numbe... |
d0fc126abdd1251d5c7555870ec36b49798c8936 | SKosztolanyi/Python-exercises | /33_Defining factorials functions iterativela and recursively.py | 374 | 4.15625 | 4 | # Recursive and iterative versions of factorial function
def factI(n):
'''
Iterative way
assume that n is an int>0, returns n!
'''
res = 1
while n >1:
res = res*n
n-=1
return res
def factR(n):
'''
Recursive way
assume that n is an int>0, returns n!
'''
... |
512b02daf706ada213f1a9fdae9eee1be7d2c51e | SKosztolanyi/Python-exercises | /65_Defining testing function Q8.py | 815 | 3.703125 | 4 | ## This function should test another function.
## The other function is unknown to me and only provided by the grader.
## I know the correct output of the function but I have to fit it.
L = ['a', 'b', 'a']
def satisfiesF(L):
"""
Assumes L is a list of strings
Assume function f is already defined for you a... |
dedce3de2121f9098d46f97b8192493ab26f1ca6 | guydanko/Machine-Learning-Projects | /Intervals-Model/assignment2.py | 11,627 | 3.875 | 4 | #################################
# Your name: Guy Dankovich
#################################
import numpy as np
import matplotlib.pyplot as plt
import intervals
import math
class Assignment2(object):
"""Assignment 2 skeleton.
Please use these function signatures for this assignment and submit this file, t... |
198cac1f99c75066f94e605e2aba9d49125f9598 | bpull/6spring | /335proj3/plan.py | 8,511 | 3.71875 | 4 | #!/usr/bin/env python3
# SI 335 Algorithms, Spring 2016
# Project 3
# Brandon Pullig
import sys
class target:
def __init__ (self, posx, posy, point):
self.posx = posx
self.posy = posy
self.point = point
class asset:
def __init__ (self, posx, posy):
self.posx = posx
... |
94f47bd9d94058cb78beafd5066ea00403386d19 | nikolska/A-guessing-game-3 | /main.py | 1,555 | 3.71875 | 4 | from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def guess_the_number():
'''
Function guess_the_number checks the expected user number, replacing the max or min limits
of the possibility of finding the number.
Function returns a new cal... |
32303a03b57b74dd916837e7705a58e324816ec0 | aleramirezsj/pruebas-en-clase-DGBD | /probando_envio_de_parametros_1.py | 1,160 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Created on 24/08/2012
@author: Ramirez'''
def Imprimir(diccionario,promedio,tipo_personas):
print "Los %s ingresados son:" %tipo_personas
for clave in diccionario:
print clave
print "el promedio de edad de los %s es %0.2f " %(tipo_personas,promedi... |
9f701c31ed9c63264396d797dbfb0f60e72259a6 | Nihabr/itProject | /csvTutorial.py | 8,682 | 4.09375 | 4 | # Import packages
import csv
import sys
import itertools as iterT
import nltk
# Define some variables we will need for later
# Variables that are declared inside a function will not be usable outside of
# said function. I believe the same rule applies for declared variables in loops.
# In python, you can create variab... |
4cc9273a0dc1fcf3c84f7d8fafeaed8d98215576 | bajal/6.00x | /charisInString_recur.py | 627 | 4.03125 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
lo=0
hi=len(aStr)
mi=len(aStr)/2
if aStr=='':
return False
elif char == aStr[mi]:
re... |
9800d076073029e0164efc1ff8dd5fac7dae4d8b | yshm1tsu/Python-Django-interview | / Python/AboutMe.py | 349 | 3.65625 | 4 | import random
import sys
print("commands available:")
print("name\tgroup\tmood")
mood = ["happy", "nervous", "starving", "tired", "motivated"]
while True:
command = raw_input()
if command == "name":
print('Musa')
elif command == "group":
print ('11-903')
elif command == "mood":
... |
56f369e0f87bf38445c6aa4fe0d1a9119ba1e115 | ativ97/RoboticArm | /Movement 1.py | 2,292 | 4 | 4 | from sympy import *
import matplotlib.pyplot as plt
Angle = Symbol('Angle') #Variable to hold the angles
Cosine= cos(Angle) #Variable name to hold cos
Sine= sin(Angle) #Variable name to hold sin
M1=Matrix([[Cosine, -Sine], [Sine, Cosine]]) #Variable name to hold matrix (cos -sin)
... |
e93731d2fef5f6ab9957665a1d431add2b5ff6ea | pmmorris3/Code-Wars-Solutions | /6-kyu/find-the-odd-int/python/solution.py | 190 | 3.515625 | 4 | def find_it(seq):
for x in seq:
count = 0
for y in seq:
if x == y:
count += 1
if count % 2 == 1:
return x
return None
|
2827c8423400bfe3d5c7992fd80d1a8d321dbd9f | pmmorris3/Code-Wars-Solutions | /5-kyu/valid-parentheses/python/solution.py | 471 | 4.25 | 4 | def valid_parentheses(string):
bool = False
open = 0
if len(string) == 0:
return True
for x in string:
if x == "(":
if bool == False and open == 0:
bool = True
open += 1
if x == ")" and bool == True:
if open - 1 == 0:
... |
64ed9db66c954dfef2c36611878e868903d3873f | ssep4u/Book_Programming-Python- | /fileRead.py | 421 | 3.5 | 4 | f = open("text.txt", "w", encoding="utf8")
f.write("안녕하세요")
f.write("\n")
f.write("반갑습니다.")
f.write("\n")
f.close()
f = open("text.txt", "r", encoding="utf8")
str = f.read()
print(str)
print("----")
f.close()
f = open("text.txt", "r", encoding="utf8")
line1 = f.readline()
print("Line1 : ", line1)
line2 = f.readline()... |
2013f8c2bbf81ad16cd89c025d9caa3d9d3e3c5b | aneeknroy/Daily-Coding-Problems | /Solutions/heightChecker.py | 266 | 3.890625 | 4 |
def heightChecker(nums):
fin = sorted(nums)
counter = 0
zipo = zip(nums, fin)
for x, y in zipo:
if x != y:
counter += 1
print(counter)
heightChecker([1,1,4,2,1,3])
heightChecker([1,2,3,4,5])
heightChecker([5,1,2,3,4])
|
65ad9017602ceb707bdba3c32f22d84875a15218 | aneeknroy/Daily-Coding-Problems | /Solutions/palindromeNumber_Leet.py | 743 | 4.09375 | 4 |
#Given an integer x, return true if x is palindrome integer.
#An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
class Solution:
def isPalindrome(self, x: int) -> bool:
temp = str(x)
bruh = len(temp) // 2
first = temp[:... |
fe9d31bb9c89122b085b25f02d8cbfd10a061466 | aneeknroy/Daily-Coding-Problems | /Solutions/highestRank.py | 479 | 3.734375 | 4 | def highest_rank(arr):
theCount = collections.Counter(arr)
theKeys = []
temp = 0
fin = []
for key in theCount.items():
theKeys.append(key[1])
for j in range(len(theKeys)):
if theKeys[j] > temp:
temp = theKeys[j]
for number, count in theCount.items():
if co... |
1dd8a62cd05e97514c16cbe8f8abb5b9d30d96c5 | aneeknroy/Daily-Coding-Problems | /Solutions/getEvens.py | 250 | 4.03125 | 4 | #Given an array nums of integers, return how many of them contain an even number of digits.
def findEven(nums):
evens = 0
for i in nums:
if len(str(i)) % 2 == 0:
evens += 1
return evens
findEven([555,901,482,1771]) |
e52c756caf9b40359e0d81ee8c29e987c4455103 | aneeknroy/Daily-Coding-Problems | /Solutions/validMountainArray.py | 814 | 3.625 | 4 | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
# Finding the Peak
peak = arr.index(max(arr))
if peak == len(arr) - 1 or peak == 0:
return False
# checking the uphill portion
counterUp = 0
... |
c5f9047ec0797a929b6bc4056bbe72c1adaf1526 | aneeknroy/Daily-Coding-Problems | /Solutions/tribonacci.py | 259 | 3.890625 | 4 | def tribonacci(signature,n):
z = 0
if n == 0:
return []
if n < 3:
return signature[:n]
while len(signature) < n:
signature.append(sum(signature[z:z+3]))
z += 1
print(signature)
#tribonacci([1, 1, 1], 10)
|
694da23799d5df7e80592f24f129d0ce86f5080f | SumanjaliDamarla/100daysofcode | /python/pd/pandas29235.py | 343 | 3.546875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'width': [0.7, 0.2, 0.15, 0.2, 1.1],
'length': [1.5, 0.5, 1.2, 0.9, 3]
}, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse'])
# Whether or not `column` is passed the order is still reordered to alphabetical.
df.hist(column=['width'... |
beec5441e940f8331fab14a3165759a1e6b7000f | Olu93/project_human_centered_machine_learning_assignment_programming | /assignment2/assignment2.py | 14,954 | 3.5 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython
# %% [markdown]
# # Programming Assignment II: Explainability
#
# In this assignment you will train machine learning models and experiment with techniques discussed in the lectures.
# This assignm... |
825c97cf9d692367cd43ab6ddc15f25688c2e251 | Bishwajit-Shil/Machine-Learning | /NeuralNetworks/cnn_mnist.py | 3,688 | 3.515625 | 4 | import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers.normalization import BatchNormalization
from keras.utils import np_utils
from keras.layers import Conv2D, MaxPooling2D
from keras.pre... |
a10cabf61a7c1b85faff264647e8c29e53558ff6 | vinod-designer1/competitive-programming | /HackerRank/Math/finddigits.py | 261 | 3.828125 | 4 | #https://www.hackerrank.com/challenges/find-digits
def findDigits(num):
cnum = num
cnt = 0
while num != 0:
r = num%10
if r!=0 and cnum%r == 0:
cnt += 1
num /= 10
return cnt
t = input()
while t > 0:
num = input()
print findDigits(num)
t -= 1
|
42eaab9c3b6211f70a1906550822e978ff651cc6 | vinod-designer1/competitive-programming | /GeeksForGeeks/NUmbers/odd_occuring_num.py | 377 | 4.0625 | 4 | '''
Find the Number Occurring Odd Number of Times
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.
Example:
I/P = [1, 2, 3, 2, 3, 1, 3]
O/P = 3
Algorithm:
Do bitwise XOR of all the elements. ... |
4a2188cf02ef6eea8699d1ede7bf40a76fc6a818 | vinod-designer1/competitive-programming | /GeeksForGeeks/array/majority_el.py | 773 | 3.6875 | 4 | from random import randint
#Moores Voting Algorithm
def findCandidate(ar, n):
maj_index = 0
i = 1
count = 1
while i < n:
if ar[maj_index] == ar[i]:
count += 1
else:
count -= 1
if count == 0:
maj_index = i
count = 1
i += 1
return ar[maj_index]
def isMajority(ar, n, el):
count = 0
for nu in a... |
c1f3f259adae8a95cac7f8c204409f329413e065 | vinod-designer1/competitive-programming | /codeforces/133a.py | 134 | 3.875 | 4 | st = raw_input()
y = False
for i in st:
if i == 'H' or i == 'Q' or i == '9':
y = True
break
if y:
print 'YES'
else:
print 'NO' |
b679f53c75a2a4bbc5abecbca6bf52827c09512e | jerryderry/pyimagesearchstudy | /module1/tictactoe.py | 1,402 | 3.59375 | 4 | import cv2
# load the tic-tac-toe image and convert it to grayscale
img = cv2.imread("tictactoe.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find all contours on the tic-tac-toe board
(_, contours, _) = cv2.findContours(gray, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)
# loop over the contours
fo... |
a826c00d589d63f562f9667d19e33fbbe2f06dfb | karinnecristina/hackerrank_Estatistica | /Weighted_Mean.py | 1,280 | 3.984375 | 4 | '''
## Objetivo ##
No desafio anterior, calculamos uma média. Nesse desafio, praticamos o cálculo de uma média ponderada.
## Tarefa ##
Dada uma matriz X de N números inteiros e uma matriz W representando os respectivos pesos dos X elementos, calcule e imprima a média ponderada dos elementos.
## Formato de entrada ##... |
fe6a62daf367325af8cb4a69819572f216d112a6 | fd-developer/P3_MACGYVER | /Map.py | 1,289 | 3.5 | 4 | #! /usr/bin/env python3
# coding: utf-8
import pygame
from pygame.locals import *
import json
from random import *
# Class in charge to manage the map
class Map:
GRID = {}
def __init__(self):
self.load_grid("maze.json")
@classmethod
def load_grid(cls, map_file):
with open(map_file)... |
ca15a1894498b352887b8c055ec1c3eede7d5744 | pomfy113/playground | /playground8-1.py | 1,284 | 3.859375 | 4 | def is_on(a, b, c):
"Return true iff point c intersects the line segment from a to b."
# (or the degenerate case that all 3 points are coincident)
if a[0] != b[0]:
is_within = within(a[0], c[0], b[0])
else:
is_within = within(a[1], c[1], b[1])
return collinear(a, b, c) and is_within
... |
6e414d9041d88aa87a8a39bb303215a06daeb7d2 | vipul-08/SRM05 | /SRM05C/SRM05C.py | 2,380 | 3.5 | 4 | # Contradiction Finder Function
def findContradiction(sList,dList,oList):
for i in range(0,len(sList)):
if oList[sList[i]] == 'n' or oList[dList[i]] == 'n':
continue
elif oList[sList[i]] == oList[dList[i]]:
return False
return True
# Main Code
t = int(input())
ans = []
fo... |
19da99f2054bccc6f24708964760c26838840bfb | gitiles/slides | /python/examples/files/rot13_file.py | 415 | 3.53125 | 4 | import sys
import codecs
def rot13(text):
text_in_rot_13 = ''
# Do something with text to become rot13
return text_in_rot_13
if len(sys.argv) != 2:
exit(f"Usage: {sys.argv[0]} FILENAME")
filename = sys.argv[1]
with open(filename, 'r') as fh:
original = fh.read()
encoded = codecs.encode(origi... |
862215cddcd2d6e60bc8f1877c9666cbaae74282 | SkylarLevey/Tanks | /Final_Project.py | 23,169 | 4.03125 | 4 | #Final Project COM 110
#Professor Chung
#Abe Lusk
#Skylar Levey
#12/22/15
import graphics
from button import *
from math import *
from time import sleep
from random import randrange
class Ground:
"""Creates a ground object with a list of points for the top side then two anchor points in the bottom left
and b... |
0300927ede82d4af60a4208938c3e1f49ad0be4a | PythonOpen/PyhonProjects | /scrapy/scrapy05.py | 1,195 | 3.53125 | 4 | from urllib import request, parse
# 负责处理json格式
import json
'''
大致流程是:
1.利用data构造内容,然后urlopen打开
2.返回一个json格式的结果
3.结果就应该是girl的释义
1.打开F12
2.尝试输入单词girl,发现每敲一个字母后都有请求
3.请求地址是http://fanyi.baidu,com/sug
4.利用NetWork-All-Headers查看,发现FromData的值是kw:girl
5.检查返回内容格式,发现返回的是json格式内容==>需要利用json包
'''
if __name__ == '__main__':
bas... |
e6e06c344db3831015e68ff261887f04ec72f3e3 | tohfaakib/python_playground | /collections/deque/example.py | 238 | 3.703125 | 4 | from collections import deque
d = deque()
print(d)
for i in range(10):
d.append(i)
print(d)
d = deque(range(20))
print(d)
d.appendleft(100)
print(d)
d.extendleft([56, 87])
print(d)
d.insert(10, 90)
print(d)
d.pop()
print(d)
|
f7c0b13abb2cfe195a2931f064c9c612d81a65a3 | tohfaakib/python_playground | /decorators/decorator.py | 446 | 3.8125 | 4 | from functools import wraps
def new_decorator(func):
@wraps(func)
def wrapper():
print("before calling func()")
func()
print("after calling func()")
return wrapper
def the_great_ugly_func():
print("you ugly *****, you need be decorated!")
the_great_ugly_func()
the_great... |
018d48db24ca65542976d49e13a611b5406b54e3 | sophsmcd/progBD_SophieMCD | /test_calculator2.py | 1,905 | 3.625 | 4 |
from calculator import *
import unittest
class MyTest(unittest.TestCase):
def testSum1(self):
self.assertEqual(sum(2,2), 4)
self.assertEqual(sum(5,3), 8)
self.assertEqual(sum(4,0), 4)
def testsubtract(self):
self.assertEqual(subtract(2,... |
bff81845806f726c9ebf0c35c407076314d711ff | borodasan/python-stady | /duel/1duel/1duel.py | 483 | 4.4375 | 4 | def p(p):
for i in range(0,5,2): #The range() function defaults to increment the sequence by 1,
#however it is possible to specify the increment
#value by adding a third parameter: range(0, 5, 2)
#Assignment operators are used to assign values to... |
a67e31b47c7be597942229d2f9046e4b7dc4e283 | borodasan/python-stady | /python-collections-arrays/set.py | 1,504 | 4.65625 | 5 | #A set is a collection which is unordered and unindexed.
#In Python sets are written with curly brackets.
print("A set is a collection which is")
print("unordered and unindexed".upper())
print("In Python sets are written with curly brackets.")
#Create a Set
print("Create a Set:")
thisset = {"apple", "banana", "cherry... |
409ffb0e0562634bd40ab0c6ef0491c11e4067fe | vmelnik05/Cogs18-sp19-Final-Project | /modules_and_script/test_functions.py | 550 | 3.703125 | 4 | from my_classes import Piece
test_piece = Piece('b','q')
def test_in_board():
"""Test function that tests the in_board() method contained in the Piece class.
Args:
None
Returns:
Passes silently if all asserts pass.
Otherwise, raises assertion error.
"""
for row in range(8):
for col in ... |
3c79d1990f5704d64c0e0a3d72b3cdc5cab9517f | spiritofsands/black_jack_py | /tests/unit/test_card.py | 4,031 | 3.5 | 4 | from unittest import TestCase
from blackjack.card import Card
_ = None
class TestCard(TestCase):
def test_card_attributes(self):
name = 'Ten'
value = 1
values = [value]
suit = 'Spades'
exposed = True
card = Card(name, values, suit, exposed)
self.assertEq... |
423736de6e6515f77cec66aefb7941ba34c623ae | shane806/201_Live | /13. More Lists/live.py | 297 | 4.15625 | 4 | matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3],
[4, 5, 6, 7]]
def create_new_2d_list(height, width):
pass
def main():
# how do I get at the 9?
# how do I loop through the third row?
# how do I loop through the second column?
pass
main()
|
76221ef673c13a9adb43b0ea58d26ed486f2d27e | shane806/201_Live | /6 - For loops/for-i-live.py | 199 | 3.890625 | 4 | # How can we print the even numbers between two integers x and y with a for loop?
# How can we use range to go backwards through a list?
# Print all the elements of a list with their index! How do?
|
986b91f88428ac224804795c2d9550787d1274dc | itshui3/cs-module-project-hash-tables | /applications/word_count/word_count.py | 1,350 | 3.734375 | 4 | #move through the string
#notice when a word starts
def word_count(s):
ignore = set()
ignore.add('"')
ignore.add(':')
ignore.add(';')
ignore.add(',')
ignore.add('.')
ignore.add('-')
ignore.add('+')
ignore.add('=')
ignore.add('/')
ignore.add("\r")
ignore.add("\n")
... |
bc4a1965d6beecdc5ba63932963b0f96f43e144c | jawad8106/python-files | /cars.py | 154 | 4.09375 | 4 | cars = ['mustang', 'nissan', 'toyota', 'bmw']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
_
|
4cf7a2a0d802c38ac98d19cbffa8a3dd0bd6c179 | untalinfo/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 305 | 3.78125 | 4 | #!/usr/bin/python3
"""
Module is same class
"""
def is_same_class(obj, a_class):
"""
function that returns True if the object
is exactly an instance of the specified class
Arguments:
obj
a_class
Returns:
True or False
"""
return type(obj) == a_class
|
5158eedff805fe1a02c30ccc26fbe4027407d813 | untalinfo/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 570 | 4.125 | 4 | #!/usr/bin/python3
"""
Module
"""
def append_after(filename="", search_string="", new_string=""):
"""
Inserts a line of text to a file
Args:
filename (str, optional)
search_string (str, optional) Defaults to "".
new_string (str, optional) Defaults to "".
"""
with open(file... |
9c6849390bb3d395028d1ef48772412b081e7063 | untalinfo/holbertonschool-higher_level_programming | /0x0A-python-inheritance/3-is_kind_of_class.py | 349 | 3.640625 | 4 | #!/usr/bin/python3
"""
Module for is ind of class
"""
def is_kind_of_class(obj, a_class):
"""function that returns True if the object is an
instance of, or if the object is an instance of
a class that inherited from, the specified class
Returns:
object is an instance of a class
"""
ret... |
c0829dede014a13a5f43c40e3995dc4ddfcb8308 | WNBARookie/Spider-Solitaire | /Human.py | 10,630 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 13:12:30 2019
@author: Trinity
"""
#creating the board
import random
import copy
"""
what's needed
- array for each stack
- piles - 1 2D array?
- stock - 1 1D array
-foundation - 1D array of T/F
- keep track of the what's... |
4117c18a1be459ec0eb68e72135be7039f188916 | brunsbr/Programa-Crip-Descrip | /Teste V5.0.0 bem sucedido.py | 717 | 3.84375 | 4 | def encrypt(sentence):
result = []
for letter in sentence:
l = ord(letter) - 200
result.append(l)
print("Este é seu texto criptografado:")
for numbers in result:
print(numbers, end='' )
print(" ", end='')
print()
decrypt(result)
... |
9e4a89cab60f44b67afa5ea5905851ca40b7bb26 | falian0012/secondHomeworkRepository | /Task_4/task_4.py | 200 | 3.765625 | 4 | print("Enter the string : ")
userInputString = input()
listOfWords = userInputString.split(' ')
indexRow = 1
for string in listOfWords:
print(f"{indexRow}. {string[0:10:1]}")
indexRow += 1
|
f2c750e4a1fa7376dfe18b818032751c30fe72db | Jonathangmit/scriptingGMITproject | /import datetime.py | 204 | 3.75 | 4 | import datetime
today=datetime.datetime.today()
dayofweek =today.weekday()
if dayofweek==1:
print ("Shit still tuesday")
elif dayofweek ==5:
print("bollox Tueday tomorrow")
else:
print("nope") |
ad990232a9d67150c0ccca30996206693ed6b393 | aishwarya-mustoori/ScrapingTheSpaceflight | /Scrap.py | 4,411 | 3.5 | 4 | from bs4 import BeautifulSoup
import pandas as pandass
import numpy as np
import requests
import datetime
from collections import defaultdict
#Code for assesing multiple rows in rowspan is insipired from an online link:
#https://stackoverflow.com/questions/28763891/what-should-i-do-when-tr-has-rowspan
#first three me... |
e3c68d54e8bf934ebad67db9df7217dc31546d68 | Igor0411/Python_Courses | /hometask8.py | 1,342 | 3.96875 | 4 | #! usr/bin/env python
from __future__ import division, print_function
import itertools
import random
def mergesort_recursive(lst):
"""
:type:
:param lst:
:return:
"""
halflist1 = lst[:len(lst) // 2]
halflist2 = lst[len(lst) // 2:]
def merge(a, b):
"""
:type a: list
... |
6f450e7e25faf0cc41507472e6ca947192010466 | 0x15F9/PythonCrashCourse | /Chapter10/1_LearningPython.py | 397 | 3.5625 | 4 | with open('learning_python.txt') as file_object:
contents = file_object.read()
print(contents)
print("-"*20)
with open('learning_python.txt') as file_object:
for line in file_object:
print(line.strip())
print("-"*20)
list = []
with open('learning_python.txt') as file_object:
for line in file... |
728841838fdcc631695fac74e5ce83b3f18008d2 | 0x15F9/PythonCrashCourse | /Chapter7/3_MultiplesOfTen.py | 162 | 4.1875 | 4 | num = int(raw_input("Number: "))
if num % 10 == 0 :
print("{} is a multiple of ten.".format(num))
else:
print("{} is NOT a multiple of ten.".format(num)) |
ea094df0b680605a3d51b98ab2bd11c9ae570c67 | 0x15F9/PythonCrashCourse | /Chapter3/3.3_YourOwnList.py | 199 | 3.890625 | 4 | plants = ["Cherry", "Strawberry", "Litchi", "Mango"]
statement = "I would like to own a {} tree"
# I guess i'm too lazy for the manual looping
for plant in plants:
print(statement.format(plant)) |
95baed81652cfcab0c9dcdf6536cd445aa4afbf7 | 0x15F9/PythonCrashCourse | /Chapter10/11_FavoriteNumberReader.py | 219 | 3.546875 | 4 | import json
def fetch(filename):
with open(filename, 'r') as json_file:
return(json.load(json_file))
fav_num = fetch('favorite_number.json')
print("I know that your favorite number is {}.".format(fav_num)) |
b298b8497c1fa17751bd8fa14778daca7580e699 | 0x15F9/PythonCrashCourse | /Chapter12/3_Rocket/rocket.py | 1,780 | 3.859375 | 4 | import pygame
class Rocket():
"""Class definition for creating a Rocket"""
def __init__(self, screen):
self.screen = screen
self.image = pygame.image.load('assets/rocket.bmp')
self.rect = self.image.get_rect()
self.screen_rect = self.screen.get_rec... |
122fc5d595cefd3d74d87082a841c8f538a3c794 | 0x15F9/PythonCrashCourse | /Chapter12/5_SidewayShooter/bullet.py | 650 | 3.640625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, screen, ship):
super().__init__()
self.screen = screen
self.width = 5
self.height = 2
self.color = (255, 255, 255)
self.speed_factor = 0.75
self.rect = pygame.Rect(0,... |
63b1b60ff54a308fba7e0aa15838aefed5ab0a7f | 0x15F9/PythonCrashCourse | /Chapter8/4_LargeShirts.py | 234 | 3.640625 | 4 | def make_shirt(message, size="L"):
"""Makes a shirt of size (defult: Large) with message printed on it."""
print("Make a shirt of size {} with the message '{}' printed on it.".format(size, message))
make_shirt("Hello World!") |
12ca263f56c97eda7df3061bbe8eacfc253ebee3 | 0x15F9/PythonCrashCourse | /Chapter7/4_PizzaToppings.py | 152 | 3.984375 | 4 | topping = ""
while topping != "quit":
topping = raw_input("Which topping would you like to have?\n")
print("{} will be added.".format(topping)) |
35c123971cb1de0f27fb9afb788d436e774ff19d | 0x15F9/PythonCrashCourse | /Chapter11/employee.py | 475 | 3.921875 | 4 | class Employee():
def __init__(self, first_name, last_name, annual_salary):
"""Class modelling an employee"""
self.first_name = first_name
self.last_name = last_name
self.annual_salary = annual_salary
def give_raise(self, amount=None):
"""Increase the annual salary of an ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.